🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(project): check the identifier inline and report a conflict as a field error (#21244)
Arvin Xu76124b171cac
diff --git a/apps/server/src/routers/lambda/__tests__/integration/project.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/project.integration.test.tsindex dfbd83aa218..2d933010e86 100644--- a/apps/server/src/routers/lambda/__tests__/integration/project.integration.test.ts+++ b/apps/server/src/routers/lambda/__tests__/integration/project.integration.test.ts@@ -121,6 +121,26 @@ describe('Project Router Integration', () => {);});+ it('answers a duplicate identifier as CONFLICT instead of a raw query failure', async () => {+ await caller.create({ identifier: 'LOBE', name: 'LobeHub' });++ await expect(+ caller.create({ identifier: 'LOBE', name: 'LobeHub Mobile' }),+ ).rejects.toMatchObject({+ code: 'CONFLICT',+ // The code, not prose: the create forms key off it to mark the field.+ message: 'DUPLICATE_PROJECT_IDENTIFIER',+ });+ });++ it('answers a duplicate slug with its own code, not the identifier one', async () => {+ await caller.create({ name: 'LobeHub', slug: 'taken-link-name' });++ await expect(+ caller.create({ name: 'LobeHub Mobile', slug: 'taken-link-name' }),+ ).rejects.toMatchObject({ code: 'CONFLICT', message: 'DUPLICATE_PROJECT_SLUG' });+ });+it.each(['team/launch', 'roadmap?draft', '#plan', 'two--hyphens'])('rejects the route-unsafe slug %s when creating a project',async (slug) => {diff --git a/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.tsindex b83bfbfea6b..20f53a231ba 100644--- a/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts+++ b/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts@@ -4,9 +4,9 @@ import { getTestDB } from '@lobechat/database/test-utils';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { AcceptanceModel } from '@/database/models/acceptance';-import { ProjectModel } from '@/database/models/project';import { TaskModel } from '@/database/models/task';import { TaskTopicModel } from '@/database/models/taskTopic';+import { ProjectRepository } from '@/database/repositories/project';import { TaskService } from '@/server/services/task';import { taskRouter } from '../../task';@@ -162,7 +162,7 @@ describe('Task Router Integration', () => {}const scopedCaller = taskRouter.createCaller({ ...createTestContext(userId), workspaceId });const model = new TaskModel(serverDB, userId, workspaceId);- const project = await new ProjectModel(serverDB, userId, workspaceId).create({+ const project = await new ProjectRepository(serverDB, userId, workspaceId).create({identifier: 'PROJ',name: 'Prefix project',});diff --git a/apps/server/src/routers/lambda/__tests__/project.create.test.ts b/apps/server/src/routers/lambda/__tests__/project.create.test.tsindex 86334181045..d7bf2d00257 100644--- a/apps/server/src/routers/lambda/__tests__/project.create.test.ts+++ b/apps/server/src/routers/lambda/__tests__/project.create.test.ts@@ -2,13 +2,28 @@import { TRPCError } from '@trpc/server';import { beforeEach, describe, expect, it, vi } from 'vitest';-const mocks = vi.hoisted(() => ({- assertCanPerformResourceAction: vi.fn(),- create: vi.fn(),- createDefaultChannel: vi.fn(),- createSite: vi.fn(),- resolveCoordinatorAgents: vi.fn(),-}));+const mocks = vi.hoisted(() => {+ // Stand-in for the database error the router narrows on; the real class lives+ // in the mocked `@/database/models/project` module.+ class ProjectIdentifierTakenError extends Error {+ readonly identifier: string;++ constructor(identifier: string) {+ super(`Project identifier "${identifier}" is already in use in this scope`);+ this.identifier = identifier;+ this.name = 'ProjectIdentifierTakenError';+ }+ }++ return {+ assertCanPerformResourceAction: vi.fn(),+ create: vi.fn(),+ createDefaultChannel: vi.fn(),+ createSite: vi.fn(),+ ProjectIdentifierTakenError,+ resolveCoordinatorAgents: vi.fn(),+ };+});vi.mock('@/database/core/db-adaptor', () => ({getServerDB: vi.fn(function () {@@ -23,11 +38,18 @@ vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({}));vi.mock('@/database/models/project', () => ({+ ProjectIdentifierTakenError: mocks.ProjectIdentifierTakenError,ProjectModel: vi.fn(function () {return { create: mocks.create, resolveCoordinatorAgents: mocks.resolveCoordinatorAgents };}),}));+vi.mock('@/database/repositories/project', () => ({+ ProjectRepository: vi.fn(function () {+ return { create: mocks.create };+ }),+}));+vi.mock('@/database/repositories/projectCoordinator', () => ({ProjectCoordinatorRepository: vi.fn(function () {return {};@@ -129,6 +151,37 @@ describe('project.create default Channel', () => {});});+describe('project.create duplicate field codes', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.resolveCoordinatorAgents.mockImplementation(async (projects) => projects);+ });++ it('answers a taken identifier with the identifier code the create forms key off', async () => {+ mocks.create.mockRejectedValue(new mocks.ProjectIdentifierTakenError('LOBE'));++ await expect(+ caller('ws-1').create({ identifier: 'LOBE', name: 'Launch' }),+ ).rejects.toMatchObject({ code: 'CONFLICT', message: 'DUPLICATE_PROJECT_IDENTIFIER' });+ expect(mocks.createDefaultChannel).not.toHaveBeenCalled();+ });++ it('answers a taken slug with the slug code instead of the identifier one', async () => {+ // Drizzle wraps the driver error, so the Postgres fields sit down the chain.+ mocks.create.mockRejectedValue(+ Object.assign(new Error('Failed query: insert into "projects" ...'), {+ cause: { code: '23505', constraint: 'projects_slug_workspace_id_unique' },+ }),+ );++ await expect(caller('ws-1').create({ name: 'Launch' })).rejects.toMatchObject({+ code: 'CONFLICT',+ message: 'DUPLICATE_PROJECT_SLUG',+ });+ expect(mocks.createDefaultChannel).not.toHaveBeenCalled();+ });+});+describe('project.create from a client that still sends a type or a site', () => {beforeEach(() => {vi.clearAllMocks();diff --git a/apps/server/src/routers/lambda/__tests__/trash.projectFilter.test.ts b/apps/server/src/routers/lambda/__tests__/trash.projectFilter.test.tsindex 5f85fd7a0ef..9bfd94adbf2 100644--- a/apps/server/src/routers/lambda/__tests__/trash.projectFilter.test.ts+++ b/apps/server/src/routers/lambda/__tests__/trash.projectFilter.test.ts@@ -8,6 +8,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { AgentModel } from '@/database/models/agent';import { ProjectModel } from '@/database/models/project';import { TopicModel } from '@/database/models/topic';+import { ProjectRepository } from '@/database/repositories/project';import { agents, topics, trashItems, users, workspaces } from '@/database/schemas';import { TrashService } from '@/server/services/trash';@@ -39,7 +40,7 @@ const createProject = (ws: string | undefined,identifier: string,visibility?: 'private' | 'public',-) => new ProjectModel(testDB, userId, ws).create({ identifier, name: identifier, visibility });+) => new ProjectRepository(testDB, userId, ws).create({ identifier, name: identifier, visibility });/** Create topics under a project (or none) and trash each as its own root, oldest first. */const trashTopics = async (diff --git a/apps/server/src/routers/lambda/_helpers/projectConstraintErrors.ts b/apps/server/src/routers/lambda/_helpers/projectConstraintErrors.tsindex b3a0fc1cf3c..b68ae392440 100644--- a/apps/server/src/routers/lambda/_helpers/projectConstraintErrors.ts+++ b/apps/server/src/routers/lambda/_helpers/projectConstraintErrors.ts@@ -1,13 +1,14 @@+import { PROJECT_DUPLICATE_IDENTIFIER, PROJECT_DUPLICATE_SLUG } from '@lobechat/types';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',+ projects_identifier_user_id_unique: PROJECT_DUPLICATE_IDENTIFIER,+ projects_identifier_workspace_id_unique: PROJECT_DUPLICATE_IDENTIFIER,+ projects_slug_user_id_unique: PROJECT_DUPLICATE_SLUG,+ projects_slug_workspace_id_unique: PROJECT_DUPLICATE_SLUG,};/**diff --git a/apps/server/src/routers/lambda/project.ts b/apps/server/src/routers/lambda/project.tsindex 5337d164410..7a04c0a01b3 100644--- a/apps/server/src/routers/lambda/project.ts+++ b/apps/server/src/routers/lambda/project.ts@@ -1,4 +1,9 @@-import { PROJECT_IDENTIFIER_REGEX, PROJECT_STATUSES, PROJECT_VISIBILITIES } from '@lobechat/types';+import {+ PROJECT_DUPLICATE_IDENTIFIER,+ PROJECT_IDENTIFIER_REGEX,+ PROJECT_STATUSES,+ PROJECT_VISIBILITIES,+} from '@lobechat/types';import { TRPCError } from '@trpc/server';import { z } from 'zod';@@ -7,7 +12,12 @@ import {type WorkspaceRole,wsCompatProcedure,} from '@/business/server/trpc-middlewares/workspaceAuth';-import { ProjectModel, type ProjectModelOptions } from '@/database/models/project';+import {+ ProjectIdentifierTakenError,+ ProjectModel,+ type ProjectModelOptions,+} from '@/database/models/project';+import { ProjectRepository } from '@/database/repositories/project';import { ProjectCoordinatorRepository } from '@/database/repositories/projectCoordinator';import type { LobeChatDatabase } from '@/database/type';import { router } from '@/libs/trpc/lambda';@@ -45,6 +55,7 @@ const projectProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts)options,),projectModel: new ProjectModel(ctx.serverDB, ctx.userId, workspaceId, options),+ projectRepo: new ProjectRepository(ctx.serverDB, ctx.userId, workspaceId),},});});@@ -108,6 +119,12 @@ const knowledgeBaseBindingPatch = z.object({function mapProjectError(error: unknown, operation: string): never {if (error instanceof TRPCError) throw error;+ // A duplicate identifier is a field-level problem the client renders next to+ // the input; `CONFLICT` carries the machine-readable code the create forms key+ // off, so they can mark the identifier rather than a generic failure.+ if (error instanceof ProjectIdentifierTakenError) {+ throw new TRPCError({ cause: error, code: 'CONFLICT', message: PROJECT_DUPLICATE_IDENTIFIER });+ }const message = error instanceof Error ? error.message : `Failed to ${operation} project`;console.error(`[project:${operation}]`, error);throw new TRPCError({ cause: error, code: 'BAD_REQUEST', message });@@ -198,9 +215,12 @@ export const projectRouter = router({if (input.coordinatorAgentId) {await assertResourceUsable(ctx, 'agent', input.coordinatorAgentId);}+ // The repository owns the cross-aggregate transaction (main agent,+ // coordinator link and the optional repository environment). A taken+ // slug or identifier still surfaces as the field-level CONFLICT code.const project = await withMainAgent(ctx.projectModel,- await ctx.projectModel.create(input).catch(rethrowDuplicateProjectField),+ await ctx.projectRepo.create(input).catch(rethrowDuplicateProjectField),);await createDefaultChannel({agentId: project.coordinatorAgentId,diff --git a/locales/en-US/project.json b/locales/en-US/project.jsonindex 3a0b3b7e092..f8c1d98a59a 100644--- a/locales/en-US/project.json+++ b/locales/en-US/project.json@@ -41,6 +41,7 @@"create.identifierInvalid": "Use 3–6 uppercase letters or numbers, starting with a letter.","create.identifierLabel": "Identifier (optional)","create.identifierPlaceholder": "ACE",+ "create.identifierTaken": "Another project in this workspace already uses this identifier.","create.mainAgentDedicatedDescription": "Creates an agent named after the project, with its avatar and the Project label. It stays in your agents list.","create.mainAgentDedicatedPlaceholder": "Named after the project","create.mainAgentDedicatedTag": "New",@@ -56,6 +57,7 @@"create.slugInvalid": "Use lowercase letters, numbers, and single hyphens only.","create.slugLabel": "Slug (optional)","create.slugPlaceholder": "my-project",+ "create.slugTaken": "Another project in this workspace already uses this link name.","create.title": "New project","createFromGithub.connect": "Connect GitHub","createFromGithub.disconnected": "Connect GitHub to choose from your repositories, or paste a public repository URL below.",diff --git a/locales/zh-CN/project.json b/locales/zh-CN/project.jsonindex d95df96941c..58b67d99fb7 100644--- a/locales/zh-CN/project.json+++ b/locales/zh-CN/project.json@@ -41,6 +41,7 @@"create.identifierInvalid": "请输入 3–6 位大写字母或数字,并以字母开头。","create.identifierLabel": "项目标识(可选)","create.identifierPlaceholder": "ACE",+ "create.identifierTaken": "当前空间已有项目使用该标识,请换一个。","create.mainAgentDedicatedDescription": "用项目名称和头像新建一个 Agent,并打上 Project 标签,之后可以在助理列表里找到它。","create.mainAgentDedicatedPlaceholder": "以项目名称命名","create.mainAgentDedicatedTag": "新建",@@ -56,6 +57,7 @@"create.slugInvalid": "仅可使用小写字母、数字和单个连字符。","create.slugLabel": "Slug(可选)","create.slugPlaceholder": "my-project",+ "create.slugTaken": "当前空间已有项目使用该链接名,请换一个。","create.title": "新建项目","createFromGithub.connect": "连接 GitHub","createFromGithub.disconnected": "连接 GitHub 后可直接选择你的仓库,也可以在下方粘贴公开仓库的链接。",diff --git a/packages/database/src/models/__tests__/acceptance.coverage.test.ts b/packages/database/src/models/__tests__/acceptance.coverage.test.tsindex 76e82d0b075..38b7631e16b 100644--- a/packages/database/src/models/__tests__/acceptance.coverage.test.ts+++ b/packages/database/src/models/__tests__/acceptance.coverage.test.ts@@ -3,10 +3,10 @@ import { inArray } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';+import { ProjectRepository } from '../../repositories/project';import { topics, users } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { AcceptanceModel } from '../acceptance';-import { ProjectModel } from '../project';const serverDB: LobeChatDatabase = await getTestDB();@@ -25,7 +25,7 @@ afterEach(async () => {describe('AcceptanceModel coverage', () => {it('keeps the recorded project while a later ensure fills a missing requirement', async () => {- const project = await new ProjectModel(serverDB, userId).create({+ const project = await new ProjectRepository(serverDB, userId).create({identifier: 'ACOV',name: 'Coverage project',});@@ -33,7 +33,7 @@ describe('AcceptanceModel coverage', () => {const created = await model.ensureForSubject('topic', topicIds[0], { projectId: project.id });expect(created.requirement).toBeNull();- const other = await new ProjectModel(serverDB, userId).create({+ const other = await new ProjectRepository(serverDB, userId).create({identifier: 'ACOT',name: 'Other project',});diff --git a/packages/database/src/models/__tests__/acceptance.test.ts b/packages/database/src/models/__tests__/acceptance.test.tsindex 2e969a3a78c..88db0a3faf3 100644--- a/packages/database/src/models/__tests__/acceptance.test.ts+++ b/packages/database/src/models/__tests__/acceptance.test.ts@@ -4,6 +4,7 @@ import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';+import { ProjectRepository } from '../../repositories/project';import {acceptanceComments,acceptances,@@ -108,7 +109,10 @@ describe('AcceptanceModel', () => {it('stores the project on the acceptance and becomes ungrouped when it is deleted', async () => {const projectModel = new ProjectModel(serverDB, userId);- const project = await projectModel.create({ identifier: 'ACPT', name: 'Acceptance project' });+ const project = await new ProjectRepository(serverDB, userId).create({+ identifier: 'ACPT',+ name: 'Acceptance project',+ });const model = new AcceptanceModel(serverDB, userId);const first = await model.ensureForSubject('topic', topicId);@@ -123,8 +127,10 @@ describe('AcceptanceModel', () => {});it('files an acceptance under a project and takes it back out', async () => {- const projectModel = new ProjectModel(serverDB, userId);- const project = await projectModel.create({ identifier: 'MOVE', name: 'Move target' });+ const project = await new ProjectRepository(serverDB, userId).create({+ identifier: 'MOVE',+ name: 'Move target',+ });const model = new AcceptanceModel(serverDB, userId);const acceptance = await model.ensureForSubject('topic', topicId);@@ -143,9 +149,9 @@ describe('AcceptanceModel', () => {});it('fills a project only on an ungrouped acceptance it owns', async () => {- const projectModel = new ProjectModel(serverDB, userId);- const first = await projectModel.create({ identifier: 'FILA', name: 'First' });- const second = await projectModel.create({ identifier: 'FILB', name: 'Second' });+ const projectRepo = new ProjectRepository(serverDB, userId);+ const first = await projectRepo.create({ identifier: 'FILA', name: 'First' });+ const second = await projectRepo.create({ identifier: 'FILB', name: 'Second' });const model = new AcceptanceModel(serverDB, userId);const acceptance = await model.ensureForSubject('topic', topicId);@@ -270,9 +276,9 @@ describe('AcceptanceModel', () => {});it('filters flat and paged lists by project before applying limits', async () => {- const projectModel = new ProjectModel(serverDB, userId);- const alpha = await projectModel.create({ identifier: 'ALPHA', name: 'Alpha project' });- const beta = await projectModel.create({ identifier: 'BETA', name: 'Beta project' });+ const projectRepo = new ProjectRepository(serverDB, userId);+ const alpha = await projectRepo.create({ identifier: 'ALPHA', name: 'Alpha project' });+ const beta = await projectRepo.create({ identifier: 'BETA', name: 'Beta project' });const model = new AcceptanceModel(serverDB, userId);await model.create({ projectId: alpha.id, subjectId: 'alpha-1', subjectType: 'standalone' });@@ -289,7 +295,7 @@ describe('AcceptanceModel', () => {});it('filters by project to only the unfiled acceptances when projectId is null', async () => {- const alpha = await new ProjectModel(serverDB, userId).create({+ const alpha = await new ProjectRepository(serverDB, userId).create({identifier: 'ALPHA',name: 'Alpha project',});diff --git a/packages/database/src/models/__tests__/project.coverage.test.ts b/packages/database/src/models/__tests__/project.coverage.test.tsindex 7a18a141c1c..b38273c68b5 100644--- a/packages/database/src/models/__tests__/project.coverage.test.ts+++ b/packages/database/src/models/__tests__/project.coverage.test.ts@@ -4,6 +4,7 @@ import { eq, inArray } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { getTestDB } from '../../core/getTestDB';+import { ProjectRepository } from '../../repositories/project';import { agents, projects, users } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { AgentModel } from '../agent';@@ -17,6 +18,7 @@ const otherUserId = 't863-proj-other';const serverDB: LobeChatDatabase = await getTestDB();const model = new ProjectModel(serverDB, userId);+const repo = new ProjectRepository(serverDB, userId);/** Runs `db.transaction` callbacks on a proxy that forwards to the real test database. */const runTransactionsOn = (proxy: LobeChatDatabase) =>@@ -123,7 +125,7 @@ describe('ProjectModel coverage', () => {describe('assignCoordinator', () => {it('keeps the project as is when the agent already leads it', async () => {- const project = await model.create({ name: 'Led' });+ const project = await repo.create({ name: 'Led' });const result = await model.assignCoordinator(project.id, project.coordinatorAgentId!);@@ -144,7 +146,7 @@ describe('ProjectModel coverage', () => {describe('listTasks', () => {it("lists a visible project's tasks", async () => {- const project = await model.create({ name: 'With tasks' });+ const project = await repo.create({ name: 'With tasks' });const task = await new TaskModel(serverDB, userId).create({instruction: 'Ship it',projectId: project.id,@@ -168,7 +170,7 @@ describe('ProjectModel coverage', () => {it('takes the virtual coordinator with the project that provisioned it', async () => {const legacy = await legacyCoordinator('t863-legacy-coordinator');- const project = await model.create({+ const project = await repo.create({coordinatorAgentId: legacy.id,identifier: 'LEG01',name: 'Legacy project',@@ -181,7 +183,7 @@ describe('ProjectModel coverage', () => {it('keeps a coordinator the user picked, and its sessions with it', async () => {const picked = await new AgentModel(serverDB, userId).create({ title: 'Reusable' });- const project = await model.create({+ const project = await repo.create({coordinatorAgentId: picked.id,identifier: 'LEG02',name: 'Picked project',@@ -194,7 +196,7 @@ describe('ProjectModel coverage', () => {it('does not count the project being handed over as still using the coordinator', async () => {const legacy = await legacyCoordinator('t863-handover-coordinator');- const project = await model.create({+ const project = await repo.create({coordinatorAgentId: legacy.id,identifier: 'LEG03',name: 'Handover project',diff --git a/packages/database/src/models/__tests__/project.identifier.test.ts b/packages/database/src/models/__tests__/project.identifier.test.tsnew file mode 100644index 00000000000..f9368ae2de5--- /dev/null+++ b/packages/database/src/models/__tests__/project.identifier.test.ts@@ -0,0 +1,113 @@+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { ProjectRepository } from '../../repositories/project';+import { agents, environments, projectEnvironments, users, workspaces } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { ProjectModel } from '../project';+import { ProjectIdentifierTakenError } from '../projectIdentifier';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'project-identifier-user';+const otherUserId = 'project-identifier-other-user';++describe('ProjectModel identifier allocation', () => {+ const model = new ProjectModel(serverDB, userId);+ const repo = new ProjectRepository(serverDB, userId);+ const otherRepo = new ProjectRepository(serverDB, otherUserId);++ beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+ });++ afterEach(async () => {+ vi.restoreAllMocks();+ await serverDB.delete(projectEnvironments);+ await serverDB.delete(environments);+ await serverDB.delete(users);+ });++ it('normalizes identifiers and enforces uniqueness within their ownership scope', async () => {+ const first = await repo.create({ identifier: ' lobe ', name: 'First' });+ expect(first.identifier).toBe('LOBE');++ await expect(repo.create({ identifier: 'LOBE', name: 'Duplicate' })).rejects.toThrow();+ await expect(otherRepo.create({ identifier: 'LOBE', name: 'Other user' })).resolves.toEqual(+ expect.objectContaining({ identifier: 'LOBE' }),+ );++ await serverDB.insert(workspaces).values({+ id: 'identifier-workspace',+ name: 'Identifier Workspace',+ primaryOwnerId: userId,+ slug: 'identifier-workspace',+ });+ const ownerRepo = new ProjectRepository(serverDB, userId, 'identifier-workspace');+ const memberRepo = new ProjectRepository(serverDB, otherUserId, 'identifier-workspace');+ await ownerRepo.create({ identifier: 'TEAM', name: 'Workspace project' });+ await expect(+ memberRepo.create({ identifier: 'TEAM', name: 'Workspace duplicate' }),+ ).rejects.toThrow();+ });++ it('reports a taken identifier as a field error and leaves no orphan coordinator', async () => {+ await repo.create({ identifier: 'LOBE', name: 'First' });++ expect(await model.isIdentifierTaken('lobe')).toBe(true);+ expect(await model.isIdentifierTaken('MOBILE')).toBe(false);++ const agentsBefore = await serverDB.select().from(agents).where(eq(agents.userId, userId));++ await expect(repo.create({ identifier: 'LOBE', name: 'Second' })).rejects.toThrow(+ ProjectIdentifierTakenError,+ );+ // The check runs before the coordinator is inserted, so a collision must not+ // leak an agent the failed transaction created.+ expect(await serverDB.select().from(agents).where(eq(agents.userId, userId))).toHaveLength(+ agentsBefore.length,+ );+ });++ it('treats another member private project as occupying the identifier', async () => {+ await serverDB.insert(workspaces).values({+ id: 'private-identifier-workspace',+ name: 'Private Identifier Workspace',+ primaryOwnerId: userId,+ slug: 'private-identifier-workspace',+ });+ const ownerRepo = new ProjectRepository(serverDB, userId, 'private-identifier-workspace');+ const member = new ProjectModel(serverDB, otherUserId, 'private-identifier-workspace');+ const memberRepo = new ProjectRepository(serverDB, otherUserId, 'private-identifier-workspace');+ const hidden = await ownerRepo.create({+ identifier: 'PRIV',+ name: 'Private',+ visibility: 'private',+ });++ // The member cannot see the project — which is exactly why a visibility-aware+ // check would wrongly report the identifier as free.+ expect(await member.findById(hidden.id)).toBeNull();+ // The unique index is scope-wide regardless of visibility, so it is taken.+ expect(await member.isIdentifierTaken('PRIV')).toBe(true);+ await expect(memberRepo.create({ identifier: 'PRIV', name: 'Clash' })).rejects.toThrow(+ ProjectIdentifierTakenError,+ );+ });++ it('requires identifiers to contain between 3 and 6 characters', async () => {+ await expect(repo.create({ identifier: 'AB', name: 'Too short' })).rejects.toThrow(+ 'Project identifier must be between 3 and 6 characters',+ );+ await expect(repo.create({ identifier: 'ABCDEFG', name: 'Too long' })).rejects.toThrow(+ 'Project identifier must be between 3 and 6 characters',+ );+ await expect(repo.create({ identifier: 'ABC', name: 'Minimum' })).resolves.toEqual(+ expect.objectContaining({ identifier: 'ABC' }),+ );+ await expect(repo.create({ identifier: 'ABCDEF', name: 'Maximum' })).resolves.toEqual(+ expect.objectContaining({ identifier: 'ABCDEF' }),+ );+ });+});diff --git a/packages/database/src/models/__tests__/project.mainAgent.test.ts b/packages/database/src/models/__tests__/project.mainAgent.test.tsindex 2f23c00f5f1..f10836a7005 100644--- a/packages/database/src/models/__tests__/project.mainAgent.test.ts+++ b/packages/database/src/models/__tests__/project.mainAgent.test.ts@@ -2,6 +2,7 @@ import { and, eq, inArray } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';+import { ProjectRepository } from '../../repositories/project';import {agentLabelAssignments,agentLabels,@@ -14,7 +15,6 @@ import type { LobeChatDatabase } from '../../type';import { AgentModel } from '../agent';import { AgentLabelModel } from '../agentLabel';import type { CreateProjectInput } from '../project';-import { ProjectModel } from '../project';import { createProjectMainAgent, PROJECT_AGENT_LABEL } from '../projectMainAgent';import { createProxyTestDB } from './_proxyTestDB';@@ -24,8 +24,8 @@ const memberId = 'project-main-agent-member';const workspaceId = 'project-main-agent-workspace';let projectIdentifierSequence = 0;-const createProject = (projectModel: ProjectModel, input: Omit<CreateProjectInput, 'identifier'>) =>- projectModel.create({+const createProject = (repo: ProjectRepository, input: Omit<CreateProjectInput, 'identifier'>) =>+ repo.create({...input,identifier: `M${String(++projectIdentifierSequence).padStart(5, '0')}`,});@@ -38,7 +38,7 @@ const labelsOf = async (agentId: string) =>.where(eq(agentLabelAssignments.agentId, agentId));describe('the main agent a project creates', () => {- const model = new ProjectModel(serverDB, userId);+ const repo = new ProjectRepository(serverDB, userId);beforeEach(async () => {await serverDB.delete(users);@@ -51,7 +51,7 @@ describe('the main agent a project creates', () => {});it('is an ordinary agent named after the project, wearing its avatar and the Project label', async () => {- const project = await createProject(model, { avatar: '🚀', name: 'Apollo' });+ const project = await createProject(repo, { avatar: '🚀', name: 'Apollo' });const [agent] = await serverDB.select()@@ -70,8 +70,8 @@ describe('the main agent a project creates', () => {});it('shares one Project label across the projects of a scope', async () => {- const first = await createProject(model, { name: 'First' });- const second = await createProject(model, { name: 'Second' });+ const first = await createProject(repo, { name: 'First' });+ const second = await createProject(repo, { name: 'Second' });const [firstLabel] = await labelsOf(first.coordinatorAgentId!);const [secondLabel] = await labelsOf(second.coordinatorAgentId!);@@ -86,11 +86,11 @@ describe('the main agent a project creates', () => {const archived = await labels.create({ name: PROJECT_AGENT_LABEL });await labels.update(archived.id, { archived: true });- const first = await createProject(model, { name: 'First' });+ const first = await createProject(repo, { name: 'First' });const [label] = await labelsOf(first.coordinatorAgentId!);expect(label.id).not.toBe(archived.id);- const second = await createProject(model, { name: 'Second' });+ const second = await createProject(repo, { name: 'Second' });expect(await labelsOf(second.coordinatorAgentId!)).toEqual([expect.objectContaining({ id: label.id }),]);@@ -99,7 +99,7 @@ describe('the main agent a project creates', () => {it('labels nothing when the project is led by a picked agent', async () => {const picked = await new AgentModel(serverDB, userId).create({ title: 'Planner' });- await createProject(model, { coordinatorAgentId: picked.id, name: 'Picked' });+ await createProject(repo, { coordinatorAgentId: picked.id, name: 'Picked' });expect(await labelsOf(picked.id)).toEqual([]);expect(@@ -114,11 +114,11 @@ describe('the main agent a project creates', () => {primaryOwnerId: userId,slug: workspaceId,});- const owner = new ProjectModel(serverDB, userId, workspaceId);- const member = new ProjectModel(serverDB, memberId, workspaceId);+ const ownerRepo = new ProjectRepository(serverDB, userId, workspaceId);+ const memberRepo = new ProjectRepository(serverDB, memberId, workspaceId);- const shared = await createProject(owner, { name: 'Shared', visibility: 'public' });- const own = await createProject(member, { name: 'Own', visibility: 'private' });+ const shared = await createProject(ownerRepo, { name: 'Shared', visibility: 'public' });+ const own = await createProject(memberRepo, { name: 'Own', visibility: 'private' });const [sharedLabel] = await labelsOf(shared.coordinatorAgentId!);const [ownLabel] = await labelsOf(own.coordinatorAgentId!);diff --git a/packages/database/src/models/__tests__/project.repository.test.ts b/packages/database/src/models/__tests__/project.repository.test.tsindex 80e97c8f39d..b7dfd241f4b 100644--- a/packages/database/src/models/__tests__/project.repository.test.ts+++ b/packages/database/src/models/__tests__/project.repository.test.ts@@ -1,6 +1,7 @@import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';+import { ProjectRepository } from '../../repositories/project';import { environments, projectEnvironments, users } from '../../schemas';import type { LobeChatDatabase } from '../../type';import type { CreateProjectInput } from '../project';@@ -10,13 +11,17 @@ const serverDB: LobeChatDatabase = await getTestDB();const userId = 'project-repository-user';let projectIdentifierSequence = 0;-const createProject = (projectModel: ProjectModel, input: Omit<CreateProjectInput, 'identifier'>) =>- projectModel.create({+// Creating a project spans the project and the environment aggregates, so the+// environment rides on `ProjectRepository.create`'s transaction rather than on+// the single-table model insert.+const createProject = (repo: ProjectRepository, input: Omit<CreateProjectInput, 'identifier'>) =>+ repo.create({...input,identifier: `R${String(++projectIdentifierSequence).padStart(5, '0')}`,});describe('a project created from a GitHub repository', () => {+ const repo = new ProjectRepository(serverDB, userId);const model = new ProjectModel(serverDB, userId);beforeEach(async () => {@@ -31,7 +36,7 @@ describe('a project created from a GitHub repository', () => {});it('creates a project from a GitHub repository with its environment attached', async () => {- const project = await createProject(model, {+ const project = await createProject(repo, {name: 'lobehub',repository: {defaultBranch: 'canary',@@ -51,7 +56,7 @@ describe('a project created from a GitHub repository', () => {]);// A second project on the same repository shares the definition.- const second = await createProject(model, {+ const second = await createProject(repo, {name: 'lobehub again',repository: { name: 'lobehub/lobehub', url: '[email protected]:lobehub/lobehub.git' },});@@ -62,8 +67,8 @@ describe('a project created from a GitHub repository', () => {});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(+ await createProject(repo, { name: 'Taken', slug: 'taken' });+ const error = await createProject(repo, { name: 'Taken again', slug: 'taken' }).catch((e: unknown) => e,);let cause: any = error;@@ -73,7 +78,7 @@ describe('a project created from a GitHub repository', () => {it('creates nothing when the repository URL is not a GitHub repository', async () => {await expect(- createProject(model, {+ createProject(repo, {name: 'Broken',repository: { name: 'broken', url: 'https://example.com/a/b' },}),diff --git a/packages/database/src/models/__tests__/project.test.ts b/packages/database/src/models/__tests__/project.test.tsindex 55aa506e8a3..d1ad7c9b281 100644--- a/packages/database/src/models/__tests__/project.test.ts+++ b/packages/database/src/models/__tests__/project.test.ts@@ -5,6 +5,7 @@ import { and, eq, inArray } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { getTestDB } from '../../core/getTestDB';+import { ProjectRepository } from '../../repositories/project';import {agentOperations,agents,@@ -34,15 +35,17 @@ const userId = 'project-model-user';const otherUserId = 'project-model-other-user';let projectIdentifierSequence = 0;-const createProject = (projectModel: ProjectModel, input: Omit<CreateProjectInput, 'identifier'>) =>- projectModel.create({+const createProject = (repo: ProjectModel, input: Omit<CreateProjectInput, 'identifier'>) =>+ repo.create({...input,identifier: `P${String(++projectIdentifierSequence).padStart(5, '0')}`,});describe('ProjectModel', () => {const model = new ProjectModel(serverDB, userId);+ const repo = new ProjectRepository(serverDB, userId);const otherModel = new ProjectModel(serverDB, otherUserId);+ const otherRepo = new ProjectRepository(serverDB, otherUserId);beforeEach(async () => {await serverDB.delete(users);@@ -68,17 +71,17 @@ describe('ProjectModel', () => {.map((p) => p.name);it('leaves the list API in recently-updated order', async () => {- const a = await createProject(model, { name: 'A' });- const b = await createProject(model, { name: 'B' });+ const a = await createProject(repo, { name: 'A' });+ const b = await createProject(repo, { name: 'B' });await model.move(a.id, { beforeId: b.id });expect((await model.list()).map((p) => p.name)).toEqual(['B', 'A']);});it('places a project before or after another and keeps the order', async () => {- const a = await createProject(model, { name: 'A' });- const b = await createProject(model, { name: 'B' });- const c = await createProject(model, { name: 'C' });+ const a = await createProject(repo, { name: 'A' });+ const b = await createProject(repo, { name: 'B' });+ const c = await createProject(repo, { name: 'C' });expect(await ids(model)).toEqual(['C', 'B', 'A']);await model.move(a.id, { beforeId: c.id });@@ -90,17 +93,17 @@ describe('ProjectModel', () => {});it('lists projects never placed above placed ones', async () => {- const a = await createProject(model, { name: 'A' });- const b = await createProject(model, { name: 'B' });+ const a = await createProject(repo, { name: 'A' });+ const b = await createProject(repo, { name: 'B' });await model.move(a.id, { beforeId: b.id });- await createProject(model, { name: 'New' });+ await createProject(repo, { name: 'New' });expect(await ids(model)).toEqual(['New', 'A', 'B']);});it('keeps updatedAt so the recently-updated order does not move', async () => {- const a = await createProject(model, { name: 'A' });- const b = await createProject(model, { name: 'B' });+ const a = await createProject(repo, { name: 'A' });+ const b = await createProject(repo, { name: 'B' });const before = await model.findByIds([a.id, b.id]);await model.move(a.id, { beforeId: b.id });@@ -112,8 +115,8 @@ describe('ProjectModel', () => {});it('rejects projects outside the caller scope', async () => {- const mine = await createProject(model, { name: 'Mine' });- const theirs = await createProject(otherModel, { name: 'Theirs' });+ const mine = await createProject(repo, { name: 'Mine' });+ const theirs = await createProject(otherRepo, { name: 'Theirs' });await expect(model.move(theirs.id, { beforeId: mine.id })).rejects.toThrow('Project not found',@@ -130,10 +133,12 @@ describe('ProjectModel', () => {});const alice = new ProjectModel(serverDB, userId, 'project-order-workspace');const bob = new ProjectModel(serverDB, otherUserId, 'project-order-workspace');- const publicA = await createProject(alice, { name: 'PublicA' });- const publicB = await createProject(alice, { name: 'PublicB' });- const privateA = await createProject(alice, { name: 'PrivateA', visibility: 'private' });- const privateB = await createProject(bob, { name: 'PrivateB', visibility: 'private' });+ const aliceRepo = new ProjectRepository(serverDB, userId, 'project-order-workspace');+ const bobRepo = new ProjectRepository(serverDB, otherUserId, 'project-order-workspace');+ const publicA = await createProject(aliceRepo, { name: 'PublicA' });+ const publicB = await createProject(aliceRepo, { name: 'PublicB' });+ const privateA = await createProject(aliceRepo, { name: 'PrivateA', visibility: 'private' });+ const privateB = await createProject(bobRepo, { name: 'PrivateB', visibility: 'private' });await alice.move(privateA.id, { beforeId: publicA.id });await alice.move(publicB.id, { afterId: publicA.id });@@ -148,8 +153,8 @@ describe('ProjectModel', () => {it('lets several projects share one main agent', async () => {const shared = await new AgentModel(serverDB, userId).create({ title: 'Planner' });- const first = await createProject(model, { name: 'First' });- const second = await createProject(model, { name: 'Second' });+ const first = await createProject(repo, { name: 'First' });+ const second = await createProject(repo, { name: 'Second' });await serverDB.update(projects)@@ -162,8 +167,8 @@ describe('ProjectModel', () => {it('keeps a shared main agent when one of its projects is deleted', async () => {const shared = await new AgentModel(serverDB, userId).create({ title: 'Planner' });- const first = await createProject(model, { name: 'First' });- const second = await createProject(model, { name: 'Second' });+ const first = await createProject(repo, { name: 'First' });+ const second = await createProject(repo, { name: 'Second' });await serverDB.update(projects).set({ coordinatorAgentId: shared.id })@@ -177,7 +182,7 @@ describe('ProjectModel', () => {it('keeps LobeAI when a project led by it is deleted', async () => {const inbox = (await new AgentModel(serverDB, userId).getBuiltinAgent(INBOX_SESSION_ID))!;- const project = await createProject(model, { name: 'Inbox-led' });+ const project = await createProject(repo, { name: 'Inbox-led' });await serverDB.update(projects).set({ coordinatorAgentId: inbox.id })@@ -190,7 +195,7 @@ describe('ProjectModel', () => {it('clears the main agent when it is deleted and resolves to LobeAI', async () => {const agentModel = new AgentModel(serverDB, userId);const agent = await agentModel.create({ title: 'Short-lived' });- const project = await createProject(model, { name: 'Orphan' });+ const project = await createProject(repo, { name: 'Orphan' });await serverDB.update(projects).set({ coordinatorAgentId: agent.id })@@ -213,14 +218,14 @@ describe('ProjectModel', () => {title: 'Disposition Coordinator',virtual: true,});- const project = await createProject(model, {+ const project = await createProject(repo, {coordinatorAgentId: legacy.id,name: 'Disposition',});const inbox = (await new AgentModel(serverDB, userId).getBuiltinAgent(INBOX_SESSION_ID))!;const user = await new AgentModel(serverDB, userId).create({ title: 'Planner' });// The agent a project creates now is the user's to keep.- const created = await createProject(model, { name: 'Created' });+ const created = await createProject(repo, { name: 'Created' });expect(await model.isDedicatedCoordinator(created.coordinatorAgentId, {exceptProjectId: created.id,@@ -235,7 +240,7 @@ describe('ProjectModel', () => {).toBe(true);expect(await model.isDedicatedCoordinator(project.coordinatorAgentId)).toBe(false);// A member of another project is still in use there.- const other = await createProject(model, { name: 'Borrower' });+ const other = await createProject(repo, { name: 'Borrower' });await model.addAgent(other.id, { agentId: project.coordinatorAgentId });expect(await model.isDedicatedCoordinator(project.coordinatorAgentId, {@@ -255,7 +260,7 @@ describe('ProjectModel', () => {const agentCount = (await serverDB.select().from(agents).where(eq(agents.userId, userId))).length;- const project = await createProject(model, { coordinatorAgentId: picked.id, name: 'Picked' });+ const project = await createProject(repo, { coordinatorAgentId: picked.id, name: 'Picked' });expect(project.coordinatorAgentId).toBe(picked.id);expect(await serverDB.select().from(agents).where(eq(agents.userId, userId))).toHaveLength(@@ -273,8 +278,8 @@ describe('ProjectModel', () => {});it('lets the identifier be omitted, keeping the default task prefix', async () => {- const named = await model.create({ identifier: 'ace', name: 'Named' });- const unnamed = await model.create({ name: 'Unnamed' });+ const named = await repo.create({ identifier: 'ace', name: 'Named' });+ const unnamed = await repo.create({ name: 'Unnamed' });const taskModel = new TaskModel(serverDB, userId);const namedTask = await taskModel.create({ instruction: 'a', projectId: named.id });@@ -290,13 +295,13 @@ describe('ProjectModel', () => {const foreign = await new AgentModel(serverDB, otherUserId).create({ title: 'Foreign' });await expect(- createProject(model, { coordinatorAgentId: foreign.id, name: 'Foreign-led' }),+ createProject(repo, { coordinatorAgentId: foreign.id, name: 'Foreign-led' }),).rejects.toThrow('Agent not found');expect(await serverDB.select().from(projects).where(eq(projects.userId, userId))).toEqual([]);});it('creates, lists, updates, and deletes a project in the owner scope', async () => {- const project = await createProject(model, { description: 'A large effort', name: 'Apollo' });+ const project = await createProject(repo, { description: 'A large effort', name: 'Apollo' });expect(project.status).toBe('backlog');expect(project.coordinatorAgentId).toBeTruthy();expect(@@ -324,8 +329,8 @@ describe('ProjectModel', () => {});it('resolves a project by slug without escaping the current scope', async () => {- const project = await createProject(model, { name: 'Apollo', slug: 'apollo' });- await createProject(otherModel, { name: 'Other Apollo', slug: 'other-apollo' });+ const project = await createProject(repo, { name: 'Apollo', slug: 'apollo' });+ await createProject(otherRepo, { name: 'Other Apollo', slug: 'other-apollo' });expect(await model.findByReference('apollo')).toEqual(expect.objectContaining({ id: project.id }),@@ -337,8 +342,8 @@ describe('ProjectModel', () => {});it('resolves a project by its identifier, case-insensitively, within the current scope', async () => {- const project = await model.create({ identifier: 'APLO', name: 'Apollo' });- await otherModel.create({ identifier: 'OTHR', name: 'Other' });+ const project = await repo.create({ identifier: 'APLO', name: 'Apollo' });+ await otherRepo.create({ identifier: 'OTHR', name: 'Other' });expect(await model.findByReference('APLO')).toEqual(expect.objectContaining({ id: project.id }),@@ -350,16 +355,16 @@ describe('ProjectModel', () => {});it('prefers an exact id or slug over another project whose identifier matches', async () => {- const bySlug = await createProject(model, { name: 'By slug', slug: 'crux' });- await model.create({ identifier: 'CRUX', name: 'By identifier' });+ const bySlug = await createProject(repo, { name: 'By slug', slug: 'crux' });+ await repo.create({ identifier: 'CRUX', name: 'By identifier' });expect(await model.findByReference('crux')).toEqual(expect.objectContaining({ id: bySlug.id }));});it('finds a bounded set of readable projects', async () => {- const first = await createProject(model, { name: 'First' });- const second = await createProject(model, { name: 'Second' });- const hidden = await createProject(otherModel, { name: 'Hidden', visibility: 'private' });+ const first = await createProject(repo, { name: 'First' });+ const second = await createProject(repo, { name: 'Second' });+ const hidden = await createProject(otherRepo, { name: 'Hidden', visibility: 'private' });expect(await model.findByIds([])).toEqual([]);expect(await model.findByIds([first.id, second.id, hidden.id])).toEqual(@@ -371,47 +376,9 @@ describe('ProjectModel', () => {expect(await model.findByIds([first.id, second.id, hidden.id])).toHaveLength(2);});- it('normalizes identifiers and enforces uniqueness within their ownership scope', async () => {- const first = await model.create({ identifier: ' lobe ', name: 'First' });- expect(first.identifier).toBe('LOBE');-- await expect(model.create({ identifier: 'LOBE', name: 'Duplicate' })).rejects.toThrow();- await expect(otherModel.create({ identifier: 'LOBE', name: 'Other user' })).resolves.toEqual(- expect.objectContaining({ identifier: 'LOBE' }),- );-- await serverDB.insert(workspaces).values({- id: 'identifier-workspace',- name: 'Identifier Workspace',- primaryOwnerId: userId,- slug: 'identifier-workspace',- });- const owner = new ProjectModel(serverDB, userId, 'identifier-workspace');- const member = new ProjectModel(serverDB, otherUserId, 'identifier-workspace');- await owner.create({ identifier: 'TEAM', name: 'Workspace project' });- await expect(- member.create({ identifier: 'TEAM', name: 'Workspace duplicate' }),- ).rejects.toThrow();- });-- it('requires identifiers to contain between 3 and 6 characters', async () => {- await expect(model.create({ identifier: 'AB', name: 'Too short' })).rejects.toThrow(- 'Project identifier must be between 3 and 6 characters',- );- await expect(model.create({ identifier: 'ABCDEFG', name: 'Too long' })).rejects.toThrow(- 'Project identifier must be between 3 and 6 characters',- );- await expect(model.create({ identifier: 'ABC', name: 'Minimum' })).resolves.toEqual(- expect.objectContaining({ identifier: 'ABC' }),- );- await expect(model.create({ identifier: 'ABCDEF', name: 'Maximum' })).resolves.toEqual(- expect.objectContaining({ identifier: 'ABCDEF' }),- );- });-it('filters and paginates projects', async () => {- await createProject(model, { name: 'Backlog' });- const active = await createProject(model, { name: 'Active' });+ await createProject(repo, { name: 'Backlog' });+ const active = await createProject(repo, { name: 'Active' });await model.updateStatus(active.id, 'active');expect(await model.list({ limit: 1, offset: 0, statuses: ['active'] })).toEqual([@@ -422,9 +389,9 @@ describe('ProjectModel', () => {});it('lists projects with their main agent display meta', async () => {- const project = await createProject(model, { name: 'Apollo' });- const styled = await createProject(model, { name: 'Gemini' });- const cleared = await createProject(model, { name: 'Cleared' });+ const project = await createProject(repo, { name: 'Apollo' });+ const styled = await createProject(repo, { name: 'Gemini' });+ const cleared = await createProject(repo, { name: 'Cleared' });await serverDB.update(agents).set({ avatar: '🚀', backgroundColor: '#000', name: 'Ada' })@@ -463,7 +430,7 @@ describe('ProjectModel', () => {});it('does not expose or mutate another user project in personal mode', async () => {- const project = await createProject(otherModel, { name: 'Private effort' });+ const project = await createProject(otherRepo, { name: 'Private effort' });expect(await model.findById(project.id)).toBeNull();expect(await model.update(project.id, { name: 'Hacked' })).toBeNull();expect(await model.delete(project.id)).toBeNull();@@ -477,10 +444,13 @@ describe('ProjectModel', () => {primaryOwnerId: userId,slug: 'project-workspace',});- const owner = new ProjectModel(serverDB, userId, 'project-workspace');+ const ownerRepo = new ProjectRepository(serverDB, userId, 'project-workspace');const member = new ProjectModel(serverDB, otherUserId, 'project-workspace');- const publicProject = await createProject(owner, { name: 'Public' });- const privateProject = await createProject(owner, { name: 'Private', visibility: 'private' });+ const publicProject = await createProject(ownerRepo, { name: 'Public' });+ const privateProject = await createProject(ownerRepo, {+ name: 'Private',+ visibility: 'private',+ });expect(await member.findById(publicProject.id)).toEqual(expect.objectContaining({ id: publicProject.id }),@@ -498,8 +468,9 @@ describe('ProjectModel', () => {slug: 'project-manage-workspace',});const owner = new ProjectModel(serverDB, userId, 'project-manage-workspace');+ const ownerRepo = new ProjectRepository(serverDB, userId, 'project-manage-workspace');const member = new ProjectModel(serverDB, otherUserId, 'project-manage-workspace');- const project = await createProject(owner, { name: 'Shared' });+ const project = await createProject(ownerRepo, { name: 'Shared' });expect(await member.findManageableById(project.id)).toEqual(expect.objectContaining({ id: project.id }),@@ -525,7 +496,7 @@ describe('ProjectModel', () => {});it('lists the main agent first whatever order the other members carry', async () => {- const project = await createProject(model, { name: 'Ordering' });+ const project = await createProject(repo, { name: 'Ordering' });const [agent] = await serverDB.insert(agents).values({ title: 'Early bird', userId })@@ -539,7 +510,7 @@ describe('ProjectModel', () => {});it('still lists members of a project whose main agent was cleared', async () => {- const project = await createProject(model, { name: 'Orphaned' });+ const project = await createProject(repo, { name: 'Orphaned' });const [agent] = await serverDB.insert(agents).values({ title: 'Stays', userId }).returning();await model.addAgent(project.id, { agentId: agent.id });// Deleting the main agent clears the column (ON DELETE SET NULL).@@ -554,7 +525,7 @@ describe('ProjectModel', () => {});it('binds only accessible agents and knowledge bases', async () => {- const project = await createProject(model, { name: 'Bindings' });+ const project = await createProject(repo, { name: 'Bindings' });const [agent] = await serverDB.insert(agents).values({ title: 'Researcher', userId })@@ -611,14 +582,14 @@ describe('ProjectModel', () => {primaryOwnerId: userId,slug: workspaceId,});- const creator = new ProjectModel(serverDB, userId, workspaceId);+ const creatorRepo = new ProjectRepository(serverDB, userId, workspaceId);const [privateAgent] = await serverDB.insert(agents).values({ title: 'Private lead', userId, visibility: 'private', workspaceId }).returning();await expect(- createProject(creator, {+ createProject(creatorRepo, {coordinatorAgentId: privateAgent.id,name: 'Shared-led',visibility: 'public',@@ -639,8 +610,12 @@ describe('ProjectModel', () => {slug: workspaceId,});const creator = new ProjectModel(serverDB, userId, workspaceId);- const sharedProject = await createProject(creator, { name: 'Shared' });- const privateProject = await createProject(creator, { name: 'Mine', visibility: 'private' });+ const creatorRepo = new ProjectRepository(serverDB, userId, workspaceId);+ const sharedProject = await createProject(creatorRepo, { name: 'Shared' });+ const privateProject = await createProject(creatorRepo, {+ name: 'Mine',+ visibility: 'private',+ });const [privateAgent] = await serverDB.insert(agents).values({ title: 'Private agent', userId, visibility: 'private', workspaceId })@@ -668,7 +643,7 @@ describe('ProjectModel', () => {});it('updates member and knowledge bindings without touching the coordinator', async () => {- const project = await createProject(model, { name: 'Patch bindings' });+ const project = await createProject(repo, { name: 'Patch bindings' });const [agent] = await serverDB.insert(agents).values({ title: 'Writer', userId }).returning();const [knowledgeBase] = await serverDB.insert(knowledgeBases)@@ -705,11 +680,12 @@ describe('ProjectModel', () => {});const workspaceId = 'project-member-workspace';const creator = new ProjectModel(serverDB, userId, workspaceId);+ const creatorRepo = new ProjectRepository(serverDB, userId, workspaceId);const member = new ProjectModel(serverDB, otherUserId, workspaceId);const admin = new ProjectModel(serverDB, otherUserId, workspaceId, {canManageAllMembers: true,});- const project = await createProject(creator, { name: 'Shared' });+ const project = await createProject(creatorRepo, { name: 'Shared' });const [agent] = await serverDB.insert(agents).values({ title: 'Shared agent', userId, visibility: 'public', workspaceId })@@ -763,7 +739,7 @@ describe('ProjectModel', () => {slug: 'project-viewer-workspace',});const workspaceId = 'project-viewer-workspace';- const project = await createProject(new ProjectModel(serverDB, userId, workspaceId), {+ const project = await createProject(new ProjectRepository(serverDB, userId, workspaceId), {name: 'Viewed',});const downgradedCreator = new ProjectModel(serverDB, userId, workspaceId, { readOnly: true });@@ -786,9 +762,12 @@ describe('ProjectModel', () => {primaryOwnerId: userId,slug: workspaceId,});- const creator = new ProjectModel(serverDB, userId, workspaceId);- const project = await createProject(creator, { name: 'Shared work' });- const privateProject = await createProject(creator, { name: 'Solo', visibility: 'private' });+ const creatorRepo = new ProjectRepository(serverDB, userId, workspaceId);+ const project = await createProject(creatorRepo, { name: 'Shared work' });+ const privateProject = await createProject(creatorRepo, {+ name: 'Solo',+ visibility: 'private',+ });const memberTasks = new TaskModel(serverDB, otherUserId, workspaceId);expect(await memberTasks.create({ instruction: 'Pitch in', projectId: project.id })).toEqual(@@ -800,7 +779,7 @@ describe('ProjectModel', () => {});it('returns null or false for binding operations on inaccessible projects and resources', async () => {- const foreignProject = await createProject(otherModel, { name: 'Foreign' });+ const foreignProject = await createProject(otherRepo, { name: 'Foreign' });const [foreignKnowledgeBase] = await serverDB.insert(knowledgeBases).values({ name: 'Foreign KB', userId: otherUserId })@@ -832,7 +811,7 @@ describe('ProjectModel', () => {expect(await model.addWork(foreignProject.id, { workId: 'missing' })).toBeNull();expect(await model.removeWork(foreignProject.id, 'missing')).toBe(false);- const project = await createProject(model, { name: 'Local' });+ const project = await createProject(repo, { name: 'Local' });await expect(model.addKnowledgeBase(project.id, { knowledgeBaseId: foreignKnowledgeBase.id }),).rejects.toThrow('Knowledge base not found');@@ -842,8 +821,8 @@ describe('ProjectModel', () => {});it('associates one durable Work with multiple projects without changing Work ownership', async () => {- const firstProject = await createProject(model, { name: 'First Work Project' });- const secondProject = await createProject(model, { name: 'Second Work Project' });+ const firstProject = await createProject(repo, { name: 'First Work Project' });+ const secondProject = await createProject(repo, { name: 'Second Work Project' });const [work] = await serverDB.insert(works).values({@@ -878,8 +857,8 @@ describe('ProjectModel', () => {});it('enforces project boundaries in the shared dependency model path', async () => {- const firstProject = await createProject(model, { name: 'First' });- const secondProject = await createProject(model, { name: 'Second' });+ const firstProject = await createProject(repo, { name: 'First' });+ const secondProject = await createProject(repo, { name: 'Second' });const taskModel = new TaskModel(serverDB, userId);const first = await taskModel.create({ instruction: 'First', projectId: firstProject.id });const second = await taskModel.create({ instruction: 'Second', projectId: secondProject.id });@@ -891,7 +870,7 @@ describe('ProjectModel', () => {});it('requires review state and records immutable human completion decisions', async () => {- const project = await createProject(model, { name: 'Reviewed' });+ const project = await createProject(repo, { name: 'Reviewed' });await model.updateStatus(project.id, 'active');await model.requestCompletion(project.id);@@ -926,7 +905,7 @@ describe('ProjectModel', () => {});it('requires reopen for completed projects even after archival', async () => {- const project = await createProject(model, { name: 'Archived completion' });+ const project = await createProject(repo, { name: 'Archived completion' });await model.updateStatus(project.id, 'active');await model.requestCompletion(project.id);await model.reviewCompletion(project.id, 'accepted');@@ -941,7 +920,7 @@ describe('ProjectModel', () => {});it('covers lifecycle guards and missing review targets', async () => {- const project = await createProject(model, { name: 'Lifecycle' });+ const project = await createProject(repo, { name: 'Lifecycle' });expect(await model.updateStatus('missing', 'active')).toBeNull();await expect(model.updateStatus(project.id, 'completed')).rejects.toThrow('Completion states must be changed through the review workflow',@@ -969,7 +948,7 @@ describe('ProjectModel', () => {});it('handles completed transitions and a concurrent deletion during status update', async () => {- const completed = await createProject(model, { name: 'Completed' });+ const completed = await createProject(repo, { name: 'Completed' });await model.updateStatus(completed.id, 'active');await model.requestCompletion(completed.id);await model.reviewCompletion(completed.id, 'accepted');@@ -977,7 +956,7 @@ describe('ProjectModel', () => {'A completed project must be reopened',);- const disappearing = await createProject(model, { name: 'Disappearing' });+ const disappearing = await createProject(repo, { name: 'Disappearing' });const snapshot = await model.findManageableById(disappearing.id);await serverDB.delete(projects).where(eq(projects.id, disappearing.id));vi.spyOn(model, 'findManageableById').mockResolvedValueOnce(snapshot);@@ -985,7 +964,7 @@ describe('ProjectModel', () => {});it('rejects completion requests from invalid states', async () => {- const project = await createProject(model, { name: 'Backlog' });+ const project = await createProject(repo, { name: 'Backlog' });await expect(model.requestCompletion(project.id)).rejects.toThrow('Only active or paused projects can request completion',);@@ -999,7 +978,7 @@ describe('ProjectModel', () => {});it('attaches environments and lists them per project in the owner scope', async () => {- const project = await createProject(model, { name: 'Env host' });+ const project = await createProject(repo, { name: 'Env host' });const environmentModel = new EnvironmentModel(serverDB, userId);const env = await environmentModel.save({name: 'Shared GitHub',@@ -1019,7 +998,7 @@ describe('ProjectModel', () => {});it('lists project conversations with or without directories, retaining each agent', async () => {- const project = await createProject(model, { name: 'Topics host' });+ const project = await createProject(repo, { name: 'Topics host' });const topicModel = new TopicModel(serverDB, userId);const plain = await topicModel.create({agentId: project.coordinatorAgentId,@@ -1050,7 +1029,7 @@ describe('ProjectModel', () => {});it("carries each agent's execution-target pin on its project topics", async () => {- const project = await createProject(model, { name: 'Pinned host' });+ const project = await createProject(repo, { name: 'Pinned host' });const [pinned] = await serverDB.insert(agents).values({@@ -1079,7 +1058,7 @@ describe('ProjectModel', () => {});it("carries each agent's heterogeneous provider type on its project topics", async () => {- const project = await createProject(model, { name: 'External runtime' });+ const project = await createProject(repo, { name: 'External runtime' });const [external] = await serverDB.insert(agents).values({@@ -1106,7 +1085,7 @@ describe('ProjectModel', () => {});it('keeps agentless conversations visible in project listings', async () => {- const project = await createProject(model, { name: 'Agentless host' });+ const project = await createProject(repo, { name: 'Agentless host' });const topic = await new TopicModel(serverDB, userId).create({projectId: project.id,title: 'Agentless',@@ -1120,7 +1099,7 @@ describe('ProjectModel', () => {// the client holds no local operation for (every non-active running topic// after a refresh) otherwise show a spinner with no timer.it('resolves runStartedAt for running project topics', async () => {- const project = await createProject(model, { name: 'Running work' });+ const project = await createProject(repo, { name: 'Running work' });await serverDB.insert(topics).values([{ id: 't-op', projectId: project.id, status: 'running', title: 'server run', userId },{diff --git a/packages/database/src/models/__tests__/project.topicAgents.test.ts b/packages/database/src/models/__tests__/project.topicAgents.test.tsindex 38ac39c8eff..0d27e8bf1ec 100644--- a/packages/database/src/models/__tests__/project.topicAgents.test.ts+++ b/packages/database/src/models/__tests__/project.topicAgents.test.ts@@ -3,6 +3,7 @@ import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';+import { ProjectRepository } from '../../repositories/project';import { agents, projectAgents, projects, topics, users, workspaces } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { AgentModel } from '../agent';@@ -14,8 +15,8 @@ const serverDB: LobeChatDatabase = await getTestDB();const userId = 'project-topic-agents-user';let projectIdentifierSequence = 0;-const createProject = (projectModel: ProjectModel, input: Omit<CreateProjectInput, 'identifier'>) =>- projectModel.create({+const createProject = (repo: ProjectRepository, input: Omit<CreateProjectInput, 'identifier'>) =>+ repo.create({...input,identifier: `T${String(++projectIdentifierSequence).padStart(5, '0')}`,});@@ -25,6 +26,7 @@ const memberIds = async (model: ProjectModel, projectId: string) =>describe('project members from project topics', () => {const model = new ProjectModel(serverDB, userId);+ const repo = new ProjectRepository(serverDB, userId);const topicModel = new TopicModel(serverDB, userId);beforeEach(async () => {@@ -37,7 +39,7 @@ describe('project members from project topics', () => {});it('adds the agent of a topic created in the project', async () => {- const project = await createProject(model, { name: 'Build' });+ const project = await createProject(repo, { name: 'Build' });const agent = await new AgentModel(serverDB, userId).create({ title: 'Codex' });await topicModel.create({ agentId: agent.id, projectId: project.id, title: 'Plan' });@@ -46,7 +48,7 @@ describe('project members from project topics', () => {});it('adds the agent when an existing topic moves into the project', async () => {- const project = await createProject(model, { name: 'Build' });+ const project = await createProject(repo, { name: 'Build' });const agent = await new AgentModel(serverDB, userId).create({ title: 'Claude Code' });const topic = await topicModel.create({ agentId: agent.id, title: 'Loose' });expect(await memberIds(model, project.id)).not.toContain(agent.id);@@ -57,7 +59,7 @@ describe('project members from project topics', () => {});it('keeps an existing member binding untouched', async () => {- const project = await createProject(model, { name: 'Build' });+ const project = await createProject(repo, { name: 'Build' });const agent = await new AgentModel(serverDB, userId).create({ title: 'Reviewer' });await model.addAgent(project.id, { agentId: agent.id, enabled: false, role: 'reviewer' });@@ -71,7 +73,7 @@ describe('project members from project topics', () => {});it('never adds the project coordinator as a regular member', async () => {- const project = await createProject(model, { name: 'Build' });+ const project = await createProject(repo, { name: 'Build' });const before = await serverDB.select().from(projectAgents)@@ -90,7 +92,7 @@ describe('project members from project topics', () => {/** @example Review: a project whose main agent was cleared is led by LobeAI. */it('never adds LobeAI as a member when it leads a project with a cleared main agent', async () => {- const project = await createProject(model, { name: 'Cleared' });+ const project = await createProject(repo, { name: 'Cleared' });await serverDB.update(projects).set({ coordinatorAgentId: null })@@ -115,7 +117,8 @@ describe('project members from project topics', () => {slug: workspaceId,});const creator = new ProjectModel(serverDB, userId, workspaceId);- const sharedProject = await createProject(creator, { name: 'Shared' });+ const creatorRepo = new ProjectRepository(serverDB, userId, workspaceId);+ const sharedProject = await createProject(creatorRepo, { name: 'Shared' });const [privateAgent] = await serverDB.insert(agents).values({ title: 'Private agent', userId, visibility: 'private', workspaceId })@@ -132,7 +135,7 @@ describe('project members from project topics', () => {// TODO(2026-12-31): remove with `ProjectModel.joinTopicAgents`.it('backfills agents of topics filed before members were added on write', async () => {- const project = await createProject(model, { name: 'Legacy' });+ const project = await createProject(repo, { name: 'Legacy' });const agent = await new AgentModel(serverDB, userId).create({ title: 'Architect' });await serverDB.insert(topics)@@ -146,7 +149,7 @@ describe('project members from project topics', () => {// TODO(2026-12-31): remove with `ProjectModel.joinTopicAgents`.it('leaves members alone when a read-only viewer opens the project', async () => {- const project = await createProject(model, { name: 'Legacy' });+ const project = await createProject(repo, { name: 'Legacy' });const agent = await new AgentModel(serverDB, userId).create({ title: 'Architect' });await serverDB.insert(topics)diff --git a/packages/database/src/models/__tests__/projectReview.test.ts b/packages/database/src/models/__tests__/projectReview.test.tsindex 422ff82028c..5b667ff88c2 100644--- a/packages/database/src/models/__tests__/projectReview.test.ts+++ b/packages/database/src/models/__tests__/projectReview.test.ts@@ -2,9 +2,9 @@ import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';+import { ProjectRepository } from '../../repositories/project';import { projectMembers, projectSites, users, workspaceMembers, workspaces } from '../../schemas';import type { LobeChatDatabase } from '../../type';-import { ProjectModel } from '../project';import { ProjectMemberModel, ProjectSiteModel } from '../projectReview';import { WorkspaceMemberModel } from '../workspaceMember';@@ -13,7 +13,7 @@ const ownerId = 'project-review-owner';const guestId = 'project-review-guest';const createProject = () =>- new ProjectModel(serverDB, ownerId).create({ identifier: 'SITE', name: 'Fieldnotes' });+ new ProjectRepository(serverDB, ownerId).create({ identifier: 'SITE', name: 'Fieldnotes' });beforeEach(async () => {await serverDB.delete(users);@@ -119,7 +119,7 @@ describe('ProjectMemberModel', () => {{ workspaceId, userId: guestId },]);projectId = (- await new ProjectModel(serverDB, ownerId, workspaceId).create({+ await new ProjectRepository(serverDB, ownerId, workspaceId).create({identifier: 'SITE',name: 'Fieldnotes',})diff --git a/packages/database/src/models/__tests__/task.test.ts b/packages/database/src/models/__tests__/task.test.tsindex 7ba3ee63d1f..23bbda3621f 100644--- a/packages/database/src/models/__tests__/task.test.ts+++ b/packages/database/src/models/__tests__/task.test.ts@@ -8,6 +8,7 @@ import { eq, sql } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';+import { ProjectRepository } from '../../repositories/project';import {agents,briefs,@@ -21,7 +22,6 @@ import {import { taskTopics } from '../../schemas/task';import { works } from '../../schemas/work';import type { LobeChatDatabase } from '../../type';-import { ProjectModel } from '../project';import { taskActivityActor, TaskModel } from '../task';import { WorkModel } from '../work';@@ -559,7 +559,7 @@ describe('TaskModel', () => {it('should filter by projectId', async () => {const model = new TaskModel(serverDB, userId);- const project = await new ProjectModel(serverDB, userId).create({+ const project = await new ProjectRepository(serverDB, userId).create({identifier: 'TLIST',name: 'Scoped project',});@@ -849,7 +849,7 @@ describe('TaskModel', () => {it('should group only tasks from the requested project', async () => {const model = new TaskModel(serverDB, userId);- const project = await new ProjectModel(serverDB, userId).create({+ const project = await new ProjectRepository(serverDB, userId).create({identifier: 'TGRP',name: 'Scoped project',});diff --git a/packages/database/src/models/project.ts b/packages/database/src/models/project.tsindex 75232a1eabe..7fd0aba0372 100644--- a/packages/database/src/models/project.ts+++ b/packages/database/src/models/project.ts@@ -24,12 +24,22 @@ import type { LobeChatDatabase } from '../type';import { isUserKnowledgeBase } from '../utils/knowledgeBaseType';import { joinTopicAgentsToProjects } from '../utils/projectTopicAgents';import { topicRunStartedAtColumn } from '../utils/topicRunStartedAt';-import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';+import {+ buildWorkspacePayload,+ buildWorkspaceWhere,+ normalizeWorkspaceId,+} from '../utils/workspace';import { AgentModel } from './agent';import { EnvironmentModel } from './environment';-import { createProjectMainAgent } from './projectMainAgent';+import {+ isProjectIdentifierConflict,+ normalizeProjectIdentifier,+ ProjectIdentifierTakenError,+} from './projectIdentifier';import { topicHasGoal } from './topicGoal';+export { normalizeProjectIdentifier, ProjectIdentifierTakenError } from './projectIdentifier';+export interface CreateProjectInput {avatar?: string;/** Lead the project with an existing agent instead of creating one named after it. */@@ -44,6 +54,15 @@ export interface CreateProjectInput {visibility?: ProjectVisibility;}+/**+ * Input for the single-aggregate insert. The main agent belongs to AgentModel's+ * aggregate, so `ProjectRepository.create` resolves or creates it first and only+ * its id reaches this model.+ */+export interface InsertProjectInput extends Omit<CreateProjectInput, 'repository'> {+ coordinatorAgentId: string;+}+const BUILTIN_SLUGS: ReadonlySet<string> = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));export interface UpdateProjectInput {@@ -134,7 +153,7 @@ export class ProjectModel {* or library is visible to its creator alone, so such a project binds only* public resources. Anything else would show each reader a different project.*/- private assertSharedResource(+ assertSharedResource(project: { visibility: string; workspaceId: string | null },resourceVisibility: string,message: string,@@ -150,70 +169,73 @@ export class ProjectModel {: this.ownedByCaller();}- 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');- }+ /**+ * Ownership predicate for `identifier` allocation — **visibility-blind**,+ * unlike {@link readable}.+ *+ * The unique index that guards the column (`projects_identifier_workspace_id_unique`)+ * is scope-wide, so a private project created by another member still occupies+ * its identifier. Filtering by visibility here would let a member compute a+ * "free" identifier that the index then rejects. The index also carries no+ * recycle-bin predicate, so a stamped-but-present row keeps its identifier —+ * this must not add `is_deleted` filtering either.+ */+ private identifierScope() {+ const workspaceId = normalizeWorkspaceId(this.workspaceId);- return this.db.transaction(async (tx) => {- const coordinator = input.coordinatorAgentId- ? await this.findAccessibleAgent(tx as LobeChatDatabase, input.coordinatorAgentId)- : await createProjectMainAgent(- tx as LobeChatDatabase,- { userId: this.userId, workspaceId: this.workspaceId },- { avatar: input.avatar, name: input.name, visibility: input.visibility },- );- if (!coordinator) throw new Error('Agent not found');- if (input.coordinatorAgentId) {- this.assertSharedResource(- { visibility: input.visibility ?? 'private', workspaceId: this.workspaceId ?? null },- (coordinator as { visibility: string }).visibility,- 'A shared project only takes shared agents',- );- }+ return workspaceId+ ? eq(projects.workspaceId, workspaceId)+ : and(eq(projects.userId, this.userId), isNull(projects.workspaceId));+ }- const [project] = await tx+ /**+ * Whether another project already claims `identifier` in this scope.+ * Mirrors the unique index exactly — see {@link identifierScope}.+ */+ async isIdentifierTaken(identifier: string): Promise<boolean> {+ const normalized = identifier.trim().toUpperCase();+ if (!normalized) return false;++ const [existing] = await this.db+ .select({ id: projects.id })+ .from(projects)+ .where(and(this.identifierScope(), eq(projects.identifier, normalized)))+ .limit(1);++ return Boolean(existing);+ }++ /**+ * Insert the project row only, as a plain single-table insert. The coordinator+ * agent and the `projectAgents` link that seats it span another aggregate, so+ * `ProjectRepository.create` owns the transaction (and the identifier+ * pre-check) that ties them together — see {@link ProjectRepository}.+ */+ async create(input: InsertProjectInput) {+ const identifier = normalizeProjectIdentifier(input.identifier);++ try {+ const [project] = await this.db.insert(projects).values(buildWorkspacePayload({ userId: this.userId, workspaceId: this.workspaceId },- { ...input, coordinatorAgentId: coordinator.id, identifier },+ { ...input, identifier },),).returning();- await tx.insert(projectAgents).values({- addedByUserId: this.userId,- agentId: coordinator.id,- projectId: project.id,- responsibility: 'Coordinates project conversations, work, and resources',- role: 'coordinator',- 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;- });+ } catch (error) {+ // The unique index stays the final authority: a caller that skipped the+ // repository's pre-check, or a concurrent create, lands here. Translate it+ // into the field error instead of leaking the raw insert failure.+ if (error instanceof ProjectIdentifierTakenError) throw error;+ if (identifier && isProjectIdentifierConflict(error)) {+ throw new ProjectIdentifierTakenError(identifier);+ }+ throw error;+ }}async delete(id: string) {@@ -567,7 +589,7 @@ export class ProjectModel {await joinTopicAgentsToProjects(this.db, { projectId });}- private async findAccessibleAgent(db: LobeChatDatabase, agentId: string) {+ async findAccessibleAgent(db: LobeChatDatabase, agentId: string) {const [agent] = await db.select({ id: agents.id, visibility: agents.visibility }).from(agents)diff --git a/packages/database/src/models/projectIdentifier.ts b/packages/database/src/models/projectIdentifier.tsnew file mode 100644index 00000000000..d31f276e84b--- /dev/null+++ b/packages/database/src/models/projectIdentifier.ts@@ -0,0 +1,64 @@+/**+ * Raised when the identifier a caller picked for a project is already claimed+ * in the same ownership scope.+ *+ * `(workspace_id, identifier)` / `(identifier, user_id)` are backed by unique+ * indexes, so a duplicate used to surface as a raw `insert into "projects"`+ * query failure and the create form could only show a generic failure toast.+ * Raising this instead lets the API and the form treat it as a field-level+ * validation problem.+ */+export class ProjectIdentifierTakenError extends Error {+ readonly identifier: string;++ constructor(identifier: string) {+ super(`Project identifier "${identifier}" is already in use in this scope`);+ this.name = 'ProjectIdentifierTakenError';+ this.identifier = identifier;+ }+}++/**+ * Walk the `cause` chain for the Postgres error that actually failed the+ * statement and decide whether it is the project identifier unique index.+ *+ * Drizzle wraps driver errors, so the `code` / `constraint` fields live on a+ * nested cause rather than the error we catch. The identifier indexes are+ * matched by name because the same insert can also trip `projects_slug_*` or+ * `projects_coordinator_agent_id_unique` — reporting those as "identifier+ * taken" would point the caller at the wrong field.+ */+export const isProjectIdentifierConflict = (error: unknown): boolean => {+ let current: unknown = error;+ for (let depth = 0; current && typeof current === 'object' && depth < 5; depth++) {+ const candidate = current as {+ cause?: unknown;+ code?: unknown;+ constraint?: unknown;+ message?: unknown;+ };+ const code = typeof candidate.code === 'string' ? candidate.code : '';+ const constraint = typeof candidate.constraint === 'string' ? candidate.constraint : '';+ const message = typeof candidate.message === 'string' ? candidate.message : '';++ if (constraint.startsWith('projects_identifier_')) return true;+ if (code === '23505' && /projects_identifier_|identifier/i.test(message)) return true;++ current = candidate.cause;+ }++ return false;+};++/**+ * Normalize a project identifier and enforce its shape. Shared with+ * `ProjectRepository.create`, which needs the normalized value to check the+ * scope before it writes the main agent.+ */+export const normalizeProjectIdentifier = (identifier?: string | null) => {+ const normalized = identifier?.trim().toUpperCase() || null;+ if (normalized && (normalized.length < 3 || normalized.length > 6)) {+ throw new Error('Project identifier must be between 3 and 6 characters');+ }+ return normalized;+};diff --git a/packages/database/src/repositories/project/index.ts b/packages/database/src/repositories/project/index.tsnew file mode 100644index 00000000000..53d8611c996--- /dev/null+++ b/packages/database/src/repositories/project/index.ts@@ -0,0 +1,105 @@+import { EnvironmentModel } from '../../models/environment';+import type { CreateProjectInput } from '../../models/project';+import {+ normalizeProjectIdentifier,+ ProjectIdentifierTakenError,+ ProjectModel,+} from '../../models/project';+import { createProjectMainAgent } from '../../models/projectMainAgent';+import { projectAgents } from '../../schemas/project';+import { projectEnvironments } from '../../schemas/projectEnvironment';+import type { LobeChatDatabase } from '../../type';++/**+ * Cross-aggregate write flow for projects. Creating a project also creates (or+ * binds) its main agent — an `agents` row that AgentModel owns and that outlives+ * the project — so the transaction spanning both aggregates lives here, while+ * {@link ProjectModel.create} owns only the project row and its coordinator link+ * row.+ */+export class ProjectRepository {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ ) {}++ async create({ repository, ...input }: CreateProjectInput) {+ const identifier = normalizeProjectIdentifier(input.identifier);++ return this.db.transaction(async (tx) => {+ const db = tx as LobeChatDatabase;+ const projectModel = new ProjectModel(db, this.userId, this.workspaceId);++ // Fail before the main agent is written when the identifier is taken. The+ // model re-checks inside its own transaction and translates the unique+ // violation, which covers the concurrent-create race.+ if (identifier && (await projectModel.isIdentifierTaken(identifier))) {+ throw new ProjectIdentifierTakenError(identifier);+ }++ const mainAgent = input.coordinatorAgentId+ ? await projectModel.findAccessibleAgent(db, input.coordinatorAgentId)+ : await createProjectMainAgent(+ db,+ { userId: this.userId, workspaceId: this.workspaceId },+ { avatar: input.avatar, name: input.name, visibility: input.visibility },+ );+ if (!mainAgent) throw new Error('Agent not found');++ if (input.coordinatorAgentId) {+ projectModel.assertSharedResource(+ { visibility: input.visibility ?? 'private', workspaceId: this.workspaceId ?? null },+ (mainAgent as { visibility: string }).visibility,+ 'A shared project only takes shared agents',+ );+ }++ const project = await projectModel.create({+ ...input,+ coordinatorAgentId: mainAgent.id,+ identifier,+ });+ await this.linkCoordinator(db, project.id, mainAgent.id);++ // The environment belongs to another aggregate too, and a repository the+ // environment cannot accept must not leave a half-made project behind, so+ // it is created in the same transaction.+ if (repository) {+ const environment = await new EnvironmentModel(+ db,+ this.userId,+ this.workspaceId,+ ).ensureForRepository({+ defaultBranch: repository.defaultBranch,+ name: repository.name,+ repositoryUrl: repository.url,+ });+ await db.insert(projectEnvironments).values({+ addedByUserId: this.userId,+ environmentId: environment.id,+ projectId: project.id,+ workspaceId: this.workspaceId,+ });+ }++ return project;+ });+ }++ /**+ * Seat the main agent on the project it leads. The link lives in the project+ * aggregate but points at a row another aggregate owns, so it is written here+ * alongside the project insert rather than inside the model.+ */+ private async linkCoordinator(db: LobeChatDatabase, projectId: string, agentId: string) {+ await db.insert(projectAgents).values({+ addedByUserId: this.userId,+ agentId,+ projectId,+ responsibility: 'Coordinates project conversations, work, and resources',+ role: 'coordinator',+ workspaceId: this.workspaceId ?? null,+ });+ }+}diff --git a/packages/database/src/repositories/projectCoordinator/__tests__/index.test.ts b/packages/database/src/repositories/projectCoordinator/__tests__/index.test.tsindex ae32b7f8037..342ef816de4 100644--- a/packages/database/src/repositories/projectCoordinator/__tests__/index.test.ts+++ b/packages/database/src/repositories/projectCoordinator/__tests__/index.test.ts@@ -23,18 +23,20 @@ import {widgets,} from '../../../schemas';import { ChannelRepository } from '../../channel';+import { ProjectRepository } from '../../project';import { ProjectCoordinatorRepository } from '../index';const serverDB = await getTestDB();const userId = 'project-coordinator-user';const otherUserId = 'project-coordinator-other-user';const model = new ProjectModel(serverDB, userId);+const projectRepo = new ProjectRepository(serverDB, userId);const repo = new ProjectCoordinatorRepository(serverDB, userId);const otherRepo = new ProjectCoordinatorRepository(serverDB, otherUserId);let identifierSequence = 0;const createProject = (input: { coordinatorAgentId?: string; name: string }) =>- model.create({ ...input, identifier: `C${String(++identifierSequence).padStart(5, '0')}` });+ projectRepo.create({ ...input, identifier: `C${String(++identifierSequence).padStart(5, '0')}` });/** Projects created before main agents were ordinary agents got a virtual coordinator. */const createLegacyProject = async (name: string) => {diff --git a/packages/locales/src/default/project.ts b/packages/locales/src/default/project.tsindex 11196b59bb8..3fe1c285d83 100644--- a/packages/locales/src/default/project.ts+++ b/packages/locales/src/default/project.ts@@ -174,6 +174,7 @@ export default {'create.identifierInvalid': 'Use 3–6 uppercase letters or numbers, starting with a letter.','create.identifierLabel': 'Identifier (optional)','create.identifierPlaceholder': 'ACE',+ 'create.identifierTaken': 'Another project in this workspace already uses this identifier.','create.mainAgentDedicatedDescription':'Creates an agent named after the project, with its avatar and the Project label. It stays in your agents list.','create.mainAgentDedicatedPlaceholder': 'Named after the project',@@ -189,6 +190,7 @@ export default {'create.slugInvalid': 'Use lowercase letters, numbers, and single hyphens only.','create.slugLabel': 'Slug (optional)','create.slugPlaceholder': 'my-project',+ 'create.slugTaken': 'Another project in this workspace already uses this link name.','create.title': 'New project','createFromGithub.connect': 'Connect GitHub','createFromGithub.disconnected':diff --git a/packages/types/src/project/index.ts b/packages/types/src/project/index.tsindex 6628f97ebba..19d853e7b1b 100644--- a/packages/types/src/project/index.ts+++ b/packages/types/src/project/index.ts@@ -1,5 +1,19 @@export const PROJECT_IDENTIFIER_REGEX = /^[A-Z][A-Z0-9]{2,5}$/;+/**+ * `CONFLICT` messages for a taken project slug or identifier.+ *+ * The create router sends one of these as the tRPC error message, so a form can+ * tell which field the conflict belongs to and mark that input instead of+ * showing a generic failure.+ */+export const PROJECT_DUPLICATE_IDENTIFIER = 'DUPLICATE_PROJECT_IDENTIFIER';++export const PROJECT_DUPLICATE_SLUG = 'DUPLICATE_PROJECT_SLUG';++/** The field a person edits to resolve a duplicate project value. */+export type ProjectDuplicateField = 'identifier' | 'slug';+export const PROJECT_STATUSES = ['backlog','active',diff --git a/src/features/Projects/CreateFromGithub/Content.tsx b/src/features/Projects/CreateFromGithub/Content.tsxindex 669c068e08c..2bf12f6eb08 100644--- a/src/features/Projects/CreateFromGithub/Content.tsx+++ b/src/features/Projects/CreateFromGithub/Content.tsx@@ -18,6 +18,7 @@ import { useProjectStore } from '@/store/project';import {getCreateProjectInput,+ getProjectConflictField,getProjectFieldSuggestions,isProjectIdentifierValid,} from '../createProjectForm';@@ -26,12 +27,6 @@ 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;@@ -118,10 +113,10 @@ const CreateFromGithubContent = () => {close();navigate(`/project/${project.slug ?? project.id}`);} catch (error) {- const duplicate =- error instanceof Error- ? DUPLICATE_FIELD[error.message as keyof typeof DUPLICATE_FIELD]- : undefined;+ // A taken slug also comes back as a conflict; this dialog has no slug+ // input, so it reports it on the name the slug is derived from.+ const field = getProjectConflictField(error);+ const duplicate = field === 'slug' ? 'name' : field;if (duplicate) {setForm((current) => ({ ...current, duplicate }));} else {diff --git a/src/features/Projects/CreateProjectContent.tsx b/src/features/Projects/CreateProjectContent.tsxindex b43b358ee62..3631c984ac7 100644--- a/src/features/Projects/CreateProjectContent.tsx+++ b/src/features/Projects/CreateProjectContent.tsx@@ -6,13 +6,16 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwarimport { useAgentStore } from '@/store/agent';import { builtinAgentSelectors } from '@/store/agent/selectors';import { useHomeStore } from '@/store/home';-import { type ProjectListItem, useProjectStore } from '@/store/project';+import { type ProjectListItem, useLoadedProjectList, useProjectStore } from '@/store/project';import {buildCreateProjectRequest,DEFAULT_MAIN_AGENT_MODE,+ doesConflictApplyTo,getCreateProjectInput,+ getProjectConflictField,getProjectFieldSuggestions,+ isProjectIdentifierTaken,isProjectIdentifierValid,isProjectSlugValid,type MainAgentMode,@@ -36,12 +39,16 @@ interface CreateProjectFormState {/** Creating now would save the project, and its agent, without the avatar on its way. */avatarUploading: boolean;identifier: string;+ /** Set when the server rejects the identifier as already taken. */+ identifierConflict: boolean;loading: boolean;/** Explicit pick in this modal; otherwise LobeAI. */mainAgentId?: string;mainAgentMode: MainAgentMode;name: string;slug: string;+ /** Set when the server rejects the slug as already taken in this scope. */+ slugConflict: boolean;slugEdited: boolean;}@@ -56,13 +63,16 @@ const CreateProjectContent = memo<CreateProjectOptions>(({ onCreated }) => {const { close } = useModalContext();const navigate = useWorkspaceAwareNavigate();const createProject = useProjectStore((s) => s.createProject);+ const loadedProjects = useLoadedProjectList();const [form, setForm] = useState<CreateProjectFormState>({avatarUploading: false,identifier: '',+ identifierConflict: false,loading: false,mainAgentMode: DEFAULT_MAIN_AGENT_MODE,name: '',slug: '',+ slugConflict: false,slugEdited: false,});const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);@@ -70,7 +80,16 @@ const CreateProjectContent = memo<CreateProjectOptions>(({ onCreated }) => {const createInput = getCreateProjectInput(form);const identifierInvalid =Boolean(form.identifier.trim()) && !isProjectIdentifierValid(form.identifier);+ // Identifiers are unique per scope, so a name whose derived prefix is already+ // taken (two projects starting with "lobe…") would otherwise only fail after+ // submit, as an opaque "operation failed".+ const identifierTaken =+ form.identifierConflict ||+ (loadedProjects ? isProjectIdentifierTaken(form.identifier, loadedProjects) : false);const slugValid = isProjectSlugValid(form.slug);+ // Slugs are unique per scope too, so a name that derives an already-used slug+ // ("LobeHub" twice) must report it on the slug field, not on the identifier.+ const slugTaken = form.slugConflict;const updateForm = (patch: Partial<CreateProjectFormState>) => {setForm((current) => ({ ...current, ...patch }));@@ -82,11 +101,17 @@ const CreateProjectContent = memo<CreateProjectOptions>(({ onCreated }) => {...current,name,slug: current.slugEdited ? current.slug : suggestions.slug,+ // A derived slug changes with the name, so a conflict reported for the+ // previous one no longer applies. A slug typed by hand stays put.+ slugConflict: current.slugEdited ? current.slugConflict : false,}));};const handleCreate = async () => {- if (!createInput || form.loading || form.avatarUploading) return;+ if (!createInput || identifierTaken || slugTaken || form.loading || form.avatarUploading)+ return;+ const submittedIdentifier = createInput.identifier ?? '';+ const submittedSlug = createInput.slug ?? '';updateForm({ loading: true });try {const project = await createProject(@@ -106,6 +131,28 @@ const CreateProjectContent = memo<CreateProjectOptions>(({ onCreated }) => {else navigate(`/project/${project.slug ?? project.id}`);} catch (error) {console.error('Failed to create project', error);+ // The unique index stays the final authority: a concurrent create, or a+ // private project by another member that the loaded list cannot see, can+ // still collide after the inline check. The server names the field it+ // rejected, so the error lands on that input instead of a generic toast.+ const conflict = getProjectConflictField(error);+ if (conflict === 'identifier') {+ setForm((current) => ({+ ...current,+ // Only the identifier that was submitted is known to be taken. The+ // field stays editable while the request is in flight, so a value+ // typed meanwhile must not inherit that verdict.+ identifierConflict: doesConflictApplyTo(submittedIdentifier, current.identifier),+ }));+ return;+ }+ if (conflict === 'slug') {+ setForm((current) => ({+ ...current,+ slugConflict: doesConflictApplyTo(submittedSlug, current.slug),+ }));+ return;+ }toast.error(t('operationFailed', { ns: 'common' }));} finally {updateForm({ loading: false });@@ -148,10 +195,12 @@ const CreateProjectContent = memo<CreateProjectOptions>(({ onCreated }) => {<CreateProjectMoreFieldsidentifier={form.identifier}identifierInvalid={identifierInvalid}+ identifierTaken={identifierTaken}slug={form.slug}+ slugTaken={slugTaken}slugValid={slugValid}- onIdentifierChange={(identifier) => updateForm({ identifier })}- onSlugChange={(slug) => updateForm({ slug, slugEdited: true })}+ onIdentifierChange={(identifier) => updateForm({ identifier, identifierConflict: false })}+ onSlugChange={(slug) => updateForm({ slug, slugConflict: false, slugEdited: true })}onSubmit={handleCreate}/><Text fontSize={12} type="secondary">@@ -161,7 +210,7 @@ const CreateProjectContent = memo<CreateProjectOptions>(({ onCreated }) => {<ModalFooter><Button onClick={close}>{t('cancel', { ns: 'common' })}</Button><Button- disabled={!createInput || form.avatarUploading}+ disabled={!createInput || identifierTaken || slugTaken || form.avatarUploading}loading={form.loading}type="primary"onClick={handleCreate}diff --git a/src/features/Projects/CreateProjectMoreFields.tsx b/src/features/Projects/CreateProjectMoreFields.tsxindex d6a8b1c9457..728a88ca9bc 100644--- a/src/features/Projects/CreateProjectMoreFields.tsx+++ b/src/features/Projects/CreateProjectMoreFields.tsx@@ -6,26 +6,34 @@ import { useTranslation } from 'react-i18next';interface CreateProjectMoreFieldsProps {identifier: string;identifierInvalid: boolean;+ /** The identifier is valid but already claimed in this scope. */+ identifierTaken: boolean;onIdentifierChange: (value: string) => void;onSlugChange: (value: string) => void;onSubmit: () => void;slug: string;+ /** The slug is well-formed but already claimed in this scope. */+ slugTaken: boolean;slugValid: boolean;}const CreateProjectMoreFields = ({identifier,identifierInvalid,+ identifierTaken,onIdentifierChange,onSlugChange,onSubmit,slug,+ slugTaken,slugValid,}: CreateProjectMoreFieldsProps) => {const { t } = useTranslation('project');const [expanded, setExpanded] = useState(false);// An invalid value stays visible so its error can't hide behind the fold.- const open = expanded || identifierInvalid || !slugValid;+ const identifierError = identifierInvalid || identifierTaken;+ const slugError = !slugValid || slugTaken;+ const open = expanded || identifierError || slugError;return (<Flexbox gap={16}>@@ -48,16 +56,22 @@ const CreateProjectMoreFields = ({{t('create.identifierLabel')}</Text><Input- aria-invalid={identifierInvalid}+ aria-invalid={identifierError}maxLength={6}placeholder={t('create.identifierPlaceholder')}- style={identifierInvalid ? { borderColor: cssVar.colorError } : undefined}+ style={identifierError ? { borderColor: cssVar.colorError } : undefined}value={identifier}onChange={(event) => onIdentifierChange(event.target.value.toUpperCase())}onPressEnter={onSubmit}/>- <Text fontSize={12} type={identifierInvalid ? 'danger' : 'secondary'}>- {t(identifierInvalid ? 'create.identifierInvalid' : 'create.identifierDescription')}+ <Text fontSize={12} type={identifierError ? 'danger' : 'secondary'}>+ {t(+ identifierInvalid+ ? 'create.identifierInvalid'+ : identifierTaken+ ? 'create.identifierTaken'+ : 'create.identifierDescription',+ )}</Text></Flexbox><Flexbox gap={6}>@@ -65,16 +79,22 @@ const CreateProjectMoreFields = ({{t('create.slugLabel')}</Text><Input- aria-invalid={!slugValid}+ aria-invalid={slugError}maxLength={100}placeholder={t('create.slugPlaceholder')}- style={slugValid ? undefined : { borderColor: cssVar.colorError }}+ style={slugError ? { borderColor: cssVar.colorError } : undefined}value={slug}onChange={(event) => onSlugChange(event.target.value.toLowerCase())}onPressEnter={onSubmit}/>- <Text fontSize={12} type={slugValid ? 'secondary' : 'danger'}>- {t(slugValid ? 'create.slugDescription' : 'create.slugInvalid')}+ <Text fontSize={12} type={slugError ? 'danger' : 'secondary'}>+ {t(+ slugValid+ ? slugTaken+ ? 'create.slugTaken'+ : 'create.slugDescription'+ : 'create.slugInvalid',+ )}</Text></Flexbox></>diff --git a/src/features/Projects/createProjectForm.test.ts b/src/features/Projects/createProjectForm.test.tsindex 15c3256f69b..ad263bc416e 100644--- a/src/features/Projects/createProjectForm.test.ts+++ b/src/features/Projects/createProjectForm.test.ts@@ -3,8 +3,11 @@ import { describe, expect, it } from 'vitest';import {buildCreateProjectRequest,DEFAULT_MAIN_AGENT_MODE,+ doesConflictApplyTo,getCreateProjectInput,+ getProjectConflictField,getProjectFieldSuggestions,+ isProjectIdentifierTaken,isProjectIdentifierValid,isProjectSlugValid,PROJECT_SLUG_MAX_LENGTH,@@ -50,6 +53,48 @@ describe('createProjectForm', () => {expect(isProjectIdentifierValid('1LOBE')).toBe(false);});+ it('flags an identifier that another project in the scope already uses', () => {+ const projects = [{ identifier: 'LOBE' }, { identifier: 'MOBILE' }];++ expect(isProjectIdentifierTaken('LOBE', projects)).toBe(true);+ expect(isProjectIdentifierTaken(' lobe ', projects)).toBe(true);+ expect(isProjectIdentifierTaken('LOB', projects)).toBe(false);+ // An empty field is "not yet filled in", not "taken".+ expect(isProjectIdentifierTaken(' ', projects)).toBe(false);+ expect(isProjectIdentifierTaken('LOBE', [])).toBe(false);+ });++ it('attributes a server conflict only to the identifier that was submitted', () => {+ // Unchanged field: the conflict the server reported still describes it.+ expect(doesConflictApplyTo('LOBE', 'LOBE')).toBe(true);+ expect(doesConflictApplyTo('LOBE', ' lobe ')).toBe(true);++ // Typed a new value while the request was in flight: the verdict is stale.+ expect(doesConflictApplyTo('LOBE', 'MOBILE')).toBe(false);++ // Nothing was submitted, so there is no identifier to blame.+ expect(doesConflictApplyTo('', '')).toBe(false);+ expect(doesConflictApplyTo('', 'MOBILE')).toBe(false);+ });++ it('routes a conflict to the field the server named', () => {+ const conflict = (code: string, message: string) => ({ data: { code }, message });++ expect(getProjectConflictField(conflict('CONFLICT', 'DUPLICATE_PROJECT_IDENTIFIER'))).toBe(+ 'identifier',+ );+ expect(getProjectConflictField(conflict('CONFLICT', 'DUPLICATE_PROJECT_SLUG'))).toBe('slug');++ // A conflict without a field code, or a failure of another kind, stays+ // generic — the form must not blame a field it cannot name.+ expect(getProjectConflictField(conflict('CONFLICT', 'SOMETHING_ELSE'))).toBeUndefined();+ expect(+ getProjectConflictField(conflict('BAD_REQUEST', 'DUPLICATE_PROJECT_SLUG')),+ ).toBeUndefined();+ expect(getProjectConflictField(new Error('boom'))).toBeUndefined();+ expect(getProjectConflictField(undefined)).toBeUndefined();+ });+it('normalizes and includes a user-provided slug', () => {expect(getCreateProjectInput({diff --git a/src/features/Projects/createProjectForm.ts b/src/features/Projects/createProjectForm.tsindex 474b49bf9f9..721f9caf41f 100644--- a/src/features/Projects/createProjectForm.ts+++ b/src/features/Projects/createProjectForm.ts@@ -1,4 +1,9 @@-import { PROJECT_IDENTIFIER_REGEX } from '@lobechat/types';+import {+ PROJECT_DUPLICATE_IDENTIFIER,+ PROJECT_DUPLICATE_SLUG,+ PROJECT_IDENTIFIER_REGEX,+ type ProjectDuplicateField,+} from '@lobechat/types';import { kebabCase } from 'es-toolkit';import { pinyin } from 'pinyin-pro';@@ -36,6 +41,55 @@ export const getProjectFieldSuggestions = (name: string): ProjectFieldSuggestionexport const isProjectIdentifierValid = (identifier: string) =>PROJECT_IDENTIFIER_REGEX.test(identifier.trim().toUpperCase());+/**+ * Whether an already-loaded project in the active scope claims `identifier`.+ *+ * Identifiers are unique per scope (`projects_identifier_workspace_id_unique`),+ * so the form checks this inline and shows the conflict next to the field. The+ * list is visibility-filtered, so another member's private project can slip+ * past here — the server re-checks and answers `CONFLICT` for that case.+ */+export const isProjectIdentifierTaken = (+ identifier: string,+ projects: readonly { identifier?: string | null }[],+) => {+ const normalized = identifier.trim().toUpperCase();++ return Boolean(normalized) && projects.some((project) => project.identifier === normalized);+};++/**+ * Whether a `CONFLICT` answered for `submitted` still describes the value in the+ * field.+ *+ * The inputs stay editable while the create request is in flight, so the answer+ * can come back after the user has typed another value. The verdict belongs to+ * what was submitted; a different value typed meanwhile must not inherit it. An+ * empty submission carries no value (the server generates the slug, and leaves+ * the identifier null), so it has nothing to attribute a conflict to.+ */+export const doesConflictApplyTo = (submitted: string, current: string) => {+ const submittedValue = submitted.trim().toUpperCase();++ return Boolean(submittedValue) && current.trim().toUpperCase() === submittedValue;+};++/**+ * The field a project `CONFLICT` belongs to.+ *+ * The create router answers a taken slug or identifier with a machine-readable+ * message (see `PROJECT_DUPLICATE_*`), so the form can put the error under the+ * input that resolves it. Any other conflict stays a generic failure.+ */+export const getProjectConflictField = (error: unknown): ProjectDuplicateField | undefined => {+ const conflict = error as { data?: { code?: string }; message?: string } | null | undefined;+ if (conflict?.data?.code !== 'CONFLICT') return undefined;+ if (conflict.message === PROJECT_DUPLICATE_IDENTIFIER) return 'identifier';+ if (conflict.message === PROJECT_DUPLICATE_SLUG) return 'slug';++ return undefined;+};+export const isProjectSlugValid = (slug: string) => {const normalizedSlug = slug.trim().toLowerCase();return (