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(task): link tasks to projects, with picker, badges and grouping (#22383)

Rdmclin2fc60541fca34
diff --git a/apps/cli/src/commands/task/index.ts b/apps/cli/src/commands/task/index.ts
index 0183995b256..83c0644393e 100644
--- a/apps/cli/src/commands/task/index.ts
+++ b/apps/cli/src/commands/task/index.ts
@@ -668,6 +668,7 @@ export function registerTaskCommand(program: Command) {
.option('--agent <id>', 'Assign to agent')
.option('--user <idOrEmail>', 'Assign to a workspace member (user id, email or username)')
.option('--priority <n>', 'Priority (0-4)')
+ .option('--project <id>', 'Move to a project ("null" to remove it from its project)')
.option(
'--label <name>',
"Add a label (repeatable or comma-separated; replaces the task's other label of the same group)",
@@ -702,6 +703,7 @@ export function registerTaskCommand(program: Command) {
model?: string;
name?: string;
priority?: string;
+ project?: string;
provider?: string;
removeLabel?: string[];
status?: string;
@@ -724,6 +726,8 @@ export function registerTaskCommand(program: Command) {
if (options.agent) input.assigneeAgentId = options.agent;
if (assigneeUserId) input.assigneeUserId = assigneeUserId;
if (options.priority) input.priority = Number.parseInt(options.priority, 10);
+ if (options.project !== undefined)
+ input.projectId = options.project === 'null' ? null : options.project;
if (options.heartbeatInterval)
input.heartbeatInterval = Number.parseInt(options.heartbeatInterval, 10);
if (options.heartbeatTimeout !== undefined) {
diff --git a/apps/cli/src/commands/task/project.test.ts b/apps/cli/src/commands/task/project.test.ts
new file mode 100644
index 00000000000..1764b237fb0
--- /dev/null
+++ b/apps/cli/src/commands/task/project.test.ts
@@ -0,0 +1,59 @@
+import { Command } from 'commander';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { registerTaskCommand } from './index';
+
+const { client } = vi.hoisted(() => ({
+ client: {
+ task: {
+ update: { mutate: vi.fn() },
+ updateStatus: { mutate: vi.fn() },
+ },
+ taskLabel: { list: { query: vi.fn() } },
+ },
+}));
+
+vi.mock('../../api/client', () => ({ getTrpcClient: vi.fn(async () => client) }));
+vi.mock('./url', () => ({
+ resolveAppUrl: vi.fn(async () => 'https://app/task'),
+ resolveAppUrlBuilder: vi.fn(async () => () => 'https://app/task'),
+ taskPath: vi.fn(() => '/task'),
+}));
+vi.mock('../../utils/logger', () => ({
+ log: { error: vi.fn(), info: vi.fn(), warn: vi.fn() },
+}));
+
+const run = async (...args: string[]) => {
+ const program = new Command();
+ program.exitOverride();
+ registerTaskCommand(program);
+ await program.parseAsync(['node', 'lh', 'task', ...args]);
+};
+
+describe('lh task edit --project', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ client.task.update.mutate.mockResolvedValue({ data: { id: 'task_1', identifier: 'T-1' } });
+ });
+
+ it('moves the task to the project', async () => {
+ await run('edit', 'T-1', '--project', 'proj_1');
+ expect(client.task.update.mutate).toHaveBeenCalledWith({ id: 'T-1', projectId: 'proj_1' });
+ });
+
+ it('removes the task from its project with "null"', async () => {
+ await run('edit', 'T-1', '--project', 'null');
+ expect(client.task.update.mutate).toHaveBeenCalledWith({ id: 'T-1', projectId: null });
+ });
+
+ it('sends an empty project so the server rejects it instead of silently ignoring it', async () => {
+ await run('edit', 'T-1', '--project', '');
+ expect(client.task.update.mutate).toHaveBeenCalledWith({ id: 'T-1', projectId: '' });
+ });
+
+ it('does not send a project when the option is absent', async () => {
+ await run('edit', 'T-1', '--name', 'Renamed');
+ expect(client.task.update.mutate).toHaveBeenCalledWith({ id: 'T-1', name: 'Renamed' });
+ });
+});
diff --git a/apps/server/src/routers/lambda/__tests__/integration/task.project.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/task.project.integration.test.ts
new file mode 100644
index 00000000000..ea0bbdd85ac
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/integration/task.project.integration.test.ts
@@ -0,0 +1,299 @@
+// @vitest-environment node
+import { type LobeChatDatabase } from '@lobechat/database';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { TaskRestService } from '@lobechat/openapi/src/services/task.service';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ProjectModel } from '@/database/models/project';
+import { TaskModel } from '@/database/models/task';
+import { projects, tasks, workspaceMembers, workspaces } from '@/database/schemas';
+
+import { taskRouter } from '../../task';
+import { cleanupTestUser, createTestContext, createTestUser } from './setup';
+
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return testDB;
+ }),
+}));
+
+const WORKSPACE = 'task-project-link-ws';
+const OTHER_WORKSPACE = 'task-project-link-other-ws';
+
+describe('task.update projectId', () => {
+ let userId: string;
+ let memberId: string;
+ let strangerId: string;
+ let caller: ReturnType<typeof taskRouter.createCaller>;
+ let projectA: string;
+ let projectB: string;
+
+ const storedProjectId = async (id: string) => {
+ const [row] = await testDB.select().from(tasks).where(eq(tasks.id, id));
+ return row.projectId;
+ };
+
+ const newProject = async (owner: string, workspaceId: string | undefined, name: string) =>
+ (await new ProjectModel(testDB, owner, workspaceId).create({ name })).id;
+
+ beforeEach(async () => {
+ testDB = await getTestDB();
+ userId = await createTestUser(testDB);
+ memberId = await createTestUser(testDB);
+ strangerId = await createTestUser(testDB);
+ await testDB.insert(workspaces).values([
+ { id: WORKSPACE, name: 'Mine', primaryOwnerId: userId, slug: WORKSPACE },
+ { id: OTHER_WORKSPACE, name: 'Other', primaryOwnerId: strangerId, slug: OTHER_WORKSPACE },
+ ]);
+ await testDB.insert(workspaceMembers).values([
+ { role: 'owner', userId, workspaceId: WORKSPACE },
+ { role: 'member', userId: memberId, workspaceId: WORKSPACE },
+ // The caller belongs to both, so only the active scope can refuse the other one.
+ { role: 'member', userId, workspaceId: OTHER_WORKSPACE },
+ { role: 'owner', userId: strangerId, workspaceId: OTHER_WORKSPACE },
+ ]);
+ caller = taskRouter.createCaller({ ...createTestContext(userId), workspaceId: WORKSPACE });
+ projectA = await newProject(userId, WORKSPACE, 'Project A');
+ projectB = await newProject(userId, WORKSPACE, 'Project B');
+ });
+
+ afterEach(async () => {
+ await testDB.delete(workspaces).where(eq(workspaces.id, WORKSPACE));
+ await testDB.delete(workspaces).where(eq(workspaces.id, OTHER_WORKSPACE));
+ for (const id of [userId, memberId, strangerId]) await cleanupTestUser(testDB, id);
+ });
+
+ it('sets, changes and clears the project, keeping the identifier', async () => {
+ const { data: task } = await caller.create({ instruction: 'Movable' });
+ expect(task.projectId).toBeNull();
+
+ const set = await caller.update({ id: task.id, projectId: projectA });
+ expect(set.data.projectId).toBe(projectA);
+ expect(await storedProjectId(task.id)).toBe(projectA);
+
+ const changed = await caller.update({ id: task.identifier, projectId: projectB });
+ expect(changed.data.projectId).toBe(projectB);
+ expect(await storedProjectId(task.id)).toBe(projectB);
+
+ const cleared = await caller.update({ id: task.id, projectId: null });
+ expect(cleared.data.projectId).toBeNull();
+ expect(await storedProjectId(task.id)).toBeNull();
+ expect(cleared.data.identifier).toBe(task.identifier);
+ });
+
+ it('leaves the project alone when the patch does not send it', async () => {
+ const { data: task } = await caller.create({ instruction: 'Stay', projectId: projectA });
+
+ const renamed = await caller.update({ id: task.id, name: 'Renamed', priority: 2 });
+ expect(renamed.data.name).toBe('Renamed');
+ expect(renamed.data.projectId).toBe(projectA);
+ expect(await storedProjectId(task.id)).toBe(projectA);
+
+ const undefinedPatch = await caller.update({
+ id: task.id,
+ name: 'Again',
+ projectId: undefined,
+ });
+ expect(undefinedPatch.data.projectId).toBe(projectA);
+ });
+
+ it('applies a project change that ships with a status change', async () => {
+ const { data: task } = await caller.create({ instruction: 'Combined' });
+ const { data } = await caller.update({ id: task.id, projectId: projectA, status: 'paused' });
+ expect(data).toMatchObject({ projectId: projectA, status: 'paused' });
+ expect(await storedProjectId(task.id)).toBe(projectA);
+ });
+
+ describe('refuses a project the caller cannot file under', () => {
+ const notFound = { code: 'NOT_FOUND', message: 'Project not found' };
+
+ it('in another workspace, on update and on create', async () => {
+ const foreign = await newProject(strangerId, OTHER_WORKSPACE, 'Foreign');
+ const { data: task } = await caller.create({ instruction: 'Scoped', projectId: projectA });
+
+ await expect(caller.update({ id: task.id, projectId: foreign })).rejects.toMatchObject(
+ notFound,
+ );
+ await expect(
+ caller.create({ instruction: 'Cross', projectId: foreign }),
+ ).rejects.toMatchObject(notFound);
+ expect(await storedProjectId(task.id)).toBe(projectA);
+ });
+
+ it('owned personally by the caller, from a workspace', async () => {
+ const personal = await newProject(userId, undefined, 'Personal');
+ const { data: task } = await caller.create({ instruction: 'Scoped' });
+ await expect(caller.update({ id: task.id, projectId: personal })).rejects.toMatchObject(
+ notFound,
+ );
+ });
+
+ it('private to another member, on update and on create', async () => {
+ const hidden = (
+ await new ProjectModel(testDB, memberId, WORKSPACE).create({
+ name: 'Hidden',
+ visibility: 'private',
+ })
+ ).id;
+ const { data: task } = await caller.create({ instruction: 'Scoped' });
+ await expect(caller.update({ id: task.id, projectId: hidden })).rejects.toMatchObject(
+ notFound,
+ );
+ await expect(
+ caller.create({ instruction: 'Cross', projectId: hidden }),
+ ).rejects.toMatchObject(notFound);
+ });
+
+ it('that does not exist or is an empty id', async () => {
+ const { data: task } = await caller.create({ instruction: 'Scoped' });
+ for (const projectId of ['project-that-does-not-exist', '']) {
+ await expect(caller.update({ id: task.id, projectId })).rejects.toMatchObject(notFound);
+ }
+ });
+
+ it('that is another user’s in personal mode', async () => {
+ const foreign = await newProject(strangerId, undefined, 'Foreign personal');
+ const personalCaller = taskRouter.createCaller(createTestContext(userId));
+ const { data: task } = await personalCaller.create({ instruction: 'Personal' });
+ await expect(
+ personalCaller.update({ id: task.id, projectId: foreign }),
+ ).rejects.toMatchObject(notFound);
+ });
+ });
+
+ describe('keeps subtasks and dependencies inside one project', () => {
+ it('refuses to split a subtask from its parent, and allows detaching it', async () => {
+ const { data: parent } = await caller.create({ instruction: 'Parent', projectId: projectA });
+ const { data: child } = await caller.create({
+ instruction: 'Child',
+ parentTaskId: parent.id,
+ });
+
+ await expect(caller.update({ id: child.id, projectId: projectB })).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ message: 'Subtask must belong to the same project as its parent',
+ });
+ await expect(caller.update({ id: parent.id, projectId: null })).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ message: expect.stringContaining('subtasks'),
+ });
+ expect(await storedProjectId(child.id)).toBe(projectA);
+ expect(await storedProjectId(parent.id)).toBe(projectA);
+
+ const { data } = await caller.update({
+ id: child.id,
+ parentTaskId: null,
+ projectId: projectB,
+ });
+ expect(data).toMatchObject({ parentTaskId: null, projectId: projectB });
+ // The parent is free to move once nothing is left behind.
+ const moved = await caller.update({ id: parent.id, projectId: projectB });
+ expect(moved.data.projectId).toBe(projectB);
+ });
+
+ it('refuses to strand a dependency in either direction', async () => {
+ const model = new TaskModel(testDB, userId, WORKSPACE);
+ const { data: first } = await caller.create({ instruction: 'First', projectId: projectA });
+ const { data: second } = await caller.create({ instruction: 'Second', projectId: projectA });
+ await model.addDependency(second.id, first.id);
+
+ for (const id of [first.id, second.id]) {
+ await expect(caller.update({ id, projectId: projectB })).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ message: expect.stringContaining('dependencies cannot cross'),
+ });
+ }
+ });
+
+ it('counts a dependency on a private task the mover cannot see', async () => {
+ const owner = new TaskModel(testDB, userId, WORKSPACE);
+ const { data: shared } = await caller.create({
+ instruction: 'Shared',
+ projectId: projectA,
+ visibility: 'public',
+ });
+ const hidden = await owner.create({
+ instruction: 'Hidden',
+ projectId: projectA,
+ visibility: 'private',
+ });
+ await owner.addDependency(shared.id, hidden.id);
+
+ const memberCaller = taskRouter.createCaller({
+ ...createTestContext(memberId),
+ workspaceId: WORKSPACE,
+ });
+ await expect(
+ memberCaller.update({ id: shared.id, projectId: projectB }),
+ ).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ message: expect.stringContaining('dependencies cannot cross'),
+ });
+ expect((await owner.findById(shared.id))?.projectId).toBe(projectA);
+ });
+ });
+
+ it('reports the project in list, group list and detail reads', async () => {
+ const { data: task } = await caller.create({ instruction: 'Read me', projectId: projectA });
+ const { data: bare } = await caller.create({ instruction: 'No project' });
+
+ const detail = await caller.detail({ id: task.id });
+ expect(detail.data.projectId).toBe(projectA);
+ expect((await caller.detail({ id: bare.id })).data.projectId).toBeNull();
+
+ const list = await caller.list({ projectId: projectA });
+ expect(list.data.map((row) => [row.id, row.projectId])).toEqual([[task.id, projectA]]);
+
+ const groups = await caller.groupList({ groupBy: 'priority', projectId: projectA });
+ const cards = groups.data.flatMap((group) => group.tasks);
+ expect(cards.map((card) => [card.id, card.projectId])).toEqual([[task.id, projectA]]);
+ });
+
+ it('moves the task between the project-scoped lists', async () => {
+ const { data: task } = await caller.create({ instruction: 'Mover', projectId: projectA });
+ await caller.update({ id: task.id, projectId: projectB });
+
+ expect((await caller.list({ projectId: projectA })).data).toEqual([]);
+ const listed = await caller.list({ projectId: projectB });
+ expect(listed.data.map((row) => row.id)).toEqual([task.id]);
+ expect((await caller.detail({ id: task.id })).data.projectId).toBe(projectB);
+
+ await caller.update({ id: task.id, projectId: null });
+ expect((await caller.list({ projectId: projectB })).data).toEqual([]);
+ const all = await caller.list({});
+ expect(all.data.find((row) => row.id === task.id)?.projectId).toBeNull();
+ });
+
+ it('applies the same contract through the REST patch', async () => {
+ const rest = new TaskRestService(testDB, userId, WORKSPACE);
+ const { data: task } = await caller.create({ instruction: 'REST' });
+ const patch = (projectId?: string | null) =>
+ rest.updateTask(task.id, projectId === undefined ? { name: 'Named' } : { projectId });
+
+ await patch(projectA);
+ expect(await storedProjectId(task.id)).toBe(projectA);
+ await patch(projectB);
+ expect(await storedProjectId(task.id)).toBe(projectB);
+ await patch();
+ expect(await storedProjectId(task.id)).toBe(projectB);
+
+ const foreign = await newProject(strangerId, OTHER_WORKSPACE, 'Foreign');
+ await expect(patch(foreign)).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ message: 'Project not found',
+ });
+ expect(await storedProjectId(task.id)).toBe(projectB);
+
+ await patch(null);
+ expect(await storedProjectId(task.id)).toBeNull();
+ });
+
+ it('survives its project being deleted (the FK clears the link)', async () => {
+ const { data: task } = await caller.create({ instruction: 'Orphan', projectId: projectA });
+ await testDB.delete(projects).where(eq(projects.id, projectA));
+ expect(await storedProjectId(task.id)).toBeNull();
+ expect((await caller.detail({ id: task.id })).data.projectId).toBeNull();
+ });
+});
diff --git a/apps/server/src/routers/lambda/_helpers/taskListSchemas.test.ts b/apps/server/src/routers/lambda/_helpers/taskListSchemas.test.ts
index 323ba130e69..53122b0136b 100644
--- a/apps/server/src/routers/lambda/_helpers/taskListSchemas.test.ts
+++ b/apps/server/src/routers/lambda/_helpers/taskListSchemas.test.ts
@@ -63,3 +63,9 @@ describe('filter', () => {
).toThrow();
});
});
+
+describe('groupBy project', () => {
+ it('is accepted by groupList', () => {
+ expect(groupListSchema.parse({ groupBy: 'project' }).groupBy).toBe('project');
+ });
+});
diff --git a/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts b/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts
index 1f46445732b..e0467c0d9c5 100644
--- a/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts
+++ b/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts
@@ -92,7 +92,7 @@ export const groupListSchema = z
completedWithin: z.enum(TASK_COMPLETED_WINDOWS).optional(),
excludeStatuses: z.array(z.enum(TASK_STATUSES)).max(10).optional(),
filter: taskListFilterSchema.optional(),
- groupBy: z.enum(['agent', 'assignee', 'label', 'member', 'priority']).optional(),
+ groupBy: z.enum(['agent', 'assignee', 'label', 'member', 'priority', 'project']).optional(),
groups: z
.array(
z.object({
diff --git a/apps/server/src/routers/lambda/task/update.ts b/apps/server/src/routers/lambda/task/update.ts
index 57803e6b5f6..2a67018ead0 100644
--- a/apps/server/src/routers/lambda/task/update.ts
+++ b/apps/server/src/routers/lambda/task/update.ts
@@ -45,6 +45,8 @@ const updateSchema = z.object({
name: z.string().optional(),
parentTaskId: z.string().nullish(),
priority: z.number().min(0).max(4).optional(),
+ // `null` takes the task out of its project; omitted leaves it untouched.
+ projectId: z.string().nullish(),
schedulePattern: schedulePatternSchema.nullish(),
scheduleTimezone: scheduleTimezoneSchema.nullish(),
status: z.enum(TASK_STATUSES).optional(),
diff --git a/apps/server/src/services/task/detail.ts b/apps/server/src/services/task/detail.ts
index ce915eda012..d6902f39699 100644
--- a/apps/server/src/services/task/detail.ts
+++ b/apps/server/src/services/task/detail.ts
@@ -530,6 +530,7 @@ export class TaskDetailService {
name: task.name,
parent,
priority: task.priority,
+ projectId: task.projectId,
startedAt: task.startedAt ? new Date(task.startedAt).toISOString() : undefined,
status: task.status,
userId: task.assigneeUserId,
diff --git a/apps/server/src/services/task/patchValidation.test.ts b/apps/server/src/services/task/patchValidation.test.ts
index de74bbeb4f1..8ea0973804f 100644
--- a/apps/server/src/services/task/patchValidation.test.ts
+++ b/apps/server/src/services/task/patchValidation.test.ts
@@ -4,7 +4,16 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { resolveTaskPatchInvariants } from './patchValidation';
-const { assertAgentUsableByMock } = vi.hoisted(() => ({ assertAgentUsableByMock: vi.fn() }));
+const { assertAgentUsableByMock, findProjectMock } = vi.hoisted(() => ({
+ assertAgentUsableByMock: vi.fn(),
+ findProjectMock: vi.fn(),
+}));
+
+vi.mock('@/database/models/project', () => ({
+ ProjectModel: class {
+ findById = findProjectMock;
+ },
+}));
vi.mock('@/database/utils/agent-access', () => ({
assertAgentUsableBy: assertAgentUsableByMock,
@@ -33,6 +42,8 @@ const buildContext = (rows: Record<string, Record<string, unknown>> = {}) => {
const taskModel = {
findAllDescendants: vi.fn().mockResolvedValue([]),
findById: vi.fn(async (id: string) => storedTask(id, rows[id])),
+ hasDependencyOutsideProject: vi.fn().mockResolvedValue(false),
+ hasSubtaskOutsideProject: vi.fn().mockResolvedValue(false),
resolve: vi.fn(async (id: string) => storedTask(id, rows[id])),
};
const taskService = {
@@ -230,3 +241,118 @@ describe('resolveTaskPatchInvariants normalization', () => {
expect(result.data.editorData).toEqual({ root: {} });
});
});
+
+describe('resolveTaskPatchInvariants project', () => {
+ beforeEach(() => {
+ assertAgentUsableByMock.mockReset();
+ findProjectMock.mockReset();
+ findProjectMock.mockImplementation(async (id: string) =>
+ id.startsWith('project-') ? { id } : null,
+ );
+ });
+
+ it('accepts moving a task to a project the caller can read', async () => {
+ const { context } = buildContext();
+ const { data } = await resolveTaskPatchInvariants(context, {
+ data: { projectId: 'project-2' },
+ id: 'task-1',
+ });
+ expect(data.projectId).toBe('project-2');
+ });
+
+ it.each(['missing', ''])('refuses the unknown project id %j as not found', async (projectId) => {
+ const { context } = buildContext();
+ await expect(
+ resolveTaskPatchInvariants(context, { data: { projectId }, id: 'task-1' }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND', message: 'Project not found' });
+ });
+
+ it('clears the project without looking one up', async () => {
+ const { context } = buildContext();
+ const { data } = await resolveTaskPatchInvariants(context, {
+ data: { projectId: null },
+ id: 'task-1',
+ });
+ expect(data.projectId).toBeNull();
+ expect(findProjectMock).not.toHaveBeenCalled();
+ });
+
+ it('leaves the project out of the patch when it is not sent', async () => {
+ const { context, taskModel } = buildContext();
+ const { data } = await resolveTaskPatchInvariants(context, {
+ data: { name: 'renamed' },
+ id: 'task-1',
+ });
+ expect(data).not.toHaveProperty('projectId');
+ expect(findProjectMock).not.toHaveBeenCalled();
+ expect(taskModel.hasSubtaskOutsideProject).not.toHaveBeenCalled();
+ });
+
+ it('does not re-check links when the project stays the same', async () => {
+ const { context, taskModel } = buildContext({ 'task-1': { parentTaskId: 'parent-1' } });
+ await resolveTaskPatchInvariants(context, { data: { projectId: 'project-1' }, id: 'task-1' });
+ expect(taskModel.hasSubtaskOutsideProject).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['moved', 'project-2'],
+ ['cleared', null],
+ ])('refuses a subtask %s away from its parent', async (_label, projectId) => {
+ const { context } = buildContext({ 'task-1': { parentTaskId: 'parent-1' } });
+ await expect(
+ resolveTaskPatchInvariants(context, { data: { projectId }, id: 'task-1' }),
+ ).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ message: 'Subtask must belong to the same project as its parent',
+ });
+ });
+
+ it('accepts a move that detaches the subtask in the same patch', async () => {
+ const { context } = buildContext({ 'task-1': { parentTaskId: 'parent-1' } });
+ const { data } = await resolveTaskPatchInvariants(context, {
+ data: { projectId: 'project-2' },
+ id: 'task-1',
+ parentTaskId: null,
+ });
+ expect(data).toMatchObject({ parentTaskId: null, projectId: 'project-2' });
+ });
+
+ it('judges a new parent against the project the same patch moves to', async () => {
+ const { context } = buildContext({ 'parent-1': { projectId: 'project-2' } });
+ const { data } = await resolveTaskPatchInvariants(context, {
+ data: { projectId: 'project-2' },
+ id: 'task-1',
+ parentTaskId: 'parent-1',
+ });
+ expect(data).toMatchObject({ parentTaskId: 'parent-1', projectId: 'project-2' });
+
+ await expect(
+ resolveTaskPatchInvariants(context, {
+ data: { projectId: 'project-3' },
+ id: 'task-1',
+ parentTaskId: 'parent-1',
+ }),
+ ).rejects.toMatchObject({ message: 'Parent task must belong to the same project' });
+ });
+
+ it('refuses moving a task whose subtasks would stay behind', async () => {
+ const { context, taskModel } = buildContext();
+ taskModel.hasSubtaskOutsideProject.mockResolvedValue(true);
+ await expect(
+ resolveTaskPatchInvariants(context, { data: { projectId: 'project-2' }, id: 'task-1' }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST', message: expect.stringContaining('subtasks') });
+ expect(taskModel.hasSubtaskOutsideProject).toHaveBeenCalledWith('task-1', 'project-2');
+ });
+
+ it('refuses a move that strands a dependency', async () => {
+ const { context, taskModel } = buildContext();
+ taskModel.hasDependencyOutsideProject.mockResolvedValue(true);
+ await expect(
+ resolveTaskPatchInvariants(context, { data: { projectId: 'project-2' }, id: 'task-1' }),
+ ).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ message: expect.stringContaining('dependencies cannot cross project boundaries'),
+ });
+ expect(taskModel.hasDependencyOutsideProject).toHaveBeenCalledWith('task-1', 'project-2');
+ });
+});
diff --git a/apps/server/src/services/task/patchValidation.ts b/apps/server/src/services/task/patchValidation.ts
index 57670673529..018b434518f 100644
--- a/apps/server/src/services/task/patchValidation.ts
+++ b/apps/server/src/services/task/patchValidation.ts
@@ -2,6 +2,7 @@ import type { TaskContext } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import type { AgentModel } from '@/database/models/agent';
+import { ProjectModel } from '@/database/models/project';
import type { TaskModel } from '@/database/models/task';
import type { LobeChatDatabase } from '@/database/type';
import { assertAgentUsableBy } from '@/database/utils/agent-access';
@@ -37,6 +38,7 @@ export interface TaskPatchFields {
context?: Record<string, unknown>;
editorData?: unknown;
instruction?: string | null;
+ projectId?: string | null;
schedulePattern?: string | null;
scheduleTimezone?: string | null;
}
@@ -77,10 +79,61 @@ export async function assertAssigneeAgentBelongsToUser(
}
}
+/**
+ * A task patch may file the task under any project the caller can read — the
+ * same bar `createTask` applies, and the same NOT_FOUND: another workspace's or
+ * member's private project is indistinguishable from one that does not exist.
+ */
+async function assertProjectReadable(ctx: TaskPatchInvariantContext, projectId: string) {
+ const project = await new ProjectModel(ctx.serverDB, ctx.userId, ctx.workspaceId).findById(
+ projectId,
+ );
+ if (!project) throw new TRPCError({ code: 'NOT_FOUND', message: 'Project not found' });
+}
+
+/**
+ * Moving a task leaves its subtasks and dependencies where they are, and neither
+ * link may cross a project boundary (`createTask`, `addDependency` and reparenting
+ * all enforce that), so a move that would split them is refused rather than
+ * cascaded. A patch that also changes the parent is judged on the new parent by
+ * `resolveSafeParentTaskId` instead.
+ */
+async function assertProjectMoveKeepsLinks(
+ model: TaskModel,
+ task: ResolvedTask,
+ projectId: string | null,
+ parentChanges: boolean,
+) {
+ if (!parentChanges && task.parentTaskId) {
+ const parent = await model.findById(task.parentTaskId);
+ if (parent && parent.projectId !== projectId) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Subtask must belong to the same project as its parent',
+ });
+ }
+ }
+
+ if (await model.hasSubtaskOutsideProject(task.id, projectId)) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Task has subtasks in its current project. Move or detach them first',
+ });
+ }
+
+ if (await model.hasDependencyOutsideProject(task.id, projectId)) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Task dependencies cannot cross project boundaries. Remove them first',
+ });
+ }
+}
+
async function resolveSafeParentTaskId(
model: TaskModel,
taskId: string,
parentTaskId: string | null,
+ projectId: string | null,
): Promise<string | null> {
if (parentTaskId === null) return null;
@@ -100,8 +153,7 @@ async function resolveSafeParentTaskId(
});
}
- const task = await findTaskOrThrow(model, taskId);
- if (task.projectId !== parent.projectId) {
+ if (projectId !== parent.projectId) {
throw new TRPCError({
code: 'BAD_REQUEST',
message: 'Parent task must belong to the same project',
@@ -177,6 +229,23 @@ export async function resolveTaskPatchInvariants<Data extends TaskPatchFields>(
resolved.createdByUserId,
);
+ // `undefined` means "no change"; `null` takes the task out of its project and
+ // needs no target to check. An empty string is a target and fails as unknown.
+ if (data.projectId !== undefined && data.projectId !== null) {
+ await assertProjectReadable(ctx, data.projectId);
+ }
+ const resultingProjectId = data.projectId === undefined ? resolved.projectId : data.projectId;
+ if (resultingProjectId !== resolved.projectId) {
+ await assertProjectMoveKeepsLinks(
+ ctx.taskModel,
+ resolved,
+ resultingProjectId,
+ parentTaskId !== undefined,
+ );
+ }
+
+ // Judged against the project this patch leaves the task in, so one patch can
+ // move a task and reparent it under a task of the new project together.
const resolvedParentTaskId =
parentTaskId === undefined
? undefined
@@ -184,6 +253,7 @@ export async function resolveTaskPatchInvariants<Data extends TaskPatchFields>(
ctx.taskModel,
resolved.id,
parentTaskId === null ? null : (await resolveTaskOrThrow(ctx.taskModel, parentTaskId)).id,
+ resultingProjectId,
);
// Reparenting a public task under a private one breaks the parent visibility
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index d335e43b5e3..c9a0b0786c1 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2833,6 +2833,7 @@
"taskList.groupBy.member": "Assignee",
"taskList.groupBy.none": "No grouping",
"taskList.groupBy.priority": "Priority",
+ "taskList.groupBy.project": "Project",
"taskList.groupBy.schedule": "Schedule",
"taskList.groupBy.status": "Status",
"taskList.hiddenCompleted.count_one": "{{count}} task",
@@ -2873,6 +2874,16 @@
"taskList.viewAll": "View all",
"taskList.visibility.all": "All",
"taskList.visibility.label": "Visibility",
+ "taskProject.add": "Add to project",
+ "taskProject.empty": "No projects yet",
+ "taskProject.inheritedFromParent": "A subtask stays in its parent's project",
+ "taskProject.label": "Project",
+ "taskProject.loadFailed": "Failed to load projects",
+ "taskProject.moveRefused": "Can't move this task while its parent, subtasks or dependencies stay in the current project. Move or detach them first.",
+ "taskProject.noMatch": "No matching project",
+ "taskProject.none": "No project",
+ "taskProject.searchPlaceholder": "Search projects…",
+ "taskProject.unavailable": "Unavailable project",
"taskSchedule.advancedSettings": "Advanced settings",
"taskSchedule.clear": "Clear",
"taskSchedule.continuous": "Continuous",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 2024342d1e2..edd88fd94c2 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2833,6 +2833,7 @@
"taskList.groupBy.member": "负责人",
"taskList.groupBy.none": "不分组",
"taskList.groupBy.priority": "优先级",
+ "taskList.groupBy.project": "项目",
"taskList.groupBy.schedule": "定时",
"taskList.groupBy.status": "状态",
"taskList.hiddenCompleted.count_one": "{{count}} 个任务",
@@ -2873,6 +2874,16 @@
"taskList.viewAll": "查看全部",
"taskList.visibility.all": "全部",
"taskList.visibility.label": "可见性",
+ "taskProject.add": "添加到项目",
+ "taskProject.empty": "还没有项目",
+ "taskProject.inheritedFromParent": "子任务归属于父任务所在的项目",
+ "taskProject.label": "项目",
+ "taskProject.loadFailed": "项目加载失败",
+ "taskProject.moveRefused": "父任务、子任务或依赖仍在当前项目中,无法移动此任务。请先移动或解除它们。",
+ "taskProject.noMatch": "未找到匹配的项目",
+ "taskProject.none": "无项目",
+ "taskProject.searchPlaceholder": "搜索项目…",
+ "taskProject.unavailable": "项目不可用",
"taskSchedule.advancedSettings": "高级设置",
"taskSchedule.clear": "清除",
"taskSchedule.continuous": "持续运行",
diff --git a/packages/database/src/models/__tests__/task.groupByProject.test.ts b/packages/database/src/models/__tests__/task.groupByProject.test.ts
new file mode 100644
index 00000000000..28526cbeb22
--- /dev/null
+++ b/packages/database/src/models/__tests__/task.groupByProject.test.ts
@@ -0,0 +1,74 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { projects, users, workspaces } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { TaskModel } from '../task';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'task-group-project-user';
+const workspaceId = 'task-group-project-ws';
+
+const tasks = new TaskModel(serverDB, userId, workspaceId);
+
+const seedProject = async (id: string) => {
+ await serverDB.insert(projects).values({ id, name: id, slug: id, userId, workspaceId });
+};
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.delete(workspaces);
+ await serverDB.insert(users).values([{ id: userId }]);
+ await serverDB
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'WS', primaryOwnerId: userId, slug: workspaceId });
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.delete(workspaces);
+});
+
+describe('task board grouped by project', () => {
+ it('returns a column per project holding tasks, plus "No project"', async () => {
+ await seedProject('proj_a');
+ await seedProject('proj_empty');
+ const inProject = await tasks.create({ instruction: 'x', name: 'a', projectId: 'proj_a' });
+ const without = await tasks.create({ instruction: 'x', name: 'b' });
+
+ const groups = await tasks.groupList({ groupBy: 'project' });
+ const byKey = Object.fromEntries(groups.map((group) => [group.key, group]));
+
+ expect(Object.keys(byKey).sort()).toEqual(['project:none', 'project:proj_a']);
+ expect(byKey['project:proj_a']).toMatchObject({ projectId: 'proj_a', total: 1 });
+ expect(byKey['project:proj_a'].tasks.map((task) => task.id)).toEqual([inProject.id]);
+ expect(byKey['project:none']).toMatchObject({ projectId: null, total: 1 });
+ expect(byKey['project:none'].tasks.map((task) => task.id)).toEqual([without.id]);
+ });
+
+ it('keeps an empty "No project" column as a drop target', async () => {
+ await seedProject('proj_a');
+ await tasks.create({ instruction: 'x', name: 'a', projectId: 'proj_a' });
+
+ const groups = await tasks.groupList({ groupBy: 'project' });
+
+ expect(groups.find((group) => group.key === 'project:none')).toMatchObject({
+ projectId: null,
+ tasks: [],
+ total: 0,
+ });
+ });
+
+ it('honours the base filters and reports no project field on other boards', async () => {
+ await seedProject('proj_a');
+ await tasks.create({ instruction: 'x', name: 'a', projectId: 'proj_a', priority: 1 });
+
+ const filtered = await tasks.groupList({ excludeStatuses: ['backlog'], groupBy: 'project' });
+ expect(filtered.every((group) => group.tasks.length === 0)).toBe(true);
+
+ const byPriority = await tasks.groupList({ groupBy: 'priority' });
+ expect(byPriority.every((group) => !('projectId' in group))).toBe(true);
+ });
+});
diff --git a/packages/database/src/models/task/dependencies.test.ts b/packages/database/src/models/task/dependencies.test.ts
new file mode 100644
index 00000000000..4c1d5878c94
--- /dev/null
+++ b/packages/database/src/models/task/dependencies.test.ts
@@ -0,0 +1,94 @@
+// @vitest-environment node
+import { inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { projects, users, workspaceMembers, workspaces } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { TaskModel } from './index';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const ownerId = 'task-dep-project-owner';
+const memberId = 'task-dep-project-member';
+const workspaceId = 'task-dep-project-workspace';
+
+const projectIn = async (id: string) => {
+ await serverDB.insert(projects).values({ id, name: id, userId: ownerId, workspaceId });
+ return id;
+};
+
+beforeEach(async () => {
+ await serverDB.insert(users).values([{ id: ownerId }, { id: memberId }]);
+ await serverDB
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'Deps', primaryOwnerId: ownerId, slug: workspaceId });
+ await serverDB.insert(workspaceMembers).values([
+ { role: 'owner', userId: ownerId, workspaceId },
+ { role: 'member', userId: memberId, workspaceId },
+ ]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(workspaces).where(inArray(workspaces.id, [workspaceId]));
+ await serverDB.delete(users).where(inArray(users.id, [ownerId, memberId]));
+});
+
+describe('TaskModel.hasDependencyOutsideProject', () => {
+ it('checks both directions against a project and against no project', async () => {
+ const model = new TaskModel(serverDB, ownerId, workspaceId);
+ const inside = await projectIn('task-dep-project-a');
+ const outside = await projectIn('task-dep-project-b');
+ const task = await model.create({ instruction: 'task', projectId: inside });
+
+ expect(await model.hasDependencyOutsideProject(task.id, outside)).toBe(false);
+
+ const blocker = await model.create({ instruction: 'blocker', projectId: inside });
+ await model.addDependency(task.id, blocker.id);
+ expect(await model.hasDependencyOutsideProject(task.id, inside)).toBe(false);
+ expect(await model.hasDependencyOutsideProject(task.id, outside)).toBe(true);
+ expect(await model.hasDependencyOutsideProject(task.id, null)).toBe(true);
+
+ const dependent = await model.create({ instruction: 'dependent', projectId: inside });
+ await model.addDependency(dependent.id, blocker.id);
+ expect(await model.hasDependencyOutsideProject(blocker.id, outside)).toBe(true);
+ });
+
+ it('flags a linked task without a project when asked about a project', async () => {
+ const model = new TaskModel(serverDB, ownerId, workspaceId);
+ const target = await projectIn('task-dep-project-c');
+ const task = await model.create({ instruction: 'task' });
+ const blocker = await model.create({ instruction: 'blocker' });
+ await model.addDependency(task.id, blocker.id);
+
+ expect(await model.hasDependencyOutsideProject(task.id, null)).toBe(false);
+ expect(await model.hasDependencyOutsideProject(task.id, target)).toBe(true);
+ });
+
+ it("sees a dependency on another member's private task the caller cannot read", async () => {
+ const owner = new TaskModel(serverDB, ownerId, workspaceId);
+ const member = new TaskModel(serverDB, memberId, workspaceId);
+ const shared = await owner.create({ instruction: 'shared', visibility: 'public' });
+ const hidden = await owner.create({ instruction: 'hidden', visibility: 'private' });
+ await owner.addDependency(shared.id, hidden.id);
+ const target = await projectIn('task-dep-project-d');
+
+ expect(await member.findById(hidden.id)).toBeNull();
+ expect(await member.hasDependencyOutsideProject(shared.id, target)).toBe(true);
+ });
+
+ it('ignores a trashed linked task and links of another scope', async () => {
+ const model = new TaskModel(serverDB, ownerId, workspaceId);
+ const target = await projectIn('task-dep-project-e');
+ const task = await model.create({ instruction: 'task' });
+ const blocker = await model.create({ instruction: 'blocker' });
+ await model.addDependency(task.id, blocker.id);
+ await model.update(blocker.id, { deletedAt: new Date(), isDeleted: true });
+ expect(await model.hasDependencyOutsideProject(task.id, target)).toBe(false);
+
+ const live = await model.create({ instruction: 'live blocker' });
+ await model.addDependency(task.id, live.id);
+ const outsider = new TaskModel(serverDB, memberId);
+ expect(await outsider.hasDependencyOutsideProject(task.id, target)).toBe(false);
+ });
+});
diff --git a/packages/database/src/models/task/dependencies.ts b/packages/database/src/models/task/dependencies.ts
index 94f046b7773..dfaeaf1efa6 100644
--- a/packages/database/src/models/task/dependencies.ts
+++ b/packages/database/src/models/task/dependencies.ts
@@ -1,9 +1,9 @@
import type { TaskItem } from '@lobechat/types';
-import { and, eq, inArray, ne, sql } from 'drizzle-orm';
+import { and, eq, inArray, isNotNull, ne, or, sql } from 'drizzle-orm';
import { taskDependencies, tasks } from '../../schemas/task';
import { notTrashed } from '../../utils/softDelete';
-import { depsOwnership, type TaskModelContext, taskOwnership } from './context';
+import { depsOwnership, seqOwnership, type TaskModelContext, taskOwnership } from './context';
export const removeDependency = async (
ctx: TaskModelContext,
@@ -43,6 +43,41 @@ export const getDependents = async (ctx: TaskModelContext, taskId: string) => {
.where(and(eq(taskDependencies.dependsOnId, taskId), depsOwnership(ctx)));
};
+/**
+ * Whether a task linked to `taskId` by a dependency, in either direction, sits
+ * outside `projectId` (`null` meaning no project). Visibility-blind, like
+ * `hasSubtaskOutsideProject`: the rule that a dependency stays inside one project
+ * holds across the workspace, so another member's private task still counts. It
+ * only answers yes or no and never exposes that task.
+ */
+export const hasDependencyOutsideProject = async (
+ ctx: TaskModelContext,
+ taskId: string,
+ projectId: string | null,
+): Promise<boolean> => {
+ const [row] = await ctx.db
+ .select({ id: tasks.id })
+ .from(taskDependencies)
+ .innerJoin(
+ tasks,
+ or(
+ and(eq(taskDependencies.taskId, taskId), eq(tasks.id, taskDependencies.dependsOnId)),
+ and(eq(taskDependencies.dependsOnId, taskId), eq(tasks.id, taskDependencies.taskId)),
+ ),
+ )
+ .where(
+ and(
+ seqOwnership(ctx),
+ notTrashed(tasks.isDeleted),
+ projectId === null
+ ? isNotNull(tasks.projectId)
+ : sql`${tasks.projectId} IS DISTINCT FROM ${projectId}`,
+ ),
+ )
+ .limit(1);
+ return !!row;
+};
+
// Check if all dependencies of a task are completed
export const areAllDependenciesCompleted = async (
ctx: TaskModelContext,
diff --git a/packages/database/src/models/task/index.ts b/packages/database/src/models/task/index.ts
index dcf9d029e37..49c0e1609ff 100644
--- a/packages/database/src/models/task/index.ts
+++ b/packages/database/src/models/task/index.ts
@@ -260,7 +260,7 @@ export class TaskModel {
async groupList(
options: TaskListFilterOptions & {
excludeStatuses?: string[];
- groupBy?: 'agent' | 'assignee' | 'label' | 'member' | 'priority';
+ groupBy?: 'agent' | 'assignee' | 'label' | 'member' | 'priority' | 'project';
groups?: Array<{
key: string;
limit?: number;
@@ -279,6 +279,7 @@ export class TaskModel {
limit: number;
offset: number;
priority?: number;
+ projectId?: string | null;
tasks: TaskItem[];
total: number;
}>
@@ -302,6 +303,10 @@ export class TaskModel {
return tree.findAllDescendants(this.ctx, rootTaskId);
}
+ async hasSubtaskOutsideProject(taskId: string, projectId: string | null): Promise<boolean> {
+ return tree.hasSubtaskOutsideProject(this.ctx, taskId, projectId);
+ }
+
async getTaskTree(rootTaskId: string): Promise<TaskItem[]> {
return tree.getTaskTree(this.ctx, rootTaskId);
}
@@ -549,6 +554,10 @@ export class TaskModel {
return dependencies.removeDependency(this.ctx, taskId, dependsOnId);
}
+ async hasDependencyOutsideProject(taskId: string, projectId: string | null): Promise<boolean> {
+ return dependencies.hasDependencyOutsideProject(this.ctx, taskId, projectId);
+ }
+
async getDependencies(taskId: string) {
return dependencies.getDependencies(this.ctx, taskId);
}
diff --git a/packages/database/src/models/task/queries.ts b/packages/database/src/models/task/queries.ts
index f222c1d65f8..eef353b7f4b 100644
--- a/packages/database/src/models/task/queries.ts
+++ b/packages/database/src/models/task/queries.ts
@@ -45,7 +45,7 @@ export const groupList = async (
ctx: TaskModelContext,
options: TaskListFilterOptions & {
excludeStatuses?: string[];
- groupBy?: 'agent' | 'assignee' | 'label' | 'member' | 'priority';
+ groupBy?: 'agent' | 'assignee' | 'label' | 'member' | 'priority' | 'project';
groups?: Array<{
key: string;
limit?: number;
@@ -66,6 +66,8 @@ export const groupList = async (
limit: number;
offset: number;
priority?: number;
+ /** Project column of a `project` board; null is the "no project" column. */
+ projectId?: string | null;
tasks: TaskItem[];
total: number;
}>
@@ -91,6 +93,7 @@ export const groupList = async (
offset: number;
prefetchedTasks?: TaskItem[];
priority?: number;
+ projectId?: string | null;
total: number;
}
@@ -176,11 +179,15 @@ export const groupList = async (
total,
};
});
- } else if (groupBy === 'agent' || groupBy === 'member') {
+ } else if (groupBy === 'agent' || groupBy === 'member' || groupBy === 'project') {
const limit = 50;
- const groupColumn = groupBy === 'agent' ? tasks.assigneeAgentId : tasks.assigneeUserId;
- const groupPrefix = groupBy === 'agent' ? 'assignee:' : 'member:';
- const unassignedKey = `${groupPrefix}unassigned`;
+ const groupColumn = {
+ agent: tasks.assigneeAgentId,
+ member: tasks.assigneeUserId,
+ project: tasks.projectId,
+ }[groupBy];
+ const groupPrefix = { agent: 'assignee:', member: 'member:', project: 'project:' }[groupBy];
+ const unassignedKey = groupBy === 'project' ? 'project:none' : `${groupPrefix}unassigned`;
const assigneeGroupKey = sql<string>`case
when ${groupColumn} is not null then ${groupPrefix} || ${groupColumn}
else ${unassignedKey}
@@ -228,8 +235,12 @@ export const groupList = async (
// Keep an empty Unassigned column as a stable drop target. Agent-scoped
// boards omit the Agent-unassigned column because their base filter
- // guarantees one assignee, while Member grouping remains independent.
- if ((groupBy === 'member' || !assigneeAgentId) && !assigneeCounts.has(unassignedKey)) {
+ // guarantees one assignee, while Member grouping remains independent. A
+ // project board likewise keeps "No project" as the way out of a project.
+ if (
+ (groupBy === 'member' || groupBy === 'project' || !assigneeAgentId) &&
+ !assigneeCounts.has(unassignedKey)
+ ) {
assigneeCounts.set(unassignedKey, 0);
}
@@ -248,6 +259,7 @@ export const groupList = async (
limit,
offset: 0,
prefetchedTasks: tasksByAssignee.get(key) ?? [],
+ projectId: groupBy === 'project' ? assigneeId : undefined,
total,
};
});
@@ -364,6 +376,7 @@ export const groupList = async (
limit: group.limit,
offset: group.offset,
...(group.priority !== undefined ? { priority: group.priority } : {}),
+ ...(group.projectId !== undefined ? { projectId: group.projectId } : {}),
tasks: groupTasks,
total: group.total,
};
diff --git a/packages/database/src/models/task/tree.test.ts b/packages/database/src/models/task/tree.test.ts
new file mode 100644
index 00000000000..ec13ee31d87
--- /dev/null
+++ b/packages/database/src/models/task/tree.test.ts
@@ -0,0 +1,90 @@
+// @vitest-environment node
+import { inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { projects, users, workspaceMembers, workspaces } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { TaskModel } from './index';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const ownerId = 'task-tree-project-owner';
+const memberId = 'task-tree-project-member';
+const workspaceId = 'task-tree-project-workspace';
+
+const projectIn = async (id: string) => {
+ await serverDB.insert(projects).values({ id, name: id, userId: ownerId, workspaceId });
+ return id;
+};
+
+beforeEach(async () => {
+ await serverDB.insert(users).values([{ id: ownerId }, { id: memberId }]);
+ await serverDB
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'Tree', primaryOwnerId: ownerId, slug: workspaceId });
+ await serverDB.insert(workspaceMembers).values([
+ { role: 'owner', userId: ownerId, workspaceId },
+ { role: 'member', userId: memberId, workspaceId },
+ ]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(workspaces).where(inArray(workspaces.id, [workspaceId]));
+ await serverDB.delete(users).where(inArray(users.id, [ownerId, memberId]));
+});
+
+describe('TaskModel.hasSubtaskOutsideProject', () => {
+ it('compares direct subtasks against a project and against no project', async () => {
+ const model = new TaskModel(serverDB, ownerId, workspaceId);
+ const inside = await projectIn('task-tree-project-a');
+ const outside = await projectIn('task-tree-project-b');
+
+ const parent = await model.create({ instruction: 'parent', projectId: inside });
+ expect(await model.hasSubtaskOutsideProject(parent.id, inside)).toBe(false);
+ expect(await model.hasSubtaskOutsideProject(parent.id, null)).toBe(false);
+
+ await model.create({ instruction: 'child', parentTaskId: parent.id });
+ expect(await model.hasSubtaskOutsideProject(parent.id, inside)).toBe(false);
+ expect(await model.hasSubtaskOutsideProject(parent.id, outside)).toBe(true);
+ expect(await model.hasSubtaskOutsideProject(parent.id, null)).toBe(true);
+ });
+
+ it('flags a subtask without a project when asked about a project', async () => {
+ const model = new TaskModel(serverDB, ownerId, workspaceId);
+ const target = await projectIn('task-tree-project-c');
+ const parent = await model.create({ instruction: 'parent' });
+ await model.create({ instruction: 'child', parentTaskId: parent.id });
+
+ expect(await model.hasSubtaskOutsideProject(parent.id, null)).toBe(false);
+ expect(await model.hasSubtaskOutsideProject(parent.id, target)).toBe(true);
+ });
+
+ it("sees another member's private subtask the caller cannot read", async () => {
+ const owner = new TaskModel(serverDB, ownerId, workspaceId);
+ const member = new TaskModel(serverDB, memberId, workspaceId);
+ const parent = await owner.create({ instruction: 'parent', visibility: 'public' });
+ const hidden = await member.create({
+ instruction: 'hidden child',
+ parentTaskId: parent.id,
+ visibility: 'private',
+ });
+ const target = await projectIn('task-tree-project-d');
+
+ expect(await owner.findById(hidden.id)).toBeNull();
+ expect(await owner.hasSubtaskOutsideProject(parent.id, target)).toBe(true);
+ });
+
+ it('ignores a trashed subtask and subtasks of another scope', async () => {
+ const model = new TaskModel(serverDB, ownerId, workspaceId);
+ const target = await projectIn('task-tree-project-e');
+ const parent = await model.create({ instruction: 'parent' });
+ const child = await model.create({ instruction: 'child', parentTaskId: parent.id });
+ await model.update(child.id, { deletedAt: new Date(), isDeleted: true });
+ expect(await model.hasSubtaskOutsideProject(parent.id, target)).toBe(false);
+
+ await model.create({ instruction: 'live child', parentTaskId: parent.id });
+ const outsider = new TaskModel(serverDB, memberId);
+ expect(await outsider.hasSubtaskOutsideProject(parent.id, target)).toBe(false);
+ });
+});
diff --git a/packages/database/src/models/task/tree.ts b/packages/database/src/models/task/tree.ts
index bb827b13b44..f771c675f92 100644
--- a/packages/database/src/models/task/tree.ts
+++ b/packages/database/src/models/task/tree.ts
@@ -10,11 +10,13 @@ import {
taskTopics,
} from '../../schemas/task';
import type { LobeChatDatabase } from '../../type';
+import { notTrashed } from '../../utils/softDelete';
import {
activitiesOwnership,
commentsOwnership,
depsOwnership,
docsOwnership,
+ seqOwnership,
type TaskModelContext,
taskOwnership,
taskOwnershipSql,
@@ -59,6 +61,34 @@ export const findAllDescendants = async (
return all;
};
+/**
+ * Whether a direct subtask sits outside `projectId` (`null` = no project). Scoped
+ * like the identifier sequence rather than by `taskOwnership`: another member's
+ * private subtask is hidden from the caller but still has to share its parent's
+ * project. A trashed subtask no longer counts, like a trashed dependency.
+ */
+export const hasSubtaskOutsideProject = async (
+ ctx: TaskModelContext,
+ taskId: string,
+ projectId: string | null,
+): Promise<boolean> => {
+ const [row] = await ctx.db
+ .select({ id: tasks.id })
+ .from(tasks)
+ .where(
+ and(
+ eq(tasks.parentTaskId, taskId),
+ seqOwnership(ctx),
+ notTrashed(tasks.isDeleted),
+ projectId === null
+ ? isNotNull(tasks.projectId)
+ : sql`${tasks.projectId} IS DISTINCT FROM ${projectId}`,
+ ),
+ )
+ .limit(1);
+ return !!row;
+};
+
// Recursive query to get full task tree
export const getTaskTree = async (
ctx: TaskModelContext,
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 758cfb9627b..fb14147e1bf 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -3283,6 +3283,7 @@ export default {
'taskList.groupBy.member': 'Assignee',
'taskList.groupBy.none': 'No grouping',
'taskList.groupBy.priority': 'Priority',
+ 'taskList.groupBy.project': 'Project',
'taskList.groupBy.schedule': 'Schedule',
'taskList.groupBy.status': 'Status',
'taskList.orderBy.assignee': 'Agent',
@@ -4403,6 +4404,17 @@ export default {
'taskLabel.noLabel': 'No label',
'taskLabel.noLabels': 'No labels',
'taskLabel.searchPlaceholder': 'Search or create labels…',
+ 'taskProject.add': 'Add to project',
+ 'taskProject.empty': 'No projects yet',
+ 'taskProject.inheritedFromParent': "A subtask stays in its parent's project",
+ 'taskProject.label': 'Project',
+ 'taskProject.loadFailed': 'Failed to load projects',
+ 'taskProject.moveRefused':
+ "Can't move this task while its parent, subtasks or dependencies stay in the current project. Move or detach them first.",
+ 'taskProject.noMatch': 'No matching project',
+ 'taskProject.none': 'No project',
+ 'taskProject.searchPlaceholder': 'Search projects…',
+ 'taskProject.unavailable': 'Unavailable project',
'taskList.filter.field.label': 'Label',
'taskList.groupBy.labelGroup': 'Label: {{name}}',
};
diff --git a/packages/openapi/openapi.yml b/packages/openapi/openapi.yml
index a04ec321cdc..67b13e5b71a 100644
--- a/packages/openapi/openapi.yml
+++ b/packages/openapi/openapi.yml
@@ -23129,6 +23129,10 @@ paths:
type: integer
minimum: 0
maximum: 4
+ projectId:
+ type:
+ - string
+ - "null"
schedulePattern:
type:
- string
diff --git a/packages/openapi/src/services/task.service.test.ts b/packages/openapi/src/services/task.service.test.ts
index 137da0e967e..575a70e695c 100644
--- a/packages/openapi/src/services/task.service.test.ts
+++ b/packages/openapi/src/services/task.service.test.ts
@@ -147,6 +147,24 @@ describe('TaskRestService patch runs the shared invariants', () => {
updateTaskMock.mockResolvedValue({ id: 'task-1' });
});
+ it.each(['proj_1', null])(
+ 'hands projectId %j to the invariants and the write',
+ async (projectId) => {
+ resolveTaskPatchInvariantsMock.mockImplementation(async (_, { data }) => ({
+ data,
+ resolved: { createdByUserId: CALLER, id: 'task-1' },
+ }));
+
+ await service().updateTask('T-1', { projectId });
+
+ expect(resolveTaskPatchInvariantsMock).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ data: { projectId }, id: 'T-1' }),
+ );
+ expect(updateTaskMock).toHaveBeenCalledWith('task-1', { projectId }, expect.anything());
+ },
+ );
+
it('preserves unchanged legacy checkpoint selections after a selected task is deleted', async () => {
const tasks = { beforeIds: ['T-2'], afterIds: ['T-2'] };
resolveTaskPatchInvariantsMock.mockImplementation(async (_, { data }) => ({
diff --git a/packages/openapi/src/types/task.type.test.ts b/packages/openapi/src/types/task.type.test.ts
index 7a6c3e73fca..47d87d639ab 100644
--- a/packages/openapi/src/types/task.type.test.ts
+++ b/packages/openapi/src/types/task.type.test.ts
@@ -44,3 +44,15 @@ describe('task schedule field schemas', () => {
expect(UpdateTaskRequestSchema.safeParse({ schedulePattern: null }).success).toBe(true);
});
});
+
+describe('task project field schemas', () => {
+ it('accepts a project id and null on a patch, and rejects a non-string', () => {
+ expect(UpdateTaskRequestSchema.parse({ projectId: 'proj_1' })).toEqual({ projectId: 'proj_1' });
+ expect(UpdateTaskRequestSchema.parse({ projectId: null })).toEqual({ projectId: null });
+ expect(UpdateTaskRequestSchema.safeParse({ projectId: 42 }).success).toBe(false);
+ });
+
+ it('keeps an omitted project out of a patch, so it cannot overwrite the stored one', () => {
+ expect(UpdateTaskRequestSchema.parse({ name: 'x' })).not.toHaveProperty('projectId');
+ });
+});
diff --git a/packages/openapi/src/types/task.type.ts b/packages/openapi/src/types/task.type.ts
index bfbea87230d..41dda17a9d4 100644
--- a/packages/openapi/src/types/task.type.ts
+++ b/packages/openapi/src/types/task.type.ts
@@ -71,6 +71,8 @@ export const UpdateTaskRequestSchema = z
name: z.string().optional(),
parentTaskId: z.string().nullish(),
priority: z.number().int().min(0).max(4).optional(),
+ // `null` takes the task out of its project; omitted leaves it untouched.
+ projectId: z.string().nullish(),
schedulePattern: schedulePatternSchema.nullish(),
scheduleTimezone: scheduleTimezoneSchema.nullish(),
})
diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.ts
index 0fd9707b794..bca65a294f4 100644
--- a/packages/types/src/task/index.ts
+++ b/packages/types/src/task/index.ts
@@ -657,6 +657,8 @@ export interface TaskDetailData {
name?: string | null;
parent?: { id?: string; agentId?: string | null; identifier: string; name: string | null } | null;
priority?: number | null;
+ /** The project this task is filed under; null when it has none. */
+ projectId?: string | null;
schedule?: {
maxExecutions?: number | null;
pattern?: string | null;
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskProperties.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskProperties.tsx
index 09309b6e148..a234d7112f3 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskProperties.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskProperties.tsx
@@ -12,7 +12,9 @@ import { taskDetailSelectors } from '@/store/task/selectors';
import AssigneeMemberSelector from '../features/AssigneeMemberSelector';
import AssigneeUserAvatar from '../features/AssigneeUserAvatar';
+import ProjectSelector from '../features/ProjectSelector';
import TaskPriorityTag from '../features/TaskPriorityTag';
+import TaskProjectValue from '../features/TaskProjectValue';
import TaskStatusTag from '../features/TaskStatusTag';
import TaskTriggerTag from '../features/TaskTriggerTag';
import { UnassignedAssigneeIcon } from '../features/UnassignedAssigneeIcon';
@@ -69,6 +71,8 @@ const TaskProperties = memo(() => {
const taskDatabaseId = useTaskStore(taskDetailSelectors.activeTaskDatabaseId);
const labels = useTaskStore(taskDetailSelectors.activeTaskLabels);
const setTaskLabels = useTaskStore((s) => s.setTaskLabels);
+ const projectId = useTaskStore(taskDetailSelectors.activeTaskProjectId);
+ const hasParent = !!useTaskStore(taskDetailSelectors.activeTaskParent);
if (!taskId) return null;
@@ -77,72 +81,139 @@ const TaskProperties = memo(() => {
return (
<div className={styles.properties}>
- <TaskStatusTag status={status} taskIdentifier={taskId}>
- <Block
- clickable
- horizontal
- align="center"
- className={styles.propertyItem}
- gap={8}
- variant={'borderless'}
- >
- {/* `running` covers both an executing agent and a stopped one whose
- acceptance round has yet to settle; only the first is "in progress". */}
- {acceptanceWait ? (
- <Icon color={cssVar.colorWarning} icon={Stamp} size={16} />
- ) : (
- <TaskStatusTag disableDropdown size={16} status={status} taskIdentifier={taskId} />
- )}
- <Text weight={500}>
- {acceptanceWait
- ? t('taskDetail.status.awaitingAcceptance')
- : t(`taskDetail.${statusMeta.labelKey}` as never)}
- </Text>
- </Block>
- </TaskStatusTag>
-
- {/* Archived is the user's close-out on top of the status, not a status
- itself — shown read-only; the header menu restores it. */}
- {isArchived && (
- <Block
- horizontal
- align="center"
- className={styles.propertyItem}
- gap={8}
- variant={'borderless'}
- >
- <Icon color={cssVar.colorTextDescription} icon={ArchiveIcon} size={16} />
- <Text style={{ color: cssVar.colorTextDescription }} weight={500}>
- {t('taskList.archived')}
- </Text>
- </Block>
- )}
-
- {/* The human layer: whether the delivery is accepted. Read-only here —
- the decision itself is made on the acceptance page this links to.
- Recurring tasks have no delivery acceptance, so no state to show. */}
- {!automationMode && <TaskAcceptanceStateRow />}
-
- <TaskPriorityTag priority={priority} taskIdentifier={taskId}>
- <Block
- clickable
- horizontal
- align="center"
- className={styles.propertyItem}
- gap={8}
- variant={'borderless'}
- >
- <TaskPriorityTag disableDropdown priority={priority} size={16} taskIdentifier={taskId} />
- <Text weight={500}>{t(`taskDetail.${priorityMeta.labelKey}` as never)}</Text>
- </Block>
- </TaskPriorityTag>
-
- {shouldShowMemberAssignee(activeWorkspaceId, assigneeUserId) && (
- <AssigneeMemberSelector
- currentUserId={assigneeUserId}
- taskCreatorId={createdByUserId}
- taskIdentifier={taskId}
- taskVisibility={visibility}
+ <section className={styles.propertyGroup}>
+ <div className={styles.propertyGroupTitle}>{t('taskDetail.properties')}</div>
+ <TaskStatusTag status={status} taskIdentifier={taskId}>
+ <Block
+ clickable
+ horizontal
+ align="center"
+ className={styles.propertyItem}
+ gap={8}
+ variant={'borderless'}
+ >
+ {/* `running` covers both an executing agent and a stopped one whose
+ acceptance round has yet to settle; only the first is "in progress". */}
+ {acceptanceWait ? (
+ <Icon color={cssVar.colorWarning} icon={Stamp} size={16} />
+ ) : (
+ <TaskStatusTag disableDropdown size={16} status={status} taskIdentifier={taskId} />
+ )}
+ <Text weight={500}>
+ {acceptanceWait
+ ? t('taskDetail.status.awaitingAcceptance')
+ : t(`taskDetail.${statusMeta.labelKey}` as never)}
+ </Text>
+ </Block>
+ </TaskStatusTag>
+
+ {/* Archived is the user's close-out on top of the status, not a status
+ itself — shown read-only; the header menu restores it. */}
+ {isArchived && (
+ <Block
+ horizontal
+ align="center"
+ className={styles.propertyItem}
+ gap={8}
+ variant={'borderless'}
+ >
+ <Icon color={cssVar.colorTextDescription} icon={ArchiveIcon} size={16} />
+ <Text style={{ color: cssVar.colorTextDescription }} weight={500}>
+ {t('taskList.archived')}
+ </Text>
+ </Block>
+ )}
+
+ {/* The human layer: whether the delivery is accepted. Read-only here —
+ the decision itself is made on the acceptance page this links to.
+ Recurring tasks have no delivery acceptance, so no state to show. */}
+ {!automationMode && <TaskAcceptanceStateRow />}
+
+ <TaskPriorityTag priority={priority} taskIdentifier={taskId}>
+ <Block
+ clickable
+ horizontal
+ align="center"
+ className={styles.propertyItem}
+ gap={8}
+ variant={'borderless'}
+ >
+ <TaskPriorityTag
+ disableDropdown
+ priority={priority}
+ size={16}
+ taskIdentifier={taskId}
+ />
+ <Text weight={500}>{t(`taskDetail.${priorityMeta.labelKey}` as never)}</Text>
+ </Block>
+ </TaskPriorityTag>
+
+ {shouldShowMemberAssignee(activeWorkspaceId, assigneeUserId) && (
+ <AssigneeMemberSelector
+ currentUserId={assigneeUserId}
+ taskCreatorId={createdByUserId}
+ taskIdentifier={taskId}
+ taskVisibility={visibility}
+ >
+ <Block
+ clickable
+ horizontal
+ align="center"
+ className={styles.propertyItem}
+ gap={8}
+ variant={'borderless'}
+ >
+ {assigneeUserId ? (
+ <>
+ <AssigneeUserAvatar size={16} userId={assigneeUserId} />
+ <Text ellipsis style={{ minWidth: 0 }} weight={500}>
+ {memberMeta?.title}
+ </Text>
+ </>
+ ) : (
+ <>
+ <UnassignedAssigneeIcon kind={'human'} size={16} />
+ <Text style={{ color: cssVar.colorTextDescription }} weight={500}>
+ {t('taskDetail.assignee')}
+ </Text>
+ </>
+ )}
+ </Block>
+ </AssigneeMemberSelector>
+ )}
+
+ {/* Where the runs go lives in the detail header's main column, next to the
+ assignee it inherits from — not in this rail. See
+ `TaskExecutionConfig`. */}
+
+ <TaskScheduleConfig>
+ <Block
+ clickable
+ horizontal
+ align="center"
+ className={styles.propertyItem}
+ gap={8}
+ variant={'borderless'}
+ >
+ <TaskTriggerTag
+ automationMode={automationMode}
+ heartbeatInterval={heartbeatInterval}
+ mode="inline"
+ schedulePattern={schedulePattern}
+ scheduleTimezone={scheduleTimezone}
+ />
+ </Block>
+ </TaskScheduleConfig>
+ </section>
+
+ <section className={styles.propertyGroup}>
+ <div className={styles.propertyGroupTitle}>{t('taskLabel.label')}</div>
+ <TaskLabelPicker
+ disabled={!taskDatabaseId}
+ value={labels}
+ onChange={(next) => {
+ if (taskDatabaseId) void setTaskLabels(taskDatabaseId, labels, next);
+ }}
>
<Block
clickable
@@ -150,80 +221,51 @@ const TaskProperties = memo(() => {
align="center"
className={styles.propertyItem}
gap={8}
+ // Property rows have a fixed height; this one grows with wrapped chips
+ // so a second line never overlaps the row below.
+ style={{ flexWrap: 'wrap', height: 'auto', minHeight: 30, paddingBlock: 4 }}
variant={'borderless'}
>
- {assigneeUserId ? (
- <>
- <AssigneeUserAvatar size={16} userId={assigneeUserId} />
- <Text ellipsis style={{ minWidth: 0 }} weight={500}>
- {memberMeta?.title}
- </Text>
- </>
+ {labels.length > 0 ? (
+ <TaskLabelChips wrap labels={labels} max={6} />
) : (
<>
- <UnassignedAssigneeIcon kind={'human'} size={16} />
+ <Icon color={cssVar.colorTextDescription} icon={TagIcon} size={16} />
<Text style={{ color: cssVar.colorTextDescription }} weight={500}>
- {t('taskDetail.assignee')}
+ {t('taskLabel.add')}
</Text>
</>
)}
</Block>
- </AssigneeMemberSelector>
- )}
-
- <TaskLabelPicker
- disabled={!taskDatabaseId}
- value={labels}
- onChange={(next) => {
- if (taskDatabaseId) void setTaskLabels(taskDatabaseId, labels, next);
- }}
- >
- <Block
- clickable
- horizontal
- align="center"
- className={styles.propertyItem}
- gap={8}
- // Property rows have a fixed height; this one grows with wrapped chips
- // so a second line never overlaps the row below.
- style={{ flexWrap: 'wrap', height: 'auto', minHeight: 30, paddingBlock: 4 }}
- variant={'borderless'}
- >
- {labels.length > 0 ? (
- <TaskLabelChips wrap labels={labels} max={6} />
- ) : (
- <>
- <Icon color={cssVar.colorTextDescription} icon={TagIcon} size={16} />
- <Text style={{ color: cssVar.colorTextDescription }} weight={500}>
- {t('taskLabel.add')}
- </Text>
- </>
- )}
- </Block>
- </TaskLabelPicker>
-
- {/* Where the runs go lives in the detail header's main column, next to the
- assignee it inherits from — not in this rail. See
- `TaskExecutionConfig`. */}
-
- <TaskScheduleConfig>
- <Block
- clickable
- horizontal
- align="center"
- className={styles.propertyItem}
- gap={8}
- variant={'borderless'}
+ </TaskLabelPicker>
+ </section>
+
+ <section className={styles.propertyGroup}>
+ <div className={styles.propertyGroupTitle}>{t('taskProject.label')}</div>
+ {/* A subtask lives in its parent's project: the server refuses to split them. */}
+ <ProjectSelector
+ fullWidth
+ disabledReason={hasParent ? t('taskProject.inheritedFromParent') : undefined}
+ taskIdentifier={taskId}
+ value={projectId}
>
- <TaskTriggerTag
- automationMode={automationMode}
- heartbeatInterval={heartbeatInterval}
- mode="inline"
- schedulePattern={schedulePattern}
- scheduleTimezone={scheduleTimezone}
- />
- </Block>
- </TaskScheduleConfig>
+ <Block
+ clickable
+ horizontal
+ align="center"
+ className={styles.propertyItem}
+ gap={8}
+ variant={'borderless'}
+ >
+ <TaskProjectValue
+ emptyLabel={t('taskProject.add')}
+ iconSize={16}
+ projectId={projectId}
+ weight={500}
+ />
+ </Block>
+ </ProjectSelector>
+ </section>
</div>
);
});
diff --git a/src/features/AgentTasks/AgentTaskDetail/taskDetailLayoutStyles.ts b/src/features/AgentTasks/AgentTaskDetail/taskDetailLayoutStyles.ts
index 2b5dbc21212..3066125b5ba 100644
--- a/src/features/AgentTasks/AgentTaskDetail/taskDetailLayoutStyles.ts
+++ b/src/features/AgentTasks/AgentTaskDetail/taskDetailLayoutStyles.ts
@@ -46,10 +46,37 @@ export const taskDetailLayoutStyles = createStaticStyles(({ css }) => ({
@container task-detail (width >= ${TASK_DETAIL_SIDEBAR_MIN_WIDTH}px) {
flex-direction: column;
- gap: 2px;
+ gap: 20px;
align-items: stretch;
}
`,
+ // Properties, Labels and Project are titled groups in the sidebar, as in
+ // Linear. The pill row has no room for titles, so there each group dissolves
+ // into the row and its triggers flow as before.
+ propertyGroup: css`
+ display: contents;
+
+ @container task-detail (width >= ${TASK_DETAIL_SIDEBAR_MIN_WIDTH}px) {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ }
+ `,
+ propertyGroupTitle: css`
+ display: none;
+
+ @container task-detail (width >= ${TASK_DETAIL_SIDEBAR_MIN_WIDTH}px) {
+ display: block;
+
+ margin-block-end: 4px;
+ padding-inline: 8px;
+
+ font-size: 12px;
+ font-weight: 500;
+ line-height: 20px;
+ color: ${cssVar.colorTextDescription};
+ }
+ `,
propertyItem: css`
max-width: 100%;
height: 28px;
diff --git a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.test.ts b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.test.ts
index eb2dc2b2fef..a28b635c9b3 100644
--- a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.test.ts
+++ b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.test.ts
@@ -4,6 +4,7 @@ import type { TaskListItem } from '@/store/task/slices/list/initialState';
import {
clampCollectionPage,
+ collectionGroupsByProject,
getMyTaskViewOptions,
getScheduledTaskViewOptions,
getTaskCreateActionBehavior,
@@ -96,6 +97,29 @@ describe('AgentTasksPage', () => {
});
});
+ describe('collectionGroupsByProject', () => {
+ const project = { ...DEFAULT_TASK_LIST_VIEW_OPTIONS, groupBy: 'project' as const };
+
+ it('ignores a stored project grouping on the scheduled tab, which replaces it', () => {
+ expect(collectionGroupsByProject('scheduled', project)).toBe(false);
+ });
+
+ it('still counts a project sub-grouping on the scheduled tab, which keeps it', () => {
+ expect(
+ collectionGroupsByProject('scheduled', {
+ ...DEFAULT_TASK_LIST_VIEW_OPTIONS,
+ subGroupBy: 'project',
+ }),
+ ).toBe(true);
+ });
+
+ it('counts it on the tabs that render the stored grouping', () => {
+ expect(collectionGroupsByProject('tasks', project)).toBe(true);
+ expect(collectionGroupsByProject('mine', project)).toBe(true);
+ expect(collectionGroupsByProject('tasks', DEFAULT_TASK_LIST_VIEW_OPTIONS)).toBe(false);
+ });
+ });
+
describe('getMyTaskViewOptions', () => {
it('pins ordering to the updatedAt-desc server page, renders every fetched row, keeps the rest', () => {
expect(
diff --git a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
index 85b6f120eab..3b53bab4f10 100644
--- a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
+++ b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
@@ -30,6 +30,7 @@ import { TASK_COLLECTION_PAGE_SIZE } from '@/store/task/slices/list/action';
import { isMobileSurface } from '@/utils/mobileSurface';
import { createTaskModal } from '../CreateTaskModal';
+import { useTaskProjectList } from '../features/useTaskProjectList';
import Breadcrumb from '../shared/Breadcrumb';
import { taskDetailPath } from '../shared/taskDetailPath';
import CreateTaskInlineEntry from './CreateTaskInlineEntry';
@@ -46,6 +47,7 @@ import KanbanBoard from './KanbanBoard';
import type { TaskListViewOptions } from './listViewOptions';
import {
dropMissingLabelGroupings,
+ dropProjectGrouping,
getCompletedWithin,
getVisibleTaskStatuses,
normalizeTaskListViewOptions,
@@ -185,6 +187,20 @@ export const getScheduledTaskViewOptions = (
groupBy: 'automationMode',
});
+/**
+ * Whether a collection's project groups need the project list to be told apart.
+ * Judged on what the collection renders: the scheduled tab replaces the stored
+ * grouping, so a stored `project` must not hold it behind the project request.
+ */
+export const collectionGroupsByProject = (
+ collection: TaskCollection,
+ viewOptions: TaskListViewOptions,
+): boolean => {
+ const { groupBy, subGroupBy } =
+ collection === 'scheduled' ? getScheduledTaskViewOptions(viewOptions) : viewOptions;
+ return groupBy === 'project' || subGroupBy === 'project';
+};
+
/**
* "My tasks" additionally sends `completedTasks` as a server filter
* (`getVisibleTaskStatuses` / `getCompletedWithin`) rather than applying it to
@@ -264,16 +280,29 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, proj
.join(',')
: undefined,
);
- const viewOptions = useMemo(
- () =>
- dropMissingLabelGroupings(
- normalizeTaskListViewOptions(rawViewOptions),
- labelGroupIdsKey === undefined
- ? undefined
- : new Set(labelGroupIdsKey.split(',').filter(Boolean)),
- ),
- [rawViewOptions, labelGroupIdsKey],
- );
+ // The one read of the project list for this page; rows map ids through its cache.
+ const {
+ enabled: projectsEnabled,
+ error: projectsError,
+ projects,
+ retry: retryProjects,
+ } = useTaskProjectList();
+ const canGroupByProject = projectsEnabled && !projectId;
+ const viewOptions = useMemo(() => {
+ const options = dropMissingLabelGroupings(
+ normalizeTaskListViewOptions(rawViewOptions),
+ labelGroupIdsKey === undefined
+ ? undefined
+ : new Set(labelGroupIdsKey.split(',').filter(Boolean)),
+ );
+ return canGroupByProject ? options : dropProjectGrouping(options);
+ }, [canGroupByProject, rawViewOptions, labelGroupIdsKey]);
+ // Project groups cannot be told apart until the list that names them loads, so
+ // a list view holds its skeleton, or surfaces the failure, instead of
+ // flashing every task under "No project".
+ const needsProjectList = !projects && collectionGroupsByProject(collection, viewOptions);
+ const projectListError = needsProjectList ? projectsError : undefined;
+ const isProjectListPending = needsProjectList && !projectsError;
// Group headers of the ordinary list offer the board's column create entry.
const groupCreateScope = useMemo(
() => (canCreateTask ? { agentId, projectId } : undefined),
@@ -546,6 +575,7 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, proj
)}
{!isScheduledCollection && headerVisibility.showViewOptions && (
<TasksGroupConfig
+ canGroupByProject={canGroupByProject}
options={viewOptions}
pinnedOptions={isMineCollection ? PAGINATED_COLLECTION_PINNED_OPTIONS : undefined}
setOptions={setViewOptions}
@@ -595,9 +625,9 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, proj
>
<TaskList
data={isCollectionListInit || undefined}
- error={collectionSWR.error}
+ error={collectionSWR.error ?? projectListError}
filter={filter}
- isLoading={collectionSWR.isLoading || (!isCollectionListInit && !collectionSWR.error)}
+ hideProject={!!projectId}
items={collectionTasks}
options={isMineCollection ? myTaskViewOptions : scheduledViewOptions}
routeScope={routeScope}
@@ -619,6 +649,11 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, proj
)
: t('taskList.scheduled.empty'))
}
+ isLoading={
+ collectionSWR.isLoading ||
+ isProjectListPending ||
+ (!isCollectionListInit && !collectionSWR.error)
+ }
selectionScope={[
collection,
isMineCollection ? myTaskScope : '',
@@ -626,7 +661,7 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, proj
agentId ?? '',
projectId ?? '',
].join(':')}
- onRetry={() => collectionSWR.mutate()}
+ onRetry={() => (projectListError ? retryProjects() : collectionSWR.mutate())}
/>
{(collectionTasksTotal > COLLECTION_PAGE_SIZE || collectionPage > 1) && (
<Flexbox horizontal justify={'center'} paddingBlock={8}>
@@ -673,13 +708,14 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, proj
data={isTaskListInit || undefined}
emptyAction={filterEmptyAction}
emptyDescription={filterEmptyDescription}
- error={error}
+ error={error ?? projectListError}
filter={filter}
- isLoading={isLoading || (!isTaskListInit && !error)}
+ hideProject={!!projectId}
+ isLoading={isLoading || isProjectListPending || (!isTaskListInit && !error)}
options={viewOptions}
queryKey={queryKey}
routeScope={routeScope}
- onRetry={() => mutate()}
+ onRetry={() => (projectListError ? retryProjects() : mutate())}
onShowHiddenCompleted={handleShowHiddenCompleted}
/>
</WideScreenContainer>
diff --git a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.project.test.tsx b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.project.test.tsx
new file mode 100644
index 00000000000..e01921975c7
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.project.test.tsx
@@ -0,0 +1,207 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import CreateTaskInlineEntry from './CreateTaskInlineEntry';
+
+const state = vi.hoisted(() => ({
+ createTask: vi.fn(async () => ({ id: 't1', identifier: 'T-1' })),
+ markdown: 'Ship it',
+ projects: [{ id: 'p1', name: 'Apollo' }] as { id: string; name: string }[],
+}));
+
+vi.mock('@lobehub/editor/react', () => ({
+ useEditor: () => EDITOR,
+}));
+const EDITOR = vi.hoisted(() => ({
+ cleanDocument: () => {},
+ getDocument: (type: string) => (type === 'markdown' ? state.markdown : {}),
+ setDocument: () => {},
+}));
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ DropdownMenu: ({ items }: { items: { key: string; label: string; onClick: () => void }[] }) => (
+ <>
+ {items.map((item) => (
+ <button key={item.key} onClick={item.onClick}>
+ {item.label}
+ </button>
+ ))}
+ </>
+ ),
+ toast: { error: vi.fn(), success: vi.fn() },
+}));
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ useActiveWorkspaceId: () => undefined,
+}));
+vi.mock('@/components/GeneratingBorder', () => ({
+ default: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+vi.mock('@/features/AgentGoals/CreateGoalModal', () => ({ createGoalModal: vi.fn() }));
+vi.mock('@/features/EditorCanvas', () => ({ EditorCanvas: () => null }));
+vi.mock('@/features/EditorCanvas/editorAttachments', () => ({
+ getAttachmentFileIdsFromEditor: () => [],
+ pickAndInsertAttachments: vi.fn(),
+}));
+vi.mock('@/features/TaskLabels/TaskLabelChips', () => ({ default: () => null }));
+vi.mock('@/features/TaskLabels/TaskLabelPicker', () => ({ default: () => null }));
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => vi.fn(),
+}));
+vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: true }) }));
+vi.mock('@/services/task', () => ({ taskService: {} }));
+vi.mock('@/store/global', () => ({
+ useGlobalStore: (selector: (s: unknown) => unknown) => selector({}),
+}));
+vi.mock('@/store/project', () => ({
+ useLoadedProjectList: () => state.projects,
+ useProjectStore: (selector: (s: unknown) => unknown) =>
+ selector({ useFetchProjectList: () => ({ isValidating: false }) }),
+}));
+vi.mock('@/store/task', () => ({
+ getTaskStoreState: () => ({ taskLabels: [], taskLabelsInit: true }),
+ useTaskStore: (selector: (s: unknown) => unknown) => selector({ createTask: state.createTask }),
+}));
+vi.mock('@/store/task/selectors', () => ({
+ taskLabelSelectors: { isLabelsInit: () => true, labels: () => [] },
+}));
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: (s: unknown) => unknown) => selector({}),
+}));
+vi.mock('@/store/user/selectors', () => ({
+ labPreferSelectors: { enableGoals: () => false, enableProjects: () => true },
+ userProfileSelectors: { userId: () => 'u1' },
+}));
+vi.mock('@/styles', () => ({ shinyTextStyles: {} }));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+vi.mock('../features/AssigneeAgentSelector', () => ({ default: () => null }));
+vi.mock('../features/AssigneeAvatar', () => ({ default: () => null }));
+vi.mock('../features/AssigneeMemberSelector', () => ({ default: () => null }));
+vi.mock('../features/AssigneeUserAvatar', () => ({ default: () => null }));
+vi.mock('../features/TaskExecutionControls', () => ({ default: () => null }));
+vi.mock('../features/TaskPriorityTag', () => ({ default: () => null }));
+vi.mock('../features/TaskVisibilityChipLabel', () => ({ default: () => null }));
+vi.mock('../features/TaskVisibilityTag', () => ({ default: () => null }));
+vi.mock('../features/UnassignedAssigneeIcon', () => ({ UnassignedAssigneeIcon: () => null }));
+vi.mock('../features/TaskProjectPickerChip', () => ({
+ default: ({
+ onChange,
+ value,
+ }: {
+ onChange: (id: string | null) => void;
+ value: string | null;
+ }) => (
+ <div>
+ <span data-testid="chip">{value ?? 'empty'}</span>
+ <button onClick={() => onChange('p1')}>pick</button>
+ <button onClick={() => onChange(null)}>clear</button>
+ </div>
+ ),
+}));
+vi.mock('../shared/memberAssigneeMode', () => ({ resolveMemberAssignee: () => undefined }));
+vi.mock('../shared/taskDetailPath', () => ({ taskDetailPath: () => '/' }));
+vi.mock('../shared/useAgentDisplayMeta', () => ({ useAgentDisplayMeta: () => undefined }));
+vi.mock('../shared/useAgentVisibility', () => ({ useAgentVisibility: () => undefined }));
+vi.mock('../shared/useDefaultMemberAssignee', () => ({
+ useDefaultMemberAssignee: () => ({
+ assignableMemberIds: new Set(),
+ isDefaultMemberPending: false,
+ isMembersLoading: false,
+ }),
+}));
+vi.mock('../shared/useUserDisplayMeta', () => ({ useUserDisplayMeta: () => undefined }));
+vi.mock('./TaskIntentReview', () => ({ default: () => null }));
+
+const ALL_KEY = 'lobehub:task-create-draft:personal:all';
+const PROJECT_KEY = 'lobehub:task-create-draft:personal:p1';
+
+const createDirectly = async () => {
+ state.createTask.mockClear();
+ fireEvent.click(screen.getByText('taskIntent.createDirectly'));
+ await waitFor(() => expect(state.createTask).toHaveBeenCalledTimes(1));
+ return (state.createTask.mock.calls as unknown as [[{ projectId?: string }]])[0][0];
+};
+
+const savedDraft = (key: string) => JSON.parse(localStorage.getItem(key) ?? '{}');
+
+beforeEach(() => {
+ localStorage.clear();
+ state.markdown = 'Ship it';
+ state.projects = [{ id: 'p1', name: 'Apollo' }];
+});
+
+describe('CreateTaskInlineEntry project', () => {
+ it('creates without a project when none is picked', async () => {
+ render(<CreateTaskInlineEntry />);
+ expect(screen.getByTestId('chip')).toHaveTextContent('empty');
+ expect((await createDirectly()).projectId).toBeUndefined();
+ });
+
+ it('creates in the picked project and goes back to empty', async () => {
+ render(<CreateTaskInlineEntry />);
+ fireEvent.click(screen.getByText('pick'));
+ expect((await createDirectly()).projectId).toBe('p1');
+ await waitFor(() => expect(screen.getByTestId('chip')).toHaveTextContent('empty'));
+ });
+
+ it('prefills the page project, returns to it after creating, and lets it be cleared', async () => {
+ render(<CreateTaskInlineEntry projectId="p1" />);
+ expect(screen.getByTestId('chip')).toHaveTextContent('p1');
+
+ fireEvent.click(screen.getByText('clear'));
+ expect((await createDirectly()).projectId).toBeUndefined();
+ await waitFor(() => expect(screen.getByTestId('chip')).toHaveTextContent('p1'));
+ });
+
+ it('saves the pick in the draft and restores it after a reload', async () => {
+ const first = render(<CreateTaskInlineEntry />);
+ fireEvent.click(screen.getByText('pick'));
+ await waitFor(() => expect(savedDraft(ALL_KEY).projectId).toBe('p1'));
+ first.unmount();
+
+ render(<CreateTaskInlineEntry />);
+ expect(screen.getByTestId('chip')).toHaveTextContent('p1');
+ });
+
+ it('restores an explicit "no project" over the page default', async () => {
+ const first = render(<CreateTaskInlineEntry projectId="p1" />);
+ fireEvent.click(screen.getByText('clear'));
+ await waitFor(() => expect(savedDraft(PROJECT_KEY).projectId).toBeNull());
+ first.unmount();
+
+ render(<CreateTaskInlineEntry projectId="p1" />);
+ expect(screen.getByTestId('chip')).toHaveTextContent('empty');
+ });
+
+ it('keeps the default for a draft saved before projects could be picked', async () => {
+ localStorage.setItem(PROJECT_KEY, JSON.stringify({ markdown: 'old', priority: 0 }));
+ render(<CreateTaskInlineEntry projectId="p1" />);
+ await act(async () => {});
+ expect(screen.getByTestId('chip')).toHaveTextContent('p1');
+ });
+
+ it('ignores a malformed project in the draft', async () => {
+ localStorage.setItem(ALL_KEY, JSON.stringify({ markdown: 'old', projectId: 42 }));
+ render(<CreateTaskInlineEntry />);
+ await act(async () => {});
+ expect(screen.getByTestId('chip')).toHaveTextContent('empty');
+ });
+
+ it('drops a draft project that no longer exists', async () => {
+ localStorage.setItem(ALL_KEY, JSON.stringify({ markdown: 'old', projectId: 'gone' }));
+ render(<CreateTaskInlineEntry />);
+ await waitFor(() => expect(screen.getByTestId('chip')).toHaveTextContent('empty'));
+ expect((await createDirectly()).projectId).toBeUndefined();
+ });
+
+ it('has no picker on the subtask composer and leaves the project to the server', async () => {
+ render(<CreateTaskInlineEntry parentTaskId="t-parent" />);
+ expect(screen.queryByTestId('chip')).not.toBeInTheDocument();
+ expect((await createDirectly()).projectId).toBeUndefined();
+ });
+});
diff --git a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx
index aba87d3107e..0a907dc60b1 100644
--- a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx
+++ b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx
@@ -46,9 +46,11 @@ import AssigneeMemberSelector from '../features/AssigneeMemberSelector';
import AssigneeUserAvatar from '../features/AssigneeUserAvatar';
import TaskExecutionControls from '../features/TaskExecutionControls';
import TaskPriorityTag from '../features/TaskPriorityTag';
+import TaskProjectPickerChip from '../features/TaskProjectPickerChip';
import TaskVisibilityChipLabel from '../features/TaskVisibilityChipLabel';
import TaskVisibilityTag from '../features/TaskVisibilityTag';
import { UnassignedAssigneeIcon } from '../features/UnassignedAssigneeIcon';
+import { useTaskProjectChoice } from '../features/useTaskProjectChoice';
import { resolveMemberAssignee } from '../shared/memberAssigneeMode';
import { taskDetailPath } from '../shared/taskDetailPath';
import { useAgentDisplayMeta } from '../shared/useAgentDisplayMeta';
@@ -88,6 +90,7 @@ interface CreateTaskInlineEntryProps {
onCreated?: (task: { id: string; agentId?: string; identifier: string }) => void;
parentTaskId?: string;
placeholder?: string;
+ /** The project the task starts in, e.g. the page it is composed on. The user can change it. */
projectId?: string;
/**
* `hero` adapts the entry for the empty-tasks landing: hides collapse,
@@ -128,6 +131,11 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
// Label ids read from a draft before the registry loaded; resolved (and
// stale ones dropped) once it has.
const pendingDraftLabelIdsRef = useRef<string[] | undefined>(undefined);
+ // A subtask has no picker: the server files it under its parent's project.
+ const { createProjectId, projectChoice, setProjectChoice } = useTaskProjectChoice(
+ projectId,
+ !parentTaskId,
+ );
const [assigneeAgentId, setAssigneeAgentId] = useState<string | undefined>(agentId);
// `undefined` follows the default (the creator); `null` is an explicit "unassigned".
const [memberChoice, setMemberChoice] = useState<string | null | undefined>();
@@ -266,6 +274,7 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
// foreign id here and fail the create.
setLabels([]);
pendingDraftLabelIdsRef.current = undefined;
+ setProjectChoice(projectId ?? null);
setVisibility(defaultVisibility);
setExecution(undefined);
if (!lockAssignee) setAssigneeAgentId(agentId);
@@ -291,6 +300,9 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
setMemberChoice(draft.assigneeUserId);
}
if (draft.visibility) setVisibility(draft.visibility);
+ // `null` restores an explicit "no project"; a missing key keeps the scope's default.
+ if (draft.projectId === null || typeof draft.projectId === 'string')
+ setProjectChoice(draft.projectId);
const labelIds = Array.isArray(draft.labelIds)
? draft.labelIds.filter((id): id is string => typeof id === 'string')
: [];
@@ -314,6 +326,8 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
editor,
isMembersLoading,
lockAssignee,
+ projectId,
+ setProjectChoice,
]);
useEffect(() => {
@@ -349,6 +363,7 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
labels.length > 0 ? labels.map((label) => label.id) : pendingDraftLabelIdsRef.current,
markdown,
priority,
+ projectId: projectChoice,
visibility,
},
draftHasTextRef.current,
@@ -364,6 +379,7 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
lockAssignee,
memberChoice,
priority,
+ projectChoice,
visibility,
]);
@@ -394,6 +410,7 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
setLabels([]);
// A restore still waiting for the registry belongs to the draft just sent.
pendingDraftLabelIdsRef.current = undefined;
+ setProjectChoice(projectId ?? null);
setAssigneeAgentId(agentId);
setMemberChoice(undefined);
setInstruction('');
@@ -403,7 +420,7 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
setIntentAnswers({});
editor?.cleanDocument?.();
if (draftStorageKey) clearTaskCreateDraft(draftStorageKey);
- }, [agentId, defaultVisibility, draftStorageKey, editor]);
+ }, [agentId, defaultVisibility, draftStorageKey, editor, projectId, setProjectChoice]);
/** What the composer currently holds, or null when there is nothing to create. */
const readDraft = useCallback(() => {
@@ -466,7 +483,7 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
name: draft.name,
parentTaskId,
priority: priority || undefined,
- projectId,
+ projectId: createProjectId,
// 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,
@@ -533,6 +550,7 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
draftStorageKey,
assigneeAgentId,
assigneeUserId,
+ createProjectId,
createTask,
execution,
labels,
@@ -540,7 +558,6 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
onCreated,
parentTaskId,
priority,
- projectId,
resetComposer,
visibility,
],
@@ -687,15 +704,15 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
initialRequirement: seed.requirement,
initialTitle: intentTitle.trim() || seed.title,
onCreated: resetComposer,
- projectId,
+ projectId: createProjectId,
});
setAnalysis(null);
}, [
analysis,
assigneeAgentId,
+ createProjectId,
intentAnswers,
intentTitle,
- projectId,
readDraft,
resetComposer,
t,
@@ -832,6 +849,10 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
</Block>
</TaskLabelPicker>
+ {!parentTaskId && (
+ <TaskProjectPickerChip value={projectChoice} onChange={setProjectChoice} />
+ )}
+
{activeWorkspaceId && (
<AssigneeMemberSelector
currentUserId={assigneeUserId}
diff --git a/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx b/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx
index 3bcf2fbfa53..33e829b554c 100644
--- a/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx
+++ b/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx
@@ -29,6 +29,7 @@ import { saveToast } from '@/store/utils/saveToast';
import type { TaskItemRouteScope } from '../features/AgentTaskItem';
import AgentTaskItem from '../features/AgentTaskItem';
+import { useTaskProjectList } from '../features/useTaskProjectList';
import { useTaskStatusChange } from '../features/useTaskStatusChange';
import HiddenColumnsPanel from './HiddenColumnsPanel';
import {
@@ -40,6 +41,7 @@ import {
getKanbanColumnCreateDefaults,
getKanbanLabelPatch,
getKanbanTaskPatch,
+ mergeUnresolvedProjectGroups,
moveTaskBetweenKanbanGroups,
normalizeKanbanGroupBy,
} from './kanbanBoardModel';
@@ -83,6 +85,8 @@ interface KanbanBoardProps {
const KanbanBoard = memo<KanbanBoardProps>((props) => {
const { agentId, emptyDescription, filter, myTaskScope, options, projectId, routeScope } = props;
+ // A project's own board does not repeat its badge on every card.
+ const hideProject = !!projectId;
const { t } = useTranslation('chat');
const { allowed: canEditTask } = usePermission('create_content');
const groupBy = normalizeKanbanGroupBy(options.groupBy);
@@ -93,6 +97,10 @@ const KanbanBoard = memo<KanbanBoardProps>((props) => {
const { error: labelsError, mutate: retryLabels } = useFetchTaskLabels();
const isLabelsInit = useTaskStore(taskLabelSelectors.isLabelsInit);
+ // Project columns are named from the project list, like label columns above.
+ const { error: projectsError, projects, retry: retryProjects } = useTaskProjectList();
+ const isProjectBoard = groupBy === 'project';
+
const useFetchTaskGroupList = useTaskStore((s) => s.useFetchTaskGroupList);
// Keep the sync handle for `error` + `mutate` (the error/Retry state) and the
// `queryKey` the groups are read by.
@@ -102,14 +110,20 @@ const KanbanBoard = memo<KanbanBoardProps>((props) => {
// A persisted label grouping may point at a deleted group; the page only
// drops it once the registry is known, so wait for that (or its failure)
// instead of sending one doomed request after every reload.
- enabled: !isTaskLabelGroupBy(groupBy) || isLabelsInit,
+ // A project board likewise waits for the list that names its columns.
+ enabled:
+ (!isTaskLabelGroupBy(groupBy) || isLabelsInit) && (!isProjectBoard || projects !== undefined),
filter,
includeArchived: options.showArchived,
});
// Each board query (scope, dimension, filters) is its own store entry, so the
// settled signal and the groups always describe the same board.
const isTaskGroupListInit = useTaskStore(taskListSelectors.isTaskGroupListInit(queryKey));
- const storedTaskGroups = useTaskStore(taskListSelectors.taskGroups(queryKey));
+ const rawTaskGroups = useTaskStore(taskListSelectors.taskGroups(queryKey));
+ const storedTaskGroups = useMemo(
+ () => (isProjectBoard ? mergeUnresolvedProjectGroups(rawTaskGroups, projects) : rawTaskGroups),
+ [isProjectBoard, projects, rawTaskGroups],
+ );
// Cards edited out of the filter leave their column before the refetch lands.
const currentTaskGroups = useMemo(() => {
if (!filter) return storedTaskGroups;
@@ -139,8 +153,8 @@ const KanbanBoard = memo<KanbanBoardProps>((props) => {
const taskLabels = useTaskStore(taskLabelSelectors.labels);
const columns = useMemo(
() => buildKanbanColumns(currentTaskGroups, groupBy),
- // eslint-disable-next-line react-hooks/exhaustive-deps -- registry changes rename label columns
- [currentTaskGroups, groupBy, taskLabels],
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- registry changes rename label and project columns
+ [currentTaskGroups, groupBy, projects, taskLabels],
);
const sensors = useSensors(
@@ -217,6 +231,15 @@ const KanbanBoard = memo<KanbanBoardProps>((props) => {
if (groupBy === 'status' && task.status === patch.status) return;
if ((groupBy === 'assignee' || groupBy === 'member') && !assigneeUpdate) return;
if (groupBy === 'priority' && (task.priority ?? 0) === (patch.priority ?? 0)) return;
+ // By column, not id: a task of an unseen project already sits in
+ // "Unavailable project", and letting it go back must not clear its project.
+ if (
+ isProjectBoard &&
+ currentTaskGroups
+ .find((group) => group.key === targetColumnKey)
+ ?.tasks.some((item) => item.id === task.id)
+ )
+ return;
if (!queryKey) return;
// The move is idempotent, so the overlay stays correct when the status
@@ -243,6 +266,8 @@ const KanbanBoard = memo<KanbanBoardProps>((props) => {
await updateTask(task.identifier, assigneeUpdate);
} else if (groupBy === 'priority') {
await updateTask(task.identifier, { priority: patch.priority ?? 0 });
+ } else if (isProjectBoard) {
+ await updateTask(task.identifier, { projectId: patch.projectId ?? null });
} else if (labelPatch) {
// The store action toasts its own failure and reports it here.
const saved = await setTaskLabels(task.id, task.labels ?? [], labelPatch.labels);
@@ -262,7 +287,9 @@ const KanbanBoard = memo<KanbanBoardProps>((props) => {
canEditTask,
changeTaskStatus,
columns,
+ currentTaskGroups,
groupBy,
+ isProjectBoard,
queryKey,
refreshTaskList,
setTaskLabels,
@@ -383,6 +410,7 @@ const KanbanBoard = memo<KanbanBoardProps>((props) => {
droppable={droppable}
groupBy={groupBy}
groupMeta={col.groupMeta}
+ hideProject={hideProject}
key={col.key}
projectId={projectId}
routeScope={routeScope}
@@ -413,7 +441,12 @@ const KanbanBoard = memo<KanbanBoardProps>((props) => {
width: COLUMN_WIDTH - 8,
}}
>
- <AgentTaskItem routeScope={routeScope} task={activeTask} variant="compact" />
+ <AgentTaskItem
+ hideProject={hideProject}
+ routeScope={routeScope}
+ task={activeTask}
+ variant="compact"
+ />
</div>
) : null}
</DragOverlay>
@@ -426,7 +459,8 @@ const KanbanBoard = memo<KanbanBoardProps>((props) => {
// A label board needs the registry for its columns (names, colors, order);
// if that failed, show it here with its own Retry rather than raw label ids.
const registryError = isTaskLabelGroupBy(groupBy) && !isLabelsInit ? labelsError : undefined;
- const boardError = registryError ?? error;
+ const projectListError = isProjectBoard && !projects ? projectsError : undefined;
+ const boardError = registryError ?? projectListError ?? error;
return (
<AsyncBoundary
data={isTaskGroupListInit || undefined}
@@ -436,7 +470,9 @@ const KanbanBoard = memo<KanbanBoardProps>((props) => {
isEmpty={totalTasks === 0}
isLoading={isLoading || (!isTaskGroupListInit && !boardError)}
loading={skeletonBoard}
- onRetry={() => (registryError ? retryLabels() : mutate())}
+ onRetry={() =>
+ registryError ? retryLabels() : projectListError ? retryProjects() : mutate()
+ }
>
{board}
</AsyncBoundary>
diff --git a/src/features/AgentTasks/AgentTaskList/KanbanColumn.tsx b/src/features/AgentTasks/AgentTaskList/KanbanColumn.tsx
index 348c6d136f2..1a265532968 100644
--- a/src/features/AgentTasks/AgentTaskList/KanbanColumn.tsx
+++ b/src/features/AgentTasks/AgentTaskList/KanbanColumn.tsx
@@ -35,9 +35,7 @@ const cardStyles = createStaticStyles(({ css, cssVar }) => ({
card: css`
border-radius: ${cssVar.borderRadiusLG};
background: ${cssVar.colorBgElevated};
- box-shadow:
- 0 1px 2px rgb(0 0 0 / 4%),
- 0 2px 6px rgb(0 0 0 / 3%);
+ box-shadow: ${cssVar.boxShadowTertiary};
&,
& * {
@@ -58,25 +56,32 @@ const cardStyles = createStaticStyles(({ css, cssVar }) => ({
`,
}));
-const DraggableTaskCard = memo<{ routeScope?: TaskItemRouteScope; task: TaskListItem }>(
- ({ routeScope, task }) => {
- const { attributes, isDragging, listeners, setNodeRef } = useDraggable({
- data: { task },
- id: task.identifier,
- });
-
- return (
- <div
- className={cx(cardStyles.card, isDragging && cardStyles.dragging)}
- ref={setNodeRef}
- {...listeners}
- {...attributes}
- >
- <AgentTaskItem routeScope={routeScope} task={task} variant="compact" />
- </div>
- );
- },
-);
+const DraggableTaskCard = memo<{
+ hideProject?: boolean;
+ routeScope?: TaskItemRouteScope;
+ task: TaskListItem;
+}>(({ hideProject, routeScope, task }) => {
+ const { attributes, isDragging, listeners, setNodeRef } = useDraggable({
+ data: { task },
+ id: task.identifier,
+ });
+
+ return (
+ <div
+ className={cx(cardStyles.card, isDragging && cardStyles.dragging)}
+ ref={setNodeRef}
+ {...listeners}
+ {...attributes}
+ >
+ <AgentTaskItem
+ hideProject={hideProject}
+ routeScope={routeScope}
+ task={task}
+ variant="compact"
+ />
+ </div>
+ );
+});
const styles = createStaticStyles(({ css, cssVar }) => ({
// The empty-column add pill stays hidden until the column is hovered, or
@@ -200,6 +205,8 @@ interface KanbanColumnProps {
droppable: boolean;
groupBy: TaskKanbanGroupBy;
groupMeta?: TaskGroupMeta;
+ /** The board already belongs to one project, so its cards do not repeat it. */
+ hideProject?: boolean;
loading?: boolean;
onHide?: () => void;
projectId?: string;
@@ -216,6 +223,7 @@ const KanbanColumn = memo<KanbanColumnProps>(
droppable,
groupBy,
groupMeta,
+ hideProject,
loading,
onHide,
projectId,
@@ -328,7 +336,12 @@ const KanbanColumn = memo<KanbanColumnProps>(
))
) : tasks.length > 0 ? (
tasks.map((task) => (
- <DraggableTaskCard key={task.identifier} routeScope={routeScope} task={task} />
+ <DraggableTaskCard
+ hideProject={hideProject}
+ key={task.identifier}
+ routeScope={routeScope}
+ task={task}
+ />
))
) : canCreate ? (
<div
diff --git a/src/features/AgentTasks/AgentTaskList/TaskGroupLabel.tsx b/src/features/AgentTasks/AgentTaskList/TaskGroupLabel.tsx
index 4bd7e25d164..5974b45765f 100644
--- a/src/features/AgentTasks/AgentTaskList/TaskGroupLabel.tsx
+++ b/src/features/AgentTasks/AgentTaskList/TaskGroupLabel.tsx
@@ -1,5 +1,5 @@
import { cssVar, Flexbox, Icon, Text } from '@lobehub/ui';
-import { CalendarClock, HeartPulse, TagIcon, UserRound } from 'lucide-react';
+import { CalendarClock, FolderXIcon, HeartPulse, TagIcon, UserRound } from 'lucide-react';
import { memo } from 'react';
import TaskLabelDot from '@/features/TaskLabels/TaskLabelDot';
@@ -11,6 +11,7 @@ import PriorityLowIcon from '../features/icons/PriorityLowIcon';
import PriorityMediumIcon from '../features/icons/PriorityMediumIcon';
import PriorityNoneIcon from '../features/icons/PriorityNoneIcon';
import PriorityUrgentIcon from '../features/icons/PriorityUrgentIcon';
+import TaskProjectChip from '../features/TaskProjectChip';
import TaskStatusIcon from '../features/TaskStatusIcon';
import { useAgentDisplayMeta } from '../shared/useAgentDisplayMeta';
import { useUserDisplayMeta } from '../shared/useUserDisplayMeta';
@@ -51,6 +52,12 @@ const TaskGroupPrefix = ({ group }: { group: TaskGroupMeta }) => {
return <Icon icon={UserRound} size={14} />;
}
+ // A named project's header is its badge alone — see `TaskGroupLabel`.
+ if (group.groupBy === 'project') {
+ if (group.projectId) return null;
+ return <Icon color={cssVar.colorTextDescription} icon={FolderXIcon} size={14} />;
+ }
+
if (group.groupBy === 'priority') {
const priority = group.priority ?? 0;
const PriorityIcon =
@@ -87,15 +94,19 @@ interface TaskGroupLabelProps {
const TaskGroupLabel = memo<TaskGroupLabelProps>(({ group }) => (
<Flexbox horizontal align={'center'} flex={'none'} gap={6} style={{ overflow: 'hidden' }}>
<TaskGroupPrefix group={group} />
- <Text ellipsis weight={500}>
- {group.groupBy === 'assignee' && group.assigneeId ? (
- <AssigneeLabel agentId={group.assigneeId} />
- ) : group.groupBy === 'member' && group.assigneeUserId ? (
- <AssigneeUserLabel userId={group.assigneeUserId} />
- ) : (
- group.label
- )}
- </Text>
+ {group.groupBy === 'project' && group.projectId ? (
+ <TaskProjectChip projectId={group.projectId} />
+ ) : (
+ <Text ellipsis weight={500}>
+ {group.groupBy === 'assignee' && group.assigneeId ? (
+ <AssigneeLabel agentId={group.assigneeId} />
+ ) : group.groupBy === 'member' && group.assigneeUserId ? (
+ <AssigneeUserLabel userId={group.assigneeUserId} />
+ ) : (
+ group.label
+ )}
+ </Text>
+ )}
</Flexbox>
));
diff --git a/src/features/AgentTasks/AgentTaskList/TaskList.tsx b/src/features/AgentTasks/AgentTaskList/TaskList.tsx
index e53c5cb108b..d8661b7cdd1 100644
--- a/src/features/AgentTasks/AgentTaskList/TaskList.tsx
+++ b/src/features/AgentTasks/AgentTaskList/TaskList.tsx
@@ -22,6 +22,7 @@ import type { Components } from 'react-virtuoso';
import { Virtuoso } from 'react-virtuoso';
import AsyncBoundary from '@/components/AsyncBoundary';
+import { useLoadedProjectList } from '@/store/project';
import { useTaskStore } from '@/store/task';
import { taskListSelectors } from '@/store/task/selectors';
import { COMPLETE_TASK_LIST_MAX_ITEMS } from '@/store/task/slices/list/action';
@@ -86,6 +87,8 @@ interface TaskListProps {
* edited out of it (priority changed, assignee swapped) leaves at once.
*/
filter?: TaskListFilter;
+ /** The list already belongs to one project, so its rows do not repeat it. */
+ hideProject?: boolean;
/** First-load / retry in flight (SWR `isLoading`). */
isLoading?: boolean;
/** Optional list source for alternate task collections such as scheduled tasks. */
@@ -222,6 +225,7 @@ const TaskList = memo<TaskListProps>((props) => {
data,
error,
filter,
+ hideProject,
isLoading,
items,
onRetry,
@@ -267,6 +271,8 @@ const TaskList = memo<TaskListProps>((props) => {
// resolve into a context row.
const taskById = useMemo(() => new Map(tasks.map((task) => [task.id, task])), [tasks]);
const nested = options.showSubTasks && options.nestedSubTasks;
+ // Project groups read their names from this list (`getTaskProjectGroupMeta`).
+ const projects = useLoadedProjectList();
const groupedTaskEntries = useMemo((): TaskListGroupEntry[] => {
const compare = (a: (typeof visibleTasks)[number], b: (typeof visibleTasks)[number]) =>
compareTaskItems(a, b, options);
@@ -298,7 +304,8 @@ const TaskList = memo<TaskListProps>((props) => {
),
};
});
- }, [effectiveSubGroupBy, groupBy, nested, options, taskById, visibleTasks]);
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- a project list change renames or folds project groups
+ }, [effectiveSubGroupBy, groupBy, nested, options, projects, taskById, visibleTasks]);
// Collapse state lives here (not in the Accordion) because headers and rows
// are flattened into one virtual list; a collapsed key simply drops its rows
@@ -408,7 +415,11 @@ const TaskList = memo<TaskListProps>((props) => {
<div style={{ paddingBlock: 1, paddingInline: 2 }}>
<TaskRowIndent depth={item.row.depth} muted={item.row.isParentContext}>
{item.row.isParentContext ? (
- <AgentTaskItem routeScope={routeScope} task={item.row.task} />
+ <AgentTaskItem
+ hideProject={hideProject}
+ routeScope={routeScope}
+ task={item.row.task}
+ />
) : (
<SelectableTaskRow
id={item.row.task.id}
@@ -419,6 +430,7 @@ const TaskList = memo<TaskListProps>((props) => {
>
<AgentTaskItem
className={selectableTaskItemClassName}
+ hideProject={hideProject}
routeScope={routeScope}
task={item.row.task}
/>
@@ -429,7 +441,7 @@ const TaskList = memo<TaskListProps>((props) => {
</div>
);
},
- [createScope, getSelectionOrder, routeScope, toggleCollapsed],
+ [createScope, getSelectionOrder, hideProject, routeScope, toggleCollapsed],
);
const skeleton = (
diff --git a/src/features/AgentTasks/AgentTaskList/TasksGroupConfig.tsx b/src/features/AgentTasks/AgentTaskList/TasksGroupConfig.tsx
index 7dc7e0c6cf7..2ea80b29300 100644
--- a/src/features/AgentTasks/AgentTaskList/TasksGroupConfig.tsx
+++ b/src/features/AgentTasks/AgentTaskList/TasksGroupConfig.tsx
@@ -39,6 +39,8 @@ import { TASK_COMPLETED_FILTERS, toTaskLabelGroupBy } from './listViewOptions';
export type TaskListPinnedOption = 'ordering' | 'showSubTasks';
interface TasksHeaderProps {
+ /** Off on a project's own page, where every task shares the one project. */
+ canGroupByProject?: boolean;
options: TaskListViewOptions;
/**
* Controls the active collection overrides (see
@@ -61,258 +63,266 @@ const styles = createStaticStyles(({ css, cssVar }) => {
};
});
-const TasksGroupConfig = memo<TasksHeaderProps>(({ options, pinnedOptions, setOptions }) => {
- const [isViewConfigOpen, setIsViewConfigOpen] = useState(false);
- const isPinned = (option: TaskListPinnedOption) => !!pinnedOptions?.includes(option);
- const { t } = useTranslation('chat');
- const viewMode = useGlobalStore(systemStatusSelectors.taskListViewMode);
- const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
- const form = useForm();
- useFetchTaskLabels();
- const labelGroups = useTaskStore(taskLabelSelectors.labelGroups);
- const groupingOptions = useMemo<Array<{ label: string; value: TaskGroupBy }>>(
- () => [
- { label: t('taskList.groupBy.none'), value: 'none' },
- { label: t('taskList.groupBy.status'), value: 'status' },
- { label: t('taskList.groupBy.assignee'), value: 'assignee' },
- { label: t('taskList.groupBy.member'), value: 'member' },
- { label: t('taskList.groupBy.priority'), value: 'priority' },
- // One entry per label group: a task carries at most one label per
- // group, so each lands in exactly one group / column.
- ...labelGroups.map((group) => ({
- label: t('taskList.groupBy.labelGroup', { name: group.name }),
- value: toTaskLabelGroupBy(group.id),
- })),
- ],
- [labelGroups, t],
- );
- const boardGroupingOptions = useMemo(
- () => groupingOptions.filter((item) => item.value !== 'none'),
- [groupingOptions],
- );
- const orderOptions = useMemo<Array<{ label: string; value: TaskOrderBy }>>(
- () => [
- { label: t('taskList.orderBy.status'), value: 'status' },
- { label: t('taskList.orderBy.priority'), value: 'priority' },
- { label: t('taskList.orderBy.updatedAt'), value: 'updatedAt' },
- { label: t('taskList.orderBy.createdAt'), value: 'createdAt' },
- { label: t('taskList.orderBy.assignee'), value: 'assignee' },
- { label: t('taskList.orderBy.title'), value: 'title' },
- ],
- [t],
- );
+const TasksGroupConfig = memo<TasksHeaderProps>(
+ ({ canGroupByProject, options, pinnedOptions, setOptions }) => {
+ const [isViewConfigOpen, setIsViewConfigOpen] = useState(false);
+ const isPinned = (option: TaskListPinnedOption) => !!pinnedOptions?.includes(option);
+ const { t } = useTranslation('chat');
+ const viewMode = useGlobalStore(systemStatusSelectors.taskListViewMode);
+ const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
+ const form = useForm();
+ useFetchTaskLabels();
+ const labelGroups = useTaskStore(taskLabelSelectors.labelGroups);
+ const groupingOptions = useMemo<Array<{ label: string; value: TaskGroupBy }>>(
+ () => [
+ { label: t('taskList.groupBy.none'), value: 'none' },
+ { label: t('taskList.groupBy.status'), value: 'status' },
+ { label: t('taskList.groupBy.assignee'), value: 'assignee' },
+ { label: t('taskList.groupBy.member'), value: 'member' },
+ { label: t('taskList.groupBy.priority'), value: 'priority' },
+ ...(canGroupByProject
+ ? [{ label: t('taskList.groupBy.project'), value: 'project' as const }]
+ : []),
+ // One entry per label group: a task carries at most one label per
+ // group, so each lands in exactly one group / column.
+ ...labelGroups.map((group) => ({
+ label: t('taskList.groupBy.labelGroup', { name: group.name }),
+ value: toTaskLabelGroupBy(group.id),
+ })),
+ ],
+ [canGroupByProject, labelGroups, t],
+ );
+ const boardGroupingOptions = useMemo(
+ () => groupingOptions.filter((item) => item.value !== 'none'),
+ [groupingOptions],
+ );
+ const orderOptions = useMemo<Array<{ label: string; value: TaskOrderBy }>>(
+ () => [
+ { label: t('taskList.orderBy.status'), value: 'status' },
+ { label: t('taskList.orderBy.priority'), value: 'priority' },
+ { label: t('taskList.orderBy.updatedAt'), value: 'updatedAt' },
+ { label: t('taskList.orderBy.createdAt'), value: 'createdAt' },
+ { label: t('taskList.orderBy.assignee'), value: 'assignee' },
+ { label: t('taskList.orderBy.title'), value: 'title' },
+ ],
+ [t],
+ );
- const subGroupingOptions = useMemo(
- () => groupingOptions.filter((item) => item.value !== options.groupBy || item.value === 'none'),
- [groupingOptions, options.groupBy],
- );
- const isSubGroupingEnabled = options.groupBy !== 'none';
- const groupingSelectOptions = viewMode === 'kanban' ? boardGroupingOptions : groupingOptions;
- const groupingValue =
- viewMode === 'kanban' && options.groupBy === 'none' ? 'status' : options.groupBy;
+ const subGroupingOptions = useMemo(
+ () =>
+ groupingOptions.filter((item) => item.value !== options.groupBy || item.value === 'none'),
+ [groupingOptions, options.groupBy],
+ );
+ const isSubGroupingEnabled = options.groupBy !== 'none';
+ const groupingSelectOptions = viewMode === 'kanban' ? boardGroupingOptions : groupingOptions;
+ const groupingValue =
+ viewMode === 'kanban' && options.groupBy === 'none' ? 'status' : options.groupBy;
- const groupingFormItem = {
- children: (
- <Select
- options={groupingSelectOptions}
- size={'small'}
- style={{ width: 150 }}
- value={groupingValue}
- onChange={(value: TaskGroupBy) => {
- setOptions((prev) => ({
- ...prev,
- groupBy: value,
- subGroupBy: prev.subGroupBy === value ? 'none' : prev.subGroupBy,
- }));
- }}
- />
- ),
- label: viewMode === 'kanban' ? t('taskList.form.columns') : t('taskList.form.grouping'),
- } satisfies FormFieldProps;
-
- const completedTasksOptions = TASK_COMPLETED_FILTERS.map((value) => ({
- label: t(`taskList.completedTasks.${value}`),
- value,
- }));
+ const groupingFormItem = {
+ children: (
+ <Select
+ options={groupingSelectOptions}
+ size={'small'}
+ style={{ width: 150 }}
+ value={groupingValue}
+ onChange={(value: TaskGroupBy) => {
+ setOptions((prev) => ({
+ ...prev,
+ groupBy: value,
+ subGroupBy: prev.subGroupBy === value ? 'none' : prev.subGroupBy,
+ }));
+ }}
+ />
+ ),
+ label: viewMode === 'kanban' ? t('taskList.form.columns') : t('taskList.form.grouping'),
+ } satisfies FormFieldProps;
- const completedTasksFormItem = {
- children: (
- <Select
- options={completedTasksOptions}
- size={'small'}
- style={{ width: 120 }}
- value={options.completedTasks}
- onChange={(value: TaskCompletedFilter) => {
- setOptions((prev) => ({ ...prev, completedTasks: value }));
- }}
- />
- ),
- label: t('taskList.form.completedTasks'),
- } satisfies FormFieldProps;
+ const completedTasksOptions = TASK_COMPLETED_FILTERS.map((value) => ({
+ label: t(`taskList.completedTasks.${value}`),
+ value,
+ }));
- const showArchivedFormItem = {
- children: (
- <Switch
- checked={options.showArchived}
- size={'small'}
- onChange={(checked) => {
- setOptions((prev) => ({ ...prev, showArchived: checked }));
- }}
- />
- ),
- minWidth: undefined,
- label: t('taskList.form.showArchived'),
- } satisfies FormFieldProps;
+ const completedTasksFormItem = {
+ children: (
+ <Select
+ options={completedTasksOptions}
+ size={'small'}
+ style={{ width: 120 }}
+ value={options.completedTasks}
+ onChange={(value: TaskCompletedFilter) => {
+ setOptions((prev) => ({ ...prev, completedTasks: value }));
+ }}
+ />
+ ),
+ label: t('taskList.form.completedTasks'),
+ } satisfies FormFieldProps;
- const formItems: FormFieldProps[] = [
- groupingFormItem,
- ...(isSubGroupingEnabled
- ? [
- {
- children: (
- <Select
- options={subGroupingOptions}
- size={'small'}
- style={{ width: 150 }}
- value={options.subGroupBy}
- onChange={(value: TaskGroupBy) => {
- setOptions((prev) => ({ ...prev, subGroupBy: value }));
- }}
- />
- ),
- label: t('taskList.form.subGrouping'),
- } satisfies FormFieldProps,
- ]
- : []),
- ...(isPinned('ordering')
- ? []
- : [
- {
- children: (
- <Flexbox horizontal align={'center'} gap={8}>
- <ActionIcon
- icon={options.orderDirection === 'asc' ? ArrowDownWideNarrow : ArrowUpNarrowWide}
- size={'small'}
- onClick={() => {
- setOptions((prev) => ({
- ...prev,
- orderDirection: prev.orderDirection === 'asc' ? 'desc' : 'asc',
- }));
- }}
- />
- <Select
- options={orderOptions}
- size={'small'}
- style={{ width: 112 }}
- value={options.orderBy}
- onChange={(value: TaskOrderBy) => {
- setOptions((prev) => ({ ...prev, orderBy: value }));
- }}
- />
- </Flexbox>
- ),
- label: t('taskList.form.ordering'),
- } satisfies FormFieldProps,
- ]),
- {
+ const showArchivedFormItem = {
children: (
<Switch
- checked={options.orderCompletedByRecency}
+ checked={options.showArchived}
size={'small'}
onChange={(checked) => {
- setOptions((prev) => ({ ...prev, orderCompletedByRecency: checked }));
+ setOptions((prev) => ({ ...prev, showArchived: checked }));
}}
/>
),
minWidth: undefined,
- label: t('taskList.form.orderCompletedByRecency'),
- },
- completedTasksFormItem,
- showArchivedFormItem,
- ...(isPinned('showSubTasks')
- ? []
- : [
- {
- children: (
- <Switch
- checked={options.showSubTasks}
- size={'small'}
- onChange={(checked) => {
- setOptions((prev) => ({ ...prev, showSubTasks: checked }));
- }}
- />
- ),
- minWidth: undefined,
- label: t('taskList.form.showSubTasks'),
- } satisfies FormFieldProps,
- ]),
- // Only meaningful once sub-tasks are on the list — otherwise the toggle
- // would sit there controlling nothing.
- ...(options.showSubTasks || isPinned('showSubTasks')
- ? [
- {
- children: (
- <Switch
- checked={options.nestedSubTasks}
- size={'small'}
- onChange={(checked) => {
- setOptions((prev) => ({ ...prev, nestedSubTasks: checked }));
- }}
- />
- ),
- minWidth: undefined,
- label: t('taskList.form.nestedSubTasks'),
- } satisfies FormFieldProps,
- ]
- : []),
- ];
- const boardFormItems = [groupingFormItem, completedTasksFormItem, showArchivedFormItem];
+ label: t('taskList.form.showArchived'),
+ } satisfies FormFieldProps;
- const panelContent = (
- <Flexbox gap={12} width={280}>
- <Tabs
- activeKey={viewMode}
- items={[
- { icon: <Icon icon={LayoutList} />, key: 'list', label: t('taskList.view.list') },
- {
- icon: <Icon icon={LayoutGrid} />,
- key: 'kanban',
- label: t('taskList.view.board'),
- },
- ]}
- styles={{
- list: { display: 'flex', width: '100%' },
- tab: { flex: 1 },
- }}
- onChange={(key) =>
- updateSystemStatus({ taskListViewMode: key as TaskViewMode }, 'updateTaskListViewMode')
- }
- />
- <Form
- className={styles.form}
- form={form}
- items={viewMode === 'kanban' ? boardFormItems : formItems}
- itemsType={'flat'}
- variant={'borderless'}
- styles={{
- item: { paddingBlock: 4, paddingInline: 0 },
- }}
- />
- </Flexbox>
- );
+ const formItems: FormFieldProps[] = [
+ groupingFormItem,
+ ...(isSubGroupingEnabled
+ ? [
+ {
+ children: (
+ <Select
+ options={subGroupingOptions}
+ size={'small'}
+ style={{ width: 150 }}
+ value={options.subGroupBy}
+ onChange={(value: TaskGroupBy) => {
+ setOptions((prev) => ({ ...prev, subGroupBy: value }));
+ }}
+ />
+ ),
+ label: t('taskList.form.subGrouping'),
+ } satisfies FormFieldProps,
+ ]
+ : []),
+ ...(isPinned('ordering')
+ ? []
+ : [
+ {
+ children: (
+ <Flexbox horizontal align={'center'} gap={8}>
+ <ActionIcon
+ size={'small'}
+ icon={
+ options.orderDirection === 'asc' ? ArrowDownWideNarrow : ArrowUpNarrowWide
+ }
+ onClick={() => {
+ setOptions((prev) => ({
+ ...prev,
+ orderDirection: prev.orderDirection === 'asc' ? 'desc' : 'asc',
+ }));
+ }}
+ />
+ <Select
+ options={orderOptions}
+ size={'small'}
+ style={{ width: 112 }}
+ value={options.orderBy}
+ onChange={(value: TaskOrderBy) => {
+ setOptions((prev) => ({ ...prev, orderBy: value }));
+ }}
+ />
+ </Flexbox>
+ ),
+ label: t('taskList.form.ordering'),
+ } satisfies FormFieldProps,
+ ]),
+ {
+ children: (
+ <Switch
+ checked={options.orderCompletedByRecency}
+ size={'small'}
+ onChange={(checked) => {
+ setOptions((prev) => ({ ...prev, orderCompletedByRecency: checked }));
+ }}
+ />
+ ),
+ minWidth: undefined,
+ label: t('taskList.form.orderCompletedByRecency'),
+ },
+ completedTasksFormItem,
+ showArchivedFormItem,
+ ...(isPinned('showSubTasks')
+ ? []
+ : [
+ {
+ children: (
+ <Switch
+ checked={options.showSubTasks}
+ size={'small'}
+ onChange={(checked) => {
+ setOptions((prev) => ({ ...prev, showSubTasks: checked }));
+ }}
+ />
+ ),
+ minWidth: undefined,
+ label: t('taskList.form.showSubTasks'),
+ } satisfies FormFieldProps,
+ ]),
+ // Only meaningful once sub-tasks are on the list — otherwise the toggle
+ // would sit there controlling nothing.
+ ...(options.showSubTasks || isPinned('showSubTasks')
+ ? [
+ {
+ children: (
+ <Switch
+ checked={options.nestedSubTasks}
+ size={'small'}
+ onChange={(checked) => {
+ setOptions((prev) => ({ ...prev, nestedSubTasks: checked }));
+ }}
+ />
+ ),
+ minWidth: undefined,
+ label: t('taskList.form.nestedSubTasks'),
+ } satisfies FormFieldProps,
+ ]
+ : []),
+ ];
+ const boardFormItems = [groupingFormItem, completedTasksFormItem, showArchivedFormItem];
- return (
- <Popover
- arrow={false}
- content={panelContent}
- open={isViewConfigOpen}
- placement={'bottomRight'}
- trigger={['click']}
- onOpenChange={setIsViewConfigOpen}
- >
- <ActionIcon icon={Settings2Icon} size={DESKTOP_HEADER_ICON_SMALL_SIZE} />
- </Popover>
- );
-});
+ const panelContent = (
+ <Flexbox gap={12} width={280}>
+ <Tabs
+ activeKey={viewMode}
+ items={[
+ { icon: <Icon icon={LayoutList} />, key: 'list', label: t('taskList.view.list') },
+ {
+ icon: <Icon icon={LayoutGrid} />,
+ key: 'kanban',
+ label: t('taskList.view.board'),
+ },
+ ]}
+ styles={{
+ list: { display: 'flex', width: '100%' },
+ tab: { flex: 1 },
+ }}
+ onChange={(key) =>
+ updateSystemStatus({ taskListViewMode: key as TaskViewMode }, 'updateTaskListViewMode')
+ }
+ />
+ <Form
+ className={styles.form}
+ form={form}
+ items={viewMode === 'kanban' ? boardFormItems : formItems}
+ itemsType={'flat'}
+ variant={'borderless'}
+ styles={{
+ item: { paddingBlock: 4, paddingInline: 0 },
+ }}
+ />
+ </Flexbox>
+ );
+
+ return (
+ <Popover
+ arrow={false}
+ content={panelContent}
+ open={isViewConfigOpen}
+ placement={'bottomRight'}
+ trigger={['click']}
+ onOpenChange={setIsViewConfigOpen}
+ >
+ <ActionIcon icon={Settings2Icon} size={DESKTOP_HEADER_ICON_SMALL_SIZE} />
+ </Popover>
+ );
+ },
+);
export default TasksGroupConfig;
diff --git a/src/features/AgentTasks/AgentTaskList/kanbanBoardModel.project.test.ts b/src/features/AgentTasks/AgentTaskList/kanbanBoardModel.project.test.ts
new file mode 100644
index 00000000000..afe2c8a0ed9
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskList/kanbanBoardModel.project.test.ts
@@ -0,0 +1,164 @@
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { type ProjectListItem, useProjectStore } from '@/store/project';
+import type { TaskGroupItem } from '@/store/task/slices/list/initialState';
+
+import {
+ buildKanbanColumns,
+ getKanbanColumnCreateDefaults,
+ getKanbanCreateTaskModalProps,
+ getKanbanTaskPatch,
+ getTaskGroupCreateDefaults,
+ getTaskSubGroupCreateDefaults,
+ mergeUnresolvedProjectGroups,
+ normalizeKanbanGroupBy,
+} from './kanbanBoardModel';
+
+const projects = [
+ { id: 'proj_b', name: 'Beta' },
+ { id: 'proj_a', name: 'Alpha' },
+] as ProjectListItem[];
+
+const group = (key: string, projectId: string | null, taskIds: string[] = []): TaskGroupItem =>
+ ({
+ hasMore: false,
+ key,
+ limit: 50,
+ offset: 0,
+ projectId,
+ tasks: taskIds.map((id) => ({ id, identifier: id, projectId })),
+ total: taskIds.length,
+ }) as unknown as TaskGroupItem;
+
+beforeEach(() => {
+ useProjectStore.setState({ projectListMap: { all: projects } });
+});
+
+describe('project board columns', () => {
+ it('keeps project as a board dimension', () => {
+ expect(normalizeKanbanGroupBy('project')).toBe('project');
+ });
+
+ it('builds one named column per project, with "No project" last', () => {
+ const columns = buildKanbanColumns(
+ [
+ group('project:none', null),
+ group('project:proj_b', 'proj_b', ['t1']),
+ group('project:proj_a', 'proj_a', ['t2']),
+ ],
+ 'project',
+ );
+
+ expect(columns.map((column) => column.key)).toEqual([
+ 'project:proj_a',
+ 'project:proj_b',
+ 'project:none',
+ ]);
+ expect(columns[0].groupMeta).toMatchObject({ label: 'Alpha', projectId: 'proj_a' });
+ expect(columns[2].groupMeta).toMatchObject({ groupBy: 'project', projectId: null });
+ expect(columns.every((column) => column.droppable)).toBe(true);
+ });
+
+ it('never names a column after a project outside the list', () => {
+ const columns = buildKanbanColumns(
+ mergeUnresolvedProjectGroups(
+ [group('project:none', null, ['t0']), group('project:gone', 'gone', ['t1', 't2'])],
+ projects,
+ ),
+ 'project',
+ );
+
+ expect(columns.map((column) => column.key)).toEqual(['project:unavailable', 'project:none']);
+ expect(columns[0].droppable).toBe(false);
+ expect(columns[1].droppable).toBe(true);
+ expect(JSON.stringify(columns)).not.toContain('gone');
+ });
+});
+
+describe('mergeUnresolvedProjectGroups', () => {
+ it('folds unseen projects into one column, leaving "No project" with only unlinked tasks', () => {
+ const merged = mergeUnresolvedProjectGroups(
+ [
+ group('project:none', null, ['t0']),
+ group('project:proj_a', 'proj_a', ['t1']),
+ group('project:gone', 'gone', ['t2', 't3']),
+ group('project:gone2', 'gone2', ['t4']),
+ ],
+ projects,
+ );
+ const byKey = new Map(merged.map((item) => [item.key, item]));
+
+ expect(byKey.get('project:none')?.tasks.map((task) => task.id)).toEqual(['t0']);
+ expect(byKey.get('project:none')?.total).toBe(1);
+ expect(byKey.get('project:unavailable')?.tasks.map((task) => task.id)).toEqual([
+ 't2',
+ 't3',
+ 't4',
+ ]);
+ expect(byKey.get('project:unavailable')?.total).toBe(3);
+ expect([...byKey.keys()]).not.toContain('project:gone');
+ });
+
+ it('keeps tasks of unseen projects on a board with no "No project" column', () => {
+ const merged = mergeUnresolvedProjectGroups([group('project:gone', 'gone', ['t1'])], projects);
+
+ expect(merged.map((item) => item.key)).toEqual(['project:unavailable']);
+ expect(merged[0].tasks.map((task) => task.id)).toEqual(['t1']);
+ });
+
+ it('decides nothing before the list has loaded', () => {
+ const groups = [group('project:gone', 'gone', ['t1'])];
+ expect(mergeUnresolvedProjectGroups(groups, undefined)).toBe(groups);
+ });
+
+ it('returns the same reference when every project is visible', () => {
+ const groups = [group('project:none', null), group('project:proj_a', 'proj_a')];
+ expect(mergeUnresolvedProjectGroups(groups, projects)).toBe(groups);
+ });
+});
+
+describe('the "Unavailable project" column', () => {
+ it('offers no create entry, since a new task could not land there', () => {
+ const [column] = buildKanbanColumns([group('project:gone', 'gone', ['t1'])], 'project');
+
+ expect(column.key).toBe('project:unavailable');
+ expect(getKanbanColumnCreateDefaults('project', column)).toBeUndefined();
+ expect(getTaskGroupCreateDefaults(column.groupMeta)).toBeUndefined();
+ });
+});
+
+describe('dropping and creating in a project column', () => {
+ const columns = () =>
+ buildKanbanColumns(
+ [group('project:proj_a', 'proj_a', ['t1']), group('project:none', null)],
+ 'project',
+ );
+
+ it('moves a dropped card into the project, or clears it on "No project"', () => {
+ const [named, none] = columns();
+ expect(getKanbanTaskPatch('project', named)).toEqual({ projectId: 'proj_a' });
+ expect(getKanbanTaskPatch('project', none)).toEqual({ projectId: null });
+ });
+
+ it('pins the column project on a new task; "No project" pins nothing', () => {
+ const [named, none] = columns();
+ expect(getKanbanColumnCreateDefaults('project', named)).toEqual({ projectId: 'proj_a' });
+ expect(getKanbanColumnCreateDefaults('project', none)).toEqual({});
+ expect(
+ getKanbanCreateTaskModalProps({ projectId: 'proj_a' }, { agentId: undefined }).projectId,
+ ).toBe('proj_a');
+ });
+
+ it('keeps both pins when a project group is split by priority', () => {
+ const [named, none] = columns();
+ expect(
+ getTaskSubGroupCreateDefaults(named.groupMeta, {
+ groupBy: 'priority',
+ key: 'priority:1',
+ label: 'Urgent',
+ priority: 1,
+ }),
+ ).toEqual({ priority: 1, projectId: 'proj_a' });
+ expect(getTaskGroupCreateDefaults(none.groupMeta)).toEqual({});
+ });
+});
diff --git a/src/features/AgentTasks/AgentTaskList/kanbanBoardModel.ts b/src/features/AgentTasks/AgentTaskList/kanbanBoardModel.ts
index b99dd00a0b9..a81b598fc5f 100644
--- a/src/features/AgentTasks/AgentTaskList/kanbanBoardModel.ts
+++ b/src/features/AgentTasks/AgentTaskList/kanbanBoardModel.ts
@@ -5,6 +5,7 @@ import type {
TaskKanbanGroupBy,
TaskListItem,
} from '@/store/task/slices/list/initialState';
+import { TASK_UNAVAILABLE_PROJECT_GROUP_KEY } from '@/store/task/slices/list/projection';
import type { CreateTaskContentProps } from '../CreateTaskModal/CreateTaskContent';
import type { TaskGroupBy, TaskGroupMeta } from './listViewOptions';
@@ -14,6 +15,7 @@ import {
getTaskLabelGroupMeta,
getTaskMemberGroupMeta,
getTaskPriorityGroupMeta,
+ getTaskProjectGroupMeta,
isTaskLabelGroupBy,
sortGroupEntries,
} from './listViewOptions';
@@ -70,6 +72,7 @@ export const normalizeKanbanGroupBy = (groupBy: TaskGroupBy): TaskKanbanGroupBy
groupBy === 'assignee' ||
groupBy === 'member' ||
groupBy === 'priority' ||
+ groupBy === 'project' ||
isTaskLabelGroupBy(groupBy)
? groupBy
: 'status';
@@ -117,6 +120,30 @@ export const buildKanbanGroupQuery = ({
return { allAgents: true, automated: false, excludeStatuses, groupBy };
};
+/**
+ * Folds the columns of projects the caller cannot see into one "Unavailable
+ * project" column: the server groups by the raw column, but only the visible
+ * project list can name a column. Before that list loads there is nothing to
+ * decide from.
+ */
+export const mergeUnresolvedProjectGroups = <T extends TaskGroupItem>(
+ groups: T[],
+ projects: ReadonlyArray<{ id: string }> | undefined,
+): T[] => {
+ if (!projects) return groups;
+ const visible = new Set(projects.map((project) => project.id));
+ const orphans = groups.filter((group) => group.projectId && !visible.has(group.projectId));
+ if (orphans.length === 0) return groups;
+ const unavailable = {
+ ...orphans[0],
+ hasMore: orphans.some((orphan) => orphan.hasMore),
+ key: TASK_UNAVAILABLE_PROJECT_GROUP_KEY,
+ tasks: orphans.flatMap((orphan) => orphan.tasks),
+ total: orphans.reduce((sum, orphan) => sum + orphan.total, 0),
+ } as T;
+ return [...groups.filter((group) => !orphans.includes(group)), unavailable];
+};
+
export const buildKanbanColumns = (
taskGroups: TaskGroupItem[],
groupBy: TaskKanbanGroupBy,
@@ -130,12 +157,15 @@ export const buildKanbanColumns = (
? getTaskAssigneeGroupMeta(group.assigneeAgentId)
: groupBy === 'member'
? getTaskMemberGroupMeta(group.assigneeUserId)
- : getTaskPriorityGroupMeta(group.priority);
+ : groupBy === 'project'
+ ? getTaskProjectGroupMeta(group.projectId)
+ : getTaskPriorityGroupMeta(group.priority);
return [meta, group.tasks as TaskListItem[]] as [TaskGroupMeta, TaskListItem[]];
});
return sortGroupEntries(groupEntries, groupBy).map(([groupMeta]) => ({
- droppable: true,
+ // Nobody can file a task under a project they cannot see.
+ droppable: !groupMeta.projectUnavailable,
groupMeta,
key: groupMeta.key,
targetStatus: null,
@@ -174,6 +204,9 @@ export const getKanbanTaskPatch = (
if (groupBy === 'priority' && column.groupMeta?.groupBy === 'priority') {
return { priority: column.groupMeta.priority ?? 0 };
}
+ if (groupBy === 'project' && column.groupMeta?.groupBy === 'project') {
+ return { projectId: column.groupMeta.projectId ?? null };
+ }
if (groupBy === 'status' && column.targetStatus) {
return { status: column.targetStatus as TaskStatus };
}
@@ -215,6 +248,7 @@ export interface KanbanColumnCreateDefaults {
*/
labelIds?: string[];
priority?: number;
+ projectId?: string;
}
/**
@@ -237,6 +271,12 @@ export const getTaskGroupCreateDefaults = (
case 'priority': {
return { priority: groupMeta.priority ?? 0 };
}
+ // A new task starts without a project, so "No project" pins nothing, and
+ // "Unavailable project" has no entry: nobody can file a task under it.
+ case 'project': {
+ if (groupMeta.projectUnavailable) return undefined;
+ return groupMeta.projectId ? { projectId: groupMeta.projectId } : {};
+ }
// The unassigned group has no entry: the modal cannot pin "no agent".
case 'assignee': {
return groupMeta.assigneeId ? { assigneeAgentId: groupMeta.assigneeId } : undefined;
@@ -287,7 +327,7 @@ export const getKanbanCreateTaskModalProps = (
defaultPriority: defaults.priority,
// An agent-scoped board only holds that agent's tasks.
lockAssignee: !!scope.agentId,
- projectId: scope.projectId,
+ projectId: defaults.projectId ?? scope.projectId,
// The board has no inline entry to minimize into.
showInlineToggle: false,
});
diff --git a/src/features/AgentTasks/AgentTaskList/listViewOptions.test.ts b/src/features/AgentTasks/AgentTaskList/listViewOptions.test.ts
index 2ffc36cd269..a0ae9e6759c 100644
--- a/src/features/AgentTasks/AgentTaskList/listViewOptions.test.ts
+++ b/src/features/AgentTasks/AgentTaskList/listViewOptions.test.ts
@@ -8,6 +8,7 @@ import {
compareTaskItems,
DEFAULT_TASK_LIST_VIEW_OPTIONS,
dropMissingLabelGroupings,
+ dropProjectGrouping,
getCompletedWithin,
getVisibleTaskStatuses,
groupTaskItems,
@@ -377,3 +378,28 @@ describe('normalizeTaskGroupBy', () => {
expect(normalizeTaskGroupBy(undefined, 'status')).toBe('status');
});
});
+
+describe('project grouping options', () => {
+ it('survives normalization at both levels', () => {
+ expect(normalizeTaskListViewOptions({ groupBy: 'project' }).groupBy).toBe('project');
+ expect(
+ normalizeTaskListViewOptions({ groupBy: 'status', subGroupBy: 'project' }).subGroupBy,
+ ).toBe('project');
+ });
+
+ it('falls back to the defaults where project grouping is not offered', () => {
+ expect(dropProjectGrouping({ groupBy: 'project', subGroupBy: 'priority' })).toEqual({
+ groupBy: DEFAULT_TASK_LIST_VIEW_OPTIONS.groupBy,
+ subGroupBy: 'priority',
+ });
+ expect(dropProjectGrouping({ groupBy: 'priority', subGroupBy: 'project' })).toEqual({
+ groupBy: 'priority',
+ subGroupBy: DEFAULT_TASK_LIST_VIEW_OPTIONS.subGroupBy,
+ });
+ });
+
+ it('keeps the same reference when no project grouping is set', () => {
+ const options = { groupBy: 'status', subGroupBy: 'none' } as const;
+ expect(dropProjectGrouping(options)).toBe(options);
+ });
+});
diff --git a/src/features/AgentTasks/AgentTaskList/listViewOptions.ts b/src/features/AgentTasks/AgentTaskList/listViewOptions.ts
index 5aa7a0f6067..977e6431b98 100644
--- a/src/features/AgentTasks/AgentTaskList/listViewOptions.ts
+++ b/src/features/AgentTasks/AgentTaskList/listViewOptions.ts
@@ -7,13 +7,26 @@ import {
import type { TaskStatus } from '@lobechat/types';
import { t } from 'i18next';
+import { projectListItemSelector, useProjectStore } from '@/store/project';
import { getTaskStoreState } from '@/store/task';
import type { TaskListItem } from '@/store/task/slices/list/initialState';
+import {
+ TASK_NO_PROJECT_GROUP_KEY,
+ TASK_UNAVAILABLE_PROJECT_GROUP_KEY,
+ taskGroupKeyByProject,
+} from '@/store/task/slices/list/projection';
/** Grouping by one label group: one group per label of that group, plus "no label". */
export type TaskLabelGroupBy = `label:${string}`;
export type TaskGroupBy =
- 'assignee' | 'automationMode' | 'member' | 'none' | 'priority' | 'status' | TaskLabelGroupBy;
+ | 'assignee'
+ | 'automationMode'
+ | 'member'
+ | 'none'
+ | 'priority'
+ | 'project'
+ | 'status'
+ | TaskLabelGroupBy;
const TASK_LABEL_GROUP_BY_PREFIX = 'label:';
@@ -115,6 +128,10 @@ export interface TaskGroupMeta {
/** Registry position of a label group, for ordering. */
labelRank?: number;
priority?: number;
+ /** The project of a project group; null is the "no project" group. */
+ projectId?: string | null;
+ /** The group of tasks filed under projects the caller cannot see. */
+ projectUnavailable?: boolean;
status?: 'backlog' | 'canceled' | 'completed' | 'failed' | 'paused' | 'running' | 'scheduled';
}
@@ -139,6 +156,7 @@ const TASK_GROUP_BY_SET = new Set<TaskGroupBy>([
'member',
'none',
'priority',
+ 'project',
'status',
]);
const TASK_ORDER_BY_SET = new Set<TaskOrderBy>([
@@ -207,6 +225,26 @@ export const dropMissingLabelGroupings = <
};
};
+/**
+ * Grouping by project means nothing where every task shares one project (a
+ * project page) or where projects are switched off. View options are shared by
+ * every task page, so the choice is set aside here rather than erased.
+ */
+export const dropProjectGrouping = <T extends Pick<TaskListViewOptions, 'groupBy' | 'subGroupBy'>>(
+ options: T,
+): T => {
+ if (options.groupBy !== 'project' && options.subGroupBy !== 'project') return options;
+ return {
+ ...options,
+ groupBy:
+ options.groupBy === 'project' ? DEFAULT_TASK_LIST_VIEW_OPTIONS.groupBy : options.groupBy,
+ subGroupBy:
+ options.subGroupBy === 'project'
+ ? DEFAULT_TASK_LIST_VIEW_OPTIONS.subGroupBy
+ : options.subGroupBy,
+ };
+};
+
/**
* A grouping the list can render, or `fallback`. `label:<groupId>` is
* open-ended; whether its group still exists is settled upstream by
@@ -364,6 +402,39 @@ export const getTaskLabelGroupMeta = (
};
};
+/**
+ * Group meta of one project. A name only comes from the cached project list, so
+ * a task filed under a project the caller cannot see joins "Unavailable project":
+ * it does have a project, so "No project" would misreport it, and heading a group
+ * with the id would expose what the viewer may not read.
+ */
+export const getTaskProjectGroupMeta = (projectId: string | null | undefined): TaskGroupMeta => {
+ const project = projectListItemSelector(projectId)(useProjectStore.getState());
+ if (project) {
+ return {
+ groupBy: 'project',
+ key: taskGroupKeyByProject(project.id),
+ label: project.name,
+ projectId: project.id,
+ };
+ }
+ if (projectId) {
+ return {
+ groupBy: 'project',
+ key: TASK_UNAVAILABLE_PROJECT_GROUP_KEY,
+ label: t('taskProject.unavailable', { ns: 'chat' }),
+ projectId: null,
+ projectUnavailable: true,
+ };
+ }
+ return {
+ groupBy: 'project',
+ key: TASK_NO_PROJECT_GROUP_KEY,
+ label: t('taskProject.none', { ns: 'chat' }),
+ projectId: null,
+ };
+};
+
const getTaskAssigneeSortValue = (task: TaskListItem) => task.assigneeAgentId ?? '';
export const getTaskPriorityGroupMeta = (
@@ -467,6 +538,9 @@ export const getTaskGroupMeta = (task: TaskListItem, groupBy: TaskGroupBy): Task
case 'member': {
return getTaskMemberGroupMeta(task.assigneeUserId);
}
+ case 'project': {
+ return getTaskProjectGroupMeta(task.projectId);
+ }
case 'automationMode': {
// Automated tasks created before automationMode was introduced are schedules.
const automationMode = task.automationMode === 'heartbeat' ? 'heartbeat' : 'schedule';
@@ -514,6 +588,11 @@ const getGroupRank = (group: TaskGroupMeta, groupBy: TaskGroupBy): number => {
case 'automationMode': {
return group.automationMode === 'schedule' ? 0 : 1;
}
+ // Named projects sort by name, then "Unavailable project"; "No project" stays last.
+ case 'project': {
+ if (group.projectId) return 0;
+ return group.projectUnavailable ? 1 : 2;
+ }
case 'priority': {
if (group.priority === undefined) return Number.MAX_SAFE_INTEGER;
return PRIORITY_RANK_MAP[group.priority] ?? Number.MAX_SAFE_INTEGER;
diff --git a/src/features/AgentTasks/AgentTaskList/taskCreateDraft.ts b/src/features/AgentTasks/AgentTaskList/taskCreateDraft.ts
index e37a049f1f3..6034d0194c0 100644
--- a/src/features/AgentTasks/AgentTaskList/taskCreateDraft.ts
+++ b/src/features/AgentTasks/AgentTaskList/taskCreateDraft.ts
@@ -11,6 +11,8 @@ export interface TaskCreateDraft {
labelIds?: unknown;
markdown?: string;
priority?: number;
+ /** `null` is an explicit "no project"; a missing key follows the scope's default. */
+ projectId?: string | null;
visibility?: 'private' | 'public';
}
diff --git a/src/features/AgentTasks/AgentTaskList/taskListVirtualModel.test.ts b/src/features/AgentTasks/AgentTaskList/taskListVirtualModel.test.ts
index 40d1381fe28..d9e754bb18e 100644
--- a/src/features/AgentTasks/AgentTaskList/taskListVirtualModel.test.ts
+++ b/src/features/AgentTasks/AgentTaskList/taskListVirtualModel.test.ts
@@ -1,6 +1,10 @@
-import { describe, expect, it } from 'vitest';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { type ProjectListItem, useProjectStore } from '@/store/project';
+import type { TaskListItem } from '@/store/task/slices/list/initialState';
import type { TaskGroupMeta, TaskRow } from './listViewOptions';
+import { groupTaskItems } from './listViewOptions';
import {
flattenTaskListEntries,
taskGroupCollapseKey,
@@ -102,3 +106,80 @@ describe('flattenTaskListEntries', () => {
expect(keys).toContain('backlog:T-1');
});
});
+
+describe('flattenTaskListEntries grouped by project', () => {
+ const task = (identifier: string, projectId?: string | null) =>
+ ({ id: identifier, identifier, projectId }) as unknown as TaskListItem;
+
+ const entries = (items: TaskListItem[]): TaskListGroupEntry[] =>
+ groupTaskItems(items, 'project').map(([groupMeta, groupItems]) => ({
+ count: groupItems.length,
+ meta: groupMeta,
+ rows: groupItems.map((item) => ({ depth: 0, isParentContext: false, task: item })),
+ subGroups: [],
+ }));
+
+ beforeEach(() => {
+ useProjectStore.setState({
+ projectListMap: {
+ all: [
+ { id: 'proj_b', name: 'Beta' },
+ { id: 'proj_a', name: 'Alpha' },
+ ] as ProjectListItem[],
+ },
+ });
+ });
+
+ it('lays out a header per project, sorted by name, with "No project" last', () => {
+ const items = flattenTaskListEntries(
+ entries([
+ task('T-1', 'proj_b'),
+ task('T-2', null),
+ task('T-3', 'proj_a'),
+ task('T-4', 'proj_b'),
+ ]),
+ { collapsed: new Set(), grouped: true },
+ );
+
+ expect(items.map((item) => item.key)).toEqual([
+ 'group:project:proj_a',
+ 'project:proj_a:T-3',
+ 'group:project:proj_b',
+ 'project:proj_b:T-1',
+ 'project:proj_b:T-4',
+ 'group:project:none',
+ 'project:none:T-2',
+ ]);
+ expect(items[0]).toMatchObject({ count: 1, first: true, meta: { label: 'Alpha' } });
+ expect(items[5]).toMatchObject({ count: 1, meta: { groupBy: 'project', projectId: null } });
+ });
+
+ it('separates tasks under an unseen project from tasks with no project', () => {
+ const items = flattenTaskListEntries(
+ entries([task('T-1', undefined), task('T-2', 'gone'), task('T-3', null)]),
+ { collapsed: new Set(), grouped: true },
+ );
+
+ expect(items.map((item) => item.key)).toEqual([
+ 'group:project:unavailable',
+ 'project:unavailable:T-2',
+ 'group:project:none',
+ 'project:none:T-1',
+ 'project:none:T-3',
+ ]);
+ expect(JSON.stringify(items[0])).not.toContain('gone');
+ });
+
+ it('drops the rows of a collapsed project group', () => {
+ const items = flattenTaskListEntries(entries([task('T-1', 'proj_a'), task('T-2', null)]), {
+ collapsed: new Set([taskGroupCollapseKey('project:proj_a')]),
+ grouped: true,
+ });
+
+ expect(items.map((item) => item.key)).toEqual([
+ 'group:project:proj_a',
+ 'group:project:none',
+ 'project:none:T-2',
+ ]);
+ });
+});
diff --git a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.project.test.tsx b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.project.test.tsx
new file mode 100644
index 00000000000..f86d563e3f7
--- /dev/null
+++ b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.project.test.tsx
@@ -0,0 +1,130 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import CreateTaskContent from './CreateTaskContent';
+
+const state = vi.hoisted(() => ({
+ createTask: vi.fn(async () => ({ id: 't1', identifier: 'T-1' })),
+}));
+
+vi.mock('@lobehub/editor/react', () => ({
+ useEditor: () => ({ getDocument: () => '' }),
+}));
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ useModalContext: () => ({ close: vi.fn() }),
+}));
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ useActiveWorkspaceId: () => undefined,
+}));
+vi.mock('@/features/EditorCanvas', () => ({ EditorCanvas: () => null }));
+vi.mock('@/features/EditorCanvas/editorAttachments', () => ({
+ getAttachmentFileIdsFromEditor: () => [],
+ pickAndInsertAttachments: vi.fn(),
+}));
+vi.mock('@/features/EditorCanvas/releaseEditorSelection', () => ({
+ releaseEditorSelection: vi.fn(),
+}));
+vi.mock('@/features/TaskLabels/TaskLabelChips', () => ({ default: () => null }));
+vi.mock('@/features/TaskLabels/TaskLabelPicker', () => ({ default: () => null }));
+vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: true }) }));
+vi.mock('@/store/global', () => ({
+ useGlobalStore: (selector: (s: unknown) => unknown) => selector({}),
+}));
+vi.mock('@/store/project', () => ({
+ useLoadedProjectList: () => [{ id: 'p1', name: 'Apollo' }],
+ useProjectStore: (selector: (s: unknown) => unknown) =>
+ selector({ useFetchProjectList: () => ({ isValidating: false }) }),
+}));
+vi.mock('@/store/task', () => ({
+ getTaskStoreState: () => ({ taskLabels: [], taskLabelsInit: true }),
+ useTaskStore: (selector: (s: unknown) => unknown) =>
+ selector({ createTask: state.createTask, taskLabels: [], taskLabelsInit: true }),
+}));
+vi.mock('@/store/task/selectors', () => ({
+ taskLabelSelectors: { isLabelsInit: () => true, labels: () => [] },
+}));
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: (s: unknown) => unknown) => selector({}),
+}));
+vi.mock('@/store/user/selectors', () => ({
+ labPreferSelectors: { enableProjects: () => true },
+ userProfileSelectors: { userId: () => 'u1' },
+}));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+vi.mock('../features/AssigneeAgentSelector', () => ({ default: () => null }));
+vi.mock('../features/AssigneeAvatar', () => ({ default: () => null }));
+vi.mock('../features/AssigneeMemberSelector', () => ({ default: () => null }));
+vi.mock('../features/AssigneeUserAvatar', () => ({ default: () => null }));
+vi.mock('../features/TaskExecutionControls', () => ({ default: () => null }));
+vi.mock('../features/TaskPriorityTag', () => ({ default: () => null }));
+vi.mock('../features/TaskVisibilityChipLabel', () => ({ default: () => null }));
+vi.mock('../features/TaskVisibilityTag', () => ({ default: () => null }));
+vi.mock('../features/UnassignedAssigneeIcon', () => ({ UnassignedAssigneeIcon: () => null }));
+vi.mock('../features/TaskProjectPickerChip', () => ({
+ default: ({
+ onChange,
+ value,
+ }: {
+ onChange: (id: string | null) => void;
+ value: string | null;
+ }) => (
+ <div>
+ <span data-testid="chip">{value ?? 'empty'}</span>
+ <button onClick={() => onChange('p1')}>pick</button>
+ <button onClick={() => onChange(null)}>clear</button>
+ </div>
+ ),
+}));
+vi.mock('../shared/memberAssigneeMode', () => ({
+ resolveMemberAssignee: () => undefined,
+}));
+vi.mock('../shared/useAgentDisplayMeta', () => ({ useAgentDisplayMeta: () => undefined }));
+vi.mock('../shared/useAgentVisibility', () => ({ useAgentVisibility: () => undefined }));
+vi.mock('../shared/useDefaultMemberAssignee', () => ({
+ useDefaultMemberAssignee: () => ({ isDefaultMemberPending: false }),
+}));
+vi.mock('../shared/useEscapeDiscardGuard', () => ({ useEscapeDiscardGuard: vi.fn() }));
+vi.mock('../shared/useUserDisplayMeta', () => ({ useUserDisplayMeta: () => undefined }));
+
+const submit = async () => {
+ fireEvent.change(screen.getByPlaceholderText('createTask.titlePlaceholder'), {
+ target: { value: 'Ship it' },
+ });
+ state.createTask.mockClear();
+ fireEvent.click(screen.getByText('createTask.submit'));
+ await waitFor(() => expect(state.createTask).toHaveBeenCalledTimes(1));
+ return (state.createTask.mock.calls as unknown as [[{ projectId?: string }]])[0][0];
+};
+
+describe('CreateTaskContent project', () => {
+ it('creates without a project when none is picked', async () => {
+ render(<CreateTaskContent />);
+ expect(screen.getByTestId('chip')).toHaveTextContent('empty');
+ expect((await submit()).projectId).toBeUndefined();
+ });
+
+ it('creates in the picked project', async () => {
+ render(<CreateTaskContent />);
+ fireEvent.click(screen.getByText('pick'));
+ expect(screen.getByTestId('chip')).toHaveTextContent('p1');
+ expect((await submit()).projectId).toBe('p1');
+ });
+
+ it('prefills the page project', async () => {
+ render(<CreateTaskContent projectId="p1" />);
+ expect(screen.getByTestId('chip')).toHaveTextContent('p1');
+ expect((await submit()).projectId).toBe('p1');
+ });
+
+ it('lets the prefill be cleared', async () => {
+ render(<CreateTaskContent projectId="p1" />);
+ fireEvent.click(screen.getByText('clear'));
+ expect((await submit()).projectId).toBeUndefined();
+ });
+});
diff --git a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
index 8e61a56d813..84c3616257f 100644
--- a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
+++ b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
@@ -42,9 +42,11 @@ import AssigneeMemberSelector from '../features/AssigneeMemberSelector';
import AssigneeUserAvatar from '../features/AssigneeUserAvatar';
import TaskExecutionControls from '../features/TaskExecutionControls';
import TaskPriorityTag from '../features/TaskPriorityTag';
+import TaskProjectPickerChip from '../features/TaskProjectPickerChip';
import TaskVisibilityChipLabel from '../features/TaskVisibilityChipLabel';
import TaskVisibilityTag from '../features/TaskVisibilityTag';
import { UnassignedAssigneeIcon } from '../features/UnassignedAssigneeIcon';
+import { useTaskProjectChoice } from '../features/useTaskProjectChoice';
import { resolveMemberAssignee } from '../shared/memberAssigneeMode';
import { useAgentDisplayMeta } from '../shared/useAgentDisplayMeta';
import { useAgentVisibility } from '../shared/useAgentVisibility';
@@ -72,6 +74,7 @@ export interface CreateTaskContentProps {
*/
lockAssignee?: boolean;
onCreated?: (task: { id: string; agentId?: string; identifier: string; name?: string }) => void;
+ /** The project the task starts in, e.g. the page it was opened from. The user can change it. */
projectId?: string;
/**
* Creates a scheduled task: the form gains a schedule chip and the task is
@@ -128,6 +131,7 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
current.length > 0 ? current : resolveTaskLabelRefs(labelRegistry, pending),
);
}, [isLabelsInit, labelRegistry]);
+ const { createProjectId, projectChoice, setProjectChoice } = useTaskProjectChoice(projectId);
const [assigneeAgentId, setAssigneeAgentId] = useState<string | undefined>(agentId);
// `undefined` follows the default (the creator); `null` is an explicit "unassigned".
const [memberChoice, setMemberChoice] = useState<string | null | undefined>();
@@ -227,7 +231,7 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
...pickedLabelIds(labels, pendingDefaultLabelIdsRef.current),
name: title.trim() || undefined,
priority: priority || undefined,
- projectId,
+ projectId: createProjectId,
// Only send visibility in workspace mode; personal mode ignores it.
visibility: activeWorkspaceId ? visibility : undefined,
});
@@ -250,6 +254,7 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
assigneeUserId,
canCreateTask,
close,
+ createProjectId,
execution,
createTask,
editor,
@@ -258,7 +263,6 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
labels,
onCreated,
priority,
- projectId,
scheduleDraft,
t,
title,
@@ -428,6 +432,8 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
</Block>
</TaskLabelPicker>
+ <TaskProjectPickerChip value={projectChoice} onChange={setProjectChoice} />
+
{activeWorkspaceId && (
<AssigneeMemberSelector
currentUserId={assigneeUserId}
diff --git a/src/features/AgentTasks/features/AgentTaskItem.test.tsx b/src/features/AgentTasks/features/AgentTaskItem.test.tsx
index 0180daaa471..6664ef955ee 100644
--- a/src/features/AgentTasks/features/AgentTaskItem.test.tsx
+++ b/src/features/AgentTasks/features/AgentTaskItem.test.tsx
@@ -11,6 +11,8 @@ const mocks = vi.hoisted(() => ({
activeWorkspaceId: 'workspace-1' as string | undefined,
fetchTaskDetail: vi.fn(),
navigate: vi.fn(),
+ projects: undefined as { id: string; name: string }[] | undefined,
+ projectsEnabled: true,
taskDetailMap: {} as Record<string, unknown>,
}));
@@ -103,6 +105,24 @@ vi.mock('./TaskTriggerTag', () => ({
),
}));
+vi.mock('@/store/project', () => ({
+ projectListItemSelector: (id?: string | null) => (s: { projects?: { id: string }[] }) =>
+ id ? s.projects?.find((project) => project.id === id) : undefined,
+ useProjectStore: (selector: (s: unknown) => unknown) => selector({ projects: mocks.projects }),
+}));
+
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: (s: unknown) => unknown) => selector({}),
+}));
+
+vi.mock('@/store/user/selectors', () => ({
+ labPreferSelectors: { enableProjects: () => mocks.projectsEnabled },
+}));
+
+vi.mock('@/features/Projects/ProjectAvatar', () => ({
+ default: () => <i data-testid="project-avatar" />,
+}));
+
vi.mock('./useTaskItemContextMenu', () => ({
useTaskItemContextMenu: () => ({ items: [], onContextMenu: vi.fn() }),
}));
@@ -124,6 +144,8 @@ describe('AgentTaskItem', () => {
mocks.activeWorkspaceId = 'workspace-1';
mocks.fetchTaskDetail.mockReset();
mocks.navigate.mockClear();
+ mocks.projects = [{ id: 'proj_a', name: 'Alpha' }];
+ mocks.projectsEnabled = true;
mocks.taskDetailMap = {};
});
@@ -155,6 +177,50 @@ describe('AgentTaskItem', () => {
expect(mocks.navigate).toHaveBeenCalledWith('/task/T-22/hourly-trend-update');
});
+ describe('project badge', () => {
+ const withProject = (projectId?: string | null) => ({
+ ...createTask('agt_owner'),
+ projectId,
+ });
+
+ it.each([['default'], ['compact']] as const)(
+ 'shows the project icon and name on a %s row, unless the surface hides it',
+ (variant) => {
+ const { rerender } = render(
+ <AgentTaskItem task={withProject('proj_a')} variant={variant} />,
+ );
+ expect(screen.getByTestId('task-project-chip')).toHaveTextContent('Alpha');
+ expect(screen.getByTestId('project-avatar')).toBeInTheDocument();
+
+ rerender(<AgentTaskItem hideProject task={withProject('proj_a')} variant={variant} />);
+ expect(screen.queryByTestId('task-project-chip')).not.toBeInTheDocument();
+ },
+ );
+
+ it.each([
+ ['no project', null],
+ ['an undefined project', undefined],
+ ['a project outside the list', 'proj_gone'],
+ ])('renders no badge for %s', (_, projectId) => {
+ render(<AgentTaskItem task={withProject(projectId)} />);
+
+ expect(screen.queryByTestId('task-project-chip')).not.toBeInTheDocument();
+ expect(screen.queryByText('proj_gone')).not.toBeInTheDocument();
+ expect(screen.getByText('Hourly trend update')).toBeInTheDocument();
+ });
+
+ it('renders no badge until the list loads, or while the Projects lab is off', () => {
+ mocks.projects = undefined;
+ const { rerender } = render(<AgentTaskItem task={withProject('proj_a')} />);
+ expect(screen.queryByTestId('task-project-chip')).not.toBeInTheDocument();
+
+ mocks.projects = [{ id: 'proj_a', name: 'Alpha' }];
+ mocks.projectsEnabled = false;
+ rerender(<AgentTaskItem task={withProject('proj_a')} variant="compact" />);
+ expect(screen.queryByTestId('task-project-chip')).not.toBeInTheDocument();
+ });
+ });
+
it('shows the assigned agent and member names in tooltips', () => {
const { container } = render(
<AgentTaskItem
diff --git a/src/features/AgentTasks/features/AgentTaskItem.tsx b/src/features/AgentTasks/features/AgentTaskItem.tsx
index 89f3f5decbd..a91ea5ed508 100644
--- a/src/features/AgentTasks/features/AgentTaskItem.tsx
+++ b/src/features/AgentTasks/features/AgentTaskItem.tsx
@@ -18,6 +18,7 @@ import AssigneeMemberSelector from './AssigneeMemberSelector';
import AssigneeUserAvatar from './AssigneeUserAvatar';
import { formatTaskItemDate } from './formatTaskItemDate';
import TaskPriorityTag from './TaskPriorityTag';
+import TaskProjectChip from './TaskProjectChip';
import TaskStatusTag from './TaskStatusTag';
import TaskSubtaskProgressTag from './TaskSubtaskProgressTag';
import TaskTriggerTag from './TaskTriggerTag';
@@ -29,6 +30,8 @@ export type TaskItemRouteScope = 'agent' | 'global';
interface TaskItemProps {
/** Extra class on the row's surface, e.g. to hand its hover fill to a wrapper. */
className?: string;
+ /** The surface already belongs to one project, so its rows do not repeat it. */
+ hideProject?: boolean;
routeScope?: TaskItemRouteScope;
task: TaskListItem;
variant?: 'compact' | 'default';
@@ -50,7 +53,7 @@ const toTaskStatus = (status: string): TaskStatus =>
TASK_STATUS_SET.has(status as TaskStatus) ? (status as TaskStatus) : 'backlog';
const AgentTaskItem = memo<TaskItemProps>((props) => {
- const { className, task, routeScope = 'agent', variant = 'default' } = props;
+ const { className, hideProject, task, routeScope = 'agent', variant = 'default' } = props;
const { t, i18n } = useTranslation('common');
const { t: tChat } = useTranslation('chat');
const fetchTaskDetail = useTaskStore((s) => s.fetchTaskDetail);
@@ -192,6 +195,8 @@ const AgentTaskItem = memo<TaskItemProps>((props) => {
</Flexbox>
);
+ const projectNode = hideProject ? null : <TaskProjectChip projectId={task.projectId} />;
+
const scheduleNode = task.automationMode ? (
<TaskTriggerTag
automationMode={task.automationMode}
@@ -249,6 +254,7 @@ const AgentTaskItem = memo<TaskItemProps>((props) => {
<Flexbox horizontal align={'center'} gap={8} style={FLEX_MIN_WIDTH_0}>
<TaskPriorityTag priority={task.priority} taskIdentifier={task.id} />
<TaskLabelChips labels={task.labels} max={2} />
+ {projectNode}
{scheduleNode}
{timeNode}
</Flexbox>
@@ -270,6 +276,7 @@ const AgentTaskItem = memo<TaskItemProps>((props) => {
<Flexbox horizontal align={'center'} gap={4} justify={'space-between'}>
{titleRow}
<Flexbox horizontal align={'center'} flex={'none'} gap={8}>
+ {projectNode}
{scheduleNode}
{assigneeNode}
{timeNode}
diff --git a/src/features/AgentTasks/features/ProjectSelector.test.tsx b/src/features/AgentTasks/features/ProjectSelector.test.tsx
new file mode 100644
index 00000000000..b21a1a810db
--- /dev/null
+++ b/src/features/AgentTasks/features/ProjectSelector.test.tsx
@@ -0,0 +1,330 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import { type ReactNode, useState } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import ProjectSelector from './ProjectSelector';
+import TaskProjectValue from './TaskProjectValue';
+
+const state = vi.hoisted(() => ({
+ allowed: true,
+ enabled: true,
+ projects: undefined as { avatar?: string; id: string; name: string }[] | undefined,
+ revalidate: vi.fn(),
+ sync: { error: undefined as unknown, isHydrated: true, isValidating: false },
+ updateTask: vi.fn(),
+}));
+
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ Popover: ({
+ children,
+ content,
+ disabled,
+ onOpenChange,
+ open,
+ }: {
+ children: ReactNode;
+ content: ReactNode;
+ disabled?: boolean;
+ onOpenChange: (open: boolean) => void;
+ open: boolean;
+ }) => (
+ <>
+ <div
+ data-testid="popover-trigger"
+ onClickCapture={() => {
+ if (!disabled) onOpenChange(!open);
+ }}
+ >
+ {children}
+ </div>
+ {open && (
+ <div
+ data-testid="popover-content"
+ onKeyDown={(event) => {
+ if (event.key === 'Escape') onOpenChange(false);
+ }}
+ >
+ {content}
+ </div>
+ )}
+ </>
+ ),
+ Tooltip: ({ children, title }: { children: ReactNode; title?: string }) => (
+ <div title={title}>{children}</div>
+ ),
+}));
+
+vi.mock('@/features/NavPanel/components/NavItem', () => ({
+ default: ({
+ active,
+ extra,
+ onClick,
+ title,
+ }: {
+ active?: boolean;
+ extra?: ReactNode;
+ onClick: () => void;
+ title: string;
+ }) => (
+ <button data-active={active || undefined} onClick={onClick}>
+ {title}
+ {extra && <span data-testid="selected-mark" />}
+ </button>
+ ),
+}));
+
+vi.mock('@/features/NavPanel/components/SkeletonList', () => ({
+ default: () => <div data-testid="skeleton" />,
+}));
+
+vi.mock('@/features/Projects/ProjectAvatar', () => ({
+ default: ({ name }: { name: string }) => <span data-testid={`avatar-${name}`} />,
+}));
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: () => ({ allowed: state.allowed, reason: 'No permission' }),
+}));
+
+vi.mock('@/store/project', () => ({
+ useCurrentProjectList: () => state.projects ?? [],
+ useLoadedProjectList: () => state.projects,
+ useProjectStore: (selector: (s: unknown) => unknown) =>
+ selector({ useFetchProjectList: () => ({ ...state.sync, revalidate: state.revalidate }) }),
+}));
+
+vi.mock('@/store/task', () => ({
+ useTaskStore: (selector: (s: unknown) => unknown) => selector({ updateTask: state.updateTask }),
+}));
+
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: (s: unknown) => unknown) => selector({}),
+}));
+
+vi.mock('@/store/user/selectors', () => ({
+ labPreferSelectors: { enableProjects: () => state.enabled },
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+/** A host holding the pick, showing it the way the composer chip does. */
+const Host = ({ initial = null }: { initial?: string | null }) => {
+ const [value, setValue] = useState<string | null>(initial);
+ return (
+ <ProjectSelector value={value} onChange={setValue}>
+ <button data-testid="trigger">
+ <TaskProjectValue emptyLabel="empty" iconSize={14} projectId={value} />
+ </button>
+ </ProjectSelector>
+ );
+};
+
+const open = () => fireEvent.click(screen.getByTestId('trigger'));
+const search = () => screen.getByPlaceholderText('taskProject.searchPlaceholder');
+const trigger = () => screen.getByTestId('trigger');
+const activeOption = () => document.querySelector('[data-active]')?.textContent;
+
+beforeEach(() => {
+ state.allowed = true;
+ state.enabled = true;
+ state.projects = [
+ { id: 'p1', name: 'Apollo' },
+ { id: 'p2', name: 'Website Redesign' },
+ ];
+ state.revalidate.mockClear();
+ state.sync = { error: undefined, isHydrated: true, isValidating: false };
+ state.updateTask.mockReset();
+ state.updateTask.mockResolvedValue(undefined);
+});
+
+describe('ProjectSelector', () => {
+ it('filters by name and says when nothing matches', () => {
+ render(<Host />);
+ open();
+ expect(screen.getByText('Apollo')).toBeInTheDocument();
+
+ fireEvent.change(search(), { target: { value: 'redes' } });
+ expect(screen.queryByText('Apollo')).not.toBeInTheDocument();
+ expect(screen.getByText('Website Redesign')).toBeInTheDocument();
+
+ fireEvent.change(search(), { target: { value: 'zzz' } });
+ expect(screen.getByText('taskProject.noMatch')).toBeInTheDocument();
+ });
+
+ it('echoes a pick on the trigger, marks it, and closes', () => {
+ render(<Host />);
+ expect(trigger()).toHaveTextContent('empty');
+
+ open();
+ fireEvent.click(screen.getByText('Apollo'));
+ expect(trigger()).toHaveTextContent('Apollo');
+ expect(screen.queryByTestId('popover-content')).not.toBeInTheDocument();
+
+ open();
+ expect(
+ within(screen.getByTestId('popover-content')).getByTestId('selected-mark').parentElement,
+ ).toHaveTextContent('Apollo');
+ });
+
+ it('clears through the "no project" row', () => {
+ render(<Host initial="p1" />);
+ expect(trigger()).toHaveTextContent('Apollo');
+
+ open();
+ fireEvent.click(screen.getByText('taskProject.none'));
+ expect(trigger()).toHaveTextContent('empty');
+ });
+
+ it('navigates with the arrow keys, wraps, picks with Enter and closes with Esc', () => {
+ render(<Host />);
+ open();
+ expect(activeOption()).toContain('taskProject.none');
+
+ fireEvent.keyDown(search(), { key: 'ArrowDown' });
+ expect(activeOption()).toContain('Apollo');
+ fireEvent.keyDown(search(), { key: 'ArrowUp' });
+ fireEvent.keyDown(search(), { key: 'ArrowUp' });
+ expect(activeOption()).toContain('Website Redesign');
+
+ fireEvent.keyDown(search(), { key: 'Escape' });
+ expect(screen.queryByTestId('popover-content')).not.toBeInTheDocument();
+ expect(trigger()).toHaveTextContent('empty');
+
+ open();
+ fireEvent.change(search(), { target: { value: 'apol' } });
+ fireEvent.keyDown(search(), { key: 'Enter' });
+ expect(trigger()).toHaveTextContent('Apollo');
+ });
+
+ it('opens on the current project', () => {
+ render(<Host initial="p2" />);
+ open();
+ expect(activeOption()).toContain('Website Redesign');
+ });
+
+ it('leaves Enter alone during IME composition and for the composer submit', () => {
+ render(<Host />);
+ open();
+ fireEvent.change(search(), { target: { value: 'apol' } });
+ fireEvent.keyDown(search(), { isComposing: true, key: 'Enter' });
+ fireEvent.keyDown(search(), { key: 'Enter', metaKey: true });
+ expect(trigger()).toHaveTextContent('empty');
+ expect(screen.getByTestId('popover-content')).toBeInTheDocument();
+ });
+
+ it('opens from the keyboard', () => {
+ render(<Host />);
+ fireEvent.keyDown(screen.getByRole('button', { expanded: false }), { key: 'Enter' });
+ expect(screen.getByTestId('popover-content')).toBeInTheDocument();
+ });
+
+ it('saves to the task when there is no draft to hold the pick', async () => {
+ render(
+ <ProjectSelector taskIdentifier="T-1" value="p1">
+ <button data-testid="trigger">row</button>
+ </ProjectSelector>,
+ );
+ open();
+ fireEvent.click(screen.getByText('Website Redesign'));
+ expect(state.updateTask).toHaveBeenCalledWith('T-1', { projectId: 'p2' });
+
+ open();
+ fireEvent.click(screen.getByText('taskProject.none'));
+ expect(state.updateTask).toHaveBeenLastCalledWith('T-1', { projectId: null });
+ });
+
+ it('does not write when the current project is picked again', () => {
+ render(
+ <ProjectSelector taskIdentifier="T-1" value="p1">
+ <button data-testid="trigger">row</button>
+ </ProjectSelector>,
+ );
+ open();
+ fireEvent.click(screen.getByText('Apollo'));
+ expect(state.updateTask).not.toHaveBeenCalled();
+ });
+
+ it('swallows a failed save, which the store has already toasted and rolled back', async () => {
+ state.updateTask.mockRejectedValue(new Error('refused'));
+ render(
+ <ProjectSelector taskIdentifier="T-1" value="p1">
+ <button data-testid="trigger">row</button>
+ </ProjectSelector>,
+ );
+ open();
+ fireEvent.click(screen.getByText('taskProject.none'));
+ await waitFor(() => expect(state.updateTask).toHaveBeenCalled());
+ });
+
+ it('renders nothing while Projects is off', () => {
+ state.enabled = false;
+ render(<Host initial="p1" />);
+ expect(screen.queryByTestId('trigger')).not.toBeInTheDocument();
+ });
+
+ it('is read-only without write permission', () => {
+ state.allowed = false;
+ render(<Host initial="p1" />);
+ expect(screen.getByTitle('No permission')).toBeInTheDocument();
+ open();
+ expect(screen.queryByTestId('popover-content')).not.toBeInTheDocument();
+ });
+
+ it('is read-only with a host-given reason', () => {
+ render(
+ <ProjectSelector disabledReason="inherited" taskIdentifier="T-1" value="p1">
+ <button data-testid="trigger">row</button>
+ </ProjectSelector>,
+ );
+ expect(screen.getByTitle('inherited')).toBeInTheDocument();
+ open();
+ expect(screen.queryByTestId('popover-content')).not.toBeInTheDocument();
+ });
+
+ it('shows a skeleton while the list first loads', () => {
+ state.projects = undefined;
+ state.sync = { error: undefined, isHydrated: false, isValidating: true };
+ render(<Host />);
+ open();
+ expect(screen.getByTestId('skeleton')).toBeInTheDocument();
+ });
+
+ it('offers a retry when the list fails to load', () => {
+ state.projects = undefined;
+ state.sync = { error: new Error('offline'), isHydrated: true, isValidating: false };
+ render(<Host />);
+ open();
+ fireEvent.click(screen.getByText('retry'));
+ expect(state.revalidate).toHaveBeenCalled();
+ });
+
+ it('keeps the clear row and says so when the workspace has no projects', () => {
+ state.projects = [];
+ render(<Host />);
+ open();
+ expect(screen.getByText('taskProject.none')).toBeInTheDocument();
+ expect(screen.getByText('taskProject.empty')).toBeInTheDocument();
+ });
+
+ it('shows no other name for a project outside the list, and can still clear it', () => {
+ render(<Host initial="gone" />);
+ expect(trigger()).toHaveTextContent('taskProject.unavailable');
+ expect(trigger()).not.toHaveTextContent('Apollo');
+
+ open();
+ expect(screen.queryByTestId('selected-mark')).not.toBeInTheDocument();
+ fireEvent.click(screen.getByText('taskProject.none'));
+ expect(trigger()).toHaveTextContent('empty');
+ });
+
+ it('does not guess a name before the list has loaded', () => {
+ state.projects = undefined;
+ render(<Host initial="p1" />);
+ expect(trigger()).toHaveTextContent('taskProject.label');
+ });
+});
diff --git a/src/features/AgentTasks/features/ProjectSelector.tsx b/src/features/AgentTasks/features/ProjectSelector.tsx
new file mode 100644
index 00000000000..1db20416495
--- /dev/null
+++ b/src/features/AgentTasks/features/ProjectSelector.tsx
@@ -0,0 +1,281 @@
+import { Button, cssVar, Flexbox, Icon, Popover, Text, Tooltip } from '@lobehub/ui';
+import { cssVar as sxVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { CheckIcon, FolderXIcon } from 'lucide-react';
+import type { CSSProperties, KeyboardEvent, ReactNode } from 'react';
+import { memo, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import NavItem from '@/features/NavPanel/components/NavItem';
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import ProjectAvatar from '@/features/Projects/ProjectAvatar';
+import { resolveProjectListState } from '@/features/Projects/projectListState';
+import { usePermission } from '@/hooks/usePermission';
+import { type ProjectListItem, useCurrentProjectList, useProjectStore } from '@/store/project';
+import { useTaskStore } from '@/store/task';
+import { useUserStore } from '@/store/user';
+import { labPreferSelectors } from '@/store/user/selectors';
+
+import { filterProjectsByName } from './projectSelectorModel';
+
+const styles = stylex.create({
+ searchInput: {
+ 'width': '100%',
+ 'paddingBlock': 6,
+ 'paddingInline': 10,
+ 'borderWidth': 0,
+ 'borderBlockEndWidth': 1,
+ 'borderBlockEndStyle': 'solid',
+ 'borderBlockEndColor': sxVar.colorBorderSecondary,
+ 'fontFamily': 'inherit',
+ 'fontSize': 13,
+ 'color': sxVar.colorText,
+ 'backgroundColor': 'transparent',
+ 'outline': 'none',
+ '::placeholder': { color: sxVar.colorTextPlaceholder },
+ },
+});
+
+const triggerStyle: CSSProperties = {
+ alignItems: 'center',
+ display: 'inline-flex',
+ maxWidth: '100%',
+ minWidth: 0,
+};
+
+// Keeps the disabled wrapper out of layout, so the trigger sits as when enabled.
+const blockedContentStyle: CSSProperties = { display: 'contents', pointerEvents: 'none' };
+
+const NONE_KEY = '__none__';
+
+type ProjectOption =
+ { key: string; kind: 'none' } | { key: string; kind: 'project'; project: ProjectListItem };
+
+interface ProjectSelectorProps {
+ children: ReactNode;
+ /** Makes the picker read-only for a reason other than permission. */
+ disabledReason?: string;
+ fullWidth?: boolean;
+ /** Reports the pick instead of saving it, for a composer holding it in a draft. */
+ onChange?: (projectId: string | null) => void;
+ /** The task a pick is saved to when there is no `onChange`. */
+ taskIdentifier?: string;
+ value?: string | null;
+}
+
+/**
+ * Single-select project picker over the current workspace's projects: search by
+ * name, arrow keys + Enter to pick, Esc to close. Renders nothing while the
+ * Projects lab is off, so no host can offer a feature the user has not enabled.
+ */
+const ProjectSelector = memo<ProjectSelectorProps>(
+ ({ children, disabledReason, fullWidth, onChange, taskIdentifier, value }) => {
+ const { t } = useTranslation('chat');
+ const enabled = useUserStore(labPreferSelectors.enableProjects);
+ const { allowed: canEdit, reason } = usePermission('create_content');
+ const updateTask = useTaskStore((s) => s.updateTask);
+
+ const [open, setOpen] = useState(false);
+ const [search, setSearch] = useState('');
+ const [activeIndex, setActiveIndex] = useState(0);
+ const listRef = useRef<HTMLDivElement>(null);
+
+ const { error, isHydrated, isValidating, revalidate } = useProjectStore(
+ (s) => s.useFetchProjectList,
+ )(enabled);
+ const projects = useCurrentProjectList();
+ // An empty list is only "no projects" once the fetch has settled.
+ const listState = resolveProjectListState({
+ error,
+ isHydrated,
+ isValidating,
+ projects: projects.length > 0 ? projects : undefined,
+ });
+
+ const query = search.trim();
+ const noneLabel = t('taskProject.none');
+ const matches = useMemo(() => filterProjectsByName(projects, query), [projects, query]);
+ const options = useMemo<ProjectOption[]>(() => {
+ const showNone = !query || noneLabel.toLowerCase().includes(query.toLowerCase());
+ return [
+ ...(showNone ? [{ key: NONE_KEY, kind: 'none' as const }] : []),
+ ...matches.map((project) => ({ key: project.id, kind: 'project' as const, project })),
+ ];
+ }, [matches, noneLabel, query]);
+ const selectedKey = value ?? NONE_KEY;
+
+ // Rest on the current project when opening; a search starts from the top match.
+ useEffect(() => {
+ if (query) {
+ setActiveIndex(0);
+ return;
+ }
+ const selectedIndex = options.findIndex((option) => option.key === selectedKey);
+ setActiveIndex(Math.max(selectedIndex, 0));
+ }, [open, options, query, selectedKey]);
+
+ useEffect(() => {
+ listRef.current
+ ?.querySelector<HTMLElement>(`[data-project-index="${activeIndex}"]`)
+ ?.scrollIntoView({ block: 'nearest' });
+ }, [activeIndex]);
+
+ if (!enabled) return null;
+
+ const handleOpenChange = (next: boolean) => {
+ setOpen(next);
+ if (!next) setSearch('');
+ };
+
+ const handleSelect = (option: ProjectOption) => {
+ handleOpenChange(false);
+ const projectId = option.kind === 'project' ? option.project.id : null;
+ if (projectId === (value ?? null)) return;
+ if (onChange) {
+ onChange(projectId);
+ return;
+ }
+ // A failed save is rolled back and toasted by the store.
+ if (taskIdentifier) void updateTask(taskIdentifier, { projectId }).catch(() => {});
+ };
+
+ const handleSearchKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
+ // Enter confirming an IME composition belongs to the search text, and
+ // Cmd/Ctrl+Enter to the composer's submit.
+ if (event.nativeEvent.isComposing || event.metaKey || event.ctrlKey) return;
+ if (options.length === 0) return;
+ if (event.key === 'ArrowDown') {
+ event.preventDefault();
+ setActiveIndex((index) => (index + 1) % options.length);
+ } else if (event.key === 'ArrowUp') {
+ event.preventDefault();
+ setActiveIndex((index) => (index - 1 + options.length) % options.length);
+ } else if (event.key === 'Enter') {
+ event.preventDefault();
+ const target = options[activeIndex];
+ if (target) handleSelect(target);
+ }
+ };
+
+ const renderOption = (option: ProjectOption, index: number) => (
+ <div data-project-index={index} key={option.key} onMouseEnter={() => setActiveIndex(index)}>
+ <NavItem
+ active={index === activeIndex}
+ style={{ flexShrink: 0 }}
+ title={option.kind === 'project' ? option.project.name : noneLabel}
+ extra={
+ option.key === selectedKey ? (
+ <Icon color={cssVar.colorTextSecondary} icon={CheckIcon} size={14} />
+ ) : null
+ }
+ icon={
+ option.kind === 'project' ? (
+ <ProjectAvatar avatar={option.project.avatar} name={option.project.name} size={18} />
+ ) : (
+ <Icon color={cssVar.colorTextDescription} icon={FolderXIcon} size={16} />
+ )
+ }
+ onClick={() => handleSelect(option)}
+ />
+ </div>
+ );
+
+ const hint = (text: string) => (
+ <Flexbox align={'center'} justify={'center'} padding={16}>
+ <Text fontSize={12} type={'secondary'}>
+ {text}
+ </Text>
+ </Flexbox>
+ );
+
+ const renderBody = () => {
+ if (listState === 'loading') return <SkeletonList rows={4} />;
+ if (listState === 'error')
+ return (
+ <Flexbox align={'center'} gap={8} justify={'center'} padding={16}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('taskProject.loadFailed')}
+ </Text>
+ <Button onClick={() => revalidate()}>{t('retry', { ns: 'common' })}</Button>
+ </Flexbox>
+ );
+ return (
+ <>
+ {options.length > 0 && (
+ <Flexbox
+ gap={4}
+ padding={8}
+ ref={listRef}
+ style={{ maxHeight: '50vh', overflowY: 'auto', width: '100%' }}
+ >
+ {options.map(renderOption)}
+ </Flexbox>
+ )}
+ {matches.length === 0 && hint(t(query ? 'taskProject.noMatch' : 'taskProject.empty'))}
+ </>
+ );
+ };
+
+ const blockedReason = !canEdit ? reason : disabledReason;
+ const blocked = !!blockedReason || !canEdit;
+ const wrapperStyle = fullWidth ? { ...triggerStyle, width: '100%' } : triggerStyle;
+
+ return (
+ <Popover
+ disabled={blocked}
+ open={open}
+ placement={'bottomLeft'}
+ styles={{ content: { padding: 0, width: 260 } }}
+ trigger={'click'}
+ content={
+ <Flexbox onClick={(event) => event.stopPropagation()}>
+ <input
+ autoFocus
+ {...stylex.props(styles.searchInput)}
+ aria-label={t('taskProject.searchPlaceholder')}
+ placeholder={t('taskProject.searchPlaceholder')}
+ value={search}
+ onChange={(event) => setSearch(event.target.value)}
+ onKeyDown={handleSearchKeyDown}
+ />
+ {renderBody()}
+ </Flexbox>
+ }
+ onOpenChange={handleOpenChange}
+ >
+ {blocked ? (
+ <Tooltip title={blockedReason}>
+ <div
+ aria-disabled
+ role={'button'}
+ style={{ ...wrapperStyle, cursor: 'not-allowed', opacity: 0.5 }}
+ onClick={(event) => event.stopPropagation()}
+ >
+ <span style={blockedContentStyle}>{children}</span>
+ </div>
+ </Tooltip>
+ ) : (
+ <div
+ aria-expanded={open}
+ aria-haspopup={'dialog'}
+ role={'button'}
+ style={wrapperStyle}
+ tabIndex={0}
+ onClick={(event) => event.stopPropagation()}
+ onKeyDown={(event) => {
+ if (event.key !== 'Enter' && event.key !== ' ') return;
+ event.preventDefault();
+ handleOpenChange(true);
+ }}
+ >
+ {children}
+ </div>
+ )}
+ </Popover>
+ );
+ },
+);
+
+ProjectSelector.displayName = 'ProjectSelector';
+
+export default ProjectSelector;
diff --git a/src/features/AgentTasks/features/TaskProjectChip.tsx b/src/features/AgentTasks/features/TaskProjectChip.tsx
new file mode 100644
index 00000000000..5f260bc09f0
--- /dev/null
+++ b/src/features/AgentTasks/features/TaskProjectChip.tsx
@@ -0,0 +1,63 @@
+import { cssVar, Text } from '@lobehub/ui';
+import { cssVar as sxVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+
+import ProjectAvatar from '@/features/Projects/ProjectAvatar';
+import { projectListItemSelector, useProjectStore } from '@/store/project';
+import { useUserStore } from '@/store/user';
+import { labPreferSelectors } from '@/store/user/selectors';
+
+const styles = stylex.create({
+ chip: {
+ display: 'inline-flex',
+ flexGrow: '0',
+ flexShrink: '1',
+ flexBasis: 'auto',
+ gap: 4,
+ alignItems: 'center',
+ minWidth: 0,
+ maxWidth: 140,
+ height: 20,
+ paddingInline: 6,
+ borderWidth: 1,
+ borderStyle: 'solid',
+ // A translucent fill rather than a border token: those are opaque greys that
+ // match the dark board card, while this stays visible on whichever row, card
+ // or group header it sits on.
+ borderColor: sxVar.colorFill,
+ borderRadius: 6,
+ lineHeight: 1,
+ },
+});
+
+interface TaskProjectChipProps {
+ projectId?: string | null;
+}
+
+/**
+ * The project a task belongs to, for list rows, board cards and group headers.
+ *
+ * Reads one row of the cached project list through a narrow selector, so a
+ * thousand rows cost no request and re-render only when their own project
+ * changes; the page that hosts them keeps that list fresh (`useTaskProjectList`).
+ * No project, or one outside the list (deleted, or private to someone else),
+ * renders nothing: never a placeholder or a raw id.
+ */
+const TaskProjectChip = ({ projectId }: TaskProjectChipProps) => {
+ const project = useProjectStore(projectListItemSelector(projectId));
+ const enabled = useUserStore(labPreferSelectors.enableProjects);
+
+ if (!enabled || !project) return null;
+
+ return (
+ <span data-testid={'task-project-chip'} title={project.name} {...stylex.props(styles.chip)}>
+ <ProjectAvatar avatar={project.avatar} name={project.name} size={14} />
+ {/* `type="secondary"` resolves to the tertiary text colour, under AA at 12px. */}
+ <Text ellipsis color={cssVar.colorTextSecondary} fontSize={12}>
+ {project.name}
+ </Text>
+ </span>
+ );
+};
+
+export default TaskProjectChip;
diff --git a/src/features/AgentTasks/features/TaskProjectPickerChip.tsx b/src/features/AgentTasks/features/TaskProjectPickerChip.tsx
new file mode 100644
index 00000000000..77dfe240903
--- /dev/null
+++ b/src/features/AgentTasks/features/TaskProjectPickerChip.tsx
@@ -0,0 +1,45 @@
+import { Block } from '@lobehub/ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import ProjectSelector from './ProjectSelector';
+import TaskProjectValue from './TaskProjectValue';
+
+interface TaskProjectPickerChipProps {
+ onChange: (projectId: string | null) => void;
+ value: string | null;
+}
+
+const CHIP_TEXT_STYLE = { maxWidth: 160 };
+
+/** The task composers' project chip. */
+const TaskProjectPickerChip = memo<TaskProjectPickerChipProps>(({ onChange, value }) => {
+ const { t } = useTranslation('chat');
+
+ return (
+ <ProjectSelector value={value} onChange={onChange}>
+ <Block
+ clickable
+ horizontal
+ align="center"
+ gap={6}
+ height={24}
+ paddingBlock={3}
+ paddingInline={8}
+ variant={'borderless'}
+ >
+ <TaskProjectValue
+ emptyLabel={t('taskProject.label')}
+ fontSize={12}
+ iconSize={14}
+ projectId={value}
+ textStyle={CHIP_TEXT_STYLE}
+ />
+ </Block>
+ </ProjectSelector>
+ );
+});
+
+TaskProjectPickerChip.displayName = 'TaskProjectPickerChip';
+
+export default TaskProjectPickerChip;
diff --git a/src/features/AgentTasks/features/TaskProjectValue.tsx b/src/features/AgentTasks/features/TaskProjectValue.tsx
new file mode 100644
index 00000000000..37c8df326de
--- /dev/null
+++ b/src/features/AgentTasks/features/TaskProjectValue.tsx
@@ -0,0 +1,62 @@
+import { cssVar, Icon, Text } from '@lobehub/ui';
+import { FolderKanbanIcon } from 'lucide-react';
+import { type CSSProperties, memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import ProjectAvatar from '@/features/Projects/ProjectAvatar';
+import { useLoadedProjectList } from '@/store/project';
+
+import { resolveTaskProjectDisplay } from './projectSelectorModel';
+
+interface TaskProjectValueProps {
+ /** Shown when no project is picked. */
+ emptyLabel: string;
+ fontSize?: number;
+ iconSize: number;
+ projectId?: string | null;
+ textStyle?: CSSProperties;
+ weight?: number;
+}
+
+/** The current project as icon + name, in the shape a picker trigger shows it. */
+const TaskProjectValue = memo<TaskProjectValueProps>(
+ ({ emptyLabel, fontSize, iconSize, projectId, textStyle, weight }) => {
+ const { t } = useTranslation('chat');
+ const projects = useLoadedProjectList();
+ const display = resolveTaskProjectDisplay(projectId, projects);
+ const style = { minWidth: 0, ...textStyle };
+
+ if (display.kind === 'project')
+ return (
+ <>
+ <ProjectAvatar
+ avatar={display.project.avatar}
+ name={display.project.name}
+ size={iconSize}
+ />
+ <Text ellipsis fontSize={fontSize} style={style} weight={weight}>
+ {display.project.name}
+ </Text>
+ </>
+ );
+
+ const labels = {
+ none: emptyLabel,
+ pending: t('taskProject.label'),
+ unavailable: t('taskProject.unavailable'),
+ };
+
+ return (
+ <>
+ <Icon color={cssVar.colorTextDescription} icon={FolderKanbanIcon} size={iconSize} />
+ <Text color={cssVar.colorTextDescription} fontSize={fontSize} style={style} weight={weight}>
+ {labels[display.kind]}
+ </Text>
+ </>
+ );
+ },
+);
+
+TaskProjectValue.displayName = 'TaskProjectValue';
+
+export default TaskProjectValue;
diff --git a/src/features/AgentTasks/features/projectSelectorModel.test.ts b/src/features/AgentTasks/features/projectSelectorModel.test.ts
new file mode 100644
index 00000000000..0bce5d998e7
--- /dev/null
+++ b/src/features/AgentTasks/features/projectSelectorModel.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ProjectListItem } from '@/store/project';
+
+import { filterProjectsByName, resolveTaskProjectDisplay } from './projectSelectorModel';
+
+const projects = [
+ { id: 'p1', name: 'Apollo' },
+ { id: 'p2', name: 'Website Redesign' },
+] as ProjectListItem[];
+
+describe('filterProjectsByName', () => {
+ it('keeps everything for a blank search', () => {
+ expect(filterProjectsByName(projects, ' ')).toEqual(projects);
+ });
+
+ it('matches any part of the name, ignoring case and outer spaces', () => {
+ expect(filterProjectsByName(projects, ' REDES ')).toEqual([projects[1]]);
+ expect(filterProjectsByName(projects, 'nope')).toEqual([]);
+ });
+});
+
+describe('resolveTaskProjectDisplay', () => {
+ it('has no project without an id, whatever the list says', () => {
+ expect(resolveTaskProjectDisplay(null, projects)).toEqual({ kind: 'none' });
+ expect(resolveTaskProjectDisplay(undefined, undefined)).toEqual({ kind: 'none' });
+ });
+
+ it('waits for the list before judging an id', () => {
+ expect(resolveTaskProjectDisplay('p1', undefined)).toEqual({ kind: 'pending' });
+ });
+
+ it('names a project only from its own row', () => {
+ expect(resolveTaskProjectDisplay('p2', projects)).toEqual({
+ kind: 'project',
+ project: projects[1],
+ });
+ expect(resolveTaskProjectDisplay('gone', projects)).toEqual({ kind: 'unavailable' });
+ });
+});
diff --git a/src/features/AgentTasks/features/projectSelectorModel.ts b/src/features/AgentTasks/features/projectSelectorModel.ts
new file mode 100644
index 00000000000..593a9611d95
--- /dev/null
+++ b/src/features/AgentTasks/features/projectSelectorModel.ts
@@ -0,0 +1,33 @@
+import type { ProjectListItem } from '@/store/project';
+
+/** Case-insensitive name match; a blank search keeps every project. */
+export const filterProjectsByName = <T extends Pick<ProjectListItem, 'name'>>(
+ projects: T[],
+ search: string,
+): T[] => {
+ const query = search.trim().toLowerCase();
+ if (!query) return projects;
+ return projects.filter((project) => project.name.toLowerCase().includes(query));
+};
+
+export type TaskProjectDisplay =
+ | { kind: 'none' }
+ /** The list has not loaded, so nothing can be said about this id yet. */
+ | { kind: 'pending' }
+ | { kind: 'project'; project: ProjectListItem }
+ /** Filed under a project the caller cannot see: deleted, or private to someone else. */
+ | { kind: 'unavailable' };
+
+/**
+ * What to show for a task's project. A name only ever comes from the row with
+ * that exact id, so a project outside the list can never show another's name.
+ */
+export const resolveTaskProjectDisplay = (
+ projectId: string | null | undefined,
+ projects: ProjectListItem[] | undefined,
+): TaskProjectDisplay => {
+ if (!projectId) return { kind: 'none' };
+ if (!projects) return { kind: 'pending' };
+ const project = projects.find((item) => item.id === projectId);
+ return project ? { kind: 'project', project } : { kind: 'unavailable' };
+};
diff --git a/src/features/AgentTasks/features/useTaskProjectChoice.test.ts b/src/features/AgentTasks/features/useTaskProjectChoice.test.ts
new file mode 100644
index 00000000000..da0987f0fd2
--- /dev/null
+++ b/src/features/AgentTasks/features/useTaskProjectChoice.test.ts
@@ -0,0 +1,95 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useTaskProjectChoice } from './useTaskProjectChoice';
+
+const state = vi.hoisted(() => ({
+ enabled: true,
+ fetch: vi.fn(),
+ projects: undefined as { id: string; name: string }[] | undefined,
+ sync: { error: undefined as unknown, isValidating: false },
+}));
+
+vi.mock('@/store/project', () => ({
+ useLoadedProjectList: () => state.projects,
+ useProjectStore: (selector: (s: unknown) => unknown) =>
+ selector({
+ useFetchProjectList: (enabled: boolean) => {
+ state.fetch(enabled);
+ return state.sync;
+ },
+ }),
+}));
+
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: (s: unknown) => unknown) => selector({}),
+}));
+
+vi.mock('@/store/user/selectors', () => ({
+ labPreferSelectors: { enableProjects: () => state.enabled },
+}));
+
+beforeEach(() => {
+ state.enabled = true;
+ state.fetch.mockClear();
+ state.projects = [{ id: 'p1', name: 'Apollo' }];
+ state.sync = { error: undefined, isValidating: false };
+});
+
+describe('useTaskProjectChoice', () => {
+ it('starts empty outside a project and sends nothing', () => {
+ const { result } = renderHook(() => useTaskProjectChoice());
+ expect(result.current.projectChoice).toBeNull();
+ expect(result.current.createProjectId).toBeUndefined();
+ });
+
+ it('prefills the page project, which the user can clear', () => {
+ const { result } = renderHook(() => useTaskProjectChoice('p1'));
+ expect(result.current.createProjectId).toBe('p1');
+
+ act(() => result.current.setProjectChoice(null));
+ expect(result.current.projectChoice).toBeNull();
+ expect(result.current.createProjectId).toBeUndefined();
+ });
+
+ it('keeps the page project while Projects is off, but never a hidden choice', () => {
+ state.enabled = false;
+ const scoped = renderHook(() => useTaskProjectChoice('p1'));
+ expect(scoped.result.current.createProjectId).toBe('p1');
+
+ const unscoped = renderHook(() => useTaskProjectChoice());
+ act(() => unscoped.result.current.setProjectChoice('p1'));
+ expect(unscoped.result.current.createProjectId).toBeUndefined();
+ expect(state.fetch).toHaveBeenCalledWith(false);
+ });
+
+ it('does not fetch or send for a composer without a picker', () => {
+ const { result } = renderHook(() => useTaskProjectChoice(undefined, false));
+ expect(state.fetch).toHaveBeenCalledWith(false);
+ expect(result.current.createProjectId).toBeUndefined();
+ });
+
+ it('drops a restored choice once a fresh list proves it is gone', () => {
+ const { result } = renderHook(() => useTaskProjectChoice());
+ act(() => result.current.setProjectChoice('gone'));
+ expect(result.current.projectChoice).toBeNull();
+ });
+
+ it.each([
+ ['the list is still revalidating', { isValidating: true }],
+ ['the list failed to load', { error: new Error('offline') }],
+ ])('keeps a choice it cannot judge while %s', (_label, sync) => {
+ state.sync = { error: undefined, isValidating: false, ...sync };
+ const { result } = renderHook(() => useTaskProjectChoice());
+ act(() => result.current.setProjectChoice('gone'));
+ expect(result.current.projectChoice).toBe('gone');
+ });
+
+ it('leaves the page project to the server even when it is not listed', () => {
+ const { result } = renderHook(() => useTaskProjectChoice('private-project'));
+ expect(result.current.createProjectId).toBe('private-project');
+ });
+});
diff --git a/src/features/AgentTasks/features/useTaskProjectChoice.ts b/src/features/AgentTasks/features/useTaskProjectChoice.ts
new file mode 100644
index 00000000000..30a7f4ba1fd
--- /dev/null
+++ b/src/features/AgentTasks/features/useTaskProjectChoice.ts
@@ -0,0 +1,41 @@
+import { useEffect, useState } from 'react';
+
+import { useLoadedProjectList, useProjectStore } from '@/store/project';
+import { useUserStore } from '@/store/user';
+import { labPreferSelectors } from '@/store/user/selectors';
+
+/**
+ * The project a task composer will file its task under.
+ *
+ * `defaultProjectId` is the page's own project, prefilled and kept when nothing
+ * is shown to change it. `active: false` is for a composer without a picker (a
+ * subtask takes its parent's project on the server).
+ */
+export const useTaskProjectChoice = (defaultProjectId?: string, active = true) => {
+ const enabled = useUserStore(labPreferSelectors.enableProjects) && active;
+ const { error, isValidating } = useProjectStore((s) => s.useFetchProjectList)(enabled);
+ const projects = useLoadedProjectList();
+ const [projectChoice, setProjectChoice] = useState<string | null>(defaultProjectId ?? null);
+
+ // A restored draft can name a project deleted since. Creating with it would
+ // fail on the server, and the chip could not name it either, so let it go once
+ // a fresh list proves it is gone. The page's own project is the server's call.
+ const isStale =
+ enabled &&
+ !!projectChoice &&
+ projectChoice !== defaultProjectId &&
+ !!projects &&
+ !isValidating &&
+ !error &&
+ !projects.some((project) => project.id === projectChoice);
+ useEffect(() => {
+ if (isStale) setProjectChoice(defaultProjectId ?? null);
+ }, [defaultProjectId, isStale]);
+
+ return {
+ /** What to send on create. With the picker hidden, a draft's choice must not apply unseen. */
+ createProjectId: enabled ? (projectChoice ?? undefined) : defaultProjectId,
+ projectChoice,
+ setProjectChoice,
+ };
+};
diff --git a/src/features/AgentTasks/features/useTaskProjectList.ts b/src/features/AgentTasks/features/useTaskProjectList.ts
new file mode 100644
index 00000000000..06a0f95adbd
--- /dev/null
+++ b/src/features/AgentTasks/features/useTaskProjectList.ts
@@ -0,0 +1,15 @@
+import { useLoadedProjectList, useProjectStore } from '@/store/project';
+import { useUserStore } from '@/store/user';
+import { labPreferSelectors } from '@/store/user/selectors';
+
+/**
+ * The project list a task surface maps ids through. Callers share one cached
+ * request; `projects` stays `undefined` until it first loads.
+ */
+export const useTaskProjectList = () => {
+ const enabled = useUserStore(labPreferSelectors.enableProjects);
+ const { error, revalidate } = useProjectStore((s) => s.useFetchProjectList)(enabled);
+ const projects = useLoadedProjectList();
+
+ return { enabled, error, projects, retry: revalidate };
+};
diff --git a/src/services/task.ts b/src/services/task.ts
index 03272e12306..be4de90244b 100644
--- a/src/services/task.ts
+++ b/src/services/task.ts
@@ -61,7 +61,7 @@ class TaskService {
completedWithin?: TaskCompletedWindow;
excludeStatuses?: TaskStatus[];
filter?: TaskListFilter;
- groupBy?: 'assignee' | 'label' | 'member' | 'priority';
+ groupBy?: 'assignee' | 'label' | 'member' | 'priority' | 'project';
groups?: Array<{
key: string;
limit?: number;
@@ -183,6 +183,8 @@ class TaskService {
name?: string;
parentTaskId?: string | null;
priority?: number;
+ // null takes the task out of its project
+ projectId?: string | null;
// schedulePattern: cron expression for scheduled automation (e.g. '0 9 * * *')
schedulePattern?: string | null;
// scheduleTimezone: IANA timezone for the cron expression (e.g. 'Asia/Shanghai')
diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.ts
index f323257f8ee..0fa84913668 100644
--- a/src/store/global/initialState.ts
+++ b/src/store/global/initialState.ts
@@ -479,7 +479,7 @@ export interface SystemStatus {
*/
completedTasks?: 'all' | 'day' | 'month' | 'none' | 'week';
/** `label:<groupId>` groups by one label group. */
- groupBy: 'assignee' | 'member' | 'none' | 'priority' | 'status' | `label:${string}`;
+ groupBy: 'assignee' | 'member' | 'none' | 'priority' | 'project' | 'status' | `label:${string}`;
/** @deprecated Replaced by `completedTasks`; read once to migrate. */
hideCompleted?: boolean;
nestedSubTasks: boolean;
@@ -487,7 +487,8 @@ export interface SystemStatus {
orderCompletedByRecency: boolean;
orderDirection: 'asc' | 'desc';
showSubTasks: boolean;
- subGroupBy: 'assignee' | 'member' | 'none' | 'priority' | 'status' | `label:${string}`;
+ subGroupBy:
+ 'assignee' | 'member' | 'none' | 'priority' | 'project' | 'status' | `label:${string}`;
};
/**
* Home team board: the attention list folded to a slim rail so the timeline
diff --git a/src/store/project/index.ts b/src/store/project/index.ts
index c934b01a125..36aa308a0a2 100644
--- a/src/store/project/index.ts
+++ b/src/store/project/index.ts
@@ -1,6 +1,7 @@
export type { ProjectDetail, ProjectListItem } from './store';
export {
projectByRefSelector,
+ projectListItemSelector,
useCurrentProjectDetail,
useCurrentProjectList,
useLoadedProjectList,
diff --git a/src/store/project/store.ts b/src/store/project/store.ts
index 1ffd9f80b72..aa800cdf24c 100644
--- a/src/store/project/store.ts
+++ b/src/store/project/store.ts
@@ -347,6 +347,12 @@ export const useCurrentProjectList = () =>
export const useLoadedProjectList = () =>
useProjectStore((state): ProjectListItem[] | undefined => state.projectListMap[PROJECT_LIST_KEY]);
+/** One row of the cached project list; `undefined` when it is not (yet) in the list. */
+export const projectListItemSelector =
+ (id: string | null | undefined) =>
+ (state: ProjectStoreState): ProjectListItem | undefined =>
+ id ? state.projectListMap[PROJECT_LIST_KEY]?.find((project) => project.id === id) : undefined;
+
export const useCurrentProjectDetail = (idOrSlug?: string) =>
useProjectStore((state) => (idOrSlug ? state.projectDetailMap[idOrSlug] : undefined));
diff --git a/src/store/task/selectors/detailSelectors.test.ts b/src/store/task/selectors/detailSelectors.test.ts
index 15461a8b8e7..b7aeb8d4914 100644
--- a/src/store/task/selectors/detailSelectors.test.ts
+++ b/src/store/task/selectors/detailSelectors.test.ts
@@ -60,6 +60,19 @@ describe('taskDetailSelectors', () => {
expect(taskDetailSelectors.activeTaskStatus(state)).toBe('running');
});
+ it('should return activeTaskProjectId', () => {
+ const withProject = createState({
+ activeTaskId: 'T-1',
+ taskDetailMap: { 'T-1': { identifier: 'T-1', projectId: 'p1' } as TaskDetailData },
+ });
+ expect(taskDetailSelectors.activeTaskProjectId(withProject)).toBe('p1');
+ });
+
+ it('should return no project when the detail has none or is missing', () => {
+ expect(taskDetailSelectors.activeTaskProjectId(state)).toBeNull();
+ expect(taskDetailSelectors.activeTaskProjectId(createState())).toBeNull();
+ });
+
it('should return activeTaskPriority', () => {
expect(taskDetailSelectors.activeTaskPriority(state)).toBe(2);
});
diff --git a/src/store/task/selectors/detailSelectors.ts b/src/store/task/selectors/detailSelectors.ts
index 341c97fcccd..10262b3bb58 100644
--- a/src/store/task/selectors/detailSelectors.ts
+++ b/src/store/task/selectors/detailSelectors.ts
@@ -29,6 +29,8 @@ const activeTaskStatus = (s: TaskStoreState) => activeTaskDetail(s)?.status;
const activeTaskPriority = (s: TaskStoreState) => activeTaskDetail(s)?.priority ?? 0;
+const activeTaskProjectId = (s: TaskStoreState) => activeTaskDetail(s)?.projectId ?? null;
+
const EMPTY_LABELS: NonNullable<TaskDetailData['labels']> = [];
const activeTaskLabels = (s: TaskStoreState) => activeTaskDetail(s)?.labels ?? EMPTY_LABELS;
@@ -201,6 +203,7 @@ export const taskDetailSelectors = {
activeTaskParent,
activeTaskPeriodicInterval,
activeTaskPriority,
+ activeTaskProjectId,
activeTaskProvider,
activeTaskRuntimeConfig,
activeTaskScheduleMaxExecutions,
diff --git a/src/store/task/slices/detail/action.project.test.ts b/src/store/task/slices/detail/action.project.test.ts
new file mode 100644
index 00000000000..e14da566856
--- /dev/null
+++ b/src/store/task/slices/detail/action.project.test.ts
@@ -0,0 +1,232 @@
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope, createReplicaState, replicaKeys } from '@/libs/replica';
+import { mutate, useClientDataSWR } from '@/libs/swr';
+import { taskService } from '@/services/task';
+import { saveToast } from '@/store/utils/saveToast';
+
+import { useTaskStore } from '../../store';
+import { taskListResource } from '../list/projection';
+import { taskDetailRefreshes } from './testUtils';
+
+vi.mock('@/services/task', () => ({
+ taskService: {
+ find: vi.fn(),
+ getDetail: vi.fn(),
+ groupList: vi.fn(),
+ list: vi.fn(),
+ update: vi.fn(),
+ },
+}));
+
+vi.mock('@/libs/swr', () => ({
+ mutate: vi.fn().mockResolvedValue(undefined),
+ useClientDataSWR: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),
+}));
+
+vi.mock('@/store/utils/saveToast', () => ({ saveToast: vi.fn() }));
+
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ ...(await import('~base-ui-stubs')).baseUiStubs,
+}));
+
+const row = (id: string, projectId: string | null) =>
+ ({ id, identifier: id, projectId, status: 'backlog' }) as any;
+
+const OLD_LIST = 'old-project-list';
+const GLOBAL_LIST = 'global-list';
+const OLD_BOARD = 'old-project-board';
+
+const seed = () =>
+ useTaskStore.setState({
+ activeTaskId: 'T-1',
+ taskDetailMap: {
+ 'T-1': { id: 'T-1', identifier: 'T-1', instruction: 'x', projectId: 'p1', status: 'backlog' },
+ },
+ taskGroupListMap: {
+ [OLD_BOARD]: {
+ groupBy: 'status',
+ groups: [{ key: 'backlog', tasks: [row('T-1', 'p1'), row('T-2', 'p1')], total: 2 }],
+ projectId: 'p1',
+ },
+ },
+ taskListMap: {
+ [GLOBAL_LIST]: { items: [row('T-1', 'p1'), row('T-2', 'p1')], total: 2 },
+ [OLD_LIST]: { items: [row('T-1', 'p1'), row('T-2', 'p1')], projectId: 'p1', total: 2 },
+ },
+ });
+
+const state = () => useTaskStore.getState();
+const ids = (key: string) => state().taskListMap[key].items.map((task) => task.id);
+const boardIds = () => state().taskGroupListMap[OLD_BOARD].groups[0].tasks.map((task) => task.id);
+
+const holdUpdate = () => {
+ let settle!: { reject: (error: Error) => void; resolve: () => void };
+ vi.mocked(taskService.update).mockReturnValue(
+ new Promise((resolve, reject) => {
+ settle = { reject, resolve: () => resolve({ success: true } as any) };
+ }) as any,
+ );
+ return settle;
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(mutate).mockResolvedValue(undefined);
+ vi.mocked(taskService.getDetail).mockResolvedValue({ data: undefined } as any);
+ useTaskStore.setState({
+ listVisibility: 'all',
+ taskDetailMap: {},
+ taskDetailReplica: createReplicaState(),
+ taskGroupListMap: {},
+ taskGroupListReplica: createReplicaState(),
+ taskListMap: {},
+ taskListReplica: createReplicaState(),
+ taskRefIndex: { 'T-1': 'T-1', 'T-2': 'T-2' },
+ taskSaveStatusMap: {},
+ });
+});
+
+describe('updateTask projectId', () => {
+ it.each([
+ ['moving', 'p2'],
+ ['clearing', null],
+ ])('%s shows at once in detail and every list, and refreshes them', async (_label, projectId) => {
+ seed();
+ const update = holdUpdate();
+
+ const pending = state().updateTask('T-1', { projectId });
+
+ expect(state().taskDetailMap['T-1'].projectId).toBe(projectId);
+ // Gone from the old project's list and board, the other row untouched.
+ expect(ids(OLD_LIST)).toEqual(['T-2']);
+ expect(state().taskListMap[OLD_LIST].total).toBe(1);
+ expect(boardIds()).toEqual(['T-2']);
+ // Still in the global list, now carrying the new project.
+ expect(ids(GLOBAL_LIST)).toEqual(['T-1', 'T-2']);
+ expect(state().taskListMap[GLOBAL_LIST].items[0].projectId).toBe(projectId);
+
+ update.resolve();
+ await pending;
+
+ expect(taskService.update).toHaveBeenCalledWith('T-1', { projectId });
+ // Revalidating every list is what fills the list of the project it moved into.
+ const listSyncKey = replicaKeys.sync(
+ taskListResource.name,
+ taskListResource.version,
+ cacheScope.get(),
+ 'any-list',
+ {},
+ );
+ const revalidates = vi
+ .mocked(mutate)
+ .mock.calls.some(([match]) => typeof match === 'function' && (match as any)(listSyncKey));
+ expect(revalidates).toBe(true);
+ expect(taskDetailRefreshes('T-1').length).toBeGreaterThan(0);
+ expect(ids(OLD_LIST)).toEqual(['T-2']);
+ });
+
+ it('restores every list exactly when the server refuses the move', async () => {
+ seed();
+ const update = holdUpdate();
+
+ const pending = state().updateTask('T-1', { projectId: 'p-foreign' });
+ expect(ids(OLD_LIST)).toEqual(['T-2']);
+
+ update.reject(new Error('Project not found'));
+ await pending.catch(() => {});
+
+ expect(ids(OLD_LIST)).toEqual(['T-1', 'T-2']);
+ expect(state().taskListMap[OLD_LIST].total).toBe(2);
+ expect(boardIds()).toEqual(['T-1', 'T-2']);
+ expect(state().taskListMap[GLOBAL_LIST].items[0].projectId).toBe('p1');
+ });
+
+ it('explains a refused move in the UI language, with no retry that would fail again', async () => {
+ seed();
+ const refused = Object.assign(new Error('Task dependencies cannot cross project boundaries'), {
+ data: { code: 'BAD_REQUEST' },
+ });
+ vi.mocked(taskService.update).mockRejectedValue(refused);
+
+ await state()
+ .updateTask('T-1', { projectId: 'p2' })
+ .catch(() => {});
+
+ expect(saveToast).toHaveBeenCalledWith(refused, {
+ hideCause: true,
+ title: expect.stringContaining("Can't move this task"),
+ });
+ });
+
+ it('keeps the server cause and retry for any other failed save', async () => {
+ seed();
+ const failed = Object.assign(new Error('boom'), { data: { code: 'INTERNAL_SERVER_ERROR' } });
+ vi.mocked(taskService.update).mockRejectedValue(failed);
+
+ await state()
+ .updateTask('T-1', { projectId: 'p2' })
+ .catch(() => {});
+
+ expect(saveToast).toHaveBeenCalledWith(failed, { retry: expect.any(Function) });
+ });
+
+ it('keeps the row in its project list when the patch does not send a project', async () => {
+ seed();
+ vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);
+
+ await state().updateTask('T-1', { name: 'Renamed' });
+
+ expect(taskService.update).toHaveBeenCalledWith('T-1', { name: 'Renamed' });
+ expect(ids(OLD_LIST)).toEqual(['T-1', 'T-2']);
+ expect(state().taskDetailMap['T-1'].projectId).toBe('p1');
+ });
+});
+
+describe('a project-scoped collection remembers its project', () => {
+ const syncOf = (name: 'taskGroupList' | 'taskList') => {
+ const call = vi
+ .mocked(useClientDataSWR)
+ .mock.calls.find(
+ ([key]) => Array.isArray(key) && key[0] === 'replica:sync' && key[1] === name,
+ );
+ return { fetcher: call![1] as () => Promise<any>, options: call![2] as any };
+ };
+
+ it('stores the project on a fetched list, so a later move can drop the row', async () => {
+ vi.mocked(taskService.list).mockResolvedValue({
+ data: [row('T-1', 'p1')],
+ total: 1,
+ } as any);
+ const { result } = renderHook(() =>
+ useTaskStore.getState().useFetchTaskList({ complete: false, projectId: 'p1' }),
+ );
+ const queryKey = result.current.queryKey!;
+
+ const { fetcher, options } = syncOf('taskList');
+ await act(async () => {
+ const fetched = await fetcher();
+ options?.onSuccess?.(fetched);
+ });
+ await waitFor(() => expect(state().taskListMap[queryKey]?.projectId).toBe('p1'));
+ });
+
+ it('stores the project on a fetched board', async () => {
+ vi.mocked(taskService.groupList).mockResolvedValue({
+ data: [{ key: 'backlog', tasks: [row('T-1', 'p1')], total: 1 }],
+ } as any);
+ const { result } = renderHook(() =>
+ useTaskStore.getState().useFetchTaskGroupList({ projectId: 'p1' }),
+ );
+ const queryKey = result.current.queryKey!;
+
+ const { fetcher, options } = syncOf('taskGroupList');
+ await act(async () => {
+ const fetched = await fetcher();
+ options?.onSuccess?.(fetched);
+ });
+ await waitFor(() => expect(state().taskGroupListMap[queryKey]?.projectId).toBe('p1'));
+ });
+});
diff --git a/src/store/task/slices/detail/action.stableId.test.ts b/src/store/task/slices/detail/action.stableId.test.ts
index 7cfc433a2b7..db7cd89dd8d 100644
--- a/src/store/task/slices/detail/action.stableId.test.ts
+++ b/src/store/task/slices/detail/action.stableId.test.ts
@@ -4,7 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { cacheScope, createReplicaState } from '@/libs/replica';
import { broadcastCacheScope, resetCacheScopeBroadcast } from '@/libs/replica/cacheScopeEvents';
-import { useClientDataSWR } from '@/libs/swr';
+import { mutate, useClientDataSWR } from '@/libs/swr';
import { taskService } from '@/services/task';
import { useTaskStore } from '../../store';
@@ -27,6 +27,9 @@ const detail = {
};
beforeEach(() => {
vi.clearAllMocks();
+ // `restoreAllMocks` below also drops the factory's resolved value, and the
+ // replica driver chains `.catch` on what `mutate` returns.
+ vi.mocked(mutate).mockResolvedValue(undefined);
resetCacheScopeBroadcast();
useTaskStore.setState({
activeTaskId: undefined,
diff --git a/src/store/task/slices/detail/action.ts b/src/store/task/slices/detail/action.ts
index 14f16e82f6b..3ec32eb3770 100644
--- a/src/store/task/slices/detail/action.ts
+++ b/src/store/task/slices/detail/action.ts
@@ -11,6 +11,7 @@ import { t } from 'i18next';
import { cacheScope, createReplicaSlice, recordLens, revalidateReplica } from '@/libs/replica';
import { subscribeCacheScope } from '@/libs/replica/cacheScopeEvents';
import { useClientDataSWR } from '@/libs/swr';
+import { normalizeAsyncError } from '@/libs/swr/normalizeError';
import { taskService } from '@/services/task';
import { workService } from '@/services/work';
import { goalGraphResource } from '@/store/goal/projection';
@@ -52,6 +53,8 @@ export interface TaskUpdatePayload {
name?: string;
parentTaskId?: string | null;
priority?: number;
+ /** `null` takes the task out of its project. */
+ projectId?: string | null;
}
export interface TaskUpdateOptions {
@@ -637,6 +640,7 @@ export class TaskDetailSliceActionImpl {
...task,
...(data.name !== undefined ? { name: data.name } : {}),
...(data.priority !== undefined ? { priority: data.priority } : {}),
+ ...(data.projectId !== undefined ? { projectId: data.projectId } : {}),
...(data.assigneeAgentId !== undefined ? { assigneeAgentId: data.assigneeAgentId } : {}),
...(data.assigneeUserId !== undefined ? { assigneeUserId: data.assigneeUserId } : {}),
}));
@@ -666,6 +670,15 @@ export class TaskDetailSliceActionImpl {
...options,
source: 'external',
}));
+ // A refused project move repeats on retry until its links are moved, and the
+ // server's reason is English-only, so the toast says what to do instead.
+ if (data.projectId !== undefined && normalizeAsyncError(error).code === 'BAD_REQUEST') {
+ saveToast(error, {
+ hideCause: true,
+ title: t('taskProject.moveRefused', { ns: 'chat' }),
+ });
+ return;
+ }
saveToast(error, { retry });
},
setStatus: (status) => this.#get().internal_setTaskSaveStatus(id, status),
@@ -682,7 +695,10 @@ export class TaskDetailSliceActionImpl {
assigneeAgentId !== undefined ||
assigneeUserId !== undefined ||
data.parentTaskId !== undefined ||
- data.priority !== undefined
+ data.priority !== undefined ||
+ // The optimistic patch drops the row from its old project's lists; only a
+ // refetch can add it to the lists of the project it moved into.
+ data.projectId !== undefined
) {
await Promise.all([
this.#get().refreshTaskList(),
diff --git a/src/store/task/slices/list/action.ts b/src/store/task/slices/list/action.ts
index bfd454e7fd2..8f79cfdf305 100644
--- a/src/store/task/slices/list/action.ts
+++ b/src/store/task/slices/list/action.ts
@@ -180,6 +180,7 @@ export class TaskListSliceActionImpl {
get,
merge: (incoming, _confirmed, query) => ({
items: incoming.data,
+ ...(query.projectId && { projectId: query.projectId }),
...(query.statuses && { statuses: query.statuses }),
total: incoming.total,
}),
@@ -196,6 +197,7 @@ export class TaskListSliceActionImpl {
...(query.excludeStatuses && { excludeStatuses: query.excludeStatuses }),
groupBy: query.groupBy,
groups: incoming.data,
+ ...(query.projectId && { projectId: query.projectId }),
}),
set,
stateKey: 'taskGroupListReplica',
@@ -232,7 +234,7 @@ export class TaskListSliceActionImpl {
? { groups: DEFAULT_KANBAN_GROUPS }
: query.groupBy.startsWith('label:')
? { groupBy: 'label' as const, labelGroupId: query.groupBy.slice('label:'.length) }
- : { groupBy: query.groupBy as 'assignee' | 'member' | 'priority' }),
+ : { groupBy: query.groupBy as 'assignee' | 'member' | 'priority' | 'project' }),
includeArchived: query.includeArchived,
projectId: query.projectId,
scope: query.scope,
diff --git a/src/store/task/slices/list/initialState.ts b/src/store/task/slices/list/initialState.ts
index 003aa27d714..6045fc3d7e2 100644
--- a/src/store/task/slices/list/initialState.ts
+++ b/src/store/task/slices/list/initialState.ts
@@ -17,7 +17,8 @@ export type TaskGroupItem = Awaited<ReturnType<typeof taskService.groupList>>['d
*/
export type TaskListVisibilityFilter = 'all' | 'private' | 'workspace';
/** `label:<groupId>` boards one column per label of that label group, plus "no label". */
-export type TaskKanbanGroupBy = 'assignee' | 'member' | 'priority' | 'status' | `label:${string}`;
+export type TaskKanbanGroupBy =
+ 'assignee' | 'member' | 'priority' | 'project' | 'status' | `label:${string}`;
export interface TaskListSliceState {
/** The viewed list is narrowed by the page's filter, so it is not every task. */
diff --git a/src/store/task/slices/list/projection.test.ts b/src/store/task/slices/list/projection.test.ts
new file mode 100644
index 00000000000..7621fd0ec04
--- /dev/null
+++ b/src/store/task/slices/list/projection.test.ts
@@ -0,0 +1,102 @@
+import { describe, expect, it } from 'vitest';
+
+import type { TaskGroupListValue, TaskListValue } from './projection';
+import { taskGroupListEntity, taskListEntity } from './projection';
+
+const row = (id: string, projectId: string | null | undefined) =>
+ ({ id, identifier: id, projectId, status: 'backlog' }) as TaskListValue['items'][number];
+
+const list = (projectId?: string): TaskListValue => ({
+ items: [row('a', 'p1'), row('b', 'p1')],
+ ...(projectId && { projectId }),
+ total: 2,
+});
+
+const board = (projectId?: string): TaskGroupListValue => ({
+ groupBy: 'status',
+ groups: [{ key: 'backlog', tasks: [row('a', 'p1'), row('b', 'p1')], total: 2 }],
+ ...(projectId && { projectId }),
+});
+
+describe('project scope of a task collection', () => {
+ it.each([['p2'], [null]])('drops a row moved to %j from the old project list', (projectId) => {
+ const next = taskListEntity.map(list('p1'), 'a', (task) => ({ ...task, projectId }));
+ expect(next?.items.map((task) => task.id)).toEqual(['b']);
+ expect(next?.total).toBe(1);
+ });
+
+ it('keeps a row that stays in the project', () => {
+ const next = taskListEntity.map(list('p1'), 'a', (task) => ({ ...task, name: 'renamed' }));
+ expect(next?.items.map((task) => task.id)).toEqual(['a', 'b']);
+ expect(next?.total).toBe(2);
+ });
+
+ it('keeps a moved row in a list that is not scoped to a project', () => {
+ const next = taskListEntity.map(list(), 'a', (task) => ({ ...task, projectId: 'p2' }));
+ expect(next?.items[0].projectId).toBe('p2');
+ expect(next?.total).toBe(2);
+ });
+
+ it('keeps a persisted row that predates the field', () => {
+ const value = { ...list('p1'), items: [row('a', undefined)] };
+ const next = taskListEntity.map(value, 'a', (task) => ({ ...task, name: 'renamed' }));
+ expect(next?.items).toHaveLength(1);
+ });
+
+ it.each([['p2'], [null]])('takes a card moved to %j off the old project board', (projectId) => {
+ const next = taskGroupListEntity.map(board('p1'), 'a', (task) => ({ ...task, projectId }));
+ expect(next?.groups[0].tasks.map((task) => task.id)).toEqual(['b']);
+ expect(next?.groups[0].total).toBe(1);
+ });
+
+ it('keeps a moved card on a board that is not scoped to a project', () => {
+ const next = taskGroupListEntity.map(board(), 'a', (task) => ({ ...task, projectId: 'p2' }));
+ expect(next?.groups[0].tasks[0].projectId).toBe('p2');
+ expect(next?.groups[0].total).toBe(2);
+ });
+});
+
+describe('a project board', () => {
+ const projectBoard = (): TaskGroupListValue =>
+ ({
+ groupBy: 'project',
+ groups: [
+ { key: 'project:p1', projectId: 'p1', tasks: [row('a', 'p1'), row('b', 'p1')], total: 2 },
+ { key: 'project:none', projectId: null, tasks: [], total: 0 },
+ ],
+ }) as unknown as TaskGroupListValue;
+
+ it('moves a card to "No project" when its project is cleared', () => {
+ const next = taskGroupListEntity.map(projectBoard(), 'a', (task) => ({
+ ...task,
+ projectId: null,
+ }));
+
+ expect(next.groups[0]).toMatchObject({ total: 1 });
+ expect(next.groups[0].tasks.map((task) => task.id)).toEqual(['b']);
+ expect(next.groups[1]).toMatchObject({ total: 1 });
+ expect(next.groups[1].tasks.map((task) => task.id)).toEqual(['a']);
+ });
+
+ it('opens a column for the first task of a project', () => {
+ const next = taskGroupListEntity.map(projectBoard(), 'a', (task) => ({
+ ...task,
+ projectId: 'p2',
+ }));
+
+ expect(next.groups[2]).toMatchObject({ key: 'project:p2', projectId: 'p2', total: 1 });
+ expect(next.groups[2].tasks[0].projectId).toBe('p2');
+ expect(next.groups[0].total).toBe(1);
+ });
+
+ it('leaves the columns alone when something else changes', () => {
+ const next = taskGroupListEntity.map(projectBoard(), 'a', (task) => ({
+ ...task,
+ status: 'running',
+ }));
+
+ expect(next.groups[0].tasks.map((task) => task.id)).toEqual(['a', 'b']);
+ expect(next.groups[0].tasks[0].status).toBe('running');
+ expect(next.groups[0].total).toBe(2);
+ });
+});
diff --git a/src/store/task/slices/list/projection.ts b/src/store/task/slices/list/projection.ts
index 854725de49b..65e7619d29b 100644
--- a/src/store/task/slices/list/projection.ts
+++ b/src/store/task/slices/list/projection.ts
@@ -49,6 +49,8 @@ export interface TaskListQuery {
export interface TaskListValue {
items: TaskListItem[];
+ /** The query's project scope, so a task moved elsewhere can drop out of this list. */
+ projectId?: string;
/** The query's status filter, so a status change can drop a row it no longer matches. */
statuses?: TaskStatus[];
total: number;
@@ -76,6 +78,8 @@ export interface TaskGroupListValue {
excludeStatuses?: TaskStatus[];
groupBy: TaskKanbanGroupBy;
groups: TaskGroupItem[];
+ /** The query's project scope, so a task moved elsewhere can drop off this board. */
+ projectId?: string;
}
export const taskListQueryKey = (query: TaskListQuery) => stableQueryKey(query);
@@ -115,6 +119,23 @@ export const taskGroupKeyByStatus: Record<TaskStatus, string> = {
scheduled: 'running',
};
+/** The "No project" column of a board grouped by project. */
+export const TASK_NO_PROJECT_GROUP_KEY = 'project:none';
+
+/** The one column for tasks filed under projects the caller cannot see. */
+export const TASK_UNAVAILABLE_PROJECT_GROUP_KEY = 'project:unavailable';
+
+/** Kanban column of a task's project when the board groups by project. */
+export const taskGroupKeyByProject = (projectId: string | null | undefined) =>
+ projectId ? `project:${projectId}` : TASK_NO_PROJECT_GROUP_KEY;
+
+/**
+ * Whether a patched row left the project a collection is scoped to. A row without
+ * the field (a card persisted before it was projected) proves nothing, so it stays.
+ */
+const leftProjectScope = (scope: string | undefined, task: CollectionTask) =>
+ !!scope && task.projectId !== undefined && task.projectId !== scope;
+
/** Tasks are addressed by stable database id across the task store. */
export const taskListEntity: ReplicaEntityAdapter<TaskListValue, TaskListItem> = {
has: (data, id) => data.items.some((task) => task.id === id),
@@ -131,6 +152,7 @@ export const taskListEntity: ReplicaEntityAdapter<TaskListValue, TaskListItem> =
// A row whose new status falls outside the query's filter leaves the list.
if (next && data.statuses && !data.statuses.includes(next.status as TaskStatus))
next = undefined;
+ if (next && leftProjectScope(data.projectId, next)) next = undefined;
if (next !== task) changed = true;
if (next === undefined) removed++;
else items.push(next);
@@ -141,7 +163,8 @@ export const taskListEntity: ReplicaEntityAdapter<TaskListValue, TaskListItem> =
/**
* A task inside the board's groups. On a status board a status change moves
- * the card to its new column (appended), keeping each column's `total` right.
+ * the card to its new column (appended), keeping each column's `total` right;
+ * a project change does the same on a project board.
*/
export const taskGroupListEntity: ReplicaEntityAdapter<TaskGroupListValue, TaskGroupTask> = {
has: (data, id) => data.groups.some((group) => group.tasks.some((task) => task.id === id)),
@@ -153,10 +176,21 @@ export const taskGroupListEntity: ReplicaEntityAdapter<TaskGroupListValue, TaskG
// A card whose new status the board hides ("Completed tasks: None") leaves it, even
// though the server still returns the hidden status's empty column.
if (next && data.excludeStatuses?.includes(next.status as TaskStatus)) next = undefined;
+ if (next && leftProjectScope(data.projectId, next)) next = undefined;
const status = next?.status as TaskStatus | undefined;
- const moves = data.groupBy === 'status' && next !== undefined && status !== current.status;
- const targetKey = moves && status ? taskGroupKeyByStatus[status] : undefined;
+ const movesStatus =
+ data.groupBy === 'status' && next !== undefined && status !== current.status;
+ const movesProject =
+ data.groupBy === 'project' &&
+ next !== undefined &&
+ (next.projectId ?? null) !== (current.projectId ?? null);
+ const moves = movesStatus || movesProject;
+ const targetKey = movesProject
+ ? taskGroupKeyByProject(next!.projectId)
+ : movesStatus && status
+ ? taskGroupKeyByStatus[status]
+ : undefined;
const groups = data.groups.map((group) => {
const contains = group.tasks.some((task) => task.id === id);
if (moves) {
@@ -178,6 +212,19 @@ export const taskGroupListEntity: ReplicaEntityAdapter<TaskGroupListValue, TaskG
total: next === undefined ? group.total - 1 : group.total,
};
});
+ // A project board only has columns for projects holding tasks, so the first
+ // task of a project opens its column.
+ if (movesProject && !groups.some((group) => group.key === targetKey)) {
+ groups.push({
+ hasMore: false,
+ key: targetKey!,
+ limit: 50,
+ offset: 0,
+ projectId: next!.projectId ?? null,
+ tasks: [next!],
+ total: 1,
+ });
+ }
return { ...data, groups };
},
};