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: add project workspaces and conversation PoC (#18020)

Arvin Xuc4cbc34db6f8
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.md
index 725161fc692..26f29ae0cf0 100644
--- a/.agents/acceptance/common-mistakes.md
+++ b/.agents/acceptance/common-mistakes.md
@@ -537,6 +537,20 @@ to the code. Never attribute it to the change under test without that A/B — an
note that `electron-dev.sh start` reports "Ready" even when the renderer never
became interactive, so its own readiness line is not the gate.
+### L-P1 — A Project conversation must preserve Project identity across routing and history
+
+**Wrong approach:** implement Project chat by navigating users to the Project coordinator's
+ordinary `/agent/:agentId/:topicId` surface and present that Agent's topic list as the Project
+history.
+
+**Why it fails:** the coordinator is an implementation detail. Leaving the Project route changes
+the visible owner and navigation contract, so users reasonably read the conversation as belonging
+to an Agent rather than to the Project that provides its tasks, goals, resources, and history.
+
+**Correct approach:** keep creation, topic selection, and resumed conversations under the Project
+route and Project sidebar. The coordinator may still execute the conversation internally, but the
+visible URL, active list, empty state, and navigation must consistently identify the Project.
+
## Historical source
Detailed incident narratives and retired pixel- or component-specific directions
diff --git a/apps/server/src/routers/lambda/task.ts b/apps/server/src/routers/lambda/task.ts
index 4cb6f4e20e3..12b52ad0fc8 100644
--- a/apps/server/src/routers/lambda/task.ts
+++ b/apps/server/src/routers/lambda/task.ts
@@ -117,6 +117,7 @@ const listSchema = z.object({
parentIdentifier: z.string().optional(),
parentTaskId: z.string().nullish(),
priorities: z.array(z.number().min(0).max(4)).max(5).optional(),
+ projectId: z.string().optional(),
statuses: z.array(z.enum(TASK_STATUSES)).max(10).optional(),
// UI-side narrowing of the result set. Omitted means "All" (the chip's
// default 'private' is enforced client-side; the server stays permissive
@@ -139,6 +140,7 @@ const groupListSchema = z.object({
.max(10),
hasGoal: z.boolean().optional(),
parentTaskId: z.string().nullish(),
+ projectId: z.string().optional(),
visibility: z.enum(['private', 'public']).optional(),
});
diff --git a/apps/server/src/routers/lambda/work.ts b/apps/server/src/routers/lambda/work.ts
index ea0c096adae..ba88fcf8029 100644
--- a/apps/server/src/routers/lambda/work.ts
+++ b/apps/server/src/routers/lambda/work.ts
@@ -123,6 +123,7 @@ export const workRouter = router({
cursor: z.string().nullable().optional(),
includeFileWorks: z.boolean().optional(),
limit: z.number().min(1).max(100).default(30),
+ originAgentId: z.string().nullable().optional(),
provider: z.enum(WORK_SKILL_PROVIDERS).optional(),
type: z.enum(['task', 'document', 'external', 'file']).nullable().optional(),
}),
diff --git a/apps/server/src/services/task/index.ts b/apps/server/src/services/task/index.ts
index a9adbba8f70..ec32f77d9be 100644
--- a/apps/server/src/services/task/index.ts
+++ b/apps/server/src/services/task/index.ts
@@ -139,11 +139,10 @@ export class TaskService {
createData.projectId ??= parent.projectId ?? undefined;
}
- if (
- createData.projectId &&
- !(await this.projectModel.findManageableById(createData.projectId))
- ) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Project not found' });
+ if (createData.projectId) {
+ const project = await this.projectModel.findManageableById(createData.projectId);
+ if (!project) throw new TRPCError({ code: 'NOT_FOUND', message: 'Project not found' });
+ createData.identifierPrefix ??= project.identifier;
}
// Pull the model/provider snapshot and the agent's visibility in a single
diff --git a/locales/en-US/labs.json b/locales/en-US/labs.json
index 90f923ca6a8..a154c8cfd9c 100644
--- a/locales/en-US/labs.json
+++ b/locales/en-US/labs.json
@@ -28,6 +28,8 @@
"features.messageTextSelectionActions.title": "Message Text Selection Actions",
"features.oauthApps.desc": "Show OAuth app management in personal and workspace settings. This feature is hidden by default.",
"features.oauthApps.title": "OAuth Apps",
+ "features.projects.desc": "Organize long-running goals into dedicated workspaces with their own agents, knowledge bases, and tasks.",
+ "features.projects.title": "Project Workspaces",
"features.taskVerify.desc": "Add a delivery-acceptance section to the task detail: describe acceptance in one sentence and let AI generate editable verify criteria.",
"features.taskVerify.title": "Task Delivery Acceptance",
"features.topicAcceptance.desc": "Author a delivery checklist for the current topic right above the composer, so the conversation is held to standards you can edit any time.",
diff --git a/locales/en-US/project.json b/locales/en-US/project.json
new file mode 100644
index 00000000000..8dc773d4604
--- /dev/null
+++ b/locales/en-US/project.json
@@ -0,0 +1,106 @@
+{
+ "acceptance.actions.accept": "Accept completion",
+ "acceptance.actions.reject": "Request changes",
+ "acceptance.actions.reopen": "Reopen project",
+ "acceptance.actions.requestCompletion": "Request completion review",
+ "acceptance.actions.start": "Start project",
+ "acceptance.cancel": "Cancel",
+ "acceptance.currentStatus": "Project status",
+ "acceptance.decision.accepted": "Accepted",
+ "acceptance.decision.rejected": "Changes requested",
+ "acceptance.description": "Completion is a human decision. Review the project and keep an auditable decision history.",
+ "acceptance.emptyDescription": "Review decisions will appear here after completion is requested.",
+ "acceptance.emptyTitle": "No completion reviews yet",
+ "acceptance.history": "Review history",
+ "acceptance.operationFailed": "Could not update the project acceptance.",
+ "acceptance.reject": "Request changes",
+ "acceptance.rejectPlaceholder": "Explain what still needs to change before this project is complete.",
+ "acceptance.rejectTitle": "Request project changes",
+ "acceptance.round": "Round {{round}}",
+ "acceptance.status.active": "Active",
+ "acceptance.status.archived": "Archived",
+ "acceptance.status.backlog": "Backlog",
+ "acceptance.status.canceled": "Canceled",
+ "acceptance.status.completed": "Completed and accepted",
+ "acceptance.status.paused": "Paused",
+ "acceptance.status.reviewing": "Awaiting your review",
+ "acceptance.success.accept": "Project completion accepted",
+ "acceptance.success.reject": "Project returned for changes",
+ "acceptance.success.reopen": "Project reopened",
+ "acceptance.success.requestCompletion": "Completion review requested",
+ "acceptance.success.start": "Project started",
+ "acceptance.title": "Acceptance",
+ "create.action": "Create project",
+ "create.identifierDescription": "Used as the task prefix, for example LOBE-123.",
+ "create.identifierLabel": "Identifier",
+ "create.identifierPlaceholder": "LOBE",
+ "create.nameLabel": "Project name",
+ "create.namePlaceholder": "What are you working on?",
+ "create.slugDescription": "Used for the project URL. Leave blank to generate one automatically.",
+ "create.slugInvalid": "Use lowercase letters, numbers, and single hyphens only.",
+ "create.slugLabel": "Slug (optional)",
+ "create.slugPlaceholder": "my-project",
+ "create.title": "New project",
+ "disabled.action": "Enable in Labs",
+ "disabled.title": "Project workspaces are an Alpha experiment",
+ "goals.create": "Create goal",
+ "goals.description": "Define the outcomes this project is pursuing and track them to acceptance.",
+ "goals.emptyDescription": "Create the first measurable outcome for this project.",
+ "goals.emptyTitle": "No goals yet",
+ "goals.loadError": "Could not load project goals.",
+ "goals.retry": "Retry",
+ "goals.status.backlog": "Backlog",
+ "goals.status.canceled": "Canceled",
+ "goals.status.completed": "Completed",
+ "goals.status.failed": "Needs attention",
+ "goals.status.paused": "Paused",
+ "goals.status.running": "Pursuing",
+ "goals.status.scheduled": "Scheduled",
+ "goals.title": "Goals",
+ "overview.activeTasks": "In progress",
+ "overview.composerPlaceholder": "Tell the project what to move forward next…",
+ "overview.contextEnabled": "Project context loaded",
+ "overview.contextTitle": "Project context",
+ "overview.description": "Start with a question, or review the project’s progress and outputs.",
+ "overview.goalCount": "{{completed}} of {{total}} goals completed",
+ "overview.goalProgress": "Goal progress",
+ "overview.goalSummary": "Project goals",
+ "overview.goalsEmpty": "Add a goal to make project progress visible here.",
+ "overview.latestWorks": "Latest outputs",
+ "overview.needsAttention": "Needs your attention",
+ "overview.nextActionDescription": "Tell {{name}} what you want to achieve. Its coordinator will use the project context to move it forward.",
+ "overview.nextActionTitle": "What should we move forward next?",
+ "overview.noActiveTasks": "There are no active project tasks.",
+ "overview.noDescription": "A dedicated workspace for this long-running goal.",
+ "overview.nothingNeedsAttention": "Nothing needs your attention right now.",
+ "overview.openTasks": "Open task workspace",
+ "overview.projectSummary": "Project summary",
+ "overview.prompts.findBlockers": "Find the current blockers",
+ "overview.prompts.planMilestone": "Plan the next milestone",
+ "overview.prompts.summarizeProgress": "Summarize recent progress",
+ "overview.reviewProject": "Review project completion",
+ "overview.sendHint": "⌘ ↵ to send",
+ "overview.startConversation": "Start moving",
+ "overview.taskFailed": "This task needs recovery",
+ "overview.taskWaiting": "Waiting for your decision",
+ "overview.tasksEmpty": "No tasks belong to this project yet.",
+ "overview.tasksTitle": "Project tasks",
+ "overview.title": "Keep this project moving",
+ "overview.viewAllTasks": "View all tasks",
+ "overview.worksEmptyDescription": "Documents, files, tasks, and external results created by the Project Coordinator will appear here.",
+ "overview.worksEmptyTitle": "No outputs yet",
+ "sections.acceptance": "Acceptance",
+ "sections.agents": "Agents",
+ "sections.conversations": "Topics",
+ "sections.goals": "Goals",
+ "sections.home": "Project home",
+ "sections.knowledgeBases": "Libraries",
+ "sections.tasks": "Tasks",
+ "sidebar.agentsEmpty": "No agents are connected yet",
+ "sidebar.conversationsEmpty": "No project topics yet",
+ "sidebar.emptyAction": "Create your first project",
+ "sidebar.librariesEmpty": "No libraries are connected yet",
+ "sidebar.newConversation": "New conversation",
+ "sidebar.title": "Projects",
+ "sidebar.untitledConversation": "Untitled conversation"
+}
diff --git a/locales/zh-CN/labs.json b/locales/zh-CN/labs.json
index ba90c6b79c5..d6b44a53676 100644
--- a/locales/zh-CN/labs.json
+++ b/locales/zh-CN/labs.json
@@ -28,6 +28,8 @@
"features.messageTextSelectionActions.title": "消息文本选择操作",
"features.oauthApps.desc": "在个人和工作区设置中显示 OAuth 应用管理入口。此功能默认隐藏。",
"features.oauthApps.title": "OAuth 应用",
+ "features.projects.desc": "将长期目标组织到独立工作空间中,并集中管理相关智能体、资料库与任务。",
+ "features.projects.title": "项目工作空间",
"features.taskVerify.desc": "在任务详情里增加「交付验收」模块:一句话描述验收要求,AI 自动生成可编辑的验收项。",
"features.taskVerify.title": "任务交付验收",
"features.topicAcceptance.desc": "在输入框上方为当前话题编写一份交付验收清单,让对话对照你随时可编辑的标准来交付。",
diff --git a/locales/zh-CN/project.json b/locales/zh-CN/project.json
new file mode 100644
index 00000000000..2fa4f0b12bf
--- /dev/null
+++ b/locales/zh-CN/project.json
@@ -0,0 +1,106 @@
+{
+ "acceptance.actions.accept": "确认完成",
+ "acceptance.actions.reject": "要求修改",
+ "acceptance.actions.reopen": "重新打开项目",
+ "acceptance.actions.requestCompletion": "申请完成验收",
+ "acceptance.actions.start": "启动项目",
+ "acceptance.cancel": "取消",
+ "acceptance.currentStatus": "项目状态",
+ "acceptance.decision.accepted": "已通过",
+ "acceptance.decision.rejected": "已要求修改",
+ "acceptance.description": "项目是否完成必须由人确认。你可以在这里审阅项目,并保留可追溯的验收决定。",
+ "acceptance.emptyDescription": "申请完成验收后,人工验收决定会记录在这里。",
+ "acceptance.emptyTitle": "还没有验收记录",
+ "acceptance.history": "验收历史",
+ "acceptance.operationFailed": "无法更新项目验收状态。",
+ "acceptance.reject": "要求修改",
+ "acceptance.rejectPlaceholder": "说明项目在完成前还需要修改什么。",
+ "acceptance.rejectTitle": "要求修改项目",
+ "acceptance.round": "第 {{round}} 轮",
+ "acceptance.status.active": "进行中",
+ "acceptance.status.archived": "已归档",
+ "acceptance.status.backlog": "待启动",
+ "acceptance.status.canceled": "已取消",
+ "acceptance.status.completed": "已完成并通过验收",
+ "acceptance.status.paused": "已暂停",
+ "acceptance.status.reviewing": "等待你的验收",
+ "acceptance.success.accept": "已确认项目完成",
+ "acceptance.success.reject": "项目已退回修改",
+ "acceptance.success.reopen": "项目已重新打开",
+ "acceptance.success.requestCompletion": "已申请完成验收",
+ "acceptance.success.start": "项目已启动",
+ "acceptance.title": "验收",
+ "create.action": "创建项目",
+ "create.identifierDescription": "用于任务编号前缀,例如 LOBE-123。",
+ "create.identifierLabel": "项目标识",
+ "create.identifierPlaceholder": "LOBE",
+ "create.nameLabel": "项目名称",
+ "create.namePlaceholder": "你正在推进什么事情?",
+ "create.slugDescription": "用于项目 URL,留空时会自动生成。",
+ "create.slugInvalid": "仅可使用小写字母、数字和单个连字符。",
+ "create.slugLabel": "Slug(可选)",
+ "create.slugPlaceholder": "my-project",
+ "create.title": "新建项目",
+ "disabled.action": "前往实验室开启",
+ "disabled.title": "项目工作空间目前处于 Alpha 阶段",
+ "goals.create": "新建目标",
+ "goals.description": "定义这个项目正在追求的成果,并持续跟踪到验收。",
+ "goals.emptyDescription": "为这个项目创建第一个可衡量的成果。",
+ "goals.emptyTitle": "还没有目标",
+ "goals.loadError": "无法加载项目目标。",
+ "goals.retry": "重试",
+ "goals.status.backlog": "待开始",
+ "goals.status.canceled": "已取消",
+ "goals.status.completed": "已完成",
+ "goals.status.failed": "需要处理",
+ "goals.status.paused": "已暂停",
+ "goals.status.running": "推进中",
+ "goals.status.scheduled": "已计划",
+ "goals.title": "目标",
+ "overview.activeTasks": "正在推进",
+ "overview.composerPlaceholder": "告诉项目接下来要推进什么…",
+ "overview.contextEnabled": "已载入项目上下文",
+ "overview.contextTitle": "项目上下文",
+ "overview.description": "从一个问题开始,或查看项目当前的进度与产物。",
+ "overview.goalCount": "{{total}} 个目标中 {{completed}} 个已完成",
+ "overview.goalProgress": "目标进度",
+ "overview.goalSummary": "项目目标",
+ "overview.goalsEmpty": "添加目标后,可以在这里持续查看项目进度。",
+ "overview.latestWorks": "最新产物",
+ "overview.needsAttention": "需要你处理",
+ "overview.nextActionDescription": "告诉 {{name}} 你想达成什么,Project Coordinator 会结合项目上下文继续推进。",
+ "overview.nextActionTitle": "接下来推进什么?",
+ "overview.noActiveTasks": "当前没有正在推进的项目任务。",
+ "overview.noDescription": "一个围绕长期目标组织工作的独立空间。",
+ "overview.nothingNeedsAttention": "目前没有需要你处理的事项。",
+ "overview.openTasks": "打开任务工作台",
+ "overview.projectSummary": "项目概况",
+ "overview.prompts.findBlockers": "梳理当前阻塞",
+ "overview.prompts.planMilestone": "规划下一个里程碑",
+ "overview.prompts.summarizeProgress": "总结最近进展",
+ "overview.reviewProject": "验收项目完成情况",
+ "overview.sendHint": "⌘ ↵ 发送",
+ "overview.startConversation": "开始推进",
+ "overview.taskFailed": "这个任务需要恢复处理",
+ "overview.taskWaiting": "正在等待你的决定",
+ "overview.tasksEmpty": "这个项目还没有关联任务。",
+ "overview.tasksTitle": "项目任务",
+ "overview.title": "继续推进这个项目",
+ "overview.viewAllTasks": "查看全部任务",
+ "overview.worksEmptyDescription": "Project Coordinator 创建的文档、文件、任务和外部结果会显示在这里。",
+ "overview.worksEmptyTitle": "还没有产物",
+ "sections.acceptance": "验收",
+ "sections.agents": "智能体",
+ "sections.conversations": "话题",
+ "sections.goals": "目标",
+ "sections.home": "项目主页",
+ "sections.knowledgeBases": "资料库",
+ "sections.tasks": "任务",
+ "sidebar.agentsEmpty": "还没有关联智能体",
+ "sidebar.conversationsEmpty": "还没有项目话题",
+ "sidebar.emptyAction": "创建第一个项目",
+ "sidebar.librariesEmpty": "还没有关联资料库",
+ "sidebar.newConversation": "新对话",
+ "sidebar.title": "项目",
+ "sidebar.untitledConversation": "未命名对话"
+}
diff --git a/packages/database/src/models/__tests__/task.test.ts b/packages/database/src/models/__tests__/task.test.ts
index 529a0f2e7fd..d4cefcf4246 100644
--- a/packages/database/src/models/__tests__/task.test.ts
+++ b/packages/database/src/models/__tests__/task.test.ts
@@ -16,6 +16,7 @@ import {
import { taskTopics } from '../../schemas/task';
import { works } from '../../schemas/work';
import type { LobeChatDatabase } from '../../type';
+import { ProjectModel } from '../project';
import { TaskModel } from '../task';
import { WorkModel } from '../work';
@@ -430,6 +431,21 @@ describe('TaskModel', () => {
// Omitting the flag must not narrow anything.
expect((await model.list()).total).toBe(3);
});
+
+ it('should filter by projectId', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const project = await new ProjectModel(serverDB, userId).create({
+ identifier: 'TLIST',
+ name: 'Scoped project',
+ });
+ await model.create({ instruction: 'Project task', projectId: project.id });
+ await model.create({ instruction: 'Unrelated task' });
+
+ const result = await model.list({ projectId: project.id });
+
+ expect(result.total).toBe(1);
+ expect(result.tasks[0].instruction).toBe('Project task');
+ });
});
describe('groupList', () => {
@@ -570,6 +586,24 @@ describe('TaskModel', () => {
expect(ordinary[0].tasks[0].instruction).toBe('Ordinary task');
});
+ it('should group only tasks from the requested project', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const project = await new ProjectModel(serverDB, userId).create({
+ identifier: 'TGRP',
+ name: 'Scoped project',
+ });
+ await model.create({ instruction: 'Project task', projectId: project.id });
+ await model.create({ instruction: 'Unrelated task' });
+
+ const [group] = await model.groupList({
+ groups: [{ key: 'backlog', statuses: ['backlog'] }],
+ projectId: project.id,
+ });
+
+ expect(group.total).toBe(1);
+ expect(group.tasks[0].instruction).toBe('Project task');
+ });
+
it('should aggregate run cost and duration for the returned task batch', async () => {
const model = new TaskModel(serverDB, userId);
const task = await model.create({ instruction: 'Measured goal' });
diff --git a/packages/database/src/models/task.ts b/packages/database/src/models/task.ts
index 6d502160ddd..e51670c4be3 100644
--- a/packages/database/src/models/task.ts
+++ b/packages/database/src/models/task.ts
@@ -502,6 +502,7 @@ export class TaskModel {
parentTaskId?: string | null;
/** Only return tasks carrying the goal-controller marker in `config.goal`. */
hasGoal?: boolean;
+ projectId?: string;
/** Same semantics as `list({ visibility })` — UI narrowing on top of the
* already ownership-filtered set. */
visibility?: 'private' | 'public';
@@ -515,12 +516,13 @@ export class TaskModel {
total: number;
}>
> {
- const { groups, assigneeAgentId, hasGoal, parentTaskId, visibility } = options;
+ const { groups, assigneeAgentId, hasGoal, parentTaskId, projectId, visibility } = options;
const baseConditions = [this.ownership()];
if (assigneeAgentId) baseConditions.push(eq(tasks.assigneeAgentId, assigneeAgentId));
if (hasGoal === true) baseConditions.push(sql`COALESCE(${tasks.config} ->> 'goal', '') <> ''`);
if (hasGoal === false) baseConditions.push(sql`COALESCE(${tasks.config} ->> 'goal', '') = ''`);
+ if (projectId) baseConditions.push(eq(tasks.projectId, projectId));
if (visibility) baseConditions.push(eq(tasks.visibility, visibility));
if (parentTaskId === null) {
baseConditions.push(isNull(tasks.parentTaskId));
@@ -643,6 +645,7 @@ export class TaskModel {
orderBy?: 'createdAt' | 'updatedAt';
parentTaskId?: string | null;
priorities?: number[];
+ projectId?: string;
statuses?: string[];
/**
* UI-side narrowing of the (already ownership-filtered) result set.
@@ -658,6 +661,7 @@ export class TaskModel {
assigneeAgentId,
automated,
hasGoal,
+ projectId,
visibility,
limit = 50,
offset = 0,
@@ -677,6 +681,7 @@ export class TaskModel {
if (automated === false) conditions.push(sql`${RUNNABLE_AUTOMATION} IS NOT TRUE`);
if (hasGoal === true) conditions.push(sql`COALESCE(${tasks.config} ->> 'goal', '') <> ''`);
if (hasGoal === false) conditions.push(sql`COALESCE(${tasks.config} ->> 'goal', '') = ''`);
+ if (projectId) conditions.push(eq(tasks.projectId, projectId));
if (visibility) conditions.push(eq(tasks.visibility, visibility));
if (parentTaskId === null) {
diff --git a/packages/database/src/models/work/__tests__/workspace.test.ts b/packages/database/src/models/work/__tests__/workspace.test.ts
index 9a71eb34e27..78f1cd3b7a4 100644
--- a/packages/database/src/models/work/__tests__/workspace.test.ts
+++ b/packages/database/src/models/work/__tests__/workspace.test.ts
@@ -1,7 +1,8 @@
// @vitest-environment node
+import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { topics, workspaces } from '../../../schemas';
+import { topics, works, workspaces } from '../../../schemas';
import { AgentDocumentModel } from '../../agentDocuments';
import { TaskModel } from '../../task';
import { WorkModel } from '..';
@@ -128,6 +129,39 @@ describe('WorkModel · listByWorkspace', () => {
expect(items[0].type).toBe('document');
});
+ it('narrows to Works produced by one agent', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const firstTask = await taskModel.create({ instruction: 'First', name: 'First task' });
+ const secondTask = await taskModel.create({ instruction: 'Second', name: 'Second task' });
+ const firstWork = await workModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-agent-filter-1',
+ toolCallId: 'tool-call-agent-filter-1',
+ toolIdentifier: 'lobe-task',
+ toolName: 'createTask',
+ taskId: firstTask.id,
+ topicId,
+ });
+ await workModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-agent-filter-2',
+ toolCallId: 'tool-call-agent-filter-2',
+ toolIdentifier: 'lobe-task',
+ toolName: 'createTask',
+ taskId: secondTask.id,
+ topicId,
+ });
+
+ await serverDB.update(works).set({ originAgentId: agentId }).where(eq(works.id, firstWork!.id));
+
+ const { items } = await workModel.listByWorkspace({
+ originAgentId: agentId,
+ });
+
+ expect(items.map((item) => item.id)).toEqual([firstWork!.id]);
+ });
+
it('pages over the keyset cursor without gaps or overlaps', async () => {
const taskModel = new TaskModel(serverDB, userId);
const workModel = new WorkModel(serverDB, userId);
diff --git a/packages/database/src/models/work/queries.ts b/packages/database/src/models/work/queries.ts
index 2eb9990783b..4d4c6e411c9 100644
--- a/packages/database/src/models/work/queries.ts
+++ b/packages/database/src/models/work/queries.ts
@@ -260,6 +260,8 @@ export interface ListByWorkspaceParams {
/** Opt-in gate for the `file` work type; see {@link resolveAllowedWorkTypes}. */
includeFileWorks?: boolean;
limit?: number;
+ /** Narrow results to Works first produced by one agent. */
+ originAgentId?: string | null;
/** Narrow the `external` type to a single skill provider's resource types. */
provider?: WorkSkillProvider | null;
type?: WorkType | null;
@@ -316,6 +318,7 @@ export const listByWorkspace = async (
inArray(works.type, resolveAllowedWorkTypes(params.includeFileWorks)),
];
if (params.type) filters.push(eq(works.type, params.type));
+ if (params.originAgentId) filters.push(eq(works.originAgentId, params.originAgentId));
// User-visible gallery tabs stay per-provider (Linear / GitHub) but filter by
// provider — its resource types — over the unified `external` Work type.
if (params.provider) {
diff --git a/packages/locales/src/default/index.ts b/packages/locales/src/default/index.ts
index a3a64a04def..fb9694960ef 100644
--- a/packages/locales/src/default/index.ts
+++ b/packages/locales/src/default/index.ts
@@ -36,6 +36,7 @@ import opStatusTray from './opStatusTray';
import pageShare from './pageShare';
import plugin from './plugin';
import portal from './portal';
+import project from './project';
import providers from './providers';
import ragEval from './ragEval';
import setting from './setting';
@@ -90,6 +91,7 @@ const resources = {
plugin,
portal,
providers,
+ project,
ragEval,
setting,
spend,
diff --git a/packages/locales/src/default/labs.ts b/packages/locales/src/default/labs.ts
index cb3fd512b8c..f2c87d001d3 100644
--- a/packages/locales/src/default/labs.ts
+++ b/packages/locales/src/default/labs.ts
@@ -42,6 +42,9 @@ export default {
'features.oauthApps.desc':
'Show OAuth app management in personal and workspace settings. This feature is hidden by default.',
'features.oauthApps.title': 'OAuth Apps',
+ 'features.projects.desc':
+ 'Organize long-running goals into dedicated workspaces with their own agents, knowledge bases, and tasks.',
+ 'features.projects.title': 'Project Workspaces',
'features.taskVerify.desc':
'Add a delivery-acceptance section to the task detail: describe acceptance in one sentence and let AI generate editable verify criteria.',
'features.taskVerify.title': 'Task Delivery Acceptance',
diff --git a/packages/locales/src/default/project.ts b/packages/locales/src/default/project.ts
new file mode 100644
index 00000000000..5fc20282516
--- /dev/null
+++ b/packages/locales/src/default/project.ts
@@ -0,0 +1,110 @@
+export default {
+ 'acceptance.actions.accept': 'Accept completion',
+ 'acceptance.actions.reject': 'Request changes',
+ 'acceptance.actions.reopen': 'Reopen project',
+ 'acceptance.actions.requestCompletion': 'Request completion review',
+ 'acceptance.actions.start': 'Start project',
+ 'acceptance.cancel': 'Cancel',
+ 'acceptance.currentStatus': 'Project status',
+ 'acceptance.decision.accepted': 'Accepted',
+ 'acceptance.decision.rejected': 'Changes requested',
+ 'acceptance.description':
+ 'Completion is a human decision. Review the project and keep an auditable decision history.',
+ 'acceptance.emptyDescription': 'Review decisions will appear here after completion is requested.',
+ 'acceptance.emptyTitle': 'No completion reviews yet',
+ 'acceptance.history': 'Review history',
+ 'acceptance.operationFailed': 'Could not update the project acceptance.',
+ 'acceptance.reject': 'Request changes',
+ 'acceptance.rejectPlaceholder':
+ 'Explain what still needs to change before this project is complete.',
+ 'acceptance.rejectTitle': 'Request project changes',
+ 'acceptance.round': 'Round {{round}}',
+ 'acceptance.status.active': 'Active',
+ 'acceptance.status.archived': 'Archived',
+ 'acceptance.status.backlog': 'Backlog',
+ 'acceptance.status.canceled': 'Canceled',
+ 'acceptance.status.completed': 'Completed and accepted',
+ 'acceptance.status.paused': 'Paused',
+ 'acceptance.status.reviewing': 'Awaiting your review',
+ 'acceptance.success.accept': 'Project completion accepted',
+ 'acceptance.success.reject': 'Project returned for changes',
+ 'acceptance.success.reopen': 'Project reopened',
+ 'acceptance.success.requestCompletion': 'Completion review requested',
+ 'acceptance.success.start': 'Project started',
+ 'acceptance.title': 'Acceptance',
+ 'create.action': 'Create project',
+ 'create.identifierDescription': 'Used as the task prefix, for example LOBE-123.',
+ 'create.identifierLabel': 'Identifier',
+ 'create.identifierPlaceholder': 'LOBE',
+ 'create.nameLabel': 'Project name',
+ 'create.namePlaceholder': 'What are you working on?',
+ 'create.slugDescription': 'Used for the project URL. Leave blank to generate one automatically.',
+ 'create.slugInvalid': 'Use lowercase letters, numbers, and single hyphens only.',
+ 'create.slugLabel': 'Slug (optional)',
+ 'create.slugPlaceholder': 'my-project',
+ 'create.title': 'New project',
+ 'disabled.action': 'Enable in Labs',
+ 'disabled.title': 'Project workspaces are an Alpha experiment',
+ 'goals.create': 'Create goal',
+ 'goals.description': 'Define the outcomes this project is pursuing and track them to acceptance.',
+ 'goals.emptyDescription': 'Create the first measurable outcome for this project.',
+ 'goals.emptyTitle': 'No goals yet',
+ 'goals.loadError': 'Could not load project goals.',
+ 'goals.retry': 'Retry',
+ 'goals.status.backlog': 'Backlog',
+ 'goals.status.canceled': 'Canceled',
+ 'goals.status.completed': 'Completed',
+ 'goals.status.failed': 'Needs attention',
+ 'goals.status.paused': 'Paused',
+ 'goals.status.running': 'Pursuing',
+ 'goals.status.scheduled': 'Scheduled',
+ 'goals.title': 'Goals',
+ 'overview.noDescription': 'A dedicated workspace for this long-running goal.',
+ 'overview.activeTasks': 'In progress',
+ 'overview.contextEnabled': 'Project context loaded',
+ 'overview.contextTitle': 'Project context',
+ 'overview.description': 'Start with a question, or review the project’s progress and outputs.',
+ 'overview.goalCount': '{{completed}} of {{total}} goals completed',
+ 'overview.goalProgress': 'Goal progress',
+ 'overview.goalSummary': 'Project goals',
+ 'overview.goalsEmpty': 'Add a goal to make project progress visible here.',
+ 'overview.latestWorks': 'Latest outputs',
+ 'overview.needsAttention': 'Needs your attention',
+ 'overview.nextActionDescription':
+ 'Tell {{name}} what you want to achieve. Its coordinator will use the project context to move it forward.',
+ 'overview.nextActionTitle': 'What should we move forward next?',
+ 'overview.noActiveTasks': 'There are no active project tasks.',
+ 'overview.nothingNeedsAttention': 'Nothing needs your attention right now.',
+ 'overview.projectSummary': 'Project summary',
+ 'overview.reviewProject': 'Review project completion',
+ 'overview.taskFailed': 'This task needs recovery',
+ 'overview.taskWaiting': 'Waiting for your decision',
+ 'overview.title': 'Keep this project moving',
+ 'overview.viewAllTasks': 'View all tasks',
+ 'overview.worksEmptyDescription':
+ 'Documents, files, tasks, and external results created by the Project Coordinator will appear here.',
+ 'overview.worksEmptyTitle': 'No outputs yet',
+ 'overview.openTasks': 'Open task workspace',
+ 'overview.composerPlaceholder': 'Tell the project what to move forward next…',
+ 'overview.prompts.findBlockers': 'Find the current blockers',
+ 'overview.prompts.planMilestone': 'Plan the next milestone',
+ 'overview.prompts.summarizeProgress': 'Summarize recent progress',
+ 'overview.sendHint': '⌘ ↵ to send',
+ 'overview.startConversation': 'Start moving',
+ 'overview.tasksEmpty': 'No tasks belong to this project yet.',
+ 'overview.tasksTitle': 'Project tasks',
+ 'sections.agents': 'Agents',
+ 'sections.acceptance': 'Acceptance',
+ 'sections.goals': 'Goals',
+ 'sections.home': 'Project home',
+ 'sections.knowledgeBases': 'Libraries',
+ 'sections.conversations': 'Topics',
+ 'sections.tasks': 'Tasks',
+ 'sidebar.emptyAction': 'Create your first project',
+ 'sidebar.agentsEmpty': 'No agents are connected yet',
+ 'sidebar.conversationsEmpty': 'No project topics yet',
+ 'sidebar.librariesEmpty': 'No libraries are connected yet',
+ 'sidebar.newConversation': 'New conversation',
+ 'sidebar.title': 'Projects',
+ 'sidebar.untitledConversation': 'Untitled conversation',
+};
diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.ts
index 858305e2898..9c0a4717cba 100644
--- a/packages/types/src/user/preference.ts
+++ b/packages/types/src/user/preference.ts
@@ -201,6 +201,10 @@ export const UserLabSchema = z.object({
* show OAuth app management in personal and workspace settings
*/
enableOAuthApps: z.boolean().optional(),
+ /**
+ * enable the project workspace experiment
+ */
+ enableProjects: z.boolean().optional(),
/**
* enable the task delivery-acceptance (verify) config UI on the task detail
*/
diff --git a/src/features/AgentGoals/AgentGoalsPage.tsx b/src/features/AgentGoals/AgentGoalsPage.tsx
index cdd519e295e..7212299c398 100644
--- a/src/features/AgentGoals/AgentGoalsPage.tsx
+++ b/src/features/AgentGoals/AgentGoalsPage.tsx
@@ -65,15 +65,17 @@ const styles = createStaticStyles(({ css }) => ({
}));
interface AgentGoalsPageProps {
- agentId: string;
+ agentId?: string;
+ projectId?: string;
}
-const AgentGoalsPage = memo<AgentGoalsPageProps>(({ agentId }) => {
+const AgentGoalsPage = memo<AgentGoalsPageProps>(({ agentId, projectId }) => {
const { t } = useTranslation('chat');
+ const scopeId = projectId ? `project:${projectId}` : agentId!;
const useFetchGoals = useGoalStore((s) => s.useFetchGoals);
const refreshGoals = useGoalStore((s) => s.refreshGoals);
- const goals = useGoalStore(goalSelectors.goalList(agentId));
- const isInitialized = useGoalStore(goalSelectors.isGoalListInitialized(agentId));
+ const goals = useGoalStore(goalSelectors.goalList(scopeId));
+ const isInitialized = useGoalStore(goalSelectors.isGoalListInitialized(scopeId));
const filter = useGoalStore((s) => s.goalListFilter);
const viewMode = useGoalStore((s) => s.goalViewMode);
const visibleLimit = useGoalStore((s) => s.goalListVisibleLimit);
@@ -82,7 +84,7 @@ const AgentGoalsPage = memo<AgentGoalsPageProps>(({ agentId }) => {
const loadMoreGoals = useGoalStore((s) => s.loadMoreGoals);
const acceptanceBySubjectMap = useVerifyStore((s) => s.acceptanceBySubjectMap);
const acceptanceBundleMap = useVerifyStore((s) => s.acceptanceBundleMap);
- const { error, isLoading } = useFetchGoals(agentId);
+ const { error, isLoading } = useFetchGoals(agentId, projectId);
const summary = useMemo(() => {
const delivered = goals.filter((goal) => goal.status === 'completed').length;
@@ -114,14 +116,21 @@ const AgentGoalsPage = memo<AgentGoalsPageProps>(({ agentId }) => {
initialRequirement: seed?.requirement,
initialRoundBudget: seed?.roundBudget,
initialTitle: seed?.title,
- onCreated: () => void refreshGoals(agentId),
+ projectId,
+ onCreated: () => void refreshGoals(scopeId),
});
};
return (
<Flexbox flex={1} height={'100%'}>
<NavHeader
- left={<AgentBreadcrumb agentId={agentId} title={t('goalList.title')} />}
+ left={
+ agentId ? (
+ <AgentBreadcrumb agentId={agentId} title={t('goalList.title')} />
+ ) : (
+ <Text weight={600}>{t('goalList.title')}</Text>
+ )
+ }
right={
<Button icon={PlusIcon} size={'small'} type={'fill'} onClick={() => openCreateGoal()}>
{t('goalPage.create')}
@@ -148,7 +157,7 @@ const AgentGoalsPage = memo<AgentGoalsPageProps>(({ agentId }) => {
<Button
icon={RefreshCwIcon}
size={'small'}
- onClick={() => void refreshGoals(agentId)}
+ onClick={() => void refreshGoals(scopeId)}
>
{t('goalList.retry')}
</Button>
@@ -248,7 +257,12 @@ const AgentGoalsPage = memo<AgentGoalsPageProps>(({ agentId }) => {
filteredGoals
.slice(0, visibleLimit)
.map((goal) => (
- <GoalItem hideAchieved={filter === 'active'} key={goal.id} task={goal} />
+ <GoalItem
+ hideAchieved={filter === 'active'}
+ key={goal.id}
+ projectId={projectId}
+ task={goal}
+ />
))
)}
</div>
diff --git a/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx b/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx
index 68ee2cacf76..f45329a16fa 100644
--- a/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx
+++ b/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx
@@ -236,6 +236,7 @@ export interface CreateGoalContentProps {
initialRoundBudget?: number;
initialTitle?: string;
onCreated?: (goal: { agentId?: string; identifier: string }) => void;
+ projectId?: string;
}
/**
@@ -247,7 +248,8 @@ export interface CreateGoalContentProps {
* hardcoded), so this form asks for them outright.
*/
const CreateGoalContent = memo<CreateGoalContentProps>((props) => {
- const { agentId, initialRequirement, initialRoundBudget, initialTitle, onCreated } = props;
+ const { agentId, initialRequirement, initialRoundBudget, initialTitle, onCreated, projectId } =
+ props;
const { t } = useTranslation('chat');
const { close } = useModalContext();
const { allowed: canCreate, reason } = usePermission('create_content');
@@ -414,6 +416,7 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {
editorData,
instruction,
name: plan.name.trim() || undefined,
+ projectId,
visibility: activeWorkspaceId ? visibility : undefined,
});
@@ -438,6 +441,7 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {
editor,
onCreated,
plan,
+ projectId,
requirement,
t,
visibility,
diff --git a/src/features/AgentGoals/GoalCardItem.tsx b/src/features/AgentGoals/GoalCardItem.tsx
index 735a3506cdb..db668d81fe0 100644
--- a/src/features/AgentGoals/GoalCardItem.tsx
+++ b/src/features/AgentGoals/GoalCardItem.tsx
@@ -38,12 +38,13 @@ export const GoalCardItem = memo<GoalItemProps>((props) => {
const { t } = useTranslation('chat');
const navigate = useWorkspaceAwareNavigate();
const { aid } = useActiveRouteParams<{ aid?: string }>();
- const { hideAchieved = false, task } = props;
+ const { hideAchieved = false, projectId, task } = props;
const config = task.config as { goal?: { maxIterations?: number | null } } | null;
const title = task.name?.trim() || task.instruction.trim() || task.identifier;
const description = getGoalDescription(task);
const handleClick = () => {
- if (aid) navigate(`/agent/${aid}/goal/${task.identifier}`);
+ if (projectId) navigate(`/task/${task.identifier}`);
+ else if (aid) navigate(`/agent/${aid}/goal/${task.identifier}`);
};
const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
if (event.key !== 'Enter' && event.key !== ' ') return;
diff --git a/src/features/AgentGoals/GoalListItem.tsx b/src/features/AgentGoals/GoalListItem.tsx
index 11086b6d4ff..d033bbb5eb9 100644
--- a/src/features/AgentGoals/GoalListItem.tsx
+++ b/src/features/AgentGoals/GoalListItem.tsx
@@ -37,12 +37,13 @@ export const GoalListItem = memo<GoalItemProps>((props) => {
const { t } = useTranslation('chat');
const navigate = useWorkspaceAwareNavigate();
const { aid } = useActiveRouteParams<{ aid?: string }>();
- const { hideAchieved = false, task } = props;
+ const { hideAchieved = false, projectId, task } = props;
const config = task.config as { goal?: { maxIterations?: number | null } } | null;
const title = task.name?.trim() || task.instruction.trim() || task.identifier;
const description = getGoalDescription(task);
const handleClick = () => {
- if (aid) navigate(`/agent/${aid}/goal/${task.identifier}`);
+ if (projectId) navigate(`/task/${task.identifier}`);
+ else if (aid) navigate(`/agent/${aid}/goal/${task.identifier}`);
};
const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
if (event.key !== 'Enter' && event.key !== ' ') return;
diff --git a/src/features/AgentGoals/types.ts b/src/features/AgentGoals/types.ts
index e89ad7abea6..4b9514288b0 100644
--- a/src/features/AgentGoals/types.ts
+++ b/src/features/AgentGoals/types.ts
@@ -2,5 +2,6 @@ import type { GoalListItem } from '@/store/goal/initialState';
export interface GoalItemProps {
hideAchieved?: boolean;
+ projectId?: string;
task: GoalListItem;
}
diff --git a/src/features/AgentSidebar/Header/Agent/SwitchPanel.tsx b/src/features/AgentSidebar/Header/Agent/SwitchPanel.tsx
index d52e0bb5e7b..2c63957e173 100644
--- a/src/features/AgentSidebar/Header/Agent/SwitchPanel.tsx
+++ b/src/features/AgentSidebar/Header/Agent/SwitchPanel.tsx
@@ -1,6 +1,6 @@
-import { Flexbox, Popover, Text } from '@lobehub/ui';
+import { Flexbox, Text } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
-import { type PropsWithChildren } from 'react';
+import type { PropsWithChildren } from 'react';
import { memo, Suspense, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -9,22 +9,18 @@ import AgentListContent from '@/features/HomeSidebar/Body/Agent/List/AgentListCo
import { AgentModalProvider } from '@/features/HomeSidebar/Body/Agent/ModalProvider';
import PrivateList from '@/features/HomeSidebar/Body/Private/List';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { SidebarHeaderSelectPopover } from '@/features/NavPanel/SidebarHeaderSelect';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useFetchAgentList } from '@/hooks/useFetchAgentList';
import { useHomeStore } from '@/store/home';
import { homeAgentListSelectors } from '@/store/home/selectors';
-const styles = createStaticStyles(({ cssVar, css }) => ({
+const styles = createStaticStyles(({ css }) => ({
sectionHeader: css`
padding-block: 4px;
padding-inline: 8px;
line-height: 20px;
`,
- trigger: css`
- &[data-popup-open] {
- background: ${cssVar.colorFillTertiary};
- }
- `,
}));
interface SectionHeaderProps {
@@ -82,23 +78,7 @@ const SwitchPanel = memo<PropsWithChildren>(({ children }) => {
[handleMoreClick, showPrivateSection, t],
);
- return (
- <Popover
- classNames={{ trigger: styles.trigger }}
- content={content}
- nativeButton={false}
- placement="bottomLeft"
- trigger="click"
- styles={{
- content: {
- padding: 0,
- width: 240,
- },
- }}
- >
- {children}
- </Popover>
- );
+ return <SidebarHeaderSelectPopover content={content}>{children}</SidebarHeaderSelectPopover>;
});
export default SwitchPanel;
diff --git a/src/features/AgentSidebar/Header/Agent/index.tsx b/src/features/AgentSidebar/Header/Agent/index.tsx
index ae2ca16713b..82190a3395b 100644
--- a/src/features/AgentSidebar/Header/Agent/index.tsx
+++ b/src/features/AgentSidebar/Header/Agent/index.tsx
@@ -1,14 +1,12 @@
'use client';
-import { ActionIcon, Avatar, Block, Text } from '@lobehub/ui';
-import { ChevronsUpDownIcon } from 'lucide-react';
-import { type PropsWithChildren } from 'react';
+import type { PropsWithChildren } from 'react';
import React, { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
import { DEFAULT_AVATAR, DEFAULT_INBOX_AVATAR } from '@/const/meta';
import { SkeletonItem } from '@/features/NavPanel/components/SkeletonList';
+import { SidebarHeaderSelectTrigger } from '@/features/NavPanel/SidebarHeaderSelect';
import { useAgentStore } from '@/store/agent';
import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
@@ -33,35 +31,11 @@ const Agent = memo<PropsWithChildren>(() => {
return (
<SwitchPanel>
- <Block
- clickable
- horizontal
- align={'center'}
- gap={8}
- padding={2}
- variant={'borderless'}
- style={{
- minWidth: 32,
- overflow: 'hidden',
- }}
- >
- <Avatar
- avatar={isInbox ? avatar || DEFAULT_INBOX_AVATAR : avatar || DEFAULT_AVATAR}
- background={backgroundColor || undefined}
- shape={'square'}
- size={28}
- />
- <Text ellipsis weight={500}>
- {displayTitle}
- </Text>
- <ActionIcon
- icon={ChevronsUpDownIcon}
- size={DESKTOP_HEADER_ICON_SMALL_SIZE}
- style={{
- width: 24,
- }}
- />
- </Block>
+ <SidebarHeaderSelectTrigger
+ avatar={isInbox ? avatar || DEFAULT_INBOX_AVATAR : avatar || DEFAULT_AVATAR}
+ background={backgroundColor || undefined}
+ title={displayTitle}
+ />
</SwitchPanel>
);
});
diff --git a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
index b0969f7b478..f719b665d95 100644
--- a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
+++ b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
@@ -73,9 +73,11 @@ interface AgentTasksPageProps {
* shows tasks across all agents.
*/
agentId?: string;
+ /** When provided, shows the complete task workspace scoped to one project. */
+ projectId?: string;
}
-const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId }) => {
+const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, projectId }) => {
const navigate = useWorkspaceAwareNavigate();
const isMobile = useIsMobile();
const { allowed: canCreateTask, reason } = usePermission('create_content');
@@ -83,7 +85,7 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId }) => {
const useFetchTaskList = useTaskStore((s) => s.useFetchTaskList);
// Keep the SWR handle only for `error` + `mutate` (the error/Retry state).
const { error, isLoading, mutate } = useFetchTaskList(
- agentId ? { agentId } : { allAgents: true },
+ projectId ? { projectId, visibility: 'all' } : agentId ? { agentId } : { allAgents: true },
);
// Drive the loading/empty boundary off the store's own init flag, NOT SWR's
// per-key `data`. On a scope (agent ↔ all) or visibility switch the store
@@ -133,11 +135,12 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId }) => {
createTaskModal({
agentId,
lockAssignee: !!agentId,
+ projectId,
onCreated: (task) => {
navigate(taskDetailPath(task.identifier, agentId ? task.agentId : undefined));
},
});
- }, [agentId, canCreateTask, createActionBehavior.mode, navigate, updateSystemStatus]);
+ }, [agentId, canCreateTask, createActionBehavior.mode, navigate, projectId, updateSystemStatus]);
const handleShowHiddenCompleted = useCallback(() => {
setViewOptions((prev) => ({ ...prev, hideCompleted: false }));
@@ -151,7 +154,7 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId }) => {
left={headerVisibility.showBreadcrumb ? <Breadcrumb /> : undefined}
right={
<Flexbox horizontal align={'center'} gap={4}>
- {!agentId && <TaskListVisibilityFilter />}
+ {!agentId && !projectId && <TaskListVisibilityFilter />}
{(inlineCollapsed || viewMode === 'kanban') && (
<ActionIcon
disabled={createActionBehavior.disabled}
@@ -181,10 +184,10 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId }) => {
}}
/>
{isEmptyHero ? (
- <EmptyState agentId={agentId} />
+ <EmptyState agentId={agentId} projectId={projectId} />
) : viewMode === 'kanban' ? (
<Flexbox flex={1} style={{ overflowX: 'auto', overflowY: 'hidden' }}>
- <KanbanBoard agentId={agentId} routeScope={routeScope} />
+ <KanbanBoard agentId={agentId} projectId={projectId} routeScope={routeScope} />
</Flexbox>
) : (
<WideScreenContainer
@@ -192,7 +195,13 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId }) => {
paddingBlock={16}
wrapperStyle={{ flex: 1, overflowY: 'auto' }}
>
- {!inlineCollapsed && <CreateTaskInlineEntry agentId={agentId} lockAssignee={!!agentId} />}
+ {!inlineCollapsed && (
+ <CreateTaskInlineEntry
+ agentId={agentId}
+ lockAssignee={!!agentId}
+ projectId={projectId}
+ />
+ )}
<TaskList
data={isTaskListInit || undefined}
error={error}
diff --git a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx
index ce4975463e9..782f899016d 100644
--- a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx
+++ b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx
@@ -39,6 +39,7 @@ interface CreateTaskInlineEntryProps {
onCreated?: (task: { agentId?: string; identifier: string }) => void;
parentTaskId?: string;
placeholder?: string;
+ projectId?: string;
/**
* `hero` adapts the entry for the empty-tasks landing: hides collapse,
* enlarges the editor area, and forces autoFocus.
@@ -55,6 +56,7 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
onCreated,
parentTaskId,
placeholder,
+ projectId,
variant = 'default',
} = props;
const isHero = variant === 'hero';
@@ -87,8 +89,8 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
// Persist the in-progress draft per scope so a reload / accidental close
// doesn't eat a long prompt. Skipped for the transient subtask composer.
const draftStorageKey = useMemo(
- () => (parentTaskId ? null : `lobehub:task-create-draft:${agentId ?? 'all'}`),
- [agentId, parentTaskId],
+ () => (parentTaskId ? null : `lobehub:task-create-draft:${projectId ?? agentId ?? 'all'}`),
+ [agentId, parentTaskId, projectId],
);
// Tracks which scope key the editor is currently hydrated for. The component
// is reused across /agent/A/tasks -> /agent/B/tasks -> /tasks without
@@ -228,6 +230,7 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
name,
parentTaskId,
priority: priority || undefined,
+ projectId,
// Only send visibility in workspace mode; personal mode lets the server
// fall through to the schema default ('public', inert in personal mode).
visibility: activeWorkspaceId ? visibility : undefined,
@@ -266,6 +269,7 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
onCreated,
parentTaskId,
priority,
+ projectId,
canCreateTask,
visibility,
]);
diff --git a/src/features/AgentTasks/AgentTaskList/EmptyState.tsx b/src/features/AgentTasks/AgentTaskList/EmptyState.tsx
index c7234bccb3d..fb2773cec52 100644
--- a/src/features/AgentTasks/AgentTaskList/EmptyState.tsx
+++ b/src/features/AgentTasks/AgentTaskList/EmptyState.tsx
@@ -31,9 +31,10 @@ const styles = createStaticStyles(({ css }) => ({
interface EmptyStateProps {
/** When set, scopes task creation to this agent and locks the assignee. */
agentId?: string;
+ projectId?: string;
}
-const EmptyState = memo<EmptyStateProps>(({ agentId }) => {
+const EmptyState = memo<EmptyStateProps>(({ agentId, projectId }) => {
const { t } = useTranslation('chat');
const { t: tCommon } = useTranslation('common');
const templatesState = useDailyBriefRecommendationsUI({ count: EMPTY_STATE_RECOMMEND_COUNT });
@@ -51,9 +52,14 @@ const EmptyState = memo<EmptyStateProps>(({ agentId }) => {
</Text>
</Flexbox>
- <CreateTaskInlineEntry agentId={agentId} lockAssignee={!!agentId} variant={'hero'} />
+ <CreateTaskInlineEntry
+ agentId={agentId}
+ lockAssignee={!!agentId}
+ projectId={projectId}
+ variant={'hero'}
+ />
- {templatesState.mode !== 'hidden' && (
+ {!projectId && templatesState.mode !== 'hidden' && (
<Flexbox gap={12}>
<Flexbox horizontal align={'center'} justify={'space-between'}>
<Text fontSize={13} type={'secondary'} weight={500}>
diff --git a/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx b/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx
index 656b2430cfb..dc632ff51f0 100644
--- a/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx
+++ b/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx
@@ -79,10 +79,11 @@ const optimisticMoveTask = (
interface KanbanBoardProps {
/** When set, scopes the board (and task creation) to a single agent. */
agentId?: string;
+ projectId?: string;
routeScope?: TaskItemRouteScope;
}
-const KanbanBoard = memo<KanbanBoardProps>(({ agentId, routeScope }) => {
+const KanbanBoard = memo<KanbanBoardProps>(({ agentId, projectId, routeScope }) => {
const { t } = useTranslation('chat');
const navigate = useWorkspaceAwareNavigate();
const { allowed: canEditTask } = usePermission('create_content');
@@ -90,7 +91,7 @@ const KanbanBoard = memo<KanbanBoardProps>(({ agentId, routeScope }) => {
const useFetchTaskGroupList = useTaskStore((s) => s.useFetchTaskGroupList);
// Keep the SWR handle only for `error` + `mutate` (the error/Retry state).
const { error, isLoading, mutate } = useFetchTaskGroupList(
- agentId ? { agentId } : { allAgents: true },
+ projectId ? { projectId } : agentId ? { agentId } : { allAgents: true },
);
// Drive the loading/empty boundary off the store's own init flag, NOT SWR's
// per-key `data`. On a scope or visibility switch the store resets
@@ -163,12 +164,13 @@ const KanbanBoard = memo<KanbanBoardProps>(({ agentId, routeScope }) => {
createTaskModal({
agentId,
lockAssignee: !!agentId,
+ projectId,
onCreated: (task) => {
navigate(taskDetailPath(task.identifier, agentId ? task.agentId : undefined));
},
showInlineToggle: false,
});
- }, [agentId, canEditTask, navigate]);
+ }, [agentId, canEditTask, navigate, projectId]);
const handleHideColumn = useCallback(
(columnKey: string) => {
diff --git a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
index 9776719cdb7..46d75eb81b2 100644
--- a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
+++ b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
@@ -34,6 +34,7 @@ export interface CreateTaskContentProps {
*/
lockAssignee?: boolean;
onCreated?: (task: { agentId?: string; identifier: string }) => void;
+ projectId?: string;
/**
* Whether to show the "minimize to inline entry" button. Only the list view has an
* inline entry target, so contexts like the Kanban board pass `false` to hide it.
@@ -42,7 +43,7 @@ export interface CreateTaskContentProps {
}
const CreateTaskContent = memo<CreateTaskContentProps>(
- ({ agentId, lockAssignee, onCreated, showInlineToggle = true }) => {
+ ({ agentId, lockAssignee, onCreated, projectId, showInlineToggle = true }) => {
const { t } = useTranslation('chat');
const { close } = useModalContext();
const { allowed: canCreateTask, reason } = usePermission('create_content');
@@ -106,6 +107,7 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
instruction: instruction || title.trim(),
name: title.trim() || undefined,
priority: priority || undefined,
+ projectId,
// Only send visibility in workspace mode; personal mode ignores it.
visibility: activeWorkspaceId ? visibility : undefined,
});
@@ -129,6 +131,7 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
editor,
onCreated,
priority,
+ projectId,
t,
title,
visibility,
diff --git a/src/features/DailyBrief/__tests__/BriefCardActions.test.tsx b/src/features/DailyBrief/__tests__/BriefCardActions.test.tsx
index 616e6f8b3a6..ad0e3e88c2d 100644
--- a/src/features/DailyBrief/__tests__/BriefCardActions.test.tsx
+++ b/src/features/DailyBrief/__tests__/BriefCardActions.test.tsx
@@ -127,7 +127,7 @@ describe('BriefCardActions', () => {
/>,
);
- const link = screen.getByRole('button', { name: 'Review acceptance' });
+ const link = screen.getByRole('button', { name: 'Review delivery' });
expect(link).not.toHaveAttribute(RENDERER_HANDLED_LINK_ATTR);
expect(fireEvent.click(link)).toBe(true);
});
diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx
index d176f81fb0e..0e5bf28836f 100644
--- a/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx
@@ -76,10 +76,11 @@ interface AgentItemProps {
className?: string;
item: SidebarAgentItem;
onNavigate?: () => void;
+ secondaryLabel?: string | null;
style?: CSSProperties;
}
-const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate }) => {
+const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate, secondaryLabel }) => {
const { id, avatar, backgroundColor, pinned, slug, userId, visibility } = item;
// Unread count is server-computed (topics.status === 'unread') and carried on
// the sidebar list item, so it stays accurate across agents whose topics
@@ -100,7 +101,7 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate })
const displayTitle = agentDisplayName(item, t('untitledAgent'));
// The role shown beside the name — same rule for every agent, heterogeneous
// ones included (see agentSecondaryDisplayName).
- const roleTag = agentSecondaryDisplayName(item);
+ const roleTag = secondaryLabel || agentSecondaryDisplayName(item);
const agentUrl = usePreservedAgentUrl(id);
diff --git a/src/features/HomeSidebar/Body/CustomizeSidebarModal.test.ts b/src/features/HomeSidebar/Body/CustomizeSidebarModal.test.ts
index 7745b0e7c4e..e3f30582597 100644
--- a/src/features/HomeSidebar/Body/CustomizeSidebarModal.test.ts
+++ b/src/features/HomeSidebar/Body/CustomizeSidebarModal.test.ts
@@ -11,6 +11,11 @@ describe('CustomizeSidebarModal', () => {
expect(items.some((item) => item.id === 'memory')).toBe(true);
});
+ it('allows Projects to be reordered and hidden', () => {
+ expect(getAvailableSidebarItems(false).some((item) => item.id === 'project')).toBe(true);
+ expect(getSortableSidebarItemIds(false).has('project')).toBe(true);
+ });
+
it('removes Memory from workspace mode customization', () => {
const items = getAvailableSidebarItems(true);
diff --git a/src/features/HomeSidebar/Body/CustomizeSidebarModal.tsx b/src/features/HomeSidebar/Body/CustomizeSidebarModal.tsx
index 3197a3c05b9..e98e8795d20 100644
--- a/src/features/HomeSidebar/Body/CustomizeSidebarModal.tsx
+++ b/src/features/HomeSidebar/Body/CustomizeSidebarModal.tsx
@@ -59,6 +59,7 @@ const ALL_SIDEBAR_ITEMS: SidebarItemConfig[] = [
{ id: 'tasks', labelKey: 'tab.tasks', routeId: 'tasks' },
{ id: 'pages', labelKey: 'tab.pages', routeId: 'page' },
{ id: 'recents', labelKey: 'recents' },
+ { id: 'project', labelKey: 'project:sidebar.title' },
{ id: 'private', labelKey: 'navPanel.privateAgents' },
{ alwaysVisible: true, id: 'agent', labelKey: 'navPanel.agent' },
{ id: 'image', labelKey: 'tab.generation', routeId: 'image' },
diff --git a/src/features/HomeSidebar/Body/Project/index.tsx b/src/features/HomeSidebar/Body/Project/index.tsx
new file mode 100644
index 00000000000..7fa30a5f04b
--- /dev/null
+++ b/src/features/HomeSidebar/Body/Project/index.tsx
@@ -0,0 +1,75 @@
+'use client';
+
+import { AccordionItem, ActionIcon, Flexbox, Text } from '@lobehub/ui';
+import { PlusIcon, SquareKanbanIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncError from '@/components/AsyncError';
+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
+import NavItem from '@/features/NavPanel/components/NavItem';
+import { openCreateProjectModal } from '@/features/Projects/CreateProjectModal';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useCurrentProjectList, useProjectStore } from '@/store/project';
+import { useUserStore } from '@/store/user';
+import { labPreferSelectors } from '@/store/user/selectors';
+
+interface ProjectProps {
+ itemKey: string;
+}
+
+const Project = memo<ProjectProps>(({ itemKey }) => {
+ const { t } = useTranslation('project');
+ const enabled = useUserStore(labPreferSelectors.enableProjects);
+ const navigate = useWorkspaceAwareNavigate();
+ const projects = useCurrentProjectList();
+ const { error, isLoading, mutate } = useProjectStore((s) => s.useFetchProjectList)(enabled);
+
+ if (!enabled) return null;
+
+ return (
+ <AccordionItem
+ itemKey={itemKey}
+ paddingBlock={4}
+ paddingInline="8px 4px"
+ action={
+ <ActionIcon
+ icon={PlusIcon}
+ size="small"
+ title={t('create.title')}
+ onClick={openCreateProjectModal}
+ />
+ }
+ title={
+ <Text ellipsis fontSize={12} type="secondary" weight={500}>
+ {t('sidebar.title')}
+ </Text>
+ }
+ >
+ {error ? (
+ <AsyncError error={error} variant="inline" onRetry={() => mutate()} />
+ ) : isLoading ? (
+ <Flexbox align="center" padding={12}>
+ <NeuralNetworkLoading size={18} />
+ </Flexbox>
+ ) : projects.length === 0 ? (
+ <NavItem
+ icon={PlusIcon}
+ title={t('sidebar.emptyAction')}
+ onClick={openCreateProjectModal}
+ />
+ ) : (
+ projects.map((project) => (
+ <NavItem
+ icon={project.avatar || SquareKanbanIcon}
+ key={project.id}
+ title={project.name}
+ onClick={() => navigate(`/project/${project.id}`)}
+ />
+ ))
+ )}
+ </AccordionItem>
+ );
+});
+
+export default Project;
diff --git a/src/features/HomeSidebar/Body/index.tsx b/src/features/HomeSidebar/Body/index.tsx
index a15a03c5bb9..ea12b8ca29f 100644
--- a/src/features/HomeSidebar/Body/index.tsx
+++ b/src/features/HomeSidebar/Body/index.tsx
@@ -20,11 +20,13 @@ import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { SIDEBAR_SPACER_ID } from '@/store/global/selectors/systemStatus';
import { useUserStore } from '@/store/user';
+import { labPreferSelectors } from '@/store/user/selectors';
import { isModifierClick } from '@/utils/navigation';
import Agent from './Agent';
import { openCustomizeSidebarModal } from './CustomizeSidebarModal';
import Private from './Private';
+import Project from './Project';
import { useSyncWorkspaceSidebarPreference } from './useSyncWorkspaceSidebarPreference';
export enum GroupKey {
@@ -37,7 +39,12 @@ export enum GroupKey {
Resource = 'resource',
}
-const ACCORDION_KEYS = new Set<string>([GroupKey.Recents, GroupKey.Agent, GroupKey.Private]);
+const ACCORDION_KEYS = new Set<string>([
+ GroupKey.Project,
+ GroupKey.Recents,
+ GroupKey.Agent,
+ GroupKey.Private,
+]);
/** Keys rendered in the header — must be excluded from the body to avoid duplicates
* when migrating users whose persisted sidebarItems still include them. */
@@ -46,6 +53,7 @@ const HEADER_KEYS = new Set<string>(['home', 'search']);
const accordionComponents: Record<string, (key: string) => ReactElement> = {
[GroupKey.Agent]: (key) => <Agent itemKey={key} key={key} />,
[GroupKey.Private]: (key) => <Private itemKey={key} key={key} />,
+ [GroupKey.Project]: (key) => <Project itemKey={key} key={key} />,
[GroupKey.Recents]: (key) => <Recents itemKey={key} key={key} />,
};
@@ -78,6 +86,7 @@ const Body = memo(() => {
// and the section layout syncs per-member — both live in the workspace
// user preference, so load it alongside the sidebar.
const useFetchWorkspaceUserPreference = useUserStore((s) => s.useFetchWorkspaceUserPreference);
+ const enableProjects = useUserStore(labPreferSelectors.enableProjects);
useFetchWorkspaceUserPreference();
useSyncWorkspaceSidebarPreference(activeWorkspaceId);
const sidebarItems = useGlobalStore(systemStatusSelectors.sidebarItems(activeWorkspaceId));
@@ -135,9 +144,10 @@ const Body = memo(() => {
// implicitly owner-private, so a dedicated bucket would be a noisy
// empty section.
if (k === GroupKey.Private && !activeWorkspaceId) return false;
+ if (k === GroupKey.Project && !enableProjects) return false;
return k === GroupKey.Agent || k === SIDEBAR_SPACER_ID || !hiddenSections.includes(k);
},
- [hiddenSections, activeWorkspaceId],
+ [hiddenSections, activeWorkspaceId, enableProjects],
);
const visibleKeys = useMemo(
diff --git a/src/features/NavPanel/SidebarHeaderSelect.tsx b/src/features/NavPanel/SidebarHeaderSelect.tsx
new file mode 100644
index 00000000000..806f35c94ab
--- /dev/null
+++ b/src/features/NavPanel/SidebarHeaderSelect.tsx
@@ -0,0 +1,71 @@
+'use client';
+
+import { ActionIcon, Avatar, Block, Popover, Text } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { ChevronsUpDownIcon } from 'lucide-react';
+import type { ReactNode } from 'react';
+import { memo } from 'react';
+
+import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ trigger: css`
+ &[data-popup-open] {
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+}));
+
+interface SidebarHeaderSelectPopoverProps {
+ children: ReactNode;
+ content: ReactNode;
+ width?: number;
+}
+
+export const SidebarHeaderSelectPopover = memo<SidebarHeaderSelectPopoverProps>(
+ ({ children, content, width = 240 }) => (
+ <Popover
+ classNames={{ trigger: styles.trigger }}
+ content={content}
+ nativeButton={false}
+ placement={'bottomLeft'}
+ styles={{ content: { padding: 0, width } }}
+ trigger={'click'}
+ >
+ {children}
+ </Popover>
+ ),
+);
+
+interface SidebarHeaderSelectTriggerProps {
+ avatar?: ReactNode | string;
+ background?: string;
+ title: ReactNode;
+}
+
+export const SidebarHeaderSelectTrigger = memo<SidebarHeaderSelectTriggerProps>(
+ ({ avatar, background, title }) => (
+ <Block
+ clickable
+ horizontal
+ align={'center'}
+ gap={8}
+ padding={2}
+ style={{ minWidth: 32, overflow: 'hidden' }}
+ variant={'borderless'}
+ >
+ <Avatar avatar={avatar} background={background} shape={'square'} size={28} />
+ <Text ellipsis weight={500}>
+ {title}
+ </Text>
+ <ActionIcon
+ icon={ChevronsUpDownIcon}
+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}
+ style={{ width: 24 }}
+ />
+ </Block>
+ ),
+);
+
+SidebarHeaderSelectPopover.displayName = 'SidebarHeaderSelectPopover';
+SidebarHeaderSelectTrigger.displayName = 'SidebarHeaderSelectTrigger';
diff --git a/src/features/NavPanel/routeKey.test.ts b/src/features/NavPanel/routeKey.test.ts
index d1a39be0bfb..61ab6994995 100644
--- a/src/features/NavPanel/routeKey.test.ts
+++ b/src/features/NavPanel/routeKey.test.ts
@@ -20,6 +20,8 @@ describe('resolveNavPanelKey', () => {
['/lobe-team/eval', 'lobe-team', 'eval'],
['/lobe-team/eval/bench/benchmark-1', 'lobe-team', 'evalBench'],
['/lobe-team/page/page-1', 'lobe-team', 'page'],
+ ['/project/project-1', null, 'project'],
+ ['/lobe-team/project/project-1/library/kb-1', 'lobe-team', 'project'],
['/lobe-team/image', 'lobe-team', 'image'],
['/lobe-team/video', 'lobe-team', 'video'],
])('maps %s to %s', (pathname, activeWorkspaceSlug, expected) => {
diff --git a/src/features/NavPanel/routeKey.ts b/src/features/NavPanel/routeKey.ts
index 7d39bcd59ff..ce012548d71 100644
--- a/src/features/NavPanel/routeKey.ts
+++ b/src/features/NavPanel/routeKey.ts
@@ -41,6 +41,10 @@ export const resolveNavPanelKey = (
return 'page';
}
+ case 'project': {
+ return 'project';
+ }
+
case 'resource': {
return childSegment === 'library' ? 'resourceLibrary' : 'resource';
}
diff --git a/src/features/Projects/Acceptance/RejectModal.tsx b/src/features/Projects/Acceptance/RejectModal.tsx
new file mode 100644
index 00000000000..853cbacbbd3
--- /dev/null
+++ b/src/features/Projects/Acceptance/RejectModal.tsx
@@ -0,0 +1,56 @@
+'use client';
+
+import { TextArea } from '@lobehub/ui';
+import { Button, createModal, ModalFooter, useModalContext } from '@lobehub/ui/base-ui';
+import { t as translate } from 'i18next';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const RejectContent = memo<{ onReject: (comment: string) => Promise<void> }>(({ onReject }) => {
+ const { t } = useTranslation('project');
+ const { close } = useModalContext();
+ const [comment, setComment] = useState('');
+ const [loading, setLoading] = useState(false);
+
+ return (
+ <>
+ <div style={{ padding: 16 }}>
+ <TextArea
+ autoFocus
+ placeholder={t('acceptance.rejectPlaceholder')}
+ rows={4}
+ value={comment}
+ onChange={(event) => setComment(event.target.value)}
+ />
+ </div>
+ <ModalFooter>
+ <Button onClick={close}>{t('acceptance.cancel')}</Button>
+ <Button
+ disabled={!comment.trim()}
+ loading={loading}
+ type={'primary'}
+ onClick={async () => {
+ setLoading(true);
+ try {
+ await onReject(comment.trim());
+ close();
+ } finally {
+ setLoading(false);
+ }
+ }}
+ >
+ {t('acceptance.reject')}
+ </Button>
+ </ModalFooter>
+ </>
+ );
+});
+
+export const openRejectProjectModal = (onReject: (comment: string) => Promise<void>) =>
+ createModal({
+ content: <RejectContent onReject={onReject} />,
+ footer: null,
+ styles: { content: { padding: 0 } },
+ title: translate('acceptance.rejectTitle', { ns: 'project' }),
+ width: 440,
+ });
diff --git a/src/features/Projects/Acceptance/actions.test.ts b/src/features/Projects/Acceptance/actions.test.ts
new file mode 100644
index 00000000000..b4096c542e7
--- /dev/null
+++ b/src/features/Projects/Acceptance/actions.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from 'vitest';
+
+import { getProjectAcceptanceActions } from './actions';
+
+describe('getProjectAcceptanceActions', () => {
+ it.each([
+ ['backlog', ['start']],
+ ['active', ['requestCompletion']],
+ ['paused', ['requestCompletion']],
+ ['reviewing', ['reject', 'accept']],
+ ['completed', ['reopen']],
+ ['archived', ['reopen']],
+ ] as const)('returns valid human workflow actions for %s', (status, expected) => {
+ expect(getProjectAcceptanceActions(status)).toEqual(expected);
+ });
+});
diff --git a/src/features/Projects/Acceptance/actions.ts b/src/features/Projects/Acceptance/actions.ts
new file mode 100644
index 00000000000..0764c98b558
--- /dev/null
+++ b/src/features/Projects/Acceptance/actions.ts
@@ -0,0 +1,26 @@
+import type { ProjectStatus } from '@lobechat/types';
+
+export type ProjectAcceptanceAction =
+ 'accept' | 'reopen' | 'reject' | 'requestCompletion' | 'start';
+
+export const getProjectAcceptanceActions = (status: ProjectStatus): ProjectAcceptanceAction[] => {
+ switch (status) {
+ case 'backlog': {
+ return ['start'];
+ }
+ case 'active':
+ case 'paused': {
+ return ['requestCompletion'];
+ }
+ case 'reviewing': {
+ return ['reject', 'accept'];
+ }
+ case 'completed':
+ case 'archived': {
+ return ['reopen'];
+ }
+ default: {
+ return [];
+ }
+ }
+};
diff --git a/src/features/Projects/Acceptance/index.tsx b/src/features/Projects/Acceptance/index.tsx
new file mode 100644
index 00000000000..bf8f9631948
--- /dev/null
+++ b/src/features/Projects/Acceptance/index.tsx
@@ -0,0 +1,161 @@
+'use client';
+
+import type { ProjectCompletionDecision, ProjectStatus } from '@lobechat/types';
+import { Block, Empty, Flexbox, Icon, Text } from '@lobehub/ui';
+import { Button, toast } from '@lobehub/ui/base-ui';
+import { BadgeCheckIcon, Clock3Icon } from 'lucide-react';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncError from '@/components/AsyncError';
+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
+import NavHeader from '@/features/NavHeader';
+import WideScreenContainer from '@/features/WideScreenContainer';
+import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';
+import { projectService } from '@/services/project';
+import { useCurrentProjectDetail, useProjectStore } from '@/store/project';
+
+import { getProjectAcceptanceActions, type ProjectAcceptanceAction } from './actions';
+import { openRejectProjectModal } from './RejectModal';
+
+const PROJECT_STATUS_KEYS: Record<ProjectStatus, `acceptance.status.${ProjectStatus}`> = {
+ active: 'acceptance.status.active',
+ archived: 'acceptance.status.archived',
+ backlog: 'acceptance.status.backlog',
+ canceled: 'acceptance.status.canceled',
+ completed: 'acceptance.status.completed',
+ paused: 'acceptance.status.paused',
+ reviewing: 'acceptance.status.reviewing',
+};
+
+const PROJECT_DECISION_KEYS: Record<
+ ProjectCompletionDecision,
+ `acceptance.decision.${ProjectCompletionDecision}`
+> = {
+ accepted: 'acceptance.decision.accepted',
+ rejected: 'acceptance.decision.rejected',
+};
+
+const ProjectAcceptance = memo(() => {
+ const { t } = useTranslation('project');
+ const { projectId } = useActiveRouteParams<{ projectId: string }>();
+ const id = projectId ?? '';
+ const detail = useCurrentProjectDetail(id);
+ const detailSWR = useProjectStore((s) => s.useFetchProjectDetail)(projectId);
+ const [loadingAction, setLoadingAction] = useState<ProjectAcceptanceAction>();
+
+ if (detailSWR.error)
+ return <AsyncError error={detailSWR.error} variant={'page'} onRetry={detailSWR.mutate} />;
+ if (!detail)
+ return (
+ <Flexbox align={'center'} flex={1} justify={'center'}>
+ <NeuralNetworkLoading />
+ </Flexbox>
+ );
+
+ const actions = getProjectAcceptanceActions(detail.project.status);
+ const completionReviews = detail.completionReviews ?? [];
+ const execute = async (action: Exclude<ProjectAcceptanceAction, 'reject'>) => {
+ setLoadingAction(action);
+ try {
+ if (action === 'start') await projectService.updateStatus(id, 'active');
+ if (action === 'requestCompletion') await projectService.requestCompletion(id);
+ if (action === 'accept') await projectService.acceptCompletion(id);
+ if (action === 'reopen') await projectService.reopen(id);
+ await detailSWR.mutate();
+ toast.success(t(`acceptance.success.${action}`));
+ } catch {
+ toast.error(t('acceptance.operationFailed'));
+ } finally {
+ setLoadingAction(undefined);
+ }
+ };
+
+ const reject = () =>
+ openRejectProjectModal(async (comment) => {
+ await projectService.rejectCompletion(id, comment);
+ await detailSWR.mutate();
+ toast.success(t('acceptance.success.reject'));
+ });
+
+ return (
+ <Flexbox flex={1} height={'100%'}>
+ <NavHeader left={<Text weight={600}>{t('acceptance.title')}</Text>} />
+ <WideScreenContainer
+ flex={1}
+ gap={20}
+ paddingBlock={24}
+ wrapperStyle={{ flex: 1, overflowY: 'auto' }}
+ >
+ <Flexbox gap={4}>
+ <Text fontSize={24} weight={650}>
+ {t('acceptance.title')}
+ </Text>
+ <Text type={'secondary'}>{t('acceptance.description')}</Text>
+ </Flexbox>
+ <Block padding={20} variant={'filled'}>
+ <Flexbox horizontal align={'center'} gap={16} justify={'space-between'} wrap={'wrap'}>
+ <Flexbox horizontal align={'center'} gap={12}>
+ <Icon icon={BadgeCheckIcon} size={24} />
+ <Flexbox gap={2}>
+ <Text weight={600}>{t('acceptance.currentStatus')}</Text>
+ <Text type={'secondary'}>{t(PROJECT_STATUS_KEYS[detail.project.status])}</Text>
+ </Flexbox>
+ </Flexbox>
+ <Flexbox horizontal gap={8}>
+ {actions.map((action) => (
+ <Button
+ key={action}
+ loading={loadingAction === action}
+ type={
+ action === 'accept' || action === 'requestCompletion' ? 'primary' : undefined
+ }
+ onClick={() => (action === 'reject' ? reject() : void execute(action))}
+ >
+ {t(`acceptance.actions.${action}`)}
+ </Button>
+ ))}
+ </Flexbox>
+ </Flexbox>
+ </Block>
+ <Flexbox gap={10}>
+ <Text fontSize={16} weight={600}>
+ {t('acceptance.history')}
+ </Text>
+ {completionReviews.length === 0 ? (
+ <Block padding={32} variant={'outlined'}>
+ <Empty
+ description={t('acceptance.emptyDescription')}
+ title={t('acceptance.emptyTitle')}
+ />
+ </Block>
+ ) : (
+ completionReviews.map((review) => (
+ <Block
+ horizontal
+ align={'flex-start'}
+ gap={12}
+ key={review.id}
+ padding={16}
+ variant={'outlined'}
+ >
+ <Icon icon={Clock3Icon} />
+ <Flexbox gap={4}>
+ <Text weight={600}>
+ {t('acceptance.round', { round: review.round })} ·{' '}
+ {t(PROJECT_DECISION_KEYS[review.decision])}
+ </Text>
+ {review.comment && <Text type={'secondary'}>{review.comment}</Text>}
+ </Flexbox>
+ </Block>
+ ))
+ )}
+ </Flexbox>
+ </WideScreenContainer>
+ </Flexbox>
+ );
+});
+
+ProjectAcceptance.displayName = 'ProjectAcceptance';
+
+export default ProjectAcceptance;
diff --git a/src/features/Projects/Conversation/index.tsx b/src/features/Projects/Conversation/index.tsx
new file mode 100644
index 00000000000..999754ef9ad
--- /dev/null
+++ b/src/features/Projects/Conversation/index.tsx
@@ -0,0 +1,85 @@
+'use client';
+
+import { Center, Flexbox, Text } from '@lobehub/ui';
+import { memo, useCallback, useLayoutEffect } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useParams } from 'react-router';
+
+import AsyncError from '@/components/AsyncError';
+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
+import NavHeader from '@/features/NavHeader';
+import { useInitAgentConfig } from '@/hooks/useInitAgentConfig';
+import ChatConversation from '@/routes/(main)/agent/features/Conversation';
+import ChatHydration from '@/routes/(main)/agent/features/Conversation/ChatHydration';
+import { useAgentStore } from '@/store/agent';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+import { useCurrentProjectDetail, useProjectStore } from '@/store/project';
+
+import { getProjectConversationPath } from '../Layout/navigation';
+
+const ProjectConversation = memo(() => {
+ const { t } = useTranslation('project');
+ const { projectId, topicId } = useParams<{ projectId: string; topicId?: string }>();
+ const detail = useCurrentProjectDetail(projectId);
+ const detailSWR = useProjectStore((s) => s.useFetchProjectDetail)(projectId);
+ const coordinatorAgentId = detail?.project.coordinatorAgentId;
+ const topicTitle = useChatStore((s) =>
+ topicId ? topicSelectors.getTopicById(topicId)(s)?.title : undefined,
+ );
+
+ useInitAgentConfig(coordinatorAgentId);
+
+ useLayoutEffect(() => {
+ if (!coordinatorAgentId) return;
+
+ useAgentStore.setState(
+ { activeAgentId: coordinatorAgentId },
+ false,
+ 'ProjectConversation/syncAgentId',
+ );
+ useChatStore.setState(
+ { activeAgentId: coordinatorAgentId },
+ false,
+ 'ProjectConversation/syncAgentId',
+ );
+ }, [coordinatorAgentId]);
+
+ const getConversationPath = useCallback(
+ () => getProjectConversationPath(projectId!),
+ [projectId],
+ );
+ const getTopicPath = useCallback(
+ (_agentId: string, topicId: string) => getProjectConversationPath(projectId!, topicId),
+ [projectId],
+ );
+
+ if (detailSWR.error) {
+ return <AsyncError error={detailSWR.error} variant="page" onRetry={detailSWR.mutate} />;
+ }
+ if (detailSWR.isLoading || !coordinatorAgentId) {
+ return (
+ <Center height="100%" width="100%">
+ <NeuralNetworkLoading />
+ </Center>
+ );
+ }
+
+ return (
+ <Flexbox flex={1} height="100%" style={{ minHeight: 0, minWidth: 0 }}>
+ <NavHeader
+ left={
+ <Text ellipsis weight={600}>
+ {topicTitle || t('sidebar.newConversation')}
+ </Text>
+ }
+ />
+ <ChatHydration getConversationPath={getConversationPath} getTopicPath={getTopicPath} />
+ <ChatConversation />
+ </Flexbox>
+ );
+});
+
+ProjectConversation.displayName = 'ProjectConversation';
+
+export default ProjectConversation;
diff --git a/src/features/Projects/CreateProjectModal.tsx b/src/features/Projects/CreateProjectModal.tsx
new file mode 100644
index 00000000000..077f2c2441b
--- /dev/null
+++ b/src/features/Projects/CreateProjectModal.tsx
@@ -0,0 +1,122 @@
+import { Flexbox, Input, Text } from '@lobehub/ui';
+import { Button, createModal, ModalFooter, toast, useModalContext } from '@lobehub/ui/base-ui';
+import { t as translate } from 'i18next';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useProjectStore } from '@/store/project';
+
+import { getCreateProjectInput, isProjectSlugValid } from './createProjectForm';
+
+interface CreateProjectFormState {
+ identifier: string;
+ loading: boolean;
+ name: string;
+ slug: string;
+}
+
+const CreateProjectContent = memo(() => {
+ const { t } = useTranslation(['project', 'common']);
+ const { close } = useModalContext();
+ const navigate = useWorkspaceAwareNavigate();
+ const createProject = useProjectStore((s) => s.createProject);
+ const [form, setForm] = useState<CreateProjectFormState>({
+ identifier: '',
+ loading: false,
+ name: '',
+ slug: '',
+ });
+ const createInput = getCreateProjectInput(form);
+ const slugValid = isProjectSlugValid(form.slug);
+
+ const updateForm = (patch: Partial<CreateProjectFormState>) => {
+ setForm((current) => ({ ...current, ...patch }));
+ };
+
+ const handleCreate = async () => {
+ if (!createInput || form.loading) return;
+ updateForm({ loading: true });
+ try {
+ const project = await createProject(createInput);
+ close();
+ navigate(`/project/${project.id}`);
+ } catch (error) {
+ console.error('Failed to create project', error);
+ toast.error(t('operationFailed', { ns: 'common' }));
+ } finally {
+ updateForm({ loading: false });
+ }
+ };
+
+ return (
+ <>
+ <Flexbox gap={16} padding={16}>
+ <Flexbox gap={6}>
+ <Text fontSize={13} weight={500}>
+ {t('create.nameLabel')}
+ </Text>
+ <Input
+ autoFocus
+ maxLength={255}
+ placeholder={t('create.namePlaceholder')}
+ value={form.name}
+ onChange={(event) => updateForm({ name: event.target.value })}
+ onPressEnter={handleCreate}
+ />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Text fontSize={13} weight={500}>
+ {t('create.identifierLabel')}
+ </Text>
+ <Input
+ maxLength={6}
+ placeholder={t('create.identifierPlaceholder')}
+ value={form.identifier}
+ onChange={(event) => updateForm({ identifier: event.target.value.toUpperCase() })}
+ onPressEnter={handleCreate}
+ />
+ <Text fontSize={12} type="secondary">
+ {t('create.identifierDescription')}
+ </Text>
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Text fontSize={13} weight={500}>
+ {t('create.slugLabel')}
+ </Text>
+ <Input
+ maxLength={100}
+ placeholder={t('create.slugPlaceholder')}
+ status={slugValid ? undefined : 'error'}
+ value={form.slug}
+ onChange={(event) => updateForm({ slug: event.target.value.toLowerCase() })}
+ onPressEnter={handleCreate}
+ />
+ <Text fontSize={12} type={slugValid ? 'secondary' : 'danger'}>
+ {t(slugValid ? 'create.slugDescription' : 'create.slugInvalid')}
+ </Text>
+ </Flexbox>
+ </Flexbox>
+ <ModalFooter>
+ <Button onClick={close}>{t('cancel', { ns: 'common' })}</Button>
+ <Button
+ disabled={!createInput}
+ loading={form.loading}
+ type="primary"
+ onClick={handleCreate}
+ >
+ {t('create.action')}
+ </Button>
+ </ModalFooter>
+ </>
+ );
+});
+
+export const openCreateProjectModal = () =>
+ createModal({
+ content: <CreateProjectContent />,
+ footer: null,
+ styles: { content: { padding: 0 } },
+ title: translate('create.title', { ns: 'project' }),
+ width: 460,
+ });
diff --git a/src/features/Projects/Goals/index.tsx b/src/features/Projects/Goals/index.tsx
new file mode 100644
index 00000000000..c50146b984c
--- /dev/null
+++ b/src/features/Projects/Goals/index.tsx
@@ -0,0 +1,12 @@
+'use client';
+
+import { AgentGoalsPage } from '@/features/AgentGoals';
+import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';
+
+const ProjectGoals = () => {
+ const { projectId } = useActiveRouteParams<{ projectId: string }>();
+
+ return <AgentGoalsPage projectId={projectId} />;
+};
+
+export default ProjectGoals;
diff --git a/src/features/Projects/Layout/ProjectHeader.tsx b/src/features/Projects/Layout/ProjectHeader.tsx
new file mode 100644
index 00000000000..a19f402f403
--- /dev/null
+++ b/src/features/Projects/Layout/ProjectHeader.tsx
@@ -0,0 +1,61 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { SquareKanbanIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import NavItem from '@/features/NavPanel/components/NavItem';
+import SideBarHeaderLayout from '@/features/NavPanel/SideBarHeaderLayout';
+import {
+ SidebarHeaderSelectPopover,
+ SidebarHeaderSelectTrigger,
+} from '@/features/NavPanel/SidebarHeaderSelect';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import type { ProjectDetail } from '@/store/project';
+import { useCurrentProjectList, useProjectStore } from '@/store/project';
+
+interface ProjectHeaderProps {
+ project?: ProjectDetail['project'];
+}
+
+const ProjectHeader = memo<ProjectHeaderProps>(({ project }) => {
+ const { t } = useTranslation('project');
+ const navigate = useWorkspaceAwareNavigate();
+ const projects = useCurrentProjectList();
+ useProjectStore((s) => s.useFetchProjectList)(true);
+
+ const handleSelect = (projectId: string) => navigate(`/project/${projectId}`);
+
+ const content = (
+ <Flexbox gap={4} padding={8} style={{ maxHeight: '50vh', overflowY: 'auto' }}>
+ {projects.map((item) => (
+ <NavItem
+ active={item.id === project?.id}
+ icon={item.avatar || SquareKanbanIcon}
+ key={item.id}
+ title={item.name}
+ onClick={() => handleSelect(item.id)}
+ />
+ ))}
+ </Flexbox>
+ );
+
+ return (
+ <SideBarHeaderLayout
+ backTo="/"
+ left={
+ <SidebarHeaderSelectPopover content={content}>
+ <SidebarHeaderSelectTrigger
+ avatar={project?.avatar || project?.name || t('sidebar.title')}
+ title={project?.name || t('sidebar.title')}
+ />
+ </SidebarHeaderSelectPopover>
+ }
+ />
+ );
+});
+
+ProjectHeader.displayName = 'ProjectHeader';
+
+export default ProjectHeader;
diff --git a/src/features/Projects/Layout/Sidebar.tsx b/src/features/Projects/Layout/Sidebar.tsx
new file mode 100644
index 00000000000..0c04d8cf026
--- /dev/null
+++ b/src/features/Projects/Layout/Sidebar.tsx
@@ -0,0 +1,71 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { ListTodoIcon, TargetIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useLocation } from 'react-router';
+
+import AsyncError from '@/components/AsyncError';
+import NavItem from '@/features/NavPanel/components/NavItem';
+import { NavPanelPortal } from '@/features/NavPanel/NavPanelPortal';
+import SideBarLayout from '@/features/NavPanel/SideBarLayout';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';
+import { useCurrentProjectDetail, useProjectStore } from '@/store/project';
+
+import { getProjectGoalsPath, getProjectTasksPath } from './navigation';
+import ProjectHeader from './ProjectHeader';
+
+const ProjectSidebarContent = memo(() => {
+ const { t } = useTranslation('project');
+ const { projectId } = useActiveRouteParams<{ projectId: string }>();
+ const navigate = useWorkspaceAwareNavigate();
+ const { pathname } = useLocation();
+ const detail = useCurrentProjectDetail(projectId);
+ const detailSWR = useProjectStore((s) => s.useFetchProjectDetail)(projectId);
+ const projectTasksPath = getProjectTasksPath(projectId!);
+ const projectGoalsPath = getProjectGoalsPath(projectId!);
+
+ const header = <ProjectHeader project={detail?.project} />;
+
+ if (detailSWR.error)
+ return (
+ <SideBarLayout
+ body={<AsyncError error={detailSWR.error} variant="inline" onRetry={detailSWR.mutate} />}
+ header={header}
+ />
+ );
+
+ return (
+ <SideBarLayout
+ header={header}
+ body={
+ <Flexbox gap={8} paddingInline={4}>
+ <NavItem
+ active={pathname === projectTasksPath}
+ icon={ListTodoIcon}
+ title={t('sections.tasks')}
+ onClick={() => navigate(projectTasksPath)}
+ />
+ <NavItem
+ active={pathname === projectGoalsPath}
+ icon={TargetIcon}
+ title={t('sections.goals')}
+ onClick={() => navigate(projectGoalsPath)}
+ />
+ </Flexbox>
+ }
+ />
+ );
+});
+
+const ProjectSidebar = memo(() => (
+ <NavPanelPortal navKey="project">
+ <ProjectSidebarContent />
+ </NavPanelPortal>
+));
+
+ProjectSidebar.displayName = 'ProjectSidebar';
+
+export default ProjectSidebar;
diff --git a/src/features/Projects/Layout/index.tsx b/src/features/Projects/Layout/index.tsx
new file mode 100644
index 00000000000..fe5a5a7c66a
--- /dev/null
+++ b/src/features/Projects/Layout/index.tsx
@@ -0,0 +1,47 @@
+'use client';
+
+import { Center, Flexbox, Icon, Text } from '@lobehub/ui';
+import { Button } from '@lobehub/ui/base-ui';
+import { FolderKanbanIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Outlet } from 'react-router';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useUserStore } from '@/store/user';
+import { labPreferSelectors } from '@/store/user/selectors';
+
+import ProjectSidebar from './Sidebar';
+
+const ProjectLayout = memo(() => {
+ const { t } = useTranslation('project');
+ const navigate = useWorkspaceAwareNavigate();
+ const enabled = useUserStore(labPreferSelectors.enableProjects);
+
+ if (!enabled) {
+ return (
+ <Center height="100%" width="100%">
+ <Flexbox align="center" gap={12}>
+ <Icon icon={FolderKanbanIcon} size={40} />
+ <Text fontSize={18} weight={600}>
+ {t('disabled.title')}
+ </Text>
+ <Button onClick={() => navigate('/settings/labs')}>{t('disabled.action')}</Button>
+ </Flexbox>
+ </Center>
+ );
+ }
+
+ return (
+ <>
+ <ProjectSidebar />
+ <Flexbox flex={1} height="100%" style={{ minWidth: 0 }}>
+ <Outlet />
+ </Flexbox>
+ </>
+ );
+});
+
+ProjectLayout.displayName = 'ProjectLayout';
+
+export default ProjectLayout;
diff --git a/src/features/Projects/Layout/navigation.test.ts b/src/features/Projects/Layout/navigation.test.ts
new file mode 100644
index 00000000000..bc2562a11fb
--- /dev/null
+++ b/src/features/Projects/Layout/navigation.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ getProjectAcceptancePath,
+ getProjectAgentPath,
+ getProjectConversationPath,
+ getProjectConversationStartPath,
+ getProjectGoalsPath,
+ getProjectLibraryPath,
+ getProjectTasksPath,
+} from './navigation';
+
+describe('project workspace navigation', () => {
+ it('builds routes for project agents and libraries', () => {
+ expect(getProjectAgentPath('agt_1')).toBe('/agent/agt_1');
+ expect(getProjectLibraryPath('prj_1', 'kb_1')).toBe('/project/prj_1/library/kb_1');
+ expect(getProjectTasksPath('prj_1')).toBe('/project/prj_1/tasks');
+ expect(getProjectGoalsPath('prj_1')).toBe('/project/prj_1/goals');
+ expect(getProjectAcceptancePath('prj_1')).toBe('/project/prj_1/acceptance');
+ });
+
+ it('builds new and existing conversation routes inside the project', () => {
+ expect(getProjectConversationPath('prj_1')).toBe('/project/prj_1/conversation');
+ expect(getProjectConversationPath('prj_1', 'tpc_1')).toBe('/project/prj_1/conversation/tpc_1');
+ expect(getProjectConversationStartPath('prj_1', 'Plan Q3 & ship')).toBe(
+ '/project/prj_1/conversation?message=Plan%20Q3%20%26%20ship',
+ );
+ });
+});
diff --git a/src/features/Projects/Layout/navigation.ts b/src/features/Projects/Layout/navigation.ts
new file mode 100644
index 00000000000..f60a41eba0e
--- /dev/null
+++ b/src/features/Projects/Layout/navigation.ts
@@ -0,0 +1,16 @@
+export const getProjectAgentPath = (agentId: string) => `/agent/${agentId}`;
+
+export const getProjectConversationPath = (projectId: string, topicId?: string) =>
+ topicId ? `/project/${projectId}/conversation/${topicId}` : `/project/${projectId}/conversation`;
+
+export const getProjectConversationStartPath = (projectId: string, message: string) =>
+ `${getProjectConversationPath(projectId)}?message=${encodeURIComponent(message)}`;
+
+export const getProjectLibraryPath = (projectId: string, libraryId: string) =>
+ `/project/${projectId}/library/${libraryId}`;
+
+export const getProjectTasksPath = (projectId: string) => `/project/${projectId}/tasks`;
+
+export const getProjectGoalsPath = (projectId: string) => `/project/${projectId}/goals`;
+
+export const getProjectAcceptancePath = (projectId: string) => `/project/${projectId}/acceptance`;
diff --git a/src/features/Projects/Workspace/ProjectDashboard.tsx b/src/features/Projects/Workspace/ProjectDashboard.tsx
new file mode 100644
index 00000000000..52c1a46d42f
--- /dev/null
+++ b/src/features/Projects/Workspace/ProjectDashboard.tsx
@@ -0,0 +1,340 @@
+'use client';
+
+import type { TaskStatus, WorkSummaryItem } from '@lobechat/types';
+import { Block, Center, Empty, Flexbox, Icon, Skeleton, Tag, Text } from '@lobehub/ui';
+import { Button } from '@lobehub/ui/base-ui';
+import { Progress } from 'antd';
+import { createStaticStyles, cssVar } from 'antd-style';
+import {
+ BadgeCheckIcon,
+ CheckCircle2Icon,
+ CircleDotIcon,
+ Clock3Icon,
+ PackageOpenIcon,
+ TargetIcon,
+ TriangleAlertIcon,
+} from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import AsyncError from '@/components/AsyncError';
+import NavItem from '@/features/NavPanel/components/NavItem';
+import {
+ getProjectAcceptancePath,
+ getProjectGoalsPath,
+ getProjectTasksPath,
+} from '@/features/Projects/Layout/navigation';
+import WorkSummaryCard from '@/features/Work/WorkSummaryCard';
+import { useOpenWork } from '@/features/WorkGallery/useOpenWork';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useClientDataSWR } from '@/libs/swr';
+import { workKeys } from '@/libs/swr/keys';
+import { workService } from '@/services/work';
+import { goalSelectors, useGoalStore } from '@/store/goal';
+import type { ProjectDetail } from '@/store/project';
+
+const styles = createStaticStyles(({ css }) => ({
+ attention: css`
+ padding-block: 10px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+
+ &:last-child {
+ border-block-end: 0;
+ }
+ `,
+ columns: css`
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) 300px;
+ gap: 32px;
+ align-items: start;
+
+ margin-block-start: 40px;
+
+ @media (width <= 960px) {
+ grid-template-columns: 1fr;
+ }
+ `,
+ goal: css`
+ padding-block: 12px;
+ padding-inline: 14px;
+ border-radius: 12px;
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ goalGrid: css`
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ gap: 10px;
+
+ @media (width <= 760px) {
+ grid-template-columns: 1fr;
+ }
+ `,
+ main: css`
+ min-width: 0;
+ `,
+ progress: css`
+ padding: 18px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 16px;
+ background: color-mix(in srgb, ${cssVar.colorBgContainer} 84%, ${cssVar.colorFillQuaternary});
+ `,
+ rail: css`
+ position: sticky;
+ inset-block-start: 24px;
+ min-width: 0;
+ `,
+ railCard: css`
+ padding: 16px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 16px;
+ background: color-mix(in srgb, ${cssVar.colorBgContainer} 78%, transparent);
+ `,
+ section: css`
+ padding-block: 18px;
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+ works: css`
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 10px;
+
+ @media (width <= 760px) {
+ grid-template-columns: 1fr;
+ }
+ `,
+}));
+
+const TERMINAL_STATUSES = new Set<TaskStatus | string>(['canceled', 'completed']);
+const ATTENTION_STATUSES = new Set<TaskStatus | string>(['failed', 'paused']);
+const isGoalTask = (task: NonNullable<ProjectDetail['tasks']>[number]) => {
+ if (!task.config || typeof task.config !== 'object') return false;
+ return Boolean((task.config as { goal?: unknown }).goal);
+};
+
+interface ProjectDashboardProps {
+ detail: ProjectDetail;
+ projectId: string;
+}
+
+const SectionTitle = memo<{
+ action?: string;
+ count?: number;
+ onAction?: () => void;
+ title: string;
+}>(({ action, count, onAction, title }) => (
+ <Flexbox horizontal align={'center'} justify={'space-between'}>
+ <Flexbox horizontal align={'center'} gap={7}>
+ <Text fontSize={16} weight={600}>
+ {title}
+ </Text>
+ {count !== undefined && <Tag>{count}</Tag>}
+ </Flexbox>
+ {action && (
+ <Button size={'small'} type={'text'} onClick={onAction}>
+ {action}
+ </Button>
+ )}
+ </Flexbox>
+));
+
+const ProjectDashboard = memo<ProjectDashboardProps>(({ detail, projectId }) => {
+ const { t } = useTranslation('project');
+ const navigate = useWorkspaceAwareNavigate();
+ const openWork = useOpenWork();
+ const workspaceId = useActiveWorkspaceId();
+ const goalScope = `project:${projectId}`;
+ const goals = useGoalStore(goalSelectors.goalList(goalScope));
+ const goalSWR = useGoalStore((s) => s.useFetchGoals)(undefined, projectId);
+ const coordinatorAgentId = detail.project.coordinatorAgentId;
+ const workSWR = useClientDataSWR(
+ coordinatorAgentId
+ ? workKeys.workspace(workspaceId, `project:${projectId}:${coordinatorAgentId}`)
+ : null,
+ () =>
+ workService.listByWorkspace({
+ limit: 4,
+ originAgentId: coordinatorAgentId,
+ }),
+ );
+
+ const tasks = (detail.tasks ?? []).filter((task) => !isGoalTask(task));
+ const activeTasks = tasks.filter((task) => !TERMINAL_STATUSES.has(task.status)).slice(0, 5);
+ const attentionTasks = tasks.filter((task) => ATTENTION_STATUSES.has(task.status)).slice(0, 3);
+ const completedGoals = goals.filter((goal) => goal.status === 'completed').length;
+ const progress = goals.length ? Math.round((completedGoals / goals.length) * 100) : 0;
+ const works = workSWR.data?.items ?? [];
+ const goalPreview = useMemo(() => goals.slice(0, 3), [goals]);
+
+ return (
+ <div className={styles.columns}>
+ <Flexbox className={styles.main} gap={24}>
+ <Flexbox gap={12}>
+ <SectionTitle title={t('overview.goalProgress')} />
+ {goalSWR.error ? (
+ <AsyncError
+ error={goalSWR.error}
+ variant={'inline'}
+ onRetry={() => void goalSWR.mutate()}
+ />
+ ) : goalSWR.isLoading && goals.length === 0 ? (
+ <Skeleton active paragraph={{ rows: 4 }} />
+ ) : goals.length === 0 ? (
+ <Block padding={24} variant={'outlined'}>
+ <Center gap={10}>
+ <Icon icon={TargetIcon} size={24} />
+ <Text type={'secondary'}>{t('overview.goalsEmpty')}</Text>
+ <Button onClick={() => navigate(getProjectGoalsPath(projectId))}>
+ {t('goals.create')}
+ </Button>
+ </Center>
+ </Block>
+ ) : (
+ <Flexbox className={styles.progress} gap={16}>
+ <Flexbox horizontal align={'flex-start'} justify={'space-between'}>
+ <Flexbox gap={4}>
+ <Text weight={600}>{t('overview.goalSummary')}</Text>
+ <Text fontSize={13} type={'secondary'}>
+ {t('overview.goalCount', { completed: completedGoals, total: goals.length })}
+ </Text>
+ </Flexbox>
+ <Text fontSize={22} weight={650}>
+ {progress}%
+ </Text>
+ </Flexbox>
+ <Progress percent={progress} showInfo={false} />
+ <div className={styles.goalGrid}>
+ {goalPreview.map((goal) => (
+ <Flexbox className={styles.goal} gap={5} key={goal.id}>
+ <Flexbox horizontal align={'center'} gap={6}>
+ <Icon
+ color={goal.status === 'completed' ? cssVar.colorSuccess : undefined}
+ icon={goal.status === 'completed' ? CheckCircle2Icon : CircleDotIcon}
+ size={15}
+ />
+ <Text ellipsis weight={500}>
+ {goal.name || goal.instruction}
+ </Text>
+ </Flexbox>
+ <Text fontSize={12} type={'secondary'}>
+ {t(`goals.status.${goal.status}`, { defaultValue: goal.status })}
+ </Text>
+ </Flexbox>
+ ))}
+ </div>
+ </Flexbox>
+ )}
+ </Flexbox>
+
+ <Flexbox className={styles.section} gap={8}>
+ <SectionTitle
+ action={t('overview.viewAllTasks')}
+ count={activeTasks.length}
+ title={t('overview.activeTasks')}
+ onAction={() => navigate(getProjectTasksPath(projectId))}
+ />
+ {activeTasks.length === 0 ? (
+ <Text style={{ paddingBlock: 16 }} type={'secondary'}>
+ {t('overview.noActiveTasks')}
+ </Text>
+ ) : (
+ activeTasks.map((task) => (
+ <NavItem
+ description={task.description || task.instruction}
+ icon={task.status === 'paused' ? Clock3Icon : CircleDotIcon}
+ key={task.id}
+ title={task.name || task.instruction}
+ extra={
+ <Tag size={'small'}>
+ {t(`goals.status.${task.status}`, { defaultValue: task.status })}
+ </Tag>
+ }
+ onClick={() => navigate(`/task/${task.id}`)}
+ />
+ ))
+ )}
+ </Flexbox>
+
+ <Flexbox className={styles.section} gap={12}>
+ <SectionTitle count={works.length} title={t('overview.latestWorks')} />
+ {workSWR.error ? (
+ <AsyncError
+ error={workSWR.error}
+ variant={'inline'}
+ onRetry={() => void workSWR.mutate()}
+ />
+ ) : workSWR.isLoading ? (
+ <Skeleton active paragraph={{ rows: 4 }} />
+ ) : works.length === 0 ? (
+ <Empty
+ description={t('overview.worksEmptyDescription')}
+ icon={PackageOpenIcon}
+ title={t('overview.worksEmptyTitle')}
+ />
+ ) : (
+ <div className={styles.works}>
+ {works.map((work: WorkSummaryItem) => (
+ <WorkSummaryCard item={work} key={work.id} onOpen={openWork} />
+ ))}
+ </div>
+ )}
+ </Flexbox>
+ </Flexbox>
+
+ <Flexbox className={styles.rail} gap={16}>
+ <Flexbox className={styles.railCard} gap={12}>
+ <SectionTitle count={attentionTasks.length} title={t('overview.needsAttention')} />
+ {attentionTasks.length === 0 ? (
+ <Flexbox align={'center'} gap={8} paddingBlock={12}>
+ <Icon color={cssVar.colorSuccess} icon={BadgeCheckIcon} size={22} />
+ <Text fontSize={13} type={'secondary'}>
+ {t('overview.nothingNeedsAttention')}
+ </Text>
+ </Flexbox>
+ ) : (
+ attentionTasks.map((task) => (
+ <Flexbox className={styles.attention} gap={4} key={task.id}>
+ <Text weight={500}>{task.name || task.instruction}</Text>
+ <Text fontSize={12} type={task.status === 'failed' ? 'danger' : 'secondary'}>
+ {task.status === 'failed' ? t('overview.taskFailed') : t('overview.taskWaiting')}
+ </Text>
+ </Flexbox>
+ ))
+ )}
+ {detail.project.status === 'reviewing' && (
+ <Button
+ icon={TriangleAlertIcon}
+ onClick={() => navigate(getProjectAcceptancePath(projectId))}
+ >
+ {t('overview.reviewProject')}
+ </Button>
+ )}
+ </Flexbox>
+
+ <Flexbox className={styles.railCard} gap={12}>
+ <SectionTitle title={t('overview.projectSummary')} />
+ <Flexbox horizontal justify={'space-between'}>
+ <Text type={'secondary'}>{t('sections.goals')}</Text>
+ <Text>{goals.length}</Text>
+ </Flexbox>
+ <Flexbox horizontal justify={'space-between'}>
+ <Text type={'secondary'}>{t('sections.tasks')}</Text>
+ <Text>{tasks.length}</Text>
+ </Flexbox>
+ <Flexbox horizontal justify={'space-between'}>
+ <Text type={'secondary'}>{t('sections.agents')}</Text>
+ <Text>{detail.agents?.length ?? 0}</Text>
+ </Flexbox>
+ <Flexbox horizontal justify={'space-between'}>
+ <Text type={'secondary'}>{t('sections.knowledgeBases')}</Text>
+ <Text>{detail.knowledgeBases?.length ?? 0}</Text>
+ </Flexbox>
+ </Flexbox>
+ </Flexbox>
+ </div>
+ );
+});
+
+ProjectDashboard.displayName = 'ProjectDashboard';
+
+export default ProjectDashboard;
diff --git a/src/features/Projects/Workspace/index.tsx b/src/features/Projects/Workspace/index.tsx
new file mode 100644
index 00000000000..2edfd16c136
--- /dev/null
+++ b/src/features/Projects/Workspace/index.tsx
@@ -0,0 +1,197 @@
+'use client';
+
+import { Center, Flexbox, Icon, Tag, Text, TextArea } from '@lobehub/ui';
+import { Button } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { FolderKanbanIcon, SendHorizontalIcon, SparklesIcon } from 'lucide-react';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useParams } from 'react-router';
+
+import AsyncError from '@/components/AsyncError';
+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
+import { getProjectConversationStartPath } from '@/features/Projects/Layout/navigation';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useCurrentProjectDetail, useProjectStore } from '@/store/project';
+import { useUserStore } from '@/store/user';
+import { labPreferSelectors } from '@/store/user/selectors';
+
+import ProjectDashboard from './ProjectDashboard';
+
+const styles = createStaticStyles(({ css }) => ({
+ composer: css`
+ overflow: hidden;
+
+ border: 1px solid ${cssVar.colorBorder};
+ border-radius: 18px;
+
+ background: ${cssVar.colorBgContainer};
+ box-shadow: ${cssVar.boxShadowSecondary};
+ `,
+ composerFooter: css`
+ padding-block: 6px 8px;
+ padding-inline: 14px 8px;
+ `,
+ content: css`
+ overflow: auto;
+ width: 100%;
+ `,
+ intro: css`
+ width: 100%;
+ max-width: 760px;
+ `,
+ page: css`
+ box-sizing: border-box;
+ width: min(1060px, calc(100% - 64px));
+ margin-inline: auto;
+ padding-block: 42px 72px;
+
+ @media (width <= 720px) {
+ width: calc(100% - 40px);
+ padding-block: 32px 48px;
+ }
+ `,
+ prompt: css`
+ cursor: pointer;
+
+ padding-block: 5px;
+ padding-inline: 10px;
+ border: 0;
+ border-radius: 999px;
+
+ color: ${cssVar.colorTextSecondary};
+
+ background: ${cssVar.colorFillQuaternary};
+
+ &:hover {
+ color: ${cssVar.colorText};
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ shell: css`
+ overflow: hidden;
+ height: 100%;
+ background: ${cssVar.colorBgContainer};
+ `,
+ textarea: css`
+ padding-block: 15px 8px !important;
+ padding-inline: 16px !important;
+ border: 0 !important;
+
+ font-size: 15px !important;
+
+ background: transparent !important;
+ box-shadow: none !important;
+ `,
+}));
+
+const ProjectWorkspace = memo(() => {
+ const { t } = useTranslation('project');
+ const { projectId } = useParams<{ projectId: string }>();
+ const navigate = useWorkspaceAwareNavigate();
+ const enabled = useUserStore(labPreferSelectors.enableProjects);
+ const detail = useCurrentProjectDetail(projectId);
+ const [message, setMessage] = useState('');
+ const { error, isLoading, mutate } = useProjectStore((s) => s.useFetchProjectDetail)(projectId);
+
+ if (!enabled) {
+ return (
+ <Center height={'100%'}>
+ <Flexbox align={'center'} gap={12}>
+ <Icon icon={FolderKanbanIcon} size={40} />
+ <Text fontSize={18} weight={600}>
+ {t('disabled.title')}
+ </Text>
+ <Button onClick={() => navigate('/settings/labs')}>{t('disabled.action')}</Button>
+ </Flexbox>
+ </Center>
+ );
+ }
+ if (error) return <AsyncError error={error} variant={'page'} onRetry={() => mutate()} />;
+ if (isLoading || !detail)
+ return (
+ <Center height={'100%'}>
+ <NeuralNetworkLoading />
+ </Center>
+ );
+
+ const startConversation = () => {
+ const content = message.trim();
+ if (!content || !projectId) return;
+ navigate(getProjectConversationStartPath(projectId, content));
+ };
+ const prompts = [
+ t('overview.prompts.summarizeProgress'),
+ t('overview.prompts.planMilestone'),
+ t('overview.prompts.findBlockers'),
+ ];
+
+ return (
+ <Flexbox className={styles.shell} flex={1}>
+ <div className={styles.content}>
+ <Flexbox className={styles.page} gap={0}>
+ <Flexbox className={styles.intro} gap={18}>
+ <Flexbox gap={5}>
+ <Text fontSize={26} weight={650}>
+ {t('overview.title')}
+ </Text>
+ <Text type={'secondary'}>{t('overview.description')}</Text>
+ </Flexbox>
+ <Flexbox gap={10}>
+ <Flexbox className={styles.composer}>
+ <TextArea
+ autoFocus
+ autoSize={{ maxRows: 7, minRows: 3 }}
+ className={styles.textarea}
+ placeholder={t('overview.composerPlaceholder')}
+ value={message}
+ onChange={(event) => setMessage(event.target.value)}
+ onKeyDown={(event) => {
+ if ((event.metaKey || event.ctrlKey) && event.key === 'Enter')
+ startConversation();
+ }}
+ />
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.composerFooter}
+ justify={'space-between'}
+ >
+ <Flexbox horizontal align={'center'} gap={7}>
+ <Tag icon={<SparklesIcon size={12} />}>{detail.project.name}</Tag>
+ <Text fontSize={12} type={'secondary'}>
+ {t('overview.contextEnabled')}
+ </Text>
+ </Flexbox>
+ <Button
+ disabled={!message.trim()}
+ icon={SendHorizontalIcon}
+ type={'primary'}
+ onClick={startConversation}
+ />
+ </Flexbox>
+ </Flexbox>
+ <Flexbox horizontal gap={8} wrap={'wrap'}>
+ {prompts.map((prompt) => (
+ <button
+ className={styles.prompt}
+ key={prompt}
+ type={'button'}
+ onClick={() => setMessage(prompt)}
+ >
+ {prompt}
+ </button>
+ ))}
+ </Flexbox>
+ </Flexbox>
+ </Flexbox>
+ <ProjectDashboard detail={detail} projectId={projectId!} />
+ </Flexbox>
+ </div>
+ </Flexbox>
+ );
+});
+
+ProjectWorkspace.displayName = 'ProjectWorkspace';
+
+export default ProjectWorkspace;
diff --git a/src/features/Projects/createProjectForm.test.ts b/src/features/Projects/createProjectForm.test.ts
new file mode 100644
index 00000000000..2e69c849214
--- /dev/null
+++ b/src/features/Projects/createProjectForm.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest';
+
+import { getCreateProjectInput, isProjectSlugValid } from './createProjectForm';
+
+describe('createProjectForm', () => {
+ it('normalizes and includes a user-provided slug', () => {
+ expect(
+ getCreateProjectInput({
+ identifier: ' lobe ',
+ name: ' LobeHub Project ',
+ slug: ' LobeHub-Project ',
+ }),
+ ).toEqual({
+ identifier: 'LOBE',
+ name: 'LobeHub Project',
+ slug: 'lobehub-project',
+ });
+ });
+
+ it('omits an empty slug so the backend can generate one', () => {
+ expect(
+ getCreateProjectInput({ identifier: 'LOBE', name: 'LobeHub Project', slug: ' ' }),
+ ).toEqual({ identifier: 'LOBE', name: 'LobeHub Project' });
+ });
+
+ it('rejects malformed slugs', () => {
+ expect(isProjectSlugValid('two--hyphens')).toBe(false);
+ expect(isProjectSlugValid('contains spaces')).toBe(false);
+ expect(
+ getCreateProjectInput({ identifier: 'LOBE', name: 'LobeHub Project', slug: '-invalid' }),
+ ).toBeNull();
+ });
+});
diff --git a/src/features/Projects/createProjectForm.ts b/src/features/Projects/createProjectForm.ts
new file mode 100644
index 00000000000..4c77e691381
--- /dev/null
+++ b/src/features/Projects/createProjectForm.ts
@@ -0,0 +1,26 @@
+import { PROJECT_IDENTIFIER_REGEX } from '@lobechat/types';
+
+const PROJECT_SLUG_REGEX = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
+
+export interface CreateProjectDraft {
+ identifier: string;
+ name: string;
+ slug: string;
+}
+
+export const isProjectSlugValid = (slug: string) => {
+ const normalizedSlug = slug.trim().toLowerCase();
+ return !normalizedSlug || PROJECT_SLUG_REGEX.test(normalizedSlug);
+};
+
+export const getCreateProjectInput = (draft: CreateProjectDraft) => {
+ const identifier = draft.identifier.trim().toUpperCase();
+ const name = draft.name.trim();
+ const slug = draft.slug.trim().toLowerCase();
+
+ if (!name || !PROJECT_IDENTIFIER_REGEX.test(identifier) || !isProjectSlugValid(slug)) {
+ return null;
+ }
+
+ return { identifier, name, ...(slug ? { slug } : {}) };
+};
diff --git a/src/features/Settings/labs/index.test.tsx b/src/features/Settings/labs/index.test.tsx
index a7cc16d94c2..bc022933ee6 100644
--- a/src/features/Settings/labs/index.test.tsx
+++ b/src/features/Settings/labs/index.test.tsx
@@ -165,8 +165,8 @@ describe('Labs settings page', () => {
const alphaTags = screen.getAllByText('stage.alpha.label');
const betaTags = screen.getAllByText('stage.beta.label');
- // Every toggle carries exactly one stage tag (6 general + 6 desktop).
- expect(alphaTags.length + betaTags.length).toBe(12);
+ // Every toggle carries exactly one stage tag.
+ expect(alphaTags.length + betaTags.length).toBe(13);
});
it('marks internal-testing experiments as alpha and usable ones as beta', () => {
diff --git a/src/features/Settings/labs/index.tsx b/src/features/Settings/labs/index.tsx
index c2b90395b3b..3630093986b 100644
--- a/src/features/Settings/labs/index.tsx
+++ b/src/features/Settings/labs/index.tsx
@@ -68,6 +68,7 @@ const LabsForm = memo(() => {
enableHeteroSessionImport,
enableMessageTextSelectionActions,
enableOAuthApps,
+ enableProjects,
enableInAppBrowser,
enableArtifactDeployment,
enableTopicAcceptance,
@@ -86,6 +87,7 @@ const LabsForm = memo(() => {
labPreferSelectors.enableHeteroSessionImport(s),
labPreferSelectors.enableMessageTextSelectionActions(s),
labPreferSelectors.enableOAuthApps(s),
+ labPreferSelectors.enableProjects(s),
labPreferSelectors.enableInAppBrowser(s),
labPreferSelectors.enableArtifactDeployment(s),
labPreferSelectors.enableTopicAcceptance(s),
@@ -155,6 +157,13 @@ const LabsForm = memo(() => {
stage: 'alpha',
title: tLabs('features.topicAcceptance.title'),
},
+ {
+ checked: enableProjects,
+ desc: tLabs('features.projects.desc'),
+ flag: 'enableProjects',
+ stage: 'alpha',
+ title: tLabs('features.projects.title'),
+ },
{
checked: enableOAuthApps,
desc: tLabs('features.oauthApps.desc'),
diff --git a/src/features/Workspace/__tests__/workspaceAwarePath.test.ts b/src/features/Workspace/__tests__/workspaceAwarePath.test.ts
index e214ebf6856..75380917aed 100644
--- a/src/features/Workspace/__tests__/workspaceAwarePath.test.ts
+++ b/src/features/Workspace/__tests__/workspaceAwarePath.test.ts
@@ -21,6 +21,7 @@ describe('buildWorkspaceAwarePath', () => {
'/acme/community/agent/jailbreak',
);
expect(buildWorkspaceAwarePath('/group/group-1', 'acme')).toBe('/acme/group/group-1');
+ expect(buildWorkspaceAwarePath('/project/project-1', 'acme')).toBe('/acme/project/project-1');
});
it('prefixes deep agent and evaluation paths used by cross-page navigation', () => {
diff --git a/src/features/Workspace/workspaceAwarePath.ts b/src/features/Workspace/workspaceAwarePath.ts
index 822a566205b..af27682e473 100644
--- a/src/features/Workspace/workspaceAwarePath.ts
+++ b/src/features/Workspace/workspaceAwarePath.ts
@@ -70,6 +70,7 @@ const WORKSPACE_MIRRORED_FIRST_SEGMENTS = new Set([
'image',
'memory',
'page',
+ 'project',
'resource',
'settings',
'task',
diff --git a/src/hooks/useActiveRouteParams.desktop.test.ts b/src/hooks/useActiveRouteParams.desktop.test.ts
index c7163657c9d..6bcc3dc99ad 100644
--- a/src/hooks/useActiveRouteParams.desktop.test.ts
+++ b/src/hooks/useActiveRouteParams.desktop.test.ts
@@ -61,6 +61,17 @@ describe('useActiveRouteParams (desktop)', () => {
expect(result.current.aid).toBe('agt_params_case');
});
+ it('resolves project params for portal sidebars', () => {
+ useElectronStore.setState({
+ activeTabId: 't1',
+ tabs: [tab('t1', '/project/prj_portal/tasks')],
+ });
+
+ const { result } = renderHook(() => useActiveRouteParams<{ projectId?: string }>());
+
+ expect(result.current.projectId).toBe('prj_portal');
+ });
+
it('re-resolves after switching back to a previously visited url', () => {
useElectronStore.setState({
activeTabId: 't1',
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 5d675e37566..7e983c582e1 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -266,11 +266,14 @@ export const taskKeys = {
detail: def('task:detail', (taskId: string) => ['task:detail', taskId]),
groupList: def(
'task:groupList',
- (agentKey: string | undefined, visibility: 'all' | 'private' | 'workspace' = 'all') => [
- 'task:groupList',
- agentKey,
- visibility,
- ],
+ (
+ agentKey: string | undefined,
+ visibility: 'all' | 'private' | 'workspace' = 'all',
+ projectId?: string,
+ ) =>
+ projectId
+ ? ['task:groupList', agentKey, visibility, projectId]
+ : ['task:groupList', agentKey, visibility],
),
/**
* The home rail's cross-agent goal roll-up. Scoped by cache scope like the
@@ -286,7 +289,11 @@ export const taskKeys = {
// Part of the key, not a detail: Home orders by activity while the Tasks
// page orders by creation, and they read the same store field.
orderBy: 'createdAt' | 'updatedAt' = 'createdAt',
- ) => ['task:list', agentKey, visibility, orderBy],
+ projectId?: string,
+ ) =>
+ projectId
+ ? ['task:list', agentKey, visibility, orderBy, projectId]
+ : ['task:list', agentKey, visibility, orderBy],
),
/**
* Home's automated-task roll-up: the tasks that fire on a schedule or a
diff --git a/src/routes/(main)/agent/_layout/AgentIdSync.test.tsx b/src/routes/(main)/agent/_layout/AgentIdSync.test.tsx
index 2707e6b56e7..26d79f0f3c0 100644
--- a/src/routes/(main)/agent/_layout/AgentIdSync.test.tsx
+++ b/src/routes/(main)/agent/_layout/AgentIdSync.test.tsx
@@ -14,6 +14,11 @@ const useParamsMock = vi.hoisted(() => vi.fn());
const useSearchParamsMock = vi.hoisted(() => vi.fn());
const useNavigateMock = vi.hoisted(() => vi.fn());
const useLocationMock = vi.hoisted(() => vi.fn());
+const useInitAgentConfigMock = vi.hoisted(() => vi.fn());
+
+vi.mock('@/hooks/useInitAgentConfig', () => ({
+ useInitAgentConfig: useInitAgentConfigMock,
+}));
vi.mock('react-router', async () => {
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
@@ -34,6 +39,7 @@ describe('AgentIdSync', () => {
useSearchParamsMock.mockReset();
useNavigateMock.mockReset();
useLocationMock.mockReset();
+ useInitAgentConfigMock.mockReset();
useLocationMock.mockReturnValue({ pathname: '/agent/agent-1' });
useChatStore.setState(
@@ -48,6 +54,15 @@ describe('AgentIdSync', () => {
);
});
+ it('hydrates the agent resolved from the current route', () => {
+ useParamsMock.mockReturnValue({ aid: 'agent-2' });
+ useSearchParamsMock.mockReturnValue([new URLSearchParams(''), vi.fn()]);
+
+ render(<AgentIdSync />);
+
+ expect(useInitAgentConfigMock).toHaveBeenCalledWith('agent-2');
+ });
+
it('clears portal state when switching to another agent without a topic in the URL', () => {
useParamsMock.mockReturnValue({ aid: 'agent-1' });
useSearchParamsMock.mockReturnValue([new URLSearchParams(''), vi.fn()]);
diff --git a/src/routes/(main)/agent/_layout/AgentIdSync.tsx b/src/routes/(main)/agent/_layout/AgentIdSync.tsx
index c2a51f90799..b77d202c727 100644
--- a/src/routes/(main)/agent/_layout/AgentIdSync.tsx
+++ b/src/routes/(main)/agent/_layout/AgentIdSync.tsx
@@ -3,6 +3,7 @@ import { useLocation, useParams, useSearchParams } from 'react-router';
import { useResolvedAgentRouteId } from '@/features/AgentRoute/useResolvedAgentRouteId';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useInitAgentConfig } from '@/hooks/useInitAgentConfig';
import { useAgentIdStoreSync } from './useAgentIdStoreSync';
@@ -13,6 +14,12 @@ const AgentIdSync = () => {
const location = useLocation();
const { agentId: activeId, isSlugRoute, resolvedAgentId } = useResolvedAgentRouteId(params.aid);
+ // Hydrate from the route-owning component. Parent layouts can retain stale
+ // params while sibling navigation changes the active agent, which leaves
+ // agents absent from the regular sidebar list (for example project
+ // coordinators) without a config and renders an empty conversation.
+ useInitAgentConfig(activeId);
+
// Redirect slug URL to real agent ID URL, preserving child path and query string
useEffect(() => {
if (isSlugRoute && resolvedAgentId) {
diff --git a/src/routes/(main)/agent/_layout/index.tsx b/src/routes/(main)/agent/_layout/index.tsx
index d3627c15ff5..d1292a4099c 100644
--- a/src/routes/(main)/agent/_layout/index.tsx
+++ b/src/routes/(main)/agent/_layout/index.tsx
@@ -6,7 +6,6 @@ import { isDesktop } from '@/const/version';
import { AgentNotFoundGuard } from '@/features/AgentNotFound';
import AgentSidebar from '@/features/AgentSidebar';
import ProtocolUrlHandler from '@/features/ProtocolUrlHandler';
-import { useInitAgentConfig } from '@/hooks/useInitAgentConfig';
import AgentIdSync from '@/routes/(main)/agent/_layout/AgentIdSync';
import PortalAutoCollapse from './PortalAutoCollapse';
@@ -14,8 +13,6 @@ import RegisterHotkeys from './RegisterHotkeys';
import { styles } from './style';
const Layout: FC = () => {
- useInitAgentConfig();
-
return (
<>
<AgentSidebar />
diff --git a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.test.tsx b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.test.tsx
index 2d472abff42..24aefa66c07 100644
--- a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.test.tsx
@@ -163,6 +163,33 @@ describe('ChatHydration', () => {
});
});
+ it('keeps topic navigation inside a project conversation route', async () => {
+ useParamsMock.mockReturnValue({ projectId: 'prj_1' });
+ useLocationMock.mockReturnValue({
+ hash: '',
+ pathname: '/project/prj_1/conversation',
+ search: '',
+ });
+ useSearchParamsMock.mockReturnValue([new URLSearchParams(''), setSearchParamsMock]);
+
+ render(
+ <ChatHydration
+ getConversationPath={() => '/project/prj_1/conversation'}
+ getTopicPath={(_agentId, topicId) => `/project/prj_1/conversation/${topicId}`}
+ />,
+ );
+
+ await act(async () => {
+ useChatStore.setState({ activeTopicId: 'tpc_project' }, false);
+ });
+
+ await waitFor(() => {
+ expect(navigateMock).toHaveBeenCalledWith('/project/prj_1/conversation/tpc_project', {
+ replace: true,
+ });
+ });
+ });
+
it('preserves the routed topic when the workspace activates after mount', async () => {
useParamsMock.mockReturnValue({ aid: 'agt_test', topicId: 'tpc_previous' });
useLocationMock.mockReturnValue({
diff --git a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx
index dd49900b7cd..cc2b07fbd0e 100644
--- a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx
@@ -1,6 +1,6 @@
'use client';
-import { memo } from 'react';
+import { type FC, memo } from 'react';
import { useParams } from 'react-router';
import { useClearActiveTopicUnread } from '@/features/Conversation/hooks';
@@ -11,7 +11,12 @@ import { topicSelectors } from '@/store/chat/selectors';
import { useChatRouteSync } from './useChatRouteSync';
// sync outside state to useChatStore
-const ChatHydration = memo(() => {
+interface ChatHydrationProps {
+ getConversationPath?: (agentId: string) => string;
+ getTopicPath?: (agentId: string, topicId: string) => string;
+}
+
+const ChatHydration: FC<ChatHydrationProps> = memo(({ getConversationPath, getTopicPath }) => {
const params = useParams<{ aid?: string; topicId?: string }>();
const routeTopicId = params.topicId;
const activeAgentId = useChatStore((s) => s.activeAgentId);
@@ -23,7 +28,7 @@ const ChatHydration = memo(() => {
useClearActiveTopicUnread();
useFetchTopicLinkedPullRequest(activeAgentId ? routeTopicId : undefined, topicMetadata);
useTopicCommentDeepLink(routeTopicId);
- useChatRouteSync();
+ useChatRouteSync({ getConversationPath, getTopicPath });
return null;
});
diff --git a/src/routes/(main)/agent/features/Conversation/ChatHydration/useChatRouteSync.desktop.ts b/src/routes/(main)/agent/features/Conversation/ChatHydration/useChatRouteSync.desktop.ts
index b1ed4022195..d6733267639 100644
--- a/src/routes/(main)/agent/features/Conversation/ChatHydration/useChatRouteSync.desktop.ts
+++ b/src/routes/(main)/agent/features/Conversation/ChatHydration/useChatRouteSync.desktop.ts
@@ -1,4 +1,9 @@
// Electron projects route state through the single ActiveConversationBridge,
// which follows activeTabId. Keeping this hook inert prevents every visible
// split-pane router from subscribing to and rewriting the global conversation.
-export const useChatRouteSync = () => {};
+interface ChatRouteSyncOptions {
+ getConversationPath?: (agentId: string) => string;
+ getTopicPath?: (agentId: string, topicId: string) => string;
+}
+
+export const useChatRouteSync = (_options: ChatRouteSyncOptions = {}) => {};
diff --git a/src/routes/(main)/agent/features/Conversation/ChatHydration/useChatRouteSync.ts b/src/routes/(main)/agent/features/Conversation/ChatHydration/useChatRouteSync.ts
index ef67408e35d..f67ba4ba1d3 100644
--- a/src/routes/(main)/agent/features/Conversation/ChatHydration/useChatRouteSync.ts
+++ b/src/routes/(main)/agent/features/Conversation/ChatHydration/useChatRouteSync.ts
@@ -12,7 +12,12 @@ const getSearchSuffix = (searchParams: URLSearchParams) => {
return search ? `?${search}` : '';
};
-export const useChatRouteSync = () => {
+interface ChatRouteSyncOptions {
+ getConversationPath?: (agentId: string) => string;
+ getTopicPath?: (agentId: string, topicId: string) => string;
+}
+
+export const useChatRouteSync = (options: ChatRouteSyncOptions = {}) => {
const location = useLocation();
const navigate = useWorkspaceAwareNavigate();
const params = useParams<{ aid?: string; topicId?: string }>();
@@ -47,8 +52,9 @@ export const useChatRouteSync = () => {
(state) => state.activeTopicId,
(state) => {
const { aid, topicId } = paramsRef.current;
+ const routeAgentId = aid || useChatStore.getState().activeAgentId;
- if (!aid || state === topicId) return;
+ if (!routeAgentId || state === topicId) return;
if (state === undefined && topicId) {
useChatStore.setState(
@@ -62,7 +68,9 @@ export const useChatRouteSync = () => {
const nextSearchParams = new URLSearchParams(searchParamsRef.current);
nextSearchParams.delete('topic');
- const nextPath = state ? AGENT_CHAT_TOPIC_URL(aid, state) : AGENT_CHAT_URL(aid);
+ const nextPath = state
+ ? options.getTopicPath?.(routeAgentId, state) || AGENT_CHAT_TOPIC_URL(routeAgentId, state)
+ : options.getConversationPath?.(routeAgentId) || AGENT_CHAT_URL(routeAgentId);
const nextUrl = `${nextPath}${getSearchSuffix(nextSearchParams)}${locationRef.current.hash}`;
const currentUrl = `${locationRef.current.pathname}${locationRef.current.search}${locationRef.current.hash}`;
@@ -80,5 +88,5 @@ export const useChatRouteSync = () => {
unsubscribeTopic();
unsubscribeThread();
};
- }, [navigate, setThread]);
+ }, [navigate, options.getConversationPath, options.getTopicPath, setThread]);
};
diff --git a/src/routes/(main)/project/[projectId]/acceptance/index.tsx b/src/routes/(main)/project/[projectId]/acceptance/index.tsx
new file mode 100644
index 00000000000..54eaddcc0d8
--- /dev/null
+++ b/src/routes/(main)/project/[projectId]/acceptance/index.tsx
@@ -0,0 +1 @@
+export { default } from '@/features/Projects/Acceptance';
diff --git a/src/routes/(main)/project/[projectId]/conversation/index.tsx b/src/routes/(main)/project/[projectId]/conversation/index.tsx
new file mode 100644
index 00000000000..77281bd5f74
--- /dev/null
+++ b/src/routes/(main)/project/[projectId]/conversation/index.tsx
@@ -0,0 +1 @@
+export { default } from '@/features/Projects/Conversation';
diff --git a/src/routes/(main)/project/[projectId]/goals/index.tsx b/src/routes/(main)/project/[projectId]/goals/index.tsx
new file mode 100644
index 00000000000..1c1cea43670
--- /dev/null
+++ b/src/routes/(main)/project/[projectId]/goals/index.tsx
@@ -0,0 +1 @@
+export { default } from '@/features/Projects/Goals';
diff --git a/src/routes/(main)/project/[projectId]/index.tsx b/src/routes/(main)/project/[projectId]/index.tsx
new file mode 100644
index 00000000000..f41c0f43aff
--- /dev/null
+++ b/src/routes/(main)/project/[projectId]/index.tsx
@@ -0,0 +1 @@
+export { default } from '@/features/Projects/Workspace';
diff --git a/src/routes/(main)/project/[projectId]/library/[id]/index.tsx b/src/routes/(main)/project/[projectId]/library/[id]/index.tsx
new file mode 100644
index 00000000000..a217da5ab89
--- /dev/null
+++ b/src/routes/(main)/project/[projectId]/library/[id]/index.tsx
@@ -0,0 +1 @@
+export { default } from '@/features/ResourceLibrary';
diff --git a/src/routes/(main)/project/[projectId]/tasks/index.tsx b/src/routes/(main)/project/[projectId]/tasks/index.tsx
new file mode 100644
index 00000000000..083819ab9e5
--- /dev/null
+++ b/src/routes/(main)/project/[projectId]/tasks/index.tsx
@@ -0,0 +1,12 @@
+'use client';
+
+import { AgentTasksPage } from '@/features/AgentTasks';
+import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';
+
+const ProjectTasks = () => {
+ const { projectId } = useActiveRouteParams<{ projectId: string }>();
+
+ return <AgentTasksPage projectId={projectId} />;
+};
+
+export default ProjectTasks;
diff --git a/src/routes/(main)/project/_layout/index.tsx b/src/routes/(main)/project/_layout/index.tsx
new file mode 100644
index 00000000000..3b9d7a800f5
--- /dev/null
+++ b/src/routes/(main)/project/_layout/index.tsx
@@ -0,0 +1 @@
+export { default } from '@/features/Projects/Layout';
diff --git a/src/services/__tests__/project.test.ts b/src/services/__tests__/project.test.ts
new file mode 100644
index 00000000000..74849ab69d3
--- /dev/null
+++ b/src/services/__tests__/project.test.ts
@@ -0,0 +1,41 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { lambdaClient } from '@/libs/trpc/client';
+import { projectService } from '@/services/project';
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: {
+ project: {
+ list: { query: vi.fn() },
+ },
+ },
+}));
+
+describe('ProjectService', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('loads every project page', async () => {
+ type ProjectRows = Awaited<ReturnType<typeof lambdaClient.project.list.query>>['data'];
+ const firstPage = Array.from({ length: 100 }, (_, index) => ({
+ id: `project-${index}`,
+ })) as ProjectRows;
+ const secondPage = [{ id: 'project-100' }] as ProjectRows;
+ vi.mocked(lambdaClient.project.list.query)
+ .mockResolvedValueOnce({ data: firstPage, success: true })
+ .mockResolvedValueOnce({ data: secondPage, success: true });
+
+ const response = await projectService.listAll();
+
+ expect(response.data).toHaveLength(101);
+ expect(lambdaClient.project.list.query).toHaveBeenNthCalledWith(1, {
+ limit: 100,
+ offset: 0,
+ });
+ expect(lambdaClient.project.list.query).toHaveBeenNthCalledWith(2, {
+ limit: 100,
+ offset: 100,
+ });
+ });
+});
diff --git a/src/services/project.ts b/src/services/project.ts
new file mode 100644
index 00000000000..2e6a3a05e85
--- /dev/null
+++ b/src/services/project.ts
@@ -0,0 +1,51 @@
+import type { ProjectStatus, ProjectVisibility } from '@lobechat/types';
+
+import { lambdaClient } from '@/libs/trpc/client';
+
+const PROJECT_PAGE_SIZE = 100;
+
+class ProjectService {
+ acceptCompletion = async (id: string, comment?: string) =>
+ lambdaClient.project.acceptCompletion.mutate({ comment, id });
+
+ listAll = async (params: { statuses?: ProjectStatus[] } = {}) => {
+ const projects = [];
+ let offset = 0;
+ let response;
+
+ do {
+ response = await lambdaClient.project.list.query({
+ limit: PROJECT_PAGE_SIZE,
+ offset,
+ ...params,
+ });
+ projects.push(...response.data);
+ offset += response.data.length;
+ } while (response.data.length === PROJECT_PAGE_SIZE);
+
+ return { ...response, data: projects };
+ };
+
+ detail = async (id: string) => lambdaClient.project.detail.query({ id });
+
+ create = async (params: {
+ avatar?: string;
+ description?: string;
+ identifier: string;
+ name: string;
+ slug?: string;
+ visibility?: ProjectVisibility;
+ }) => lambdaClient.project.create.mutate(params);
+
+ rejectCompletion = async (id: string, comment: string) =>
+ lambdaClient.project.rejectCompletion.mutate({ comment, id });
+
+ reopen = async (id: string) => lambdaClient.project.reopen.mutate({ id });
+
+ requestCompletion = async (id: string) => lambdaClient.project.requestCompletion.mutate({ id });
+
+ updateStatus = async (id: string, status: 'active' | 'archived' | 'backlog' | 'paused') =>
+ lambdaClient.project.updateStatus.mutate({ id, status });
+}
+
+export const projectService = new ProjectService();
diff --git a/src/services/task.ts b/src/services/task.ts
index 573f200530a..ed24e3659bc 100644
--- a/src/services/task.ts
+++ b/src/services/task.ts
@@ -19,6 +19,7 @@ class TaskService {
parentIdentifier?: string;
parentTaskId?: string | null;
priorities?: number[];
+ projectId?: string;
statuses?: TaskStatus[];
visibility?: 'private' | 'public';
}) => lambdaClient.task.list.query(params);
@@ -33,6 +34,7 @@ class TaskService {
}>;
hasGoal?: boolean;
parentTaskId?: string | null;
+ projectId?: string;
visibility?: 'private' | 'public';
}) => lambdaClient.task.groupList.query(params);
@@ -67,6 +69,7 @@ class TaskService {
name?: string;
parentTaskId?: string;
priority?: number;
+ projectId?: string;
schedulePattern?: string;
scheduleTimezone?: string;
visibility?: 'private' | 'public';
diff --git a/src/services/work.ts b/src/services/work.ts
index d713025c3af..82ce424fce1 100644
--- a/src/services/work.ts
+++ b/src/services/work.ts
@@ -71,6 +71,7 @@ class WorkService {
listByWorkspace = async (params: {
cursor?: string | null;
limit?: number;
+ originAgentId?: string | null;
provider?: WorkSkillProvider;
type?: WorkType | null;
}): Promise<WorkSummaryPage> =>
diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsx
index eb1379479a2..804ea52e9a5 100644
--- a/src/spa/router/desktopRouter.shared.tsx
+++ b/src/spa/router/desktopRouter.shared.tsx
@@ -810,6 +810,38 @@ export const sharedMainAreaChildren: RouteObject[] = [
},
// Task workspace routes (cross-agent)
+ {
+ children: [
+ {
+ element: redirectElement('tasks'),
+ index: true,
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/project/[projectId]/tasks'),
+ 'Desktop > Project Tasks',
+ ),
+ handle: { meta: tasksRouteMeta },
+ path: 'tasks',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/project/[projectId]/goals'),
+ 'Desktop > Project Goals',
+ ),
+ handle: { meta: goalsRouteMeta },
+ path: 'goals',
+ },
+ ],
+ element: dynamicLayout(
+ () => import('@/routes/(main)/project/_layout'),
+ 'Desktop > Project Workspace > Layout',
+ { preloadId: 'project' },
+ ),
+ errorElement: <ErrorBoundary resetPath=".." />,
+ path: 'project/:projectId',
+ },
+
{
children: [
{
diff --git a/src/spa/router/desktopRouter.sync.test.tsx b/src/spa/router/desktopRouter.sync.test.tsx
index 35dd7cb1a60..0b8a6c0abd1 100644
--- a/src/spa/router/desktopRouter.sync.test.tsx
+++ b/src/spa/router/desktopRouter.sync.test.tsx
@@ -129,6 +129,22 @@ describe('desktop router shared definition', () => {
expect(matches?.at(-1)?.route.path).toBe('stats');
});
+ it.each(mainAreaVariants)(
+ '%s exposes projects as task and goal containers only',
+ (_, factory) => {
+ const projectRoute = factory().find((route) => route.path === 'project/:projectId');
+ const projectIndexRoute = projectRoute?.children?.find((route) => route.index);
+ const projectPaths = projectRoute?.children
+ ?.map((route) => route.path)
+ .filter((routePath): routePath is string => Boolean(routePath));
+
+ expect(projectPaths).toEqual(['tasks', 'goals']);
+ expect(
+ (projectIndexRoute?.element as ReactElement<{ to: string }> | undefined)?.props.to,
+ ).toBe('tasks');
+ },
+ );
+
it.each(mainAreaVariants)(
'%s personal memory settings are not shadowed by workspace memory routes',
(_, factory) => {
diff --git a/src/store/global/selectors/systemStatus.test.ts b/src/store/global/selectors/systemStatus.test.ts
index 3ba0930ef28..38eeb2ad327 100644
--- a/src/store/global/selectors/systemStatus.test.ts
+++ b/src/store/global/selectors/systemStatus.test.ts
@@ -201,6 +201,7 @@ describe('systemStatusSelectors', () => {
'private',
'agent',
'recents',
+ 'project',
SIDEBAR_SPACER_ID,
'pages',
'tasks',
@@ -214,6 +215,7 @@ describe('systemStatusSelectors', () => {
it('should preserve a canonically-positioned spacer', () => {
const stored = [
'pages',
+ 'project',
'recents',
'private',
'agent',
@@ -252,6 +254,7 @@ describe('systemStatusSelectors', () => {
'tasks',
'pages',
'recents',
+ 'project',
'private',
'agent',
SIDEBAR_SPACER_ID,
@@ -275,11 +278,12 @@ describe('systemStatusSelectors', () => {
expect(items).toContain('resource');
expect(items).toContain('memory');
// accordion block is flush against the spacer, in stored order
- expect(items[spacerIdx - 2]).toBe('agent');
- expect(items[spacerIdx - 1]).toBe('recents');
+ expect(items[spacerIdx - 3]).toBe('agent');
+ expect(items[spacerIdx - 2]).toBe('recents');
+ expect(items[spacerIdx - 1]).toBe('project');
// missing top-group defaults slot in just before the accordion
- expect(items.indexOf('tasks')).toBeLessThan(spacerIdx - 2);
- expect(items.indexOf('resource')).toBeLessThan(spacerIdx - 2);
+ expect(items.indexOf('tasks')).toBeLessThan(spacerIdx - 3);
+ expect(items.indexOf('resource')).toBeLessThan(spacerIdx - 3);
// missing bottom-group defaults sit after the spacer
expect(items.indexOf('image')).toBeGreaterThan(spacerIdx);
expect(items.indexOf('pages')).toBeGreaterThan(spacerIdx);
@@ -298,6 +302,7 @@ describe('systemStatusSelectors', () => {
'private',
'agent',
'recents',
+ 'project',
SIDEBAR_SPACER_ID,
'image',
'community',
@@ -318,6 +323,7 @@ describe('systemStatusSelectors', () => {
'resource',
'private',
'recents',
+ 'project',
'agent',
SIDEBAR_SPACER_ID,
'image',
diff --git a/src/store/global/selectors/systemStatus.ts b/src/store/global/selectors/systemStatus.ts
index c91ddf7192b..6a429576660 100644
--- a/src/store/global/selectors/systemStatus.ts
+++ b/src/store/global/selectors/systemStatus.ts
@@ -176,6 +176,7 @@ export const DEFAULT_SIDEBAR_ITEMS: string[] = [
'tasks',
'resource',
'recents',
+ 'project',
'private',
'agent',
SIDEBAR_SPACER_ID,
@@ -188,7 +189,7 @@ export const DEFAULT_SIDEBAR_ITEMS: string[] = [
/** Items that must stay contiguous in the sidebar list (accordion block).
* `private` sits above `agent` so workspace users see their personal items
* first, with the workspace-shared agents right below. */
-export const SIDEBAR_ACCORDION_KEYS = new Set(['recents', 'private', 'agent']);
+export const SIDEBAR_ACCORDION_KEYS = new Set(['recents', 'project', 'private', 'agent']);
const DEFAULT_BOTTOM_KEYS = new Set(
DEFAULT_SIDEBAR_ITEMS.slice(DEFAULT_SIDEBAR_ITEMS.indexOf(SIDEBAR_SPACER_ID) + 1),
@@ -229,7 +230,16 @@ const normalizeSpacerPosition = (order: string[]): string[] => {
// default added in a future version would silently appear in the bottom group
// for existing users.
const withAllKnownKeys = (order: string[]): string[] => {
- const present = new Set(order);
+ let nextOrder = order;
+ if (!order.includes('project')) {
+ const recentsIndex = order.indexOf('recents');
+ const firstAgentIndex = order.findIndex((key) => key === 'private' || key === 'agent');
+ const insertAt =
+ recentsIndex >= 0 ? recentsIndex + 1 : firstAgentIndex >= 0 ? firstAgentIndex : 0;
+ nextOrder = [...order.slice(0, insertAt), 'project', ...order.slice(insertAt)];
+ }
+
+ const present = new Set(nextOrder);
const missingTop: string[] = [];
const missingBottom: string[] = [];
for (const k of DEFAULT_SIDEBAR_ITEMS) {
@@ -237,7 +247,7 @@ const withAllKnownKeys = (order: string[]): string[] => {
(DEFAULT_BOTTOM_KEYS.has(k) ? missingBottom : missingTop).push(k);
}
- const withSpacer = normalizeSpacerPosition(order);
+ const withSpacer = normalizeSpacerPosition(nextOrder);
if (missingTop.length === 0 && missingBottom.length === 0) return withSpacer;
const spacerIdx = withSpacer.indexOf(SIDEBAR_SPACER_ID);
diff --git a/src/store/goal/action.test.ts b/src/store/goal/action.test.ts
index 83be7abd95b..469d67aaf36 100644
--- a/src/store/goal/action.test.ts
+++ b/src/store/goal/action.test.ts
@@ -34,6 +34,29 @@ describe('GoalAction', () => {
expect(useGoalStore.getState().goalListInitializedAgentIds).toContain('agent-1');
});
+ it('uses the complete goal workspace with a project-scoped query and cache', () => {
+ useGoalStore.getState().useFetchGoals(undefined, 'project-1');
+ const [key, fetcher, options] = vi.mocked(useClientDataSWR).mock.calls[0];
+
+ expect(key).toEqual(['task:sidebarGroups', 'project:project-1:goals-page']);
+ expect(fetcher).toBeTypeOf('function');
+ void (fetcher as () => unknown)();
+ expect(taskService.groupList).toHaveBeenCalledWith(
+ expect.objectContaining({ hasGoal: true, projectId: 'project-1' }),
+ );
+
+ const onSuccess = (
+ options as {
+ onSuccess: (value: { data: Array<{ tasks: Array<{ id: string }> }> }) => void;
+ }
+ ).onSuccess;
+ onSuccess({ data: [{ tasks: [{ id: 'project-goal-1' }] }] });
+
+ expect(useGoalStore.getState().goalListByAgentId['project:project-1']).toEqual([
+ { id: 'project-goal-1' },
+ ]);
+ });
+
it('keeps each workspace home roll-up apart, so a late response cannot cross scopes', () => {
useGoalStore.getState().useFetchHomeGoals(true, 'user:ws-a');
useGoalStore.getState().useFetchHomeGoals(true, 'user:ws-b');
diff --git a/src/store/goal/action.ts b/src/store/goal/action.ts
index b9b028f1e9c..4d04fcad9f2 100644
--- a/src/store/goal/action.ts
+++ b/src/store/goal/action.ts
@@ -67,8 +67,8 @@ export class GoalActionImpl {
);
};
- refreshGoals = async (agentId: string): Promise<void> => {
- await mutate(taskKeys.sidebarGroups(`${agentId}:goals-page`));
+ refreshGoals = async (scopeId: string): Promise<void> => {
+ await mutate(taskKeys.sidebarGroups(`${scopeId}:goals-page`));
};
refreshHomeGoals = async (scope: string): Promise<void> => {
@@ -83,15 +83,18 @@ export class GoalActionImpl {
this.#set({ goalViewMode: mode }, false, 'setGoalViewMode');
};
- useFetchGoals = (agentId?: string) =>
- useClientDataSWR(
- agentId ? taskKeys.sidebarGroups(`${agentId}:goals-page`) : null,
+ useFetchGoals = (agentId?: string, projectId?: string) => {
+ const scopeId = projectId ? `project:${projectId}` : agentId;
+
+ return useClientDataSWR(
+ scopeId ? taskKeys.sidebarGroups(`${scopeId}:goals-page`) : null,
() =>
taskService.groupList({
assigneeAgentId: agentId,
groups: [{ key: 'goals', limit: 100, statuses: GOAL_STATUSES }],
hasGoal: true,
parentTaskId: null,
+ projectId,
}),
{
onSuccess: ({ data }) => {
@@ -99,11 +102,11 @@ export class GoalActionImpl {
({ goalListByAgentId, goalListInitializedAgentIds }) => ({
goalListByAgentId: {
...goalListByAgentId,
- [agentId!]: data[0]?.tasks ?? [],
+ [scopeId!]: data[0]?.tasks ?? [],
},
- goalListInitializedAgentIds: goalListInitializedAgentIds.includes(agentId!)
+ goalListInitializedAgentIds: goalListInitializedAgentIds.includes(scopeId!)
? goalListInitializedAgentIds
- : [...goalListInitializedAgentIds, agentId!],
+ : [...goalListInitializedAgentIds, scopeId!],
}),
false,
'useFetchGoals/success',
@@ -112,6 +115,7 @@ export class GoalActionImpl {
revalidateOnFocus: true,
},
);
+ };
/**
* Every agent's goals in one read — the home rail is a cross-agent roll-up,
diff --git a/src/store/project/index.ts b/src/store/project/index.ts
new file mode 100644
index 00000000000..1028ac7ac17
--- /dev/null
+++ b/src/store/project/index.ts
@@ -0,0 +1,2 @@
+export type { ProjectDetail, ProjectListItem } from './store';
+export { useCurrentProjectDetail, useCurrentProjectList, useProjectStore } from './store';
diff --git a/src/store/project/store.test.ts b/src/store/project/store.test.ts
new file mode 100644
index 00000000000..b6940db854e
--- /dev/null
+++ b/src/store/project/store.test.ts
@@ -0,0 +1,70 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { ProjectDetail, ProjectListItem } from './store';
+import { useCurrentProjectDetail, useCurrentProjectList, useProjectStore } from './store';
+
+const mocks = vi.hoisted(() => ({
+ activeWorkspaceId: null as string | null,
+ swrConfigs: [] as Array<{ onSuccess: (response: unknown) => void }>,
+}));
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ getActiveWorkspaceId: () => mocks.activeWorkspaceId,
+ useActiveWorkspaceId: () => mocks.activeWorkspaceId,
+}));
+
+vi.mock('@/libs/swr', () => ({
+ mutate: vi.fn(),
+ useClientDataSWR: vi.fn(
+ (_key: unknown, _fetcher: unknown, config: { onSuccess: (response: unknown) => void }) => {
+ mocks.swrConfigs.push(config);
+ return {};
+ },
+ ),
+}));
+
+describe('project store workspace scope', () => {
+ beforeEach(() => {
+ mocks.activeWorkspaceId = null;
+ mocks.swrConfigs = [];
+ useProjectStore.setState({ projectDetails: {}, projectLists: {} });
+ });
+
+ it('keeps project lists isolated between personal and workspace contexts', () => {
+ const personalProject = { id: 'personal-project' } as ProjectListItem;
+ const workspaceProject = { id: 'workspace-project' } as ProjectListItem;
+ const { rerender } = renderHook(() => useProjectStore.getState().useFetchProjectList());
+
+ act(() => mocks.swrConfigs.at(-1)?.onSuccess({ data: [personalProject], success: true }));
+ mocks.activeWorkspaceId = 'workspace-1';
+ rerender();
+ act(() => mocks.swrConfigs.at(-1)?.onSuccess({ data: [workspaceProject], success: true }));
+
+ expect(renderHook(() => useCurrentProjectList()).result.current).toEqual([workspaceProject]);
+
+ mocks.activeWorkspaceId = null;
+ expect(renderHook(() => useCurrentProjectList()).result.current).toEqual([personalProject]);
+ });
+
+ it('keeps project details isolated between personal and workspace contexts', () => {
+ const personalDetail = { project: { id: 'shared-id', name: 'Personal' } } as ProjectDetail;
+ const workspaceDetail = { project: { id: 'shared-id', name: 'Workspace' } } as ProjectDetail;
+ const { rerender } = renderHook(() =>
+ useProjectStore.getState().useFetchProjectDetail('shared-id'),
+ );
+
+ act(() => mocks.swrConfigs.at(-1)?.onSuccess({ data: personalDetail, success: true }));
+ mocks.activeWorkspaceId = 'workspace-1';
+ rerender();
+ act(() => mocks.swrConfigs.at(-1)?.onSuccess({ data: workspaceDetail, success: true }));
+
+ expect(renderHook(() => useCurrentProjectDetail('shared-id')).result.current).toBe(
+ workspaceDetail,
+ );
+ mocks.activeWorkspaceId = null;
+ expect(renderHook(() => useCurrentProjectDetail('shared-id')).result.current).toBe(
+ personalDetail,
+ );
+ });
+});
diff --git a/src/store/project/store.ts b/src/store/project/store.ts
new file mode 100644
index 00000000000..7e9c70b17a0
--- /dev/null
+++ b/src/store/project/store.ts
@@ -0,0 +1,91 @@
+import type { SWRResponse } from 'swr';
+import { shallow } from 'zustand/shallow';
+import { createWithEqualityFn } from 'zustand/traditional';
+
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { mutate, useClientDataSWR } from '@/libs/swr';
+import { projectService } from '@/services/project';
+import { createDevtools } from '@/store/middleware/createDevtools';
+import { expose } from '@/store/middleware/expose';
+
+type ProjectListResponse = Awaited<ReturnType<typeof projectService.listAll>>;
+type ProjectDetailResponse = Awaited<ReturnType<typeof projectService.detail>>;
+export type ProjectListItem = ProjectListResponse['data'][number];
+export type ProjectDetail = ProjectDetailResponse['data'];
+
+const LIST_KEY = 'project/list';
+const detailKey = (id: string) => ['project/detail', id] as const;
+const PERSONAL_SCOPE = 'personal';
+const projectScopeKey = (workspaceId: string | null) => workspaceId ?? PERSONAL_SCOPE;
+
+interface ProjectStore {
+ createProject: (input: {
+ identifier: string;
+ name: string;
+ slug?: string;
+ }) => Promise<ProjectListItem>;
+ projectDetails: Record<string, Record<string, ProjectDetail>>;
+ projectLists: Record<string, ProjectListItem[]>;
+ refreshProjectList: () => Promise<void>;
+ useFetchProjectDetail: (id?: string) => SWRResponse<ProjectDetailResponse>;
+ useFetchProjectList: (enabled?: boolean) => SWRResponse<ProjectListResponse>;
+}
+
+const devtools = createDevtools('project');
+
+export const useProjectStore = createWithEqualityFn<ProjectStore>()(
+ devtools((set, get) => ({
+ createProject: async (input) => {
+ const response = await projectService.create(input);
+ await get().refreshProjectList();
+ return response.data;
+ },
+ projectDetails: {},
+ projectLists: {},
+ refreshProjectList: async () => mutate(LIST_KEY),
+ useFetchProjectDetail: (id) => {
+ const workspaceId = useActiveWorkspaceId();
+ const scope = projectScopeKey(workspaceId);
+
+ return useClientDataSWR(id ? detailKey(id) : null, () => projectService.detail(id!), {
+ onSuccess: (response: ProjectDetailResponse) =>
+ set(
+ (state) => ({
+ projectDetails: {
+ ...state.projectDetails,
+ [scope]: { ...state.projectDetails[scope], [id!]: response.data },
+ },
+ }),
+ false,
+ 'useFetchProjectDetail/success',
+ ),
+ });
+ },
+ useFetchProjectList: (enabled = true) => {
+ const workspaceId = useActiveWorkspaceId();
+ const scope = projectScopeKey(workspaceId);
+
+ return useClientDataSWR(enabled ? LIST_KEY : null, () => projectService.listAll(), {
+ onSuccess: (response: ProjectListResponse) =>
+ set(
+ (state) => ({ projectLists: { ...state.projectLists, [scope]: response.data } }),
+ false,
+ 'useFetchProjectList/success',
+ ),
+ });
+ },
+ })),
+ shallow,
+);
+
+expose('project', useProjectStore);
+
+export const useCurrentProjectList = () => {
+ const scope = projectScopeKey(useActiveWorkspaceId());
+ return useProjectStore((state) => state.projectLists[scope] ?? []);
+};
+
+export const useCurrentProjectDetail = (id?: string) => {
+ const scope = projectScopeKey(useActiveWorkspaceId());
+ return useProjectStore((state) => (id ? state.projectDetails[scope]?.[id] : undefined));
+};
diff --git a/src/store/task/slices/detail/action.ts b/src/store/task/slices/detail/action.ts
index 035e86ce0fa..7625c8574ba 100644
--- a/src/store/task/slices/detail/action.ts
+++ b/src/store/task/slices/detail/action.ts
@@ -191,6 +191,7 @@ export class TaskDetailSliceActionImpl {
name?: string;
parentTaskId?: string;
priority?: number;
+ projectId?: string;
schedulePattern?: string;
scheduleTimezone?: string;
visibility?: 'private' | 'public';
diff --git a/src/store/task/slices/list/action.test.ts b/src/store/task/slices/list/action.test.ts
index 60896435172..55b6ba5b326 100644
--- a/src/store/task/slices/list/action.test.ts
+++ b/src/store/task/slices/list/action.test.ts
@@ -86,6 +86,27 @@ describe('TaskListSliceAction', () => {
});
describe('useFetchTaskList', () => {
+ it('requests only tasks from the selected project', async () => {
+ const { useClientDataSWR } = await import('@/libs/swr');
+ const { taskService } = await import('@/services/task');
+
+ useTaskStore.getState().useFetchTaskList({ projectId: 'project-1', visibility: 'all' });
+
+ expect(useClientDataSWR).toHaveBeenCalledWith(
+ ['task:list', '__project__:project-1', 'all', 'createdAt', 'project-1'],
+ expect.any(Function),
+ expect.any(Object),
+ );
+ const fetcher = vi.mocked(useClientDataSWR).mock.calls[0][1] as (key: string[]) => unknown;
+ await fetcher(['task:list', '__project__:project-1', 'all', 'project-1']);
+ expect(taskService.list).toHaveBeenCalledWith(
+ expect.objectContaining({ projectId: 'project-1' }),
+ );
+ expect(taskService.list).toHaveBeenCalledWith(
+ expect.not.objectContaining({ assigneeAgentId: expect.anything() }),
+ );
+ });
+
it('allows embedded overviews to ignore the Task page visibility filter', async () => {
const { useClientDataSWR } = await import('@/libs/swr');
useTaskStore.setState({ listVisibility: 'private' });
diff --git a/src/store/task/slices/list/action.ts b/src/store/task/slices/list/action.ts
index f4bd3b85810..5ac90ac6868 100644
--- a/src/store/task/slices/list/action.ts
+++ b/src/store/task/slices/list/action.ts
@@ -17,6 +17,10 @@ import type {
* the two don't collide and `refreshTaskList()` can invalidate the correct entry.
*/
export const ALL_AGENTS_LIST_KEY = '__all__';
+const PROJECT_LIST_KEY_PREFIX = '__project__:';
+
+const projectIdFromListKey = (key?: string) =>
+ key?.startsWith(PROJECT_LIST_KEY_PREFIX) ? key.slice(PROJECT_LIST_KEY_PREFIX.length) : undefined;
// Default kanban groups: 5 columns
// 'scheduled' shares the 'running' column — both represent "automation in
@@ -76,7 +80,9 @@ export class TaskListSliceActionImpl {
refreshTaskGroupList = async (): Promise<void> => {
const { listAgentId, listVisibility } = this.#get();
- await mutate(taskKeys.groupList(listAgentId, listVisibility));
+ await mutate(
+ taskKeys.groupList(listAgentId, listVisibility, projectIdFromListKey(listAgentId)),
+ );
};
fetchTaskList = async (params: Parameters<typeof taskService.list>[0]) =>
@@ -84,13 +90,14 @@ export class TaskListSliceActionImpl {
refreshTaskList = async (): Promise<void> => {
const { listAgentId, listQueryVisibility, listVisibility } = this.#get();
+ const projectId = projectIdFromListKey(listAgentId);
await Promise.all([
// Both orderings of the same list: the Tasks page holds the createdAt
// entry and Home the updatedAt one, and an edit invalidates both — an
// edit is exactly what moves a task in the updatedAt ordering.
- mutate(taskKeys.list(listAgentId, listQueryVisibility, 'createdAt')),
- mutate(taskKeys.list(listAgentId, listQueryVisibility, 'updatedAt')),
- mutate(taskKeys.groupList(listAgentId, listVisibility)),
+ mutate(taskKeys.list(listAgentId, listQueryVisibility, 'createdAt', projectId)),
+ mutate(taskKeys.list(listAgentId, listQueryVisibility, 'updatedAt', projectId)),
+ mutate(taskKeys.groupList(listAgentId, listVisibility, projectId)),
// A schedule can be attached, changed or removed from any task edit, so
// the automated roll-up has to be revalidated alongside the main list.
mutate(taskKeys.scheduledList(ALL_AGENTS_LIST_KEY)),
@@ -125,10 +132,15 @@ export class TaskListSliceActionImpl {
agentId?: string;
allAgents?: boolean;
enabled?: boolean;
+ projectId?: string;
} = {},
) => {
- const { agentId, allAgents = false, enabled = true } = options;
- const effectiveKey = allAgents ? ALL_AGENTS_LIST_KEY : agentId;
+ const { agentId, allAgents = false, enabled = true, projectId } = options;
+ const effectiveKey = projectId
+ ? `${PROJECT_LIST_KEY_PREFIX}${projectId}`
+ : allAgents
+ ? ALL_AGENTS_LIST_KEY
+ : agentId;
if (effectiveKey && this.#get().listAgentId !== effectiveKey) {
this.#set(
{ ...scopeChangeResetState, listAgentId: effectiveKey },
@@ -139,12 +151,13 @@ export class TaskListSliceActionImpl {
const listVisibility = this.#get().listVisibility;
return useClientDataSWR(
- enabled && effectiveKey ? taskKeys.groupList(effectiveKey, listVisibility) : null,
+ enabled && effectiveKey ? taskKeys.groupList(effectiveKey, listVisibility, projectId) : null,
async () => {
return taskService.groupList({
assigneeAgentId: allAgents ? undefined : agentId,
groups: DEFAULT_KANBAN_GROUPS,
hasGoal: false,
+ projectId,
visibility: filterToServerVisibility(listVisibility),
});
},
@@ -205,12 +218,17 @@ export class TaskListSliceActionImpl {
* `tasks` field and must not serve each other's ordering.
*/
orderBy?: 'createdAt' | 'updatedAt';
+ projectId?: string;
/** Override the Task page's persisted filter for embedded consumers. */
visibility?: TaskListVisibilityFilter;
} = {},
) => {
- const { agentId, allAgents = false, enabled = true, orderBy, visibility } = options;
- const effectiveKey = allAgents ? ALL_AGENTS_LIST_KEY : agentId;
+ const { agentId, allAgents = false, enabled = true, orderBy, projectId, visibility } = options;
+ const effectiveKey = projectId
+ ? `${PROJECT_LIST_KEY_PREFIX}${projectId}`
+ : allAgents
+ ? ALL_AGENTS_LIST_KEY
+ : agentId;
const listVisibility = visibility ?? this.#get().listVisibility;
const { listAgentId, listQueryVisibility } = this.#get();
@@ -230,12 +248,15 @@ export class TaskListSliceActionImpl {
}
return useClientDataSWR(
- enabled && effectiveKey ? taskKeys.list(effectiveKey, listVisibility, orderBy) : null,
+ enabled && effectiveKey
+ ? taskKeys.list(effectiveKey, listVisibility, orderBy, projectId)
+ : null,
async ([, id]: [string, string]) => {
return this.fetchTaskList({
- ...(allAgents ? {} : { assigneeAgentId: id }),
+ ...(allAgents || projectId ? {} : { assigneeAgentId: id }),
hasGoal: false,
orderBy,
+ projectId,
visibility: filterToServerVisibility(listVisibility),
});
},
diff --git a/src/store/user/slices/preference/selectors.test.ts b/src/store/user/slices/preference/selectors.test.ts
index 56d053adfb4..eace105c82a 100644
--- a/src/store/user/slices/preference/selectors.test.ts
+++ b/src/store/user/slices/preference/selectors.test.ts
@@ -94,6 +94,14 @@ describe('preferenceSelectors', () => {
expect(labPreferSelectors.enableDesktopSplitView(store)).toBe(true);
});
+ it('should default project workspaces to disabled and honor the lab preference', () => {
+ store.preference.lab = undefined;
+ expect(labPreferSelectors.enableProjects(store)).toBe(false);
+
+ store.preference.lab = { enableProjects: true };
+ expect(labPreferSelectors.enableProjects(store)).toBe(true);
+ });
+
it('returns false for message text selection actions by default', () => {
store.preference.lab = undefined;
diff --git a/src/store/user/slices/preference/selectors/labPrefer.ts b/src/store/user/slices/preference/selectors/labPrefer.ts
index 72e27126b0d..919435bb849 100644
--- a/src/store/user/slices/preference/selectors/labPrefer.ts
+++ b/src/store/user/slices/preference/selectors/labPrefer.ts
@@ -24,6 +24,7 @@ export const labPreferSelectors = {
DEFAULT_PREFERENCE.lab?.enableMessageTextSelectionActions ??
false,
enableOAuthApps: (s: UserState): boolean => s.preference.lab?.enableOAuthApps ?? false,
+ enableProjects: (s: UserState): boolean => s.preference.lab?.enableProjects ?? false,
enableTaskVerify: (s: UserState): boolean => s.preference.lab?.enableTaskVerify ?? false,
enableTopicAcceptance: (s: UserState): boolean =>
s.preference.lab?.enableTopicAcceptance ?? false,