Skip to content

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

✨ feat: implement Project backend and CLI (#18006)

Arvin Xu4c0ff6614f7b
diff --git a/apps/cli/src/commands/project.test.ts b/apps/cli/src/commands/project.test.ts
new file mode 100644
index 00000000000..63fe4e8244f
--- /dev/null
+++ b/apps/cli/src/commands/project.test.ts
@@ -0,0 +1,127 @@
+import { Command } from 'commander';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { registerProjectCommand } from './project';
+
+const { mockClient } = vi.hoisted(() => ({
+ mockClient: {
+ project: {
+ acceptCompletion: { mutate: vi.fn() },
+ addAgent: { mutate: vi.fn() },
+ addKnowledgeBase: { mutate: vi.fn() },
+ create: { mutate: vi.fn() },
+ delete: { mutate: vi.fn() },
+ detail: { query: vi.fn() },
+ list: { query: vi.fn() },
+ moveTask: { mutate: vi.fn() },
+ rejectCompletion: { mutate: vi.fn() },
+ removeAgent: { mutate: vi.fn() },
+ removeKnowledgeBase: { mutate: vi.fn() },
+ reopen: { mutate: vi.fn() },
+ requestCompletion: { mutate: vi.fn() },
+ update: { mutate: vi.fn() },
+ updateStatus: { mutate: vi.fn() },
+ },
+ task: { create: { mutate: vi.fn() } },
+ },
+}));
+
+vi.mock('../api/client', () => ({ getTrpcClient: vi.fn().mockResolvedValue(mockClient) }));
+vi.mock('../utils/logger', () => ({
+ log: { error: vi.fn(), info: vi.fn(), warn: vi.fn() },
+}));
+
+function createProgram() {
+ const program = new Command();
+ program.exitOverride();
+ registerProjectCommand(program);
+ return program;
+}
+
+describe('project command', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ });
+
+ it('creates a project', async () => {
+ mockClient.project.create.mutate.mockResolvedValue({ data: { id: 'prj_1' } });
+ await createProgram().parseAsync([
+ 'node',
+ 'test',
+ 'project',
+ 'create',
+ '--name',
+ 'Apollo',
+ '--visibility',
+ 'private',
+ ]);
+ expect(mockClient.project.create.mutate).toHaveBeenCalledWith({
+ name: 'Apollo',
+ visibility: 'private',
+ });
+ });
+
+ it('binds an agent with its project role', async () => {
+ mockClient.project.addAgent.mutate.mockResolvedValue({ success: true });
+ await createProgram().parseAsync([
+ 'node',
+ 'test',
+ 'project',
+ 'agent',
+ 'add',
+ 'prj_1',
+ 'agent_1',
+ '--role',
+ 'lead',
+ ]);
+ expect(mockClient.project.addAgent.mutate).toHaveBeenCalledWith({
+ agentId: 'agent_1',
+ id: 'prj_1',
+ role: 'lead',
+ });
+ });
+
+ it('creates a task directly in the project', async () => {
+ mockClient.task.create.mutate.mockResolvedValue({ data: { identifier: 'T-1' } });
+ await createProgram().parseAsync([
+ 'node',
+ 'test',
+ 'project',
+ 'task',
+ 'create',
+ 'prj_1',
+ '--instruction',
+ 'Ship it',
+ '--agent',
+ 'agent_1',
+ ]);
+ expect(mockClient.task.create.mutate).toHaveBeenCalledWith({
+ assigneeAgentId: 'agent_1',
+ instruction: 'Ship it',
+ name: undefined,
+ parentTaskId: undefined,
+ projectId: 'prj_1',
+ });
+ });
+
+ it('requests and accepts human completion review', async () => {
+ mockClient.project.requestCompletion.mutate.mockResolvedValue({ success: true });
+ mockClient.project.acceptCompletion.mutate.mockResolvedValue({ success: true });
+ await createProgram().parseAsync(['node', 'test', 'project', 'request-review', 'prj_1']);
+ await createProgram().parseAsync([
+ 'node',
+ 'test',
+ 'project',
+ 'accept',
+ 'prj_1',
+ '--comment',
+ 'Approved',
+ ]);
+ expect(mockClient.project.requestCompletion.mutate).toHaveBeenCalledWith({ id: 'prj_1' });
+ expect(mockClient.project.acceptCompletion.mutate).toHaveBeenCalledWith({
+ comment: 'Approved',
+ id: 'prj_1',
+ });
+ });
+});
diff --git a/apps/cli/src/commands/project.ts b/apps/cli/src/commands/project.ts
new file mode 100644
index 00000000000..52f67869c41
--- /dev/null
+++ b/apps/cli/src/commands/project.ts
@@ -0,0 +1,225 @@
+import { PROJECT_STATUSES, PROJECT_VISIBILITIES } from '@lobechat/types';
+import type { Command } from 'commander';
+import pc from 'picocolors';
+
+import { getTrpcClient } from '../api/client';
+import { confirm, outputJson, printTable, timeAgo, truncate } from '../utils/format';
+import { log } from '../utils/logger';
+
+const statusValues = PROJECT_STATUSES.join(', ');
+
+export function registerProjectCommand(program: Command) {
+ const project = program.command('project').description('Manage goal-oriented projects');
+
+ project
+ .command('list')
+ .description('List projects')
+ .option('--status <statuses...>', `Filter by status (${statusValues})`)
+ .option('--json [fields]', 'Output JSON')
+ .action(async (options: { json?: boolean | string; status?: string[] }) => {
+ const client = await getTrpcClient();
+ const result = await client.project.list.query({
+ statuses: options.status as (typeof PROJECT_STATUSES)[number][] | undefined,
+ });
+ if (options.json !== undefined) return outputJson(result.data, options.json);
+ if (result.data.length === 0) return console.log('No projects found.');
+ printTable(
+ result.data.map((item) => [
+ item.id,
+ truncate(item.name, 40),
+ item.status,
+ item.visibility,
+ timeAgo(item.updatedAt),
+ ]),
+ ['ID', 'NAME', 'STATUS', 'VISIBILITY', 'UPDATED'],
+ );
+ });
+
+ project
+ .command('view <id>')
+ .description('View project detail')
+ .option('--json [fields]', 'Output JSON')
+ .action(async (id: string, options: { json?: boolean | string }) => {
+ const { data } = await (await getTrpcClient()).project.detail.query({ id });
+ if (options.json !== undefined) return outputJson(data, options.json);
+ console.log(`\n${pc.bold(data.project.name)} ${pc.dim(data.project.id)}`);
+ console.log(`${pc.dim('Status:')} ${data.project.status}`);
+ console.log(`${pc.dim('Visibility:')} ${data.project.visibility}`);
+ if (data.project.description) console.log(`\n${data.project.description}`);
+ console.log(
+ `\n${data.agents?.length ?? 0} agent(s) Β· ${data.knowledgeBases?.length ?? 0} knowledge base(s) Β· ${data.tasks?.length ?? 0} task(s)`,
+ );
+ });
+
+ project
+ .command('create')
+ .description('Create a project')
+ .requiredOption('-n, --name <name>', 'Project name')
+ .option('-d, --description <description>', 'Description')
+ .option('--slug <slug>', 'Project slug')
+ .option('--visibility <visibility>', `Visibility (${PROJECT_VISIBILITIES.join(', ')})`)
+ .action(
+ async (options: {
+ description?: string;
+ name: string;
+ slug?: string;
+ visibility?: (typeof PROJECT_VISIBILITIES)[number];
+ }) => {
+ const result = await (await getTrpcClient()).project.create.mutate(options);
+ console.log(`${pc.green('βœ“')} Created project ${pc.bold(result.data.id)}`);
+ },
+ );
+
+ project
+ .command('edit <id>')
+ .description('Edit a project')
+ .option('-n, --name <name>', 'Project name')
+ .option('-d, --description <description>', 'Description')
+ .option('--slug <slug>', 'Project slug')
+ .option('--visibility <visibility>', `Visibility (${PROJECT_VISIBILITIES.join(', ')})`)
+ .action(
+ async (
+ id: string,
+ options: {
+ description?: string;
+ name?: string;
+ slug?: string;
+ visibility?: (typeof PROJECT_VISIBILITIES)[number];
+ },
+ ) => {
+ await (await getTrpcClient()).project.update.mutate({ id, ...options });
+ console.log(`${pc.green('βœ“')} Updated project ${pc.bold(id)}`);
+ },
+ );
+
+ project
+ .command('delete <id>')
+ .description('Delete a project; tasks are retained without a project')
+ .option('--yes', 'Skip confirmation')
+ .action(async (id: string, options: { yes?: boolean }) => {
+ if (!options.yes && !(await confirm('Delete this project? Its tasks will be retained.')))
+ return;
+ await (await getTrpcClient()).project.delete.mutate({ id });
+ console.log(`${pc.green('βœ“')} Deleted project ${pc.bold(id)}`);
+ });
+
+ project
+ .command('status <id> <status>')
+ .description(`Change project status (${statusValues}; reviewing/completed use review commands)`)
+ .action(async (id: string, status: (typeof PROJECT_STATUSES)[number]) => {
+ if (!PROJECT_STATUSES.includes(status) || ['completed', 'reviewing'].includes(status)) {
+ log.error('Use request-review and accept to complete a project.');
+ process.exitCode = 1;
+ return;
+ }
+ await (
+ await getTrpcClient()
+ ).project.updateStatus.mutate({
+ id,
+ status: status as 'active' | 'archived' | 'backlog' | 'canceled' | 'paused',
+ });
+ console.log(`${pc.green('βœ“')} Project status changed to ${status}`);
+ });
+
+ const agent = project.command('agent').description('Manage project agents');
+ agent
+ .command('add <projectId> <agentId>')
+ .option('--role <role>', 'Project-specific role')
+ .option('--responsibility <text>', 'Project-specific responsibility')
+ .action(
+ async (
+ projectId: string,
+ agentId: string,
+ options: { responsibility?: string; role?: string },
+ ) => {
+ await (
+ await getTrpcClient()
+ ).project.addAgent.mutate({ agentId, id: projectId, ...options });
+ console.log(`${pc.green('βœ“')} Added agent ${pc.bold(agentId)}`);
+ },
+ );
+ agent
+ .command('remove <projectId> <agentId>')
+ .action(async (projectId: string, agentId: string) => {
+ await (await getTrpcClient()).project.removeAgent.mutate({ agentId, id: projectId });
+ console.log(`${pc.green('βœ“')} Removed agent ${pc.bold(agentId)}`);
+ });
+
+ const kb = project.command('kb').description('Manage project knowledge bases');
+ kb.command('add <projectId> <knowledgeBaseId>').action(
+ async (projectId: string, knowledgeBaseId: string) => {
+ await (
+ await getTrpcClient()
+ ).project.addKnowledgeBase.mutate({
+ id: projectId,
+ knowledgeBaseId,
+ });
+ console.log(`${pc.green('βœ“')} Added knowledge base ${pc.bold(knowledgeBaseId)}`);
+ },
+ );
+ kb.command('remove <projectId> <knowledgeBaseId>').action(
+ async (projectId: string, knowledgeBaseId: string) => {
+ await (
+ await getTrpcClient()
+ ).project.removeKnowledgeBase.mutate({
+ id: projectId,
+ knowledgeBaseId,
+ });
+ console.log(`${pc.green('βœ“')} Removed knowledge base ${pc.bold(knowledgeBaseId)}`);
+ },
+ );
+
+ const task = project.command('task').description('Manage project tasks');
+ task
+ .command('create <projectId>')
+ .requiredOption('-i, --instruction <instruction>', 'Task instruction')
+ .option('-n, --name <name>', 'Task name')
+ .option('--agent <agentId>', 'Assignee agent ID')
+ .option('--parent <taskId>', 'Parent task ID or identifier')
+ .action(
+ async (
+ projectId: string,
+ options: { agent?: string; instruction: string; name?: string; parent?: string },
+ ) => {
+ const result = await (
+ await getTrpcClient()
+ ).task.create.mutate({
+ assigneeAgentId: options.agent,
+ instruction: options.instruction,
+ name: options.name,
+ parentTaskId: options.parent,
+ projectId,
+ });
+ console.log(`${pc.green('βœ“')} Created task ${pc.bold(result.data.identifier)}`);
+ },
+ );
+ task.command('move <projectId> <taskId>').action(async (projectId: string, taskId: string) => {
+ const result = await (await getTrpcClient()).project.moveTask.mutate({ id: projectId, taskId });
+ console.log(`${pc.green('βœ“')} Moved ${result.data.length} task(s)`);
+ });
+
+ project.command('request-review <id>').action(async (id: string) => {
+ await (await getTrpcClient()).project.requestCompletion.mutate({ id });
+ console.log(`${pc.green('βœ“')} Project is awaiting human review`);
+ });
+ project
+ .command('accept <id>')
+ .option('-m, --comment <comment>', 'Review comment')
+ .action(async (id: string, options: { comment?: string }) => {
+ await (await getTrpcClient()).project.acceptCompletion.mutate({ id, ...options });
+ console.log(`${pc.green('βœ“')} Project completed`);
+ });
+ project
+ .command('reject <id>')
+ .requiredOption('-m, --comment <comment>', 'Rejection feedback')
+ .action(async (id: string, options: { comment: string }) => {
+ await (
+ await getTrpcClient()
+ ).project.rejectCompletion.mutate({ id, comment: options.comment });
+ console.log(`${pc.green('βœ“')} Project returned to active`);
+ });
+ project.command('reopen <id>').action(async (id: string) => {
+ await (await getTrpcClient()).project.reopen.mutate({ id });
+ console.log(`${pc.green('βœ“')} Project reopened`);
+ });
+}
diff --git a/apps/cli/src/program.ts b/apps/cli/src/program.ts
index 6b523fe94a3..9c46388792c 100644
--- a/apps/cli/src/program.ts
+++ b/apps/cli/src/program.ts
@@ -23,6 +23,7 @@ import { registerMigrateCommand } from './commands/migrate';
import { registerModelCommand } from './commands/model';
import { registerNotifyCommand } from './commands/notify';
import { registerPluginCommand } from './commands/plugin';
+import { registerProjectCommand } from './commands/project';
import { registerProviderCommand } from './commands/provider';
import { registerSearchCommand } from './commands/search';
import { registerSessionGroupCommand } from './commands/session-group';
@@ -94,6 +95,7 @@ export function createProgram() {
registerModelCommand(program);
registerNotifyCommand(program);
registerProviderCommand(program);
+ registerProjectCommand(program);
registerPluginCommand(program);
registerUserCommand(program);
registerVerifyCommand(program);
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.ts
new file mode 100644
index 00000000000..157182ad3f7
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/integration/project.integration.test.ts
@@ -0,0 +1,78 @@
+// @vitest-environment node
+import type { LobeChatDatabase } from '@lobechat/database';
+import { agents, knowledgeBases } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { projectRouter } from '../../project';
+import { taskRouter } from '../../task';
+import { cleanupTestUser, createTestContext, createTestUser } from './setup';
+
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(() => testDB) }));
+
+describe('Project Router Integration', () => {
+ let serverDB: LobeChatDatabase;
+ let userId: string;
+ let caller: ReturnType<typeof projectRouter.createCaller>;
+
+ beforeEach(async () => {
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ userId = await createTestUser(serverDB);
+ caller = projectRouter.createCaller(createTestContext(userId));
+ });
+
+ afterEach(async () => {
+ await cleanupTestUser(serverDB, userId);
+ });
+
+ it('serves the complete project management and human review flow', async () => {
+ const created = await caller.create({ name: 'Apollo', visibility: 'private' });
+ await caller.updateStatus({ id: created.data.id, status: 'active' });
+
+ const [agent] = await serverDB.insert(agents).values({ title: 'Lead', userId }).returning();
+ const [knowledgeBase] = await serverDB
+ .insert(knowledgeBases)
+ .values({ name: 'Mission data', userId })
+ .returning();
+ await caller.addAgent({ agentId: agent.id, id: created.data.id, role: 'lead' });
+ await caller.addKnowledgeBase({ id: created.data.id, knowledgeBaseId: knowledgeBase.id });
+
+ const taskCaller = taskRouter.createCaller(createTestContext(userId));
+ const task = await taskCaller.create({
+ instruction: 'Prepare launch',
+ projectId: created.data.id,
+ });
+ const detail = await caller.detail({ id: created.data.id });
+ expect(detail.data.agents).toHaveLength(1);
+ expect(detail.data.knowledgeBases).toHaveLength(1);
+ expect(detail.data.tasks?.[0].id).toBe(task.data.id);
+
+ await caller.requestCompletion({ id: created.data.id });
+ const completed = await caller.acceptCompletion({
+ comment: 'Human approved',
+ id: created.data.id,
+ });
+ expect(completed.data.project.status).toBe('completed');
+ expect(completed.data.review.reviewerUserId).toBe(userId);
+
+ const reopened = await caller.reopen({ id: created.data.id });
+ expect(reopened.data.status).toBe('active');
+ });
+
+ it('rejects cross-project task dependencies', async () => {
+ const first = await caller.create({ name: 'First' });
+ const second = await caller.create({ name: 'Second' });
+ const taskCaller = taskRouter.createCaller(createTestContext(userId));
+ const firstTask = await taskCaller.create({ instruction: 'First', projectId: first.data.id });
+ const secondTask = await taskCaller.create({
+ instruction: 'Second',
+ projectId: second.data.id,
+ });
+
+ await expect(
+ taskCaller.addDependency({ dependsOnId: secondTask.data.id, taskId: firstTask.data.id }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ });
+});
diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.ts
index 66ac266e537..9c9b6c5aeb4 100644
--- a/apps/server/src/routers/lambda/index.ts
+++ b/apps/server/src/routers/lambda/index.ts
@@ -68,6 +68,7 @@ import { notificationRouter } from './notification';
import { oauthAppRouter } from './oauthApp';
import { oauthDeviceFlowRouter } from './oauthDeviceFlow';
import { pluginRouter } from './plugin';
+import { projectRouter } from './project';
import { pushTokenRouter } from './pushToken';
import { ragEvalRouter } from './ragEval';
import { recentRouter } from './recent';
@@ -144,6 +145,7 @@ export const lambdaRouter = router({
oauthApp: oauthAppRouter,
oauthDeviceFlow: oauthDeviceFlowRouter,
plugin: pluginRouter,
+ project: projectRouter,
pushToken: pushTokenRouter,
ragEval: ragEvalRouter,
recent: recentRouter,
diff --git a/apps/server/src/routers/lambda/project.ts b/apps/server/src/routers/lambda/project.ts
new file mode 100644
index 00000000000..fdafad9e6f3
--- /dev/null
+++ b/apps/server/src/routers/lambda/project.ts
@@ -0,0 +1,295 @@
+import { PROJECT_STATUSES, PROJECT_VISIBILITIES } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
+import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
+import { ProjectModel } from '@/database/models/project';
+import { router } from '@/libs/trpc/lambda';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+
+const projectProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+ return opts.next({
+ ctx: {
+ projectModel: new ProjectModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined),
+ },
+ });
+});
+
+const projectWriteProcedure = projectProcedure.use(withScopedPermission('agent:update'));
+const idInput = z.object({ id: z.string() });
+
+function requireResult<T>(result: T | null, message = 'Project not found'): T {
+ if (!result) throw new TRPCError({ code: 'NOT_FOUND', message });
+ return result;
+}
+
+function mapProjectError(error: unknown, operation: string): never {
+ if (error instanceof TRPCError) throw error;
+ 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 });
+}
+
+export const projectRouter = router({
+ acceptCompletion: projectWriteProcedure
+ .input(idInput.extend({ comment: z.string().optional() }))
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return {
+ data: requireResult(
+ await ctx.projectModel.reviewCompletion(input.id, 'accepted', input.comment),
+ ),
+ message: 'Project completion accepted',
+ success: true,
+ };
+ } catch (error) {
+ mapProjectError(error, 'acceptCompletion');
+ }
+ }),
+
+ addAgent: projectWriteProcedure
+ .input(
+ idInput.extend({
+ agentId: z.string(),
+ enabled: z.boolean().optional(),
+ responsibility: z.string().nullish(),
+ role: z.string().nullish(),
+ sortOrder: z.number().int().optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input: { id, ...input } }) => {
+ try {
+ return {
+ data: requireResult(await ctx.projectModel.addAgent(id, input)),
+ message: 'Agent added to project',
+ success: true,
+ };
+ } catch (error) {
+ mapProjectError(error, 'addAgent');
+ }
+ }),
+
+ addKnowledgeBase: projectWriteProcedure
+ .input(
+ idInput.extend({
+ enabled: z.boolean().optional(),
+ knowledgeBaseId: z.string(),
+ sortOrder: z.number().int().optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input: { id, ...input } }) => {
+ try {
+ return {
+ data: requireResult(await ctx.projectModel.addKnowledgeBase(id, input)),
+ message: 'Knowledge base added to project',
+ success: true,
+ };
+ } catch (error) {
+ mapProjectError(error, 'addKnowledgeBase');
+ }
+ }),
+
+ create: projectWriteProcedure
+ .input(
+ z.object({
+ avatar: z.string().optional(),
+ description: z.string().optional(),
+ name: z.string().min(1).max(255),
+ slug: z.string().max(100).optional(),
+ visibility: z.enum(PROJECT_VISIBILITIES).optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return {
+ data: await ctx.projectModel.create(input),
+ message: 'Project created',
+ success: true,
+ };
+ } catch (error) {
+ mapProjectError(error, 'create');
+ }
+ }),
+
+ delete: projectWriteProcedure.input(idInput).mutation(async ({ ctx, input }) => {
+ try {
+ return {
+ data: requireResult(await ctx.projectModel.delete(input.id)),
+ message: 'Project deleted',
+ success: true,
+ };
+ } catch (error) {
+ mapProjectError(error, 'delete');
+ }
+ }),
+
+ detail: projectProcedure.input(idInput).query(async ({ ctx, input }) => {
+ try {
+ const project = requireResult(await ctx.projectModel.findById(input.id));
+ const [agents, completionReviews, knowledgeBases, tasks] = await Promise.all([
+ ctx.projectModel.listAgents(project.id),
+ ctx.projectModel.listCompletionReviews(project.id),
+ ctx.projectModel.listKnowledgeBases(project.id),
+ ctx.projectModel.listTasks(project.id),
+ ]);
+ return {
+ data: { agents, completionReviews, knowledgeBases, project, tasks },
+ success: true,
+ };
+ } catch (error) {
+ mapProjectError(error, 'detail');
+ }
+ }),
+
+ find: projectProcedure.input(idInput).query(async ({ ctx, input }) => {
+ try {
+ return { data: requireResult(await ctx.projectModel.findById(input.id)), success: true };
+ } catch (error) {
+ mapProjectError(error, 'find');
+ }
+ }),
+
+ list: projectProcedure
+ .input(
+ z.object({
+ limit: z.number().min(1).max(100).default(50),
+ offset: z.number().min(0).default(0),
+ statuses: z.array(z.enum(PROJECT_STATUSES)).optional(),
+ }),
+ )
+ .query(async ({ ctx, input }) => {
+ try {
+ return { data: await ctx.projectModel.list(input), success: true };
+ } catch (error) {
+ mapProjectError(error, 'list');
+ }
+ }),
+
+ listCompletionReviews: projectProcedure.input(idInput).query(async ({ ctx, input }) => {
+ try {
+ return {
+ data: requireResult(await ctx.projectModel.listCompletionReviews(input.id)),
+ success: true,
+ };
+ } catch (error) {
+ mapProjectError(error, 'listCompletionReviews');
+ }
+ }),
+
+ moveTask: projectWriteProcedure
+ .input(idInput.extend({ taskId: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ try {
+ const rows = requireResult(await ctx.projectModel.moveTaskTree(input.id, input.taskId));
+ return { data: rows, message: `${rows.length} task(s) moved`, success: true };
+ } catch (error) {
+ mapProjectError(error, 'moveTask');
+ }
+ }),
+
+ rejectCompletion: projectWriteProcedure
+ .input(idInput.extend({ comment: z.string().min(1) }))
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return {
+ data: requireResult(
+ await ctx.projectModel.reviewCompletion(input.id, 'rejected', input.comment),
+ ),
+ message: 'Project completion rejected',
+ success: true,
+ };
+ } catch (error) {
+ mapProjectError(error, 'rejectCompletion');
+ }
+ }),
+
+ removeAgent: projectWriteProcedure
+ .input(idInput.extend({ agentId: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ try {
+ const removed = await ctx.projectModel.removeAgent(input.id, input.agentId);
+ if (!removed) throw new TRPCError({ code: 'NOT_FOUND', message: 'Binding not found' });
+ return { message: 'Agent removed from project', success: true };
+ } catch (error) {
+ mapProjectError(error, 'removeAgent');
+ }
+ }),
+
+ removeKnowledgeBase: projectWriteProcedure
+ .input(idInput.extend({ knowledgeBaseId: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ try {
+ const removed = await ctx.projectModel.removeKnowledgeBase(input.id, input.knowledgeBaseId);
+ if (!removed) throw new TRPCError({ code: 'NOT_FOUND', message: 'Binding not found' });
+ return { message: 'Knowledge base removed from project', success: true };
+ } catch (error) {
+ mapProjectError(error, 'removeKnowledgeBase');
+ }
+ }),
+
+ reopen: projectWriteProcedure.input(idInput).mutation(async ({ ctx, input }) => {
+ try {
+ return {
+ data: requireResult(await ctx.projectModel.reopen(input.id)),
+ message: 'Project reopened',
+ success: true,
+ };
+ } catch (error) {
+ mapProjectError(error, 'reopen');
+ }
+ }),
+
+ requestCompletion: projectWriteProcedure.input(idInput).mutation(async ({ ctx, input }) => {
+ try {
+ return {
+ data: requireResult(await ctx.projectModel.requestCompletion(input.id)),
+ message: 'Project completion requested',
+ success: true,
+ };
+ } catch (error) {
+ mapProjectError(error, 'requestCompletion');
+ }
+ }),
+
+ update: projectWriteProcedure
+ .input(
+ idInput.extend({
+ avatar: z.string().nullish(),
+ description: z.string().nullish(),
+ name: z.string().min(1).max(255).optional(),
+ slug: z.string().max(100).nullish(),
+ visibility: z.enum(PROJECT_VISIBILITIES).optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input: { id, ...input } }) => {
+ try {
+ return {
+ data: requireResult(await ctx.projectModel.update(id, input)),
+ message: 'Project updated',
+ success: true,
+ };
+ } catch (error) {
+ mapProjectError(error, 'update');
+ }
+ }),
+
+ updateStatus: projectWriteProcedure
+ .input(
+ idInput.extend({
+ status: z.enum(PROJECT_STATUSES).exclude(['completed', 'reviewing']),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return {
+ data: requireResult(await ctx.projectModel.updateStatus(input.id, input.status)),
+ message: 'Project status updated',
+ success: true,
+ };
+ } catch (error) {
+ mapProjectError(error, 'updateStatus');
+ }
+ }),
+});
diff --git a/apps/server/src/routers/lambda/task.ts b/apps/server/src/routers/lambda/task.ts
index a1ca8a972ce..796062d251b 100644
--- a/apps/server/src/routers/lambda/task.ts
+++ b/apps/server/src/routers/lambda/task.ts
@@ -66,6 +66,7 @@ const createSchema = z.object({
name: z.string().optional(),
parentTaskId: z.string().optional(),
priority: z.number().min(0).max(4).optional(),
+ projectId: z.string().optional(),
schedulePattern: z.string().optional(),
scheduleTimezone: z.string().optional(),
// When omitted, the server derives visibility from the parent task or the
@@ -183,6 +184,14 @@ async function resolveSafeParentTaskId(
});
}
+ const task = await resolveOrThrow(model, taskId);
+ if (task.projectId !== parent.projectId) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Parent task must belong to the same project',
+ });
+ }
+
return parent.id;
}
@@ -348,6 +357,9 @@ export const taskRouter = router({
} catch (error) {
if (error instanceof TRPCError) throw error;
console.error('[task:addDependency]', error);
+ if (error instanceof Error && error.message.includes('project boundaries')) {
+ throw new TRPCError({ cause: error, code: 'BAD_REQUEST', message: error.message });
+ }
throw new TRPCError({
cause: error,
code: 'INTERNAL_SERVER_ERROR',
diff --git a/apps/server/src/services/task/index.ts b/apps/server/src/services/task/index.ts
index 33d9a5fe151..cad5deba395 100644
--- a/apps/server/src/services/task/index.ts
+++ b/apps/server/src/services/task/index.ts
@@ -16,6 +16,7 @@ import type {
import { TRPCError } from '@trpc/server';
import { AgentModel } from '@/database/models/agent';
+import { ProjectModel } from '@/database/models/project';
import { TaskModel } from '@/database/models/task';
import { TaskTopicModel } from '@/database/models/taskTopic';
import { TopicModel } from '@/database/models/topic';
@@ -64,6 +65,7 @@ export interface CreateTaskInput {
name?: string;
parentTaskId?: string;
priority?: number;
+ projectId?: string;
schedulePattern?: string;
scheduleTimezone?: string;
sortOrder?: number;
@@ -93,6 +95,7 @@ export class TaskService {
private agentModel: AgentModel;
private db: LobeChatDatabase;
private taskModel: TaskModel;
+ private projectModel: ProjectModel;
private taskTopicModel: TaskTopicModel;
private topicModel: TopicModel;
private userId: string;
@@ -104,6 +107,7 @@ export class TaskService {
this.userId = userId;
this.workspaceId = workspaceId;
this.agentModel = new AgentModel(db, userId, workspaceId);
+ this.projectModel = new ProjectModel(db, userId, workspaceId);
this.taskModel = new TaskModel(db, userId, workspaceId);
this.taskTopicModel = new TaskTopicModel(db, userId, workspaceId);
this.topicModel = new TopicModel(db, userId, workspaceId);
@@ -125,6 +129,20 @@ export class TaskService {
const parent = await this.resolveOrThrow(createData.parentTaskId);
createData.parentTaskId = parent.id;
parentVisibility = parent.visibility;
+ if (createData.projectId && createData.projectId !== parent.projectId) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Subtask must belong to the same project as its parent',
+ });
+ }
+ createData.projectId ??= parent.projectId ?? undefined;
+ }
+
+ if (
+ createData.projectId &&
+ !(await this.projectModel.findManageableById(createData.projectId))
+ ) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Project not found' });
}
// Pull the model/provider snapshot and the agent's visibility in a single
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts b/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts
index 418af9031ff..da37b70a109 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts
@@ -4,6 +4,7 @@ import { KnowledgeBaseExecutionRuntime } from '@lobechat/builtin-tool-knowledge-
import { AgentModel } from '@/database/models/agent';
import { FileModel } from '@/database/models/file';
import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';
+import { ProjectModel } from '@/database/models/project';
import { KnowledgeRepo } from '@/database/repositories/knowledge';
import { DocumentService } from '@/server/services/document';
import { FileService } from '@/server/services/file';
@@ -13,13 +14,14 @@ import { type ServerRuntimeRegistration } from './types';
export const knowledgeBaseRuntime: ServerRuntimeRegistration = {
factory: (context) => {
- const { userId, serverDB, agentId, agentVisibility, workspaceId } = context;
+ const { userId, serverDB, agentId, agentVisibility, taskId, workspaceId } = context;
if (!userId || !serverDB) {
throw new Error('userId and serverDB are required for Knowledge Base execution');
}
const fileModel = new FileModel(serverDB, userId, workspaceId);
const knowledgeBaseModel = new KnowledgeBaseModel(serverDB, userId, workspaceId);
+ const projectModel = new ProjectModel(serverDB, userId, workspaceId);
const knowledgeRepo = new KnowledgeRepo(serverDB, userId, workspaceId);
const documentService = new DocumentService(serverDB, userId, workspaceId, agentVisibility);
const fileService = new FileService(serverDB, userId, workspaceId);
@@ -32,10 +34,17 @@ export const knowledgeBaseRuntime: ServerRuntimeRegistration = {
const agentModel = agentId ? new AgentModel(serverDB, userId, workspaceId) : null;
const resolveAgentKnowledgeBaseIds = async (override?: string[]): Promise<string[]> => {
- if (override && override.length > 0) return override;
- if (!agentModel || !agentId) return [];
- const knowledge = await agentModel.getAgentAssignedKnowledge(agentId);
- return knowledge.knowledgeBases.filter((k) => k.enabled && k.id).map((k) => k.id as string);
+ const agentKnowledgeBaseIds = async () => {
+ if (override && override.length > 0) return override;
+ if (!agentModel || !agentId) return [];
+ const knowledge = await agentModel.getAgentAssignedKnowledge(agentId);
+ return knowledge.knowledgeBases.filter((k) => k.enabled && k.id).map((k) => k.id as string);
+ };
+ const [agentIds, projectIds] = await Promise.all([
+ agentKnowledgeBaseIds(),
+ taskId ? projectModel.getEnabledKnowledgeBaseIdsForTask(taskId) : Promise.resolve([]),
+ ]);
+ return [...new Set([...agentIds, ...projectIds])];
};
return new KnowledgeBaseExecutionRuntime(
diff --git a/packages/database/src/models/__tests__/project.test.ts b/packages/database/src/models/__tests__/project.test.ts
new file mode 100644
index 00000000000..089d0b954fc
--- /dev/null
+++ b/packages/database/src/models/__tests__/project.test.ts
@@ -0,0 +1,331 @@
+import { and, eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import {
+ agents,
+ knowledgeBases,
+ projectCompletionReviews,
+ projects,
+ tasks,
+ users,
+ workspaces,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { ProjectModel } from '../project';
+import { TaskModel } from '../task';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+const userId = 'project-model-user';
+const otherUserId = 'project-model-other-user';
+
+describe('ProjectModel', () => {
+ const model = new ProjectModel(serverDB, userId);
+ const otherModel = new ProjectModel(serverDB, otherUserId);
+
+ beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ });
+
+ afterEach(async () => {
+ vi.restoreAllMocks();
+ await serverDB.delete(users);
+ });
+
+ it('creates, lists, updates, and deletes a project in the owner scope', async () => {
+ const project = await model.create({ description: 'A large effort', name: 'Apollo' });
+ expect(project.status).toBe('backlog');
+ expect(await model.list()).toEqual([expect.objectContaining({ id: project.id })]);
+
+ const updated = await model.update(project.id, { name: 'Apollo 2' });
+ expect(updated?.name).toBe('Apollo 2');
+ expect(await model.delete(project.id)).toEqual(expect.objectContaining({ id: project.id }));
+ expect(await model.findById(project.id)).toBeNull();
+ });
+
+ it('filters and paginates projects', async () => {
+ await model.create({ name: 'Backlog' });
+ const active = await model.create({ name: 'Active' });
+ await model.updateStatus(active.id, 'active');
+
+ expect(await model.list({ limit: 1, offset: 0, statuses: ['active'] })).toEqual([
+ expect.objectContaining({ id: active.id }),
+ ]);
+ expect(await model.list({ statuses: [] })).toHaveLength(2);
+ expect(await model.list({ limit: 1, offset: 1 })).toHaveLength(1);
+ });
+
+ it('does not expose or mutate another user project in personal mode', async () => {
+ const project = await otherModel.create({ 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();
+ expect(await model.findManageableById(project.id)).toBeNull();
+ });
+
+ it('applies public and private visibility in workspace mode', async () => {
+ await serverDB.insert(workspaces).values({
+ id: 'project-workspace',
+ name: 'Project Workspace',
+ primaryOwnerId: userId,
+ slug: 'project-workspace',
+ });
+ const owner = new ProjectModel(serverDB, userId, 'project-workspace');
+ const member = new ProjectModel(serverDB, otherUserId, 'project-workspace');
+ const publicProject = await owner.create({ name: 'Public' });
+ const privateProject = await owner.create({ name: 'Private', visibility: 'private' });
+
+ expect(await member.findById(publicProject.id)).toEqual(
+ expect.objectContaining({ id: publicProject.id }),
+ );
+ expect(await member.findById(privateProject.id)).toBeNull();
+ expect(await member.update(publicProject.id, { name: 'Nope' })).toBeNull();
+ });
+
+ it('binds only accessible agents and knowledge bases', async () => {
+ const project = await model.create({ name: 'Bindings' });
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({ title: 'Researcher', userId })
+ .returning();
+ const [knowledgeBase] = await serverDB
+ .insert(knowledgeBases)
+ .values({ name: 'Research', userId })
+ .returning();
+ const [foreignAgent] = await serverDB
+ .insert(agents)
+ .values({ title: 'Foreign', userId: otherUserId })
+ .returning();
+
+ await model.addAgent(project.id, { agentId: agent.id, role: 'lead' });
+ await model.addKnowledgeBase(project.id, { knowledgeBaseId: knowledgeBase.id });
+ await model.addAgent(project.id, { agentId: agent.id, enabled: false, role: 'reviewer' });
+ await model.addKnowledgeBase(project.id, {
+ enabled: false,
+ knowledgeBaseId: knowledgeBase.id,
+ sortOrder: 2,
+ });
+ const task = await new TaskModel(serverDB, userId).create({
+ instruction: 'Use project knowledge',
+ projectId: project.id,
+ });
+ expect(await model.listAgents(project.id)).toEqual([
+ expect.objectContaining({ binding: expect.objectContaining({ role: 'reviewer' }) }),
+ ]);
+ expect(await model.listKnowledgeBases(project.id)).toHaveLength(1);
+ expect(await model.getEnabledKnowledgeBaseIdsForTask(task.id)).toEqual([]);
+ await model.addKnowledgeBase(project.id, { enabled: true, knowledgeBaseId: knowledgeBase.id });
+ expect(await model.getEnabledKnowledgeBaseIdsForTask(task.id)).toEqual([knowledgeBase.id]);
+ await expect(model.addAgent(project.id, { agentId: foreignAgent.id })).rejects.toThrow(
+ 'Agent not found',
+ );
+
+ expect(await model.removeAgent(project.id, agent.id)).toBe(true);
+ expect(await model.removeKnowledgeBase(project.id, knowledgeBase.id)).toBe(true);
+ expect(await model.removeAgent(project.id, agent.id)).toBe(false);
+ expect(await model.removeKnowledgeBase(project.id, knowledgeBase.id)).toBe(false);
+ });
+
+ it('returns null or false for binding operations on inaccessible projects and resources', async () => {
+ const foreignProject = await otherModel.create({ name: 'Foreign' });
+ const [foreignKnowledgeBase] = await serverDB
+ .insert(knowledgeBases)
+ .values({ name: 'Foreign KB', userId: otherUserId })
+ .returning();
+
+ expect(await model.listAgents(foreignProject.id)).toBeNull();
+ expect(await model.listKnowledgeBases(foreignProject.id)).toBeNull();
+ expect(await model.listTasks(foreignProject.id)).toBeNull();
+ expect(await model.listCompletionReviews(foreignProject.id)).toBeNull();
+ expect(await model.addAgent(foreignProject.id, { agentId: 'missing' })).toBeNull();
+ expect(
+ await model.addKnowledgeBase(foreignProject.id, { knowledgeBaseId: foreignKnowledgeBase.id }),
+ ).toBeNull();
+ expect(await model.removeAgent(foreignProject.id, 'missing')).toBe(false);
+ expect(await model.removeKnowledgeBase(foreignProject.id, foreignKnowledgeBase.id)).toBe(false);
+
+ const project = await model.create({ name: 'Local' });
+ await expect(
+ model.addKnowledgeBase(project.id, { knowledgeBaseId: foreignKnowledgeBase.id }),
+ ).rejects.toThrow('Knowledge base not found');
+ });
+
+ it('moves a task subtree into a project', async () => {
+ const project = await model.create({ name: 'Tasks' });
+ const taskModel = new TaskModel(serverDB, userId);
+ const parent = await taskModel.create({ instruction: 'Parent' });
+ const child = await taskModel.create({ instruction: 'Child', parentTaskId: parent.id });
+
+ const moved = await model.moveTaskTree(project.id, parent.id);
+ expect(moved?.map(({ id }) => id).sort()).toEqual([child.id, parent.id].sort());
+ const projectTasks = await model.listTasks(project.id);
+ expect(projectTasks?.map(({ id }) => id).sort()).toEqual([child.id, parent.id].sort());
+ });
+
+ it('preserves project tree boundaries when moving tasks', async () => {
+ const source = await model.create({ name: 'Source' });
+ const target = await model.create({ name: 'Target' });
+ const taskModel = new TaskModel(serverDB, userId);
+ const parent = await taskModel.create({ instruction: 'Parent', projectId: source.id });
+ const child = await taskModel.create({
+ instruction: 'Child',
+ parentTaskId: parent.id,
+ projectId: source.id,
+ });
+
+ await expect(model.moveTaskTree(target.id, child.id)).rejects.toThrow(
+ 'Cannot move a task away from its parent project',
+ );
+ await serverDB.update(tasks).set({ projectId: target.id }).where(eq(tasks.id, parent.id));
+ expect(await model.moveTaskTree(target.id, child.id)).toEqual([
+ expect.objectContaining({ id: child.id }),
+ ]);
+ await expect(model.moveTaskTree(target.id, 'missing')).rejects.toThrow('Task not found');
+ expect(await model.moveTaskTree('missing', child.id)).toBeNull();
+ });
+
+ it('rejects moving a workspace task tree with descendants created by another member', async () => {
+ await serverDB.insert(workspaces).values({
+ id: 'mixed-tree-workspace',
+ name: 'Mixed Tree',
+ primaryOwnerId: userId,
+ slug: 'mixed-tree-workspace',
+ });
+ const workspaceModel = new ProjectModel(serverDB, userId, 'mixed-tree-workspace');
+ const ownerTasks = new TaskModel(serverDB, userId, 'mixed-tree-workspace');
+ const memberTasks = new TaskModel(serverDB, otherUserId, 'mixed-tree-workspace');
+ const project = await workspaceModel.create({ name: 'Target' });
+ const parent = await ownerTasks.create({ instruction: 'Parent' });
+ await memberTasks.create({
+ instruction: 'Member child',
+ parentTaskId: parent.id,
+ visibility: 'private',
+ });
+
+ await expect(workspaceModel.moveTaskTree(project.id, parent.id)).rejects.toThrow(
+ 'Cannot move a task tree containing tasks created by another user',
+ );
+ });
+
+ it('enforces project boundaries in the shared dependency model path', async () => {
+ const firstProject = await model.create({ name: 'First' });
+ const secondProject = await model.create({ 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 });
+
+ await expect(taskModel.addDependency(first.id, second.id)).rejects.toThrow(
+ 'Task dependencies cannot cross project boundaries',
+ );
+ await expect(taskModel.addDependency(first.id, 'missing')).rejects.toThrow('Task not found');
+ });
+
+ it('requires review state and records immutable human completion decisions', async () => {
+ const project = await model.create({ name: 'Reviewed' });
+ await model.updateStatus(project.id, 'active');
+ await model.requestCompletion(project.id);
+
+ const rejected = await model.reviewCompletion(project.id, 'rejected', 'Needs evidence');
+ expect(rejected?.project.status).toBe('active');
+ expect(rejected?.review.round).toBe(1);
+
+ await model.requestCompletion(project.id);
+ const accepted = await model.reviewCompletion(project.id, 'accepted', 'Approved');
+ expect(accepted?.project.status).toBe('completed');
+ expect(accepted?.project.completedReviewId).toBe(accepted?.review.id);
+ expect(accepted?.review.round).toBe(2);
+
+ const reviews = await model.listCompletionReviews(project.id);
+ expect(reviews?.map(({ decision }) => decision)).toEqual(['accepted', 'rejected']);
+ expect(
+ await serverDB
+ .select()
+ .from(projectCompletionReviews)
+ .where(
+ and(
+ eq(projectCompletionReviews.projectId, project.id),
+ eq(projectCompletionReviews.reviewerUserId, userId),
+ ),
+ ),
+ ).toHaveLength(2);
+
+ const reopened = await model.reopen(project.id);
+ expect(reopened).toEqual(
+ expect.objectContaining({ completedAt: null, completedReviewId: null, status: 'active' }),
+ );
+ });
+
+ it('requires reopen for completed projects even after archival', async () => {
+ const project = await model.create({ name: 'Archived completion' });
+ await model.updateStatus(project.id, 'active');
+ await model.requestCompletion(project.id);
+ await model.reviewCompletion(project.id, 'accepted');
+ await model.updateStatus(project.id, 'archived');
+
+ await expect(model.updateStatus(project.id, 'active')).rejects.toThrow(
+ 'An archived completed project must be reopened',
+ );
+ expect(await model.reopen(project.id)).toEqual(
+ expect.objectContaining({ completedReviewId: null, status: 'active' }),
+ );
+ });
+
+ it('covers lifecycle guards and missing review targets', async () => {
+ const project = await model.create({ 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',
+ );
+ await expect(model.updateStatus(project.id, 'reviewing')).rejects.toThrow(
+ 'Completion states must be changed through the review workflow',
+ );
+ await model.updateStatus(project.id, 'active');
+ const startedAt = (await model.findById(project.id))?.startedAt;
+ await model.updateStatus(project.id, 'paused');
+ await model.updateStatus(project.id, 'active');
+ expect((await model.findById(project.id))?.startedAt).toEqual(startedAt);
+ await model.requestCompletion(project.id);
+ await expect(model.updateStatus(project.id, 'paused')).rejects.toThrow(
+ 'A project awaiting review must be accepted or rejected',
+ );
+ await expect(model.reviewCompletion('missing', 'accepted')).resolves.toBeNull();
+ await expect(model.reviewCompletion(project.id, 'rejected')).resolves.toEqual(
+ expect.objectContaining({ project: expect.objectContaining({ status: 'active' }) }),
+ );
+ await expect(model.reviewCompletion(project.id, 'accepted')).rejects.toThrow(
+ 'Project is not awaiting review',
+ );
+ expect(await model.reopen(project.id)).toBeNull();
+ });
+
+ it('handles completed transitions and a concurrent deletion during status update', async () => {
+ const completed = await model.create({ name: 'Completed' });
+ await model.updateStatus(completed.id, 'active');
+ await model.requestCompletion(completed.id);
+ await model.reviewCompletion(completed.id, 'accepted');
+ await expect(model.updateStatus(completed.id, 'active')).rejects.toThrow(
+ 'A completed project must be reopened',
+ );
+
+ const disappearing = await model.create({ 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);
+ expect(await model.updateStatus(disappearing.id, 'active')).toBeNull();
+ });
+
+ it('rejects completion requests from invalid states', async () => {
+ const project = await model.create({ name: 'Backlog' });
+ await expect(model.requestCompletion(project.id)).rejects.toThrow(
+ 'Only active or paused projects can request completion',
+ );
+ expect(await serverDB.select().from(tasks).where(eq(tasks.projectId, project.id))).toEqual([]);
+ expect(await model.requestCompletion('missing')).toBeNull();
+ expect(await model.getEnabledKnowledgeBaseIdsForTask('missing')).toEqual([]);
+ const standaloneTask = await new TaskModel(serverDB, userId).create({
+ instruction: 'Standalone',
+ });
+ expect(await model.getEnabledKnowledgeBaseIdsForTask(standaloneTask.id)).toEqual([]);
+ });
+});
diff --git a/packages/database/src/models/project.ts b/packages/database/src/models/project.ts
new file mode 100644
index 00000000000..52f70caf0ee
--- /dev/null
+++ b/packages/database/src/models/project.ts
@@ -0,0 +1,483 @@
+import type { ProjectStatus, ProjectVisibility } from '@lobechat/types';
+import { and, asc, desc, eq, inArray, isNull, max, sql } from 'drizzle-orm';
+
+import { agents } from '../schemas/agent';
+import { knowledgeBases } from '../schemas/file';
+import {
+ projectAgents,
+ projectCompletionReviews,
+ projectKnowledgeBases,
+ projects,
+} from '../schemas/project';
+import { tasks } from '../schemas/task';
+import type { LobeChatDatabase } from '../type';
+import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
+
+export interface CreateProjectInput {
+ avatar?: string;
+ description?: string;
+ name: string;
+ slug?: string;
+ visibility?: ProjectVisibility;
+}
+
+export interface UpdateProjectInput {
+ avatar?: string | null;
+ description?: string | null;
+ name?: string;
+ slug?: string | null;
+ visibility?: ProjectVisibility;
+}
+
+export interface ProjectAgentInput {
+ agentId: string;
+ enabled?: boolean;
+ responsibility?: string | null;
+ role?: string | null;
+ sortOrder?: number;
+}
+
+export interface ProjectKnowledgeBaseInput {
+ enabled?: boolean;
+ knowledgeBaseId: string;
+ sortOrder?: number;
+}
+
+export class ProjectModel {
+ constructor(
+ private readonly db: LobeChatDatabase,
+ private readonly userId: string,
+ private readonly workspaceId?: string,
+ ) {}
+
+ private readable() {
+ return buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, projects);
+ }
+
+ private manageable() {
+ return and(this.readable(), eq(projects.userId, this.userId));
+ }
+
+ async create(input: CreateProjectInput) {
+ const [project] = await this.db
+ .insert(projects)
+ .values(buildWorkspacePayload({ userId: this.userId, workspaceId: this.workspaceId }, input))
+ .returning();
+ return project;
+ }
+
+ async delete(id: string) {
+ const [deleted] = await this.db
+ .delete(projects)
+ .where(and(eq(projects.id, id), this.manageable()))
+ .returning();
+ return deleted ?? null;
+ }
+
+ async findById(id: string) {
+ const [project] = await this.db
+ .select()
+ .from(projects)
+ .where(and(eq(projects.id, id), this.readable()))
+ .limit(1);
+ return project ?? null;
+ }
+
+ async list(options: { limit?: number; offset?: number; statuses?: ProjectStatus[] } = {}) {
+ const { limit = 50, offset = 0, statuses } = options;
+ const statusWhere = statuses?.length ? inArray(projects.status, statuses) : undefined;
+ return this.db
+ .select()
+ .from(projects)
+ .where(and(this.readable(), statusWhere))
+ .orderBy(desc(projects.updatedAt))
+ .limit(limit)
+ .offset(offset);
+ }
+
+ async update(id: string, input: UpdateProjectInput) {
+ const [project] = await this.db
+ .update(projects)
+ .set({ ...input, updatedAt: new Date() })
+ .where(and(eq(projects.id, id), this.manageable()))
+ .returning();
+ return project ?? null;
+ }
+
+ async updateStatus(id: string, status: ProjectStatus) {
+ if (status === 'completed' || status === 'reviewing') {
+ throw new Error('Completion states must be changed through the review workflow');
+ }
+ const project = await this.findManageableById(id);
+ if (!project) return null;
+ if (project.status === 'reviewing') {
+ throw new Error('A project awaiting review must be accepted or rejected');
+ }
+ if (project.status === 'completed' && status !== 'archived') {
+ throw new Error('A completed project must be reopened before changing status');
+ }
+ if (project.completedReviewId && status !== 'archived') {
+ throw new Error('An archived completed project must be reopened before changing status');
+ }
+ return this.setStatus(id, status, project.startedAt);
+ }
+
+ private async setStatus(id: string, status: ProjectStatus, startedAt?: Date | null) {
+ const now = new Date();
+ const timestamps = {
+ ...(status === 'active' ? { startedAt: startedAt ?? now } : {}),
+ ...(status === 'archived' ? { archivedAt: now } : {}),
+ ...(status !== 'archived' ? { archivedAt: null } : {}),
+ updatedAt: now,
+ };
+ const [project] = await this.db
+ .update(projects)
+ .set({ ...timestamps, status })
+ .where(and(eq(projects.id, id), this.manageable()))
+ .returning();
+ return project ?? null;
+ }
+
+ async listAgents(projectId: string) {
+ if (!(await this.findById(projectId))) return null;
+ return this.db
+ .select({ agent: agents, binding: projectAgents })
+ .from(projectAgents)
+ .innerJoin(agents, eq(projectAgents.agentId, agents.id))
+ .where(
+ and(
+ eq(projectAgents.projectId, projectId),
+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, agents),
+ ),
+ )
+ .orderBy(asc(projectAgents.sortOrder), asc(projectAgents.createdAt));
+ }
+
+ async addAgent(projectId: string, input: ProjectAgentInput) {
+ if (!(await this.findManageableById(projectId))) return null;
+ const [agent] = await this.db
+ .select({ id: agents.id })
+ .from(agents)
+ .where(
+ and(
+ eq(agents.id, input.agentId),
+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, agents),
+ ),
+ )
+ .limit(1);
+ if (!agent) throw new Error('Agent not found');
+
+ const [binding] = await this.db
+ .insert(projectAgents)
+ .values({
+ ...input,
+ addedByUserId: this.userId,
+ projectId,
+ workspaceId: this.workspaceId ?? null,
+ })
+ .onConflictDoUpdate({
+ set: {
+ enabled: input.enabled,
+ responsibility: input.responsibility,
+ role: input.role,
+ sortOrder: input.sortOrder,
+ updatedAt: new Date(),
+ },
+ target: [projectAgents.projectId, projectAgents.agentId],
+ })
+ .returning();
+ return binding;
+ }
+
+ async removeAgent(projectId: string, agentId: string) {
+ if (!(await this.findManageableById(projectId))) return false;
+ const deleted = await this.db
+ .delete(projectAgents)
+ .where(and(eq(projectAgents.projectId, projectId), eq(projectAgents.agentId, agentId)))
+ .returning({ id: projectAgents.id });
+ return deleted.length > 0;
+ }
+
+ async listKnowledgeBases(projectId: string) {
+ if (!(await this.findById(projectId))) return null;
+ return this.db
+ .select({ binding: projectKnowledgeBases, knowledgeBase: knowledgeBases })
+ .from(projectKnowledgeBases)
+ .innerJoin(knowledgeBases, eq(projectKnowledgeBases.knowledgeBaseId, knowledgeBases.id))
+ .where(
+ and(
+ eq(projectKnowledgeBases.projectId, projectId),
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ knowledgeBases,
+ ),
+ ),
+ )
+ .orderBy(asc(projectKnowledgeBases.sortOrder), asc(projectKnowledgeBases.createdAt));
+ }
+
+ async addKnowledgeBase(projectId: string, input: ProjectKnowledgeBaseInput) {
+ if (!(await this.findManageableById(projectId))) return null;
+ const [knowledgeBase] = await this.db
+ .select({ id: knowledgeBases.id })
+ .from(knowledgeBases)
+ .where(
+ and(
+ eq(knowledgeBases.id, input.knowledgeBaseId),
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ knowledgeBases,
+ ),
+ ),
+ )
+ .limit(1);
+ if (!knowledgeBase) throw new Error('Knowledge base not found');
+
+ const [binding] = await this.db
+ .insert(projectKnowledgeBases)
+ .values({
+ ...input,
+ addedByUserId: this.userId,
+ projectId,
+ workspaceId: this.workspaceId ?? null,
+ })
+ .onConflictDoUpdate({
+ set: { enabled: input.enabled, sortOrder: input.sortOrder, updatedAt: new Date() },
+ target: [projectKnowledgeBases.projectId, projectKnowledgeBases.knowledgeBaseId],
+ })
+ .returning();
+ return binding;
+ }
+
+ async removeKnowledgeBase(projectId: string, knowledgeBaseId: string) {
+ if (!(await this.findManageableById(projectId))) return false;
+ const deleted = await this.db
+ .delete(projectKnowledgeBases)
+ .where(
+ and(
+ eq(projectKnowledgeBases.projectId, projectId),
+ eq(projectKnowledgeBases.knowledgeBaseId, knowledgeBaseId),
+ ),
+ )
+ .returning({ id: projectKnowledgeBases.id });
+ return deleted.length > 0;
+ }
+
+ async listTasks(projectId: string) {
+ if (!(await this.findById(projectId))) return null;
+ return this.db
+ .select()
+ .from(tasks)
+ .where(
+ and(
+ eq(tasks.projectId, projectId),
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ {
+ userId: tasks.createdByUserId,
+ visibility: tasks.visibility,
+ workspaceId: tasks.workspaceId,
+ },
+ ),
+ ),
+ )
+ .orderBy(asc(tasks.sortOrder), asc(tasks.seq));
+ }
+
+ async getEnabledKnowledgeBaseIdsForTask(taskId: string) {
+ const [task] = await this.db
+ .select({ projectId: tasks.projectId })
+ .from(tasks)
+ .where(
+ and(
+ eq(tasks.id, taskId),
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ {
+ userId: tasks.createdByUserId,
+ visibility: tasks.visibility,
+ workspaceId: tasks.workspaceId,
+ },
+ ),
+ ),
+ )
+ .limit(1);
+ if (!task?.projectId || !(await this.findById(task.projectId))) return [];
+
+ const rows = await this.db
+ .select({ id: projectKnowledgeBases.knowledgeBaseId })
+ .from(projectKnowledgeBases)
+ .innerJoin(knowledgeBases, eq(projectKnowledgeBases.knowledgeBaseId, knowledgeBases.id))
+ .where(
+ and(
+ eq(projectKnowledgeBases.projectId, task.projectId),
+ eq(projectKnowledgeBases.enabled, true),
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ knowledgeBases,
+ ),
+ ),
+ );
+ return rows.map(({ id }) => id);
+ }
+
+ async moveTaskTree(projectId: string, taskId: string) {
+ if (!(await this.findManageableById(projectId))) return null;
+ const taskScope = buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ {
+ userId: tasks.createdByUserId,
+ visibility: tasks.visibility,
+ workspaceId: tasks.workspaceId,
+ },
+ );
+ const [root] = await this.db
+ .select()
+ .from(tasks)
+ .where(and(eq(tasks.id, taskId), taskScope, eq(tasks.createdByUserId, this.userId)))
+ .limit(1);
+ if (!root) throw new Error('Task not found');
+ if (root.parentTaskId) {
+ const [parent] = await this.db
+ .select({ projectId: tasks.projectId })
+ .from(tasks)
+ .where(and(eq(tasks.id, root.parentTaskId), taskScope))
+ .limit(1);
+ if (parent?.projectId !== projectId) {
+ throw new Error('Cannot move a task away from its parent project');
+ }
+ }
+
+ // Visibility must not hide private descendants here: moving the visible
+ // parent while leaving an unseen child behind would split one tree across
+ // projects. The creator check below still rejects any row not owned by the
+ // caller before the update runs.
+ const treeScope = this.workspaceId
+ ? eq(tasks.workspaceId, this.workspaceId)
+ : and(eq(tasks.createdByUserId, this.userId), isNull(tasks.workspaceId));
+ const descendants = await this.db.execute<{ created_by_user_id: string }>(sql`
+ WITH RECURSIVE task_tree AS (
+ SELECT ${tasks.id}, ${tasks.createdByUserId}
+ FROM ${tasks}
+ WHERE ${tasks.id} = ${root.id} AND ${treeScope}
+ UNION ALL
+ SELECT ${tasks.id}, ${tasks.createdByUserId}
+ FROM ${tasks}
+ JOIN task_tree parent ON ${tasks.parentTaskId} = parent.id
+ WHERE ${treeScope}
+ )
+ SELECT created_by_user_id FROM task_tree
+ `);
+ if (descendants.rows.some(({ created_by_user_id }) => created_by_user_id !== this.userId)) {
+ throw new Error('Cannot move a task tree containing tasks created by another user');
+ }
+
+ const { rows } = await this.db.execute<{ id: string }>(sql`
+ WITH RECURSIVE task_tree AS (
+ SELECT ${tasks.id}
+ FROM ${tasks}
+ WHERE ${tasks.id} = ${root.id} AND ${taskScope}
+ AND ${tasks.createdByUserId} = ${this.userId}
+ UNION ALL
+ SELECT ${tasks.id}
+ FROM ${tasks}
+ JOIN task_tree parent ON ${tasks.parentTaskId} = parent.id
+ WHERE ${taskScope} AND ${tasks.createdByUserId} = ${this.userId}
+ )
+ UPDATE ${tasks}
+ SET ${sql.identifier(tasks.projectId.name)} = ${projectId},
+ ${sql.identifier(tasks.updatedAt.name)} = NOW()
+ WHERE ${tasks.id} IN (SELECT id FROM task_tree)
+ RETURNING ${tasks.id}
+ `);
+ return rows;
+ }
+
+ async requestCompletion(id: string) {
+ const project = await this.findManageableById(id);
+ if (!project) return null;
+ if (!['active', 'paused'].includes(project.status)) {
+ throw new Error('Only active or paused projects can request completion');
+ }
+ return this.setStatus(id, 'reviewing', project.startedAt);
+ }
+
+ async reviewCompletion(id: string, decision: 'accepted' | 'rejected', comment?: string) {
+ return this.db.transaction(async (tx) => {
+ const [project] = await tx
+ .select()
+ .from(projects)
+ .where(and(eq(projects.id, id), this.manageable()))
+ .for('update')
+ .limit(1);
+ if (!project) return null;
+ if (project.status !== 'reviewing') throw new Error('Project is not awaiting review');
+
+ const [{ value: lastRound }] = await tx
+ .select({ value: max(projectCompletionReviews.round) })
+ .from(projectCompletionReviews)
+ .where(eq(projectCompletionReviews.projectId, id));
+ const [review] = await tx
+ .insert(projectCompletionReviews)
+ .values({
+ comment,
+ decision,
+ projectId: id,
+ reviewerUserId: this.userId,
+ round: (lastRound ?? 0) + 1,
+ workspaceId: this.workspaceId ?? null,
+ })
+ .returning();
+ const now = new Date();
+ const [updated] = await tx
+ .update(projects)
+ .set(
+ decision === 'accepted'
+ ? {
+ completedAt: now,
+ completedReviewId: review.id,
+ status: 'completed',
+ updatedAt: now,
+ }
+ : { completedAt: null, completedReviewId: null, status: 'active', updatedAt: now },
+ )
+ .where(eq(projects.id, id))
+ .returning();
+ return { project: updated, review };
+ });
+ }
+
+ async listCompletionReviews(projectId: string) {
+ if (!(await this.findById(projectId))) return null;
+ return this.db
+ .select()
+ .from(projectCompletionReviews)
+ .where(eq(projectCompletionReviews.projectId, projectId))
+ .orderBy(desc(projectCompletionReviews.round));
+ }
+
+ async reopen(id: string) {
+ const [project] = await this.db
+ .update(projects)
+ .set({ completedAt: null, completedReviewId: null, status: 'active', updatedAt: new Date() })
+ .where(
+ and(
+ eq(projects.id, id),
+ inArray(projects.status, ['completed', 'archived']),
+ sql`${projects.completedReviewId} IS NOT NULL`,
+ this.manageable(),
+ ),
+ )
+ .returning();
+ return project ?? null;
+ }
+
+ async findManageableById(id: string) {
+ const [project] = await this.db
+ .select()
+ .from(projects)
+ .where(and(eq(projects.id, id), this.manageable()))
+ .limit(1);
+ return project ?? null;
+ }
+}
diff --git a/packages/database/src/models/task.ts b/packages/database/src/models/task.ts
index e88f07bb5e9..661e7e5582e 100644
--- a/packages/database/src/models/task.ts
+++ b/packages/database/src/models/task.ts
@@ -922,6 +922,14 @@ export class TaskModel {
});
async addDependency(taskId: string, dependsOnId: string, type: string = 'blocks'): Promise<void> {
+ const dependencyTasks = await this.findByIds([taskId, dependsOnId]);
+ const task = dependencyTasks.find(({ id }) => id === taskId);
+ const dependsOn = dependencyTasks.find(({ id }) => id === dependsOnId);
+ if (!task || !dependsOn) throw new Error('Task not found');
+ if (task.projectId !== dependsOn.projectId && (task.projectId || dependsOn.projectId)) {
+ throw new Error('Task dependencies cannot cross project boundaries');
+ }
+
const visibility = await this.getTaskVisibility(taskId);
await this.db
.insert(taskDependencies)
diff --git a/packages/types/src/project/index.ts b/packages/types/src/project/index.ts
index 483b92dba7a..43f2961d972 100644
--- a/packages/types/src/project/index.ts
+++ b/packages/types/src/project/index.ts
@@ -2,6 +2,7 @@ export const PROJECT_STATUSES = [
'backlog',
'active',
'paused',
+ 'reviewing',
'completed',
'canceled',
'archived',
diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.ts
index 6d7ee8566ab..7a85450c352 100644
--- a/packages/types/src/task/index.ts
+++ b/packages/types/src/task/index.ts
@@ -264,6 +264,7 @@ export interface TaskItem {
name: string | null;
parentTaskId: string | null;
priority: number | null;
+ projectId: string | null;
schedulePattern: string | null;
scheduleTimezone: string | null;
seq: number;
@@ -308,6 +309,7 @@ export interface NewTask {
name?: string | null;
parentTaskId?: string | null;
priority?: number | null;
+ projectId?: string | null;
schedulePattern?: string | null;
scheduleTimezone?: string | null;
seq: number;