🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(task): align kanban grouping with list (#18631)
Tsuki328eba381d49
diff --git a/apps/server/src/routers/lambda/task.ts b/apps/server/src/routers/lambda/task.tsindex f1404d1be25..5f2baca8e7a 100644--- a/apps/server/src/routers/lambda/task.ts+++ b/apps/server/src/routers/lambda/task.ts@@ -160,25 +160,32 @@ const listSchema = z.object({visibility: z.enum(['private', 'public']).optional(),});-const groupListSchema = z.object({- assigneeAgentId: z.string().optional(),- automated: z.boolean().optional(),- groups: z- .array(- z.object({- key: z.string(),- limit: z.number().min(1).max(100).default(50),- offset: z.number().min(0).default(0),- statuses: z.array(z.string()).min(1).max(10),- }),- )- .min(1)- .max(10),- hasGoal: z.boolean().optional(),- parentTaskId: z.string().nullish(),- projectId: z.string().optional(),- visibility: z.enum(['private', 'public']).optional(),-});+const groupListSchema = z+ .object({+ assigneeAgentId: z.string().optional(),+ automated: z.boolean().optional(),+ excludeStatuses: z.array(z.enum(TASK_STATUSES)).max(10).optional(),+ groupBy: z.enum(['assignee', 'priority']).optional(),+ groups: z+ .array(+ z.object({+ key: z.string(),+ limit: z.number().min(1).max(100).default(50),+ offset: z.number().min(0).default(0),+ statuses: z.array(z.string()).min(1).max(10),+ }),+ )+ .min(1)+ .max(10)+ .optional(),+ hasGoal: z.boolean().optional(),+ parentTaskId: z.string().nullish(),+ projectId: z.string().optional(),+ visibility: z.enum(['private', 'public']).optional(),+ })+ .refine(({ groupBy, groups }) => Boolean(groupBy) !== Boolean(groups), {+ message: 'Provide either groups or groupBy',+ });// Helper: resolve id/identifier and throw if not foundasync function resolveOrThrow(model: TaskModel, id: string) {diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 31db17aa995..dd989d60ea0 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1511,6 +1511,7 @@"taskList.empty": "No tasks yet","taskList.emptyHero.greeting": "What should we tackle today?","taskList.emptyHero.templatesTitle": "Templates picked for you",+ "taskList.form.columns": "Columns","taskList.form.grouping": "Grouping","taskList.form.nestedSubTasks": "Nested sub-tasks","taskList.form.orderCompletedByRecency": "Sort completed tasks by recency",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex fff1bb85195..929620c5885 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1511,6 +1511,7 @@"taskList.empty": "暂无任务","taskList.emptyHero.greeting": "今天想搞定点什么?","taskList.emptyHero.templatesTitle": "为你推荐的模板",+ "taskList.form.columns": "列","taskList.form.grouping": "分组","taskList.form.nestedSubTasks": "缩进显示子任务","taskList.form.orderCompletedByRecency": "按最近完成排序",diff --git a/packages/database/src/models/__tests__/task.test.ts b/packages/database/src/models/__tests__/task.test.tsindex e2cd5f7b790..ea416c3da82 100644--- a/packages/database/src/models/__tests__/task.test.ts+++ b/packages/database/src/models/__tests__/task.test.ts@@ -451,6 +451,72 @@ describe('TaskModel', () => {});describe('groupList', () => {+ it('should group tasks by assignee and keep an unassigned column', async () => {+ const firstAgentId = await createAgent('group-assignee-first');+ const secondAgentId = await createAgent('group-assignee-second');+ const model = new TaskModel(serverDB, userId);++ await model.create({ assigneeAgentId: firstAgentId, instruction: 'First assigned task' });+ await model.create({ assigneeAgentId: secondAgentId, instruction: 'Second assigned task' });+ await model.create({ instruction: 'Unassigned task' });+ const completed = await model.create({+ assigneeAgentId: firstAgentId,+ instruction: 'Completed task',+ });+ await model.updateStatus(completed.id, 'completed', { completedAt: new Date() });++ const result = await model.groupList({+ excludeStatuses: ['completed', 'canceled'],+ groupBy: 'assignee',+ });++ expect(result).toHaveLength(3);+ expect(result.find((group) => group.key === `assignee:${firstAgentId}`)?.total).toBe(1);+ expect(result.find((group) => group.key === `assignee:${secondAgentId}`)?.total).toBe(1);+ const unassigned = result.find((group) => group.key === 'assignee:unassigned');+ expect(unassigned?.assigneeAgentId).toBeNull();+ expect(unassigned?.tasks.map((task) => task.instruction)).toEqual(['Unassigned task']);++ const agentScopedResult = await model.groupList({+ assigneeAgentId: firstAgentId,+ groupBy: 'assignee',+ });+ expect(agentScopedResult.map((group) => group.key)).toEqual([`assignee:${firstAgentId}`]);+ });++ it('should expose every priority as a kanban drop target', async () => {+ const model = new TaskModel(serverDB, userId);+ await model.create({ instruction: 'High priority', priority: 2 });++ const result = await model.groupList({ groupBy: 'priority' });++ expect(result.map((group) => group.key)).toEqual([+ 'priority:1',+ 'priority:2',+ 'priority:3',+ 'priority:4',+ 'priority:0',+ ]);+ expect(result.find((group) => group.key === 'priority:2')?.total).toBe(1);+ expect(result.find((group) => group.key === 'priority:1')?.total).toBe(0);+ });++ it('should combine null and zero values in the no-priority group total', async () => {+ const model = new TaskModel(serverDB, userId);+ await model.create({ instruction: 'Explicit no priority', priority: 0 });+ const nullablePriority = await model.create({ instruction: 'Nullable priority' });+ await serverDB.update(tasks).set({ priority: null }).where(eq(tasks.id, nullablePriority.id));++ const result = await model.groupList({ groupBy: 'priority' });+ const noPriority = result.find((group) => group.key === 'priority:0');++ expect(noPriority?.total).toBe(2);+ expect(noPriority?.tasks.map((task) => task.instruction).sort()).toEqual([+ 'Explicit no priority',+ 'Nullable priority',+ ]);+ });+it('should return grouped tasks by status', async () => {const model = new TaskModel(serverDB, userId);diff --git a/packages/database/src/models/task.ts b/packages/database/src/models/task.tsindex 11c7114e3d2..db5e1f17ec4 100644--- a/packages/database/src/models/task.ts+++ b/packages/database/src/models/task.ts@@ -11,6 +11,7 @@ import {and,desc,eq,+ getTableColumns,gt,gte,inArray,@@ -591,7 +592,9 @@ export class TaskModel {async groupList(options: TaskListFilterOptions & {- groups: Array<{+ excludeStatuses?: string[];+ groupBy?: 'assignee' | 'priority';+ groups?: Array<{key: string;limit?: number;offset?: number;@@ -600,59 +603,215 @@ export class TaskModel {},): Promise<Array<{+ assigneeAgentId?: string | null;hasMore: boolean;key: string;limit: number;offset: number;+ priority?: number;tasks: TaskItem[];total: number;}>> {- const { groups } = options;+ const { assigneeAgentId, excludeStatuses, groupBy, groups } = options;++ if ((!groups || groups.length === 0) && !groupBy) {+ throw new Error('Task groups or a grouping dimension are required');+ }+const baseConditions = this.buildListConditions(options);- const normalizedGroups = groups.map((group) => ({- ...group,- statuses: Array.from(new Set(group.statuses)),- }));+ if (excludeStatuses?.length) {+ baseConditions.push(notInArray(tasks.status, excludeStatuses));+ }- const allStatuses = Array.from(new Set(normalizedGroups.flatMap((group) => group.statuses)));- const countQuery = this.db- .select({ count: sql<number>`count(*)`, status: tasks.status })- .from(tasks)- .where(and(...baseConditions, inArray(tasks.status, allStatuses)))- .groupBy(tasks.status);+ interface GroupQuery {+ assigneeAgentId?: string | null;+ conditions: SQL[];+ key: string;+ limit: number;+ offset: number;+ prefetchedTasks?: TaskItem[];+ priority?: number;+ total: number;+ }- const groupQueries = normalizedGroups.map(async (group) => {- const limit = group.limit ?? 50;- const offset = group.offset ?? 0;+ let groupQueries: GroupQuery[];- const groupTasks = await this.db- .select()+ if (groupBy === 'assignee') {+ const limit = 50;+ const rankedTasks = this.db+ .select({+ ...getTableColumns(tasks),+ groupRank:+ sql<number>`row_number() over (partition by ${tasks.assigneeAgentId} order by ${tasks.createdAt} desc)`.as(+ 'group_rank',+ ),+ }).from(tasks)- .where(and(...baseConditions, inArray(tasks.status, group.statuses)))- .orderBy(desc(tasks.createdAt))- .limit(limit)- .offset(offset);+ .where(and(...baseConditions))+ .as('ranked_assignee_tasks');+ const [countResult, rankedTaskRows] = await Promise.all([+ this.db+ .select({ assigneeAgentId: tasks.assigneeAgentId, count: sql<number>`count(*)` })+ .from(tasks)+ .where(and(...baseConditions))+ .groupBy(tasks.assigneeAgentId),+ this.db+ .select()+ .from(rankedTasks)+ .where(sql`${rankedTasks.groupRank} <= ${limit}`)+ .orderBy(rankedTasks.assigneeAgentId, rankedTasks.groupRank),+ ]);+ const assigneeCounts = new Map(+ countResult.map((row) => [row.assigneeAgentId, Number(row.count)]),+ );+ const tasksByAssignee = new Map<string | null, TaskItem[]>();+ for (const row of rankedTaskRows) {+ const { groupRank: _groupRank, ...task } = row;+ const groupTasks = tasksByAssignee.get(task.assigneeAgentId) ?? [];+ groupTasks.push(task);+ tasksByAssignee.set(task.assigneeAgentId, groupTasks);+ }- return {- key: group.key,+ // Keep an empty Unassigned column as a stable drop target even when every+ // current task already has an owner. Other assignees are data-derived;+ // showing every agent as an empty column would make large workspaces+ // unusable without a separate "show empty columns" control.+ if (!assigneeAgentId && !assigneeCounts.has(null)) assigneeCounts.set(null, 0);++ groupQueries = [...assigneeCounts.entries()].map(([groupAssigneeAgentId, total]) => ({+ assigneeAgentId: groupAssigneeAgentId,+ conditions: [+ groupAssigneeAgentId+ ? eq(tasks.assigneeAgentId, groupAssigneeAgentId)+ : isNull(tasks.assigneeAgentId),+ ],+ key: groupAssigneeAgentId ? `assignee:${groupAssigneeAgentId}` : 'assignee:unassigned',limit,- offset,- tasks: groupTasks,- statuses: group.statuses,- };- });- const [countResult, queriedGroups] = await Promise.all([countQuery, Promise.all(groupQueries)]);- const countByStatus = new Map(countResult.map(({ count, status }) => [status, Number(count)]));- const results = queriedGroups.map(({ statuses, ...group }) => {- const total = statuses.reduce((sum, status) => sum + (countByStatus.get(status) ?? 0), 0);+ offset: 0,+ prefetchedTasks: tasksByAssignee.get(groupAssigneeAgentId) ?? [],+ total,+ }));+ } else if (groupBy === 'priority') {+ const priorities = [1, 2, 3, 4, 0];+ const countQuery = this.db+ .select({ count: sql<number>`count(*)`, priority: tasks.priority })+ .from(tasks)+ .where(and(...baseConditions))+ .groupBy(tasks.priority);+ const taskQueries = priorities.map(async (priority) => {+ const conditions = [+ priority === 0+ ? or(eq(tasks.priority, priority), isNull(tasks.priority))!+ : eq(tasks.priority, priority),+ ];+ const limit = 50;+ const offset = 0;+ const prefetchedTasks = await this.db+ .select()+ .from(tasks)+ .where(and(...baseConditions, ...conditions))+ .orderBy(desc(tasks.createdAt))+ .limit(limit)+ .offset(offset);++ return {+ conditions,+ key: `priority:${priority}`,+ limit,+ offset,+ prefetchedTasks,+ priority,+ total: 0,+ };+ });+ const [countResult, queriedGroups] = await Promise.all([+ countQuery,+ Promise.all(taskQueries),+ ]);+ const priorityCounts = new Map<number, number>();+ for (const row of countResult) {+ const priority = row.priority ?? 0;+ priorityCounts.set(priority, (priorityCounts.get(priority) ?? 0) + Number(row.count));+ }- return {+ // Priority is a finite dimension, so include empty values as usable drop+ // targets. The order matches the task list's semantic rank.+ groupQueries = queriedGroups.map((group) => ({...group,- hasMore: group.offset + group.tasks.length < total,- total,- };- });+ total: priorityCounts.get(group.priority) ?? 0,+ }));+ } else {+ const statusGroups = (groups ?? []).map((group) => ({+ ...group,+ statuses: Array.from(new Set(group.statuses)),+ }));+ const allStatuses = Array.from(new Set(statusGroups.flatMap((group) => group.statuses)));+ const countQuery = this.db+ .select({ count: sql<number>`count(*)`, status: tasks.status })+ .from(tasks)+ .where(and(...baseConditions, inArray(tasks.status, allStatuses)))+ .groupBy(tasks.status);+ const taskQueries = statusGroups.map(async (group) => {+ const conditions = [inArray(tasks.status, group.statuses)];+ const limit = group.limit ?? 50;+ const offset = group.offset ?? 0;+ const prefetchedTasks = await this.db+ .select()+ .from(tasks)+ .where(and(...baseConditions, ...conditions))+ .orderBy(desc(tasks.createdAt))+ .limit(limit)+ .offset(offset);++ return {+ conditions,+ key: group.key,+ limit,+ offset,+ prefetchedTasks,+ statuses: group.statuses,+ total: 0,+ };+ });+ const [countResult, queriedGroups] = await Promise.all([+ countQuery,+ Promise.all(taskQueries),+ ]);+ const countByStatus = new Map(countResult.map((row) => [row.status, Number(row.count)]));++ groupQueries = queriedGroups.map(({ statuses, ...group }) => ({+ ...group,+ total: statuses.reduce((sum, status) => sum + (countByStatus.get(status) ?? 0), 0),+ }));+ }++ const results = await Promise.all(+ groupQueries.map(async (group) => {+ const groupTasks =+ group.prefetchedTasks ??+ (await this.db+ .select()+ .from(tasks)+ .where(and(...baseConditions, ...group.conditions))+ .orderBy(desc(tasks.createdAt))+ .limit(group.limit)+ .offset(group.offset));++ return {+ ...(group.assigneeAgentId !== undefined+ ? { assigneeAgentId: group.assigneeAgentId }+ : {}),+ hasMore: group.offset + groupTasks.length < group.total,+ key: group.key,+ limit: group.limit,+ offset: group.offset,+ ...(group.priority !== undefined ? { priority: group.priority } : {}),+ tasks: groupTasks,+ total: group.total,+ };+ }),+ );const taskIds = Array.from(new Set(results.flatMap((group) => group.tasks.map(({ id }) => id))),diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 86529d3284f..dc842573a12 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1799,6 +1799,7 @@ export default {'taskList.empty': 'No tasks yet','taskList.emptyHero.greeting': 'What should we tackle today?','taskList.emptyHero.templatesTitle': 'Templates picked for you',+ 'taskList.form.columns': 'Columns','taskList.form.grouping': 'Grouping','taskList.form.nestedSubTasks': 'Nested sub-tasks','taskList.form.orderCompletedByRecency': 'Sort completed tasks by recency',diff --git a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsxindex 9c2787dd2d9..7521ff66fd8 100644--- a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx+++ b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx@@ -302,7 +302,12 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, projectId }) => {<EmptyState agentId={agentId} projectId={projectId} />) : viewMode === 'kanban' ? (<Flexbox flex={1} style={{ overflowX: 'auto', overflowY: 'hidden' }}>- <KanbanBoard agentId={agentId} projectId={projectId} routeScope={routeScope} />+ <KanbanBoard+ agentId={agentId}+ options={viewOptions}+ projectId={projectId}+ routeScope={routeScope}+ /></Flexbox>) : (<WideScreenContainerdiff --git a/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx b/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsxindex 80a1d65691a..ac5c0891588 100644--- a/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx+++ b/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx@@ -22,14 +22,22 @@ import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';import { useTaskStore } from '@/store/task';import { taskListSelectors } from '@/store/task/selectors';-import type { TaskGroupItem, TaskListItem } from '@/store/task/slices/list/initialState';+import type { TaskListItem } from '@/store/task/slices/list/initialState';import { createTaskModal } from '../CreateTaskModal';import type { TaskItemRouteScope } from '../features/AgentTaskItem';import AgentTaskItem from '../features/AgentTaskItem';import { taskDetailPath } from '../shared/taskDetailPath';import HiddenColumnsPanel from './HiddenColumnsPanel';+import {+ buildKanbanColumns,+ getKanbanTaskPatch,+ moveTaskBetweenKanbanGroups,+ normalizeKanbanGroupBy,+} from './kanbanBoardModel';import KanbanColumn, { COLUMN_I18N_KEYS, COLUMN_STATUS_ICON, COLUMN_WIDTH } from './KanbanColumn';+import type { TaskListViewOptions } from './listViewOptions';+import { HIDDEN_WHEN_COMPLETED_STATUSES } from './listViewOptions';const styles = createStaticStyles(({ css }) => ({board: css`@@ -43,55 +51,29 @@ const styles = createStaticStyles(({ css }) => ({`,}));-interface ColumnDef {- droppable: boolean;- key: string;- targetStatus: 'backlog' | 'canceled' | 'completed' | null;-}--const COLUMNS: ColumnDef[] = [- { droppable: true, key: 'backlog', targetStatus: 'backlog' },- { droppable: false, key: 'running', targetStatus: null },- { droppable: false, key: 'needsInput', targetStatus: null },- { droppable: true, key: 'done', targetStatus: 'completed' },- { droppable: true, key: 'canceled', targetStatus: 'canceled' },-];--const optimisticMoveTask = (- taskGroups: TaskGroupItem[],- task: TaskListItem,- targetColumnKey: string,-): TaskGroupItem[] => {- return taskGroups.map((group) => {- const filtered = (group.tasks as TaskListItem[]).filter(- (t) => t.identifier !== task.identifier,- );- const removed = filtered.length < (group.tasks as TaskListItem[]).length;-- if (group.key === targetColumnKey) {- return { ...group, tasks: [...filtered, task], total: filtered.length + 1 };- }-- return removed ? { ...group, tasks: filtered, total: group.total - 1 } : group;- });-};-interface KanbanBoardProps {/** When set, scopes the board (and task creation) to a single agent. */agentId?: string;+ options: TaskListViewOptions;projectId?: string;routeScope?: TaskItemRouteScope;}-const KanbanBoard = memo<KanbanBoardProps>(({ agentId, projectId, routeScope }) => {+const KanbanBoard = memo<KanbanBoardProps>(({ agentId, options, projectId, routeScope }) => {const { t } = useTranslation('chat');const navigate = useWorkspaceAwareNavigate();const { allowed: canEditTask } = usePermission('create_content');+ const groupBy = normalizeKanbanGroupBy(options.groupBy);+ const excludeStatuses = options.hideCompleted ? HIDDEN_WHEN_COMPLETED_STATUSES : undefined;const useFetchTaskGroupList = useTaskStore((s) => s.useFetchTaskGroupList);// Keep the SWR handle only for `error` + `mutate` (the error/Retry state).- const { error, isLoading, mutate } = useFetchTaskGroupList(- projectId ? { projectId } : agentId ? { agentId } : { allAgents: true, automated: false },+ const { error, isLoading, isQueryScopeCurrent, mutate } = useFetchTaskGroupList(+ projectId+ ? { excludeStatuses, groupBy, projectId }+ : agentId+ ? { agentId, excludeStatuses, groupBy }+ : { allAgents: true, automated: false, excludeStatuses, groupBy },);// Drive the loading/empty boundary off the store's own init flag, NOT SWR's// per-key `data`. On a scope or visibility switch the store resets@@ -103,6 +85,11 @@ const KanbanBoard = memo<KanbanBoardProps>(({ agentId, projectId, routeScope })const isTaskGroupListInit = useTaskStore(taskListSelectors.isTaskGroupListInit);const taskGroups = useTaskStore(taskListSelectors.taskGroups);+ const currentTaskGroups = useMemo(+ () => (isQueryScopeCurrent ? taskGroups : []),+ [isQueryScopeCurrent, taskGroups],+ );+ const updateTask = useTaskStore((s) => s.updateTask);const updateTaskStatus = useTaskStore((s) => s.updateTaskStatus);const hiddenColumns = useGlobalStore(systemStatusSelectors.taskKanbanHiddenColumns);@@ -110,6 +97,10 @@ const KanbanBoard = memo<KanbanBoardProps>(({ agentId, projectId, routeScope })const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);const [activeTask, setActiveTask] = useState<TaskListItem | null>(null);+ const columns = useMemo(+ () => buildKanbanColumns(currentTaskGroups, groupBy),+ [currentTaskGroups, groupBy],+ );const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),@@ -134,25 +125,40 @@ const KanbanBoard = memo<KanbanBoardProps>(({ agentId, projectId, routeScope })if (!over) return;const targetColumnKey = over.id as string;- const column = COLUMNS.find((c) => c.key === targetColumnKey);- if (!column?.droppable || !column.targetStatus) return;+ const column = columns.find((item) => item.key === targetColumnKey);+ if (!column?.droppable) return;const task = active.data.current?.task as TaskListItem | undefined;if (!task) return;- if (task.status === column.targetStatus) return;+ const patch = getKanbanTaskPatch(groupBy, column);+ if (!patch) return;+ if (groupBy === 'status' && task.status === patch.status) return;+ if (+ groupBy === 'assignee' &&+ (task.assigneeAgentId ?? null) === (patch.assigneeAgentId ?? null)+ ) {+ return;+ }+ if (groupBy === 'priority' && (task.priority ?? 0) === (patch.priority ?? 0)) return;const prevGroups = useTaskStore.getState().taskGroups;- const nextGroups = optimisticMoveTask(prevGroups, task, targetColumnKey);+ const nextGroups = moveTaskBetweenKanbanGroups(prevGroups, task, targetColumnKey, patch);useTaskStore.setState({ taskGroups: nextGroups }, false, 'kanban/optimisticMove');try {- await updateTaskStatus(task.identifier, column.targetStatus);+ if (groupBy === 'status' && column.targetStatus) {+ await updateTaskStatus(task.identifier, column.targetStatus);+ } else if (groupBy === 'assignee') {+ await updateTask(task.identifier, { assigneeAgentId: patch.assigneeAgentId ?? null });+ } else if (groupBy === 'priority') {+ await updateTask(task.identifier, { priority: patch.priority ?? 0 });+ }} catch {useTaskStore.setState({ taskGroups: prevGroups }, false, 'kanban/revertMove');}},- [canEditTask, updateTaskStatus],+ [canEditTask, columns, groupBy, updateTask, updateTaskStatus],);const handleDragCancel = useCallback(() => {@@ -198,30 +204,44 @@ const KanbanBoard = memo<KanbanBoardProps>(({ agentId, projectId, routeScope })const hiddenColumnSet = useMemo(() => new Set(hiddenColumns), [hiddenColumns]);const visibleColumns = useMemo(- () => COLUMNS.filter((col) => !hiddenColumnSet.has(col.key)),- [hiddenColumnSet],+ () =>+ groupBy === 'status' ? columns.filter((column) => !hiddenColumnSet.has(column.key)) : columns,+ [columns, groupBy, hiddenColumnSet],);const hiddenColumnEntries = useMemo(() =>- COLUMNS.filter((col) => hiddenColumnSet.has(col.key)).map((col) => ({- columnKey: col.key,- label: t(COLUMN_I18N_KEYS[col.key] as any),- statusIcon: COLUMN_STATUS_ICON[col.key],- total: taskGroups.find((group) => group.key === col.key)?.total ?? 0,- })),- [hiddenColumnSet, t, taskGroups],+ columns+ .filter((col) => hiddenColumnSet.has(col.key))+ .map((col) => ({+ columnKey: col.key,+ label: t(COLUMN_I18N_KEYS[col.key] as any),+ statusIcon: COLUMN_STATUS_ICON[col.key],+ total: currentTaskGroups.find((group) => group.key === col.key)?.total ?? 0,+ })),+ [columns, currentTaskGroups, hiddenColumnSet, t],);- const totalTasks = taskGroups.reduce((sum, g) => sum + g.total, 0);+ const totalTasks = currentTaskGroups.reduce((sum, group) => sum + group.total, 0);+ const skeletonColumns =+ visibleColumns.length > 0+ ? visibleColumns+ : Array.from({ length: 3 }, (_, index) => ({+ droppable: false,+ groupMeta: undefined,+ key: `skeleton-${index}`,+ targetStatus: null,+ }));const skeletonBoard = (<Flexbox horizontal className={styles.board}>- {visibleColumns.map((col) => (+ {skeletonColumns.map((col) => (<KanbanColumnloadingcolumnKey={col.key}droppable={false}+ groupBy={groupBy}+ groupMeta={col.groupMeta}key={col.key}tasks={[]}total={0}@@ -246,26 +266,32 @@ const KanbanBoard = memo<KanbanBoardProps>(({ agentId, projectId, routeScope })><Flexbox horizontal className={styles.board}>{visibleColumns.map((col) => {- const group = taskGroups.find((g) => g.key === col.key);+ const group = currentTaskGroups.find((item) => item.key === col.key);return (<KanbanColumncolumnKey={col.key}droppable={canEditTask && col.droppable}+ groupBy={groupBy}+ groupMeta={col.groupMeta}key={col.key}routeScope={routeScope}tasks={(group?.tasks ?? []) as TaskListItem[]}total={group?.total ?? 0}- onCreate={col.key === 'backlog' ? handleCreateTask : undefined}- onHide={() => handleHideColumn(col.key)}+ onHide={groupBy === 'status' ? () => handleHideColumn(col.key) : undefined}+ onCreate={+ groupBy === 'status' && col.key === 'backlog' ? handleCreateTask : undefined+ }/>);})}- <HiddenColumnsPanel- collapsed={hiddenPanelCollapsed}- columns={hiddenColumnEntries}- onRestore={handleRestoreColumn}- onToggleCollapsed={handleToggleHiddenPanel}- />+ {groupBy === 'status' && (+ <HiddenColumnsPanel+ collapsed={hiddenPanelCollapsed}+ columns={hiddenColumnEntries}+ onRestore={handleRestoreColumn}+ onToggleCollapsed={handleToggleHiddenPanel}+ />+ )}</Flexbox><DragOverlay dropAnimation={null}>{activeTask ? (@@ -291,12 +317,12 @@ const KanbanBoard = memo<KanbanBoardProps>(({ agentId, projectId, routeScope })// undefined until the first fetch settles.return (<AsyncBoundary- data={isTaskGroupListInit || undefined}+ data={(isQueryScopeCurrent && isTaskGroupListInit) || undefined}empty={emptyState}error={error}errorVariant={'block'}isEmpty={totalTasks === 0}- isLoading={isLoading || (!isTaskGroupListInit && !error)}+ isLoading={isLoading || (!isQueryScopeCurrent && !error) || (!isTaskGroupListInit && !error)}loading={skeletonBoard}onRetry={() => mutate()}>diff --git a/src/features/AgentTasks/AgentTaskList/KanbanColumn.tsx b/src/features/AgentTasks/AgentTaskList/KanbanColumn.tsxindex 32da0f26fb1..e2effcae6a7 100644--- a/src/features/AgentTasks/AgentTaskList/KanbanColumn.tsx+++ b/src/features/AgentTasks/AgentTaskList/KanbanColumn.tsx@@ -6,11 +6,13 @@ import { EyeOff, MoreHorizontal, Plus } from 'lucide-react';import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';-import type { TaskListItem } from '@/store/task/slices/list/initialState';+import type { TaskKanbanGroupBy, TaskListItem } from '@/store/task/slices/list/initialState';import type { TaskItemRouteScope } from '../features/AgentTaskItem';import AgentTaskItem from '../features/AgentTaskItem';import TaskStatusIcon from '../features/TaskStatusIcon';+import type { TaskGroupMeta } from './listViewOptions';+import TaskGroupLabel from './TaskGroupLabel';import TaskItemSkeleton from './TaskItemSkeleton';export const COLUMN_WIDTH = 300;@@ -172,6 +174,8 @@ export const COLUMN_STATUS_ICON: Record<string, TaskStatus> = {interface KanbanColumnProps {columnKey: string;droppable: boolean;+ groupBy: TaskKanbanGroupBy;+ groupMeta?: TaskGroupMeta;loading?: boolean;onCreate?: () => void;onHide?: () => void;@@ -181,7 +185,18 @@ interface KanbanColumnProps {}const KanbanColumn = memo<KanbanColumnProps>(- ({ columnKey, droppable, loading, onCreate, onHide, routeScope, tasks, total }) => {+ ({+ columnKey,+ droppable,+ groupBy,+ groupMeta,+ loading,+ onCreate,+ onHide,+ routeScope,+ tasks,+ total,+ }) => {const { t } = useTranslation('chat');const { active } = useDndContext();const { isOver, setNodeRef } = useDroppable({@@ -191,7 +206,7 @@ const KanbanColumn = memo<KanbanColumnProps>(const statusIcon = COLUMN_STATUS_ICON[columnKey];const i18nKey = COLUMN_I18N_KEYS[columnKey];- const label = i18nKey ? t(i18nKey as any) : columnKey;+ const label = i18nKey ? t(i18nKey as any) : t(`taskList.groupBy.${groupBy}` as any);const isDragActive = !!active;// Don't highlight if dragging a card that's already in this column@@ -226,8 +241,14 @@ const KanbanColumn = memo<KanbanColumnProps>()}><div className={styles.header}>- {statusIcon && <TaskStatusIcon size={18} status={statusIcon} />}- <Text weight={500}>{label}</Text>+ {groupMeta ? (+ <TaskGroupLabel group={groupMeta} />+ ) : (+ <>+ {statusIcon && <TaskStatusIcon size={18} status={statusIcon} />}+ <Text weight={500}>{label}</Text>+ </>+ )}{!loading && (<Text fontSize={12} type={'secondary'}>{total}diff --git a/src/features/AgentTasks/AgentTaskList/TaskGroupLabel.tsx b/src/features/AgentTasks/AgentTaskList/TaskGroupLabel.tsxnew file mode 100644index 00000000000..725b583dbc6--- /dev/null+++ b/src/features/AgentTasks/AgentTaskList/TaskGroupLabel.tsx@@ -0,0 +1,80 @@+import { Flexbox, Icon, Text } from '@lobehub/ui';+import { cssVar } from 'antd-style';+import { CalendarClock, HeartPulse, UserRound } from 'lucide-react';+import { memo } from 'react';++import AssigneeAvatar from '../features/AssigneeAvatar';+import PriorityHighIcon from '../features/icons/PriorityHighIcon';+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 TaskStatusIcon from '../features/TaskStatusIcon';+import { useAgentDisplayMeta } from '../shared/useAgentDisplayMeta';+import type { TaskGroupMeta } from './listViewOptions';++const PRIORITY_ICON_MAP = {+ 0: PriorityNoneIcon,+ 1: PriorityUrgentIcon,+ 2: PriorityHighIcon,+ 3: PriorityMediumIcon,+ 4: PriorityLowIcon,+} as const;++const AssigneeLabel = memo<{ agentId: string }>(({ agentId }) => {+ const displayMeta = useAgentDisplayMeta(agentId);+ return <>{displayMeta?.title}</>;+});++const TaskGroupPrefix = ({ group }: { group: TaskGroupMeta }) => {+ if (group.groupBy === 'assignee') {+ return group.assigneeId ? (+ <AssigneeAvatar agentId={group.assigneeId} size={18} />+ ) : (+ <Icon icon={UserRound} size={14} />+ );+ }++ if (group.groupBy === 'priority') {+ const priority = group.priority ?? 0;+ const PriorityIcon =+ PRIORITY_ICON_MAP[priority as keyof typeof PRIORITY_ICON_MAP] || PriorityNoneIcon;+ return (+ <PriorityIcon+ color={priority === 1 ? cssVar.orange : cssVar.colorTextDescription}+ size={16}+ />+ );+ }++ if (group.groupBy === 'automationMode') {+ return (+ <Icon+ color={cssVar.colorTextDescription}+ icon={group.automationMode === 'heartbeat' ? HeartPulse : CalendarClock}+ size={16}+ />+ );+ }++ if (group.groupBy === 'status') {+ return <TaskStatusIcon size={16} status={group.status ?? 'backlog'} />;+ }++ return null;+};++interface TaskGroupLabelProps {+ group: TaskGroupMeta;+}++const TaskGroupLabel = memo<TaskGroupLabelProps>(({ group }) => (+ <Flexbox horizontal align={'center'} flex={'none'} gap={6} style={{ overflow: 'hidden' }}>+ <TaskGroupPrefix group={group} />+ <Text ellipsis weight={500}>+ {group.assigneeId ? <AssigneeLabel agentId={group.assigneeId} /> : group.label}+ </Text>+ </Flexbox>+));++export default TaskGroupLabel;diff --git a/src/features/AgentTasks/AgentTaskList/TaskList.tsx b/src/features/AgentTasks/AgentTaskList/TaskList.tsxindex 5ba9558d2eb..d09f0dee221 100644--- a/src/features/AgentTasks/AgentTaskList/TaskList.tsx+++ b/src/features/AgentTasks/AgentTaskList/TaskList.tsx@@ -1,7 +1,7 @@-import { Accordion, AccordionItem, Block, Center, Empty, Flexbox, Icon, Text } from '@lobehub/ui';+import { Accordion, AccordionItem, Block, Center, Empty, Flexbox, Text } from '@lobehub/ui';import { Divider } from 'antd';import { cssVar } from 'antd-style';-import { CalendarClock, ClipboardCheckIcon, HeartPulse, UserRound } from 'lucide-react';+import { ClipboardCheckIcon } from 'lucide-react';import { Fragment, memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -12,14 +12,6 @@ import type { TaskListItem } from '@/store/task/slices/list/initialState';import type { TaskItemRouteScope } from '../features/AgentTaskItem';import AgentTaskItem from '../features/AgentTaskItem';-import AssigneeAvatar from '../features/AssigneeAvatar';-import PriorityHighIcon from '../features/icons/PriorityHighIcon';-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 TaskStatusIcon from '../features/TaskStatusIcon';-import { useAgentDisplayMeta } from '../shared/useAgentDisplayMeta';import type { TaskGroupBy, TaskGroupMeta, TaskListViewOptions, TaskRow } from './listViewOptions';import {buildTaskRows,@@ -28,6 +20,7 @@ import {groupTaskItems,HIDDEN_WHEN_COMPLETED_STATUSES,} from './listViewOptions';+import TaskGroupLabel from './TaskGroupLabel';import TaskItemSkeleton from './TaskItemSkeleton';import TaskRowIndent from './TaskRowIndent';@@ -76,14 +69,6 @@ const renderTaskListBlock = (rows: TaskRow[], sub?: boolean, routeScope?: TaskIt</Block>);-const PRIORITY_ICON_MAP = {- 0: PriorityNoneIcon,- 1: PriorityUrgentIcon,- 2: PriorityHighIcon,- 3: PriorityMediumIcon,- 4: PriorityLowIcon,-} as const;-const TASK_GROUP_BY_VALUES = new Set<TaskGroupBy>(['assignee','automationMode',@@ -97,58 +82,9 @@ const normalizeGroupBy = (value: TaskGroupBy | string | undefined, fallback: Tasreturn TASK_GROUP_BY_VALUES.has(value as TaskGroupBy) ? (value as TaskGroupBy) : fallback;};-const AssigneeLabel = memo<{ agentId: string }>(({ agentId }) => {- const displayMeta = useAgentDisplayMeta(agentId);- return <>{displayMeta?.title}</>;-});--const renderGroupPrefix = (group: TaskGroupMeta) => {- if (group.groupBy === 'assignee') {- if (group.assigneeId) {- return <AssigneeAvatar agentId={group.assigneeId} size={18} />;- }- return <Icon icon={UserRound} size={14} />;- }-- if (group.groupBy === 'priority') {- const priority = group.priority ?? 0;- const PriorityIcon =- PRIORITY_ICON_MAP[priority as keyof typeof PRIORITY_ICON_MAP] || PriorityNoneIcon;- return (- <PriorityIcon- color={priority === 1 ? cssVar.orange : cssVar.colorTextDescription}- size={16}- />- );- }-- if (group.groupBy === 'automationMode') {- return (- <Icon- color={cssVar.colorTextDescription}- icon={group.automationMode === 'heartbeat' ? HeartPulse : CalendarClock}- size={16}- />- );- }-- if (group.groupBy === 'status') {- const status = group.status ?? 'backlog';-- return <TaskStatusIcon size={16} status={status} />;- }-- return null;-};-const renderGroupTitle = (group: TaskGroupMeta, count: number, sub?: boolean) => (<Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>- <Flexbox horizontal align={'center'} flex={'none'} gap={6} style={{ overflow: 'hidden' }}>- {renderGroupPrefix(group)}- <Text ellipsis weight={500}>- {group.assigneeId ? <AssigneeLabel agentId={group.assigneeId} /> : group.label}- </Text>- </Flexbox>+ <TaskGroupLabel group={group} /><Text fontSize={12} type={'secondary'}>{count}</Text>diff --git a/src/features/AgentTasks/AgentTaskList/TasksGroupConfig.tsx b/src/features/AgentTasks/AgentTaskList/TasksGroupConfig.tsxindex 36e77b93273..600eba1881a 100644--- a/src/features/AgentTasks/AgentTaskList/TasksGroupConfig.tsx+++ b/src/features/AgentTasks/AgentTaskList/TasksGroupConfig.tsx@@ -49,6 +49,10 @@ const TasksGroupConfig = memo<TasksHeaderProps>(({ options, setOptions }) => {],[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' },@@ -66,26 +70,45 @@ const TasksGroupConfig = memo<TasksHeaderProps>(({ options, setOptions }) => {[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 FormItemProps;++ const showCompletedFormItem = {+ children: (+ <Switch+ checked={!options.hideCompleted}+ size={'small'}+ onChange={(checked) => {+ setOptions((prev) => ({ ...prev, hideCompleted: !checked }));+ }}+ />+ ),+ minWidth: undefined,+ label: t('taskList.form.showCompleted'),+ } satisfies FormItemProps;const formItems: FormItemProps[] = [- {- children: (- <Select- options={groupingOptions}- size={'small'}- style={{ width: 150 }}- value={options.groupBy}- onChange={(value: TaskGroupBy) => {- setOptions((prev) => ({- ...prev,- groupBy: value,- subGroupBy: prev.subGroupBy === value ? 'none' : prev.subGroupBy,- }));- }}- />- ),- label: t('taskList.form.grouping'),- },+ groupingFormItem,...(isSubGroupingEnabled? [{@@ -143,19 +166,7 @@ const TasksGroupConfig = memo<TasksHeaderProps>(({ options, setOptions }) => {minWidth: undefined,label: t('taskList.form.orderCompletedByRecency'),},- {- children: (- <Switch- checked={!options.hideCompleted}- size={'small'}- onChange={(checked) => {- setOptions((prev) => ({ ...prev, hideCompleted: !checked }));- }}- />- ),- minWidth: undefined,- label: t('taskList.form.showCompleted'),- },+ showCompletedFormItem,{children: (<Switch@@ -189,6 +200,7 @@ const TasksGroupConfig = memo<TasksHeaderProps>(({ options, setOptions }) => {]: []),];+ const boardFormItems = [groupingFormItem, showCompletedFormItem];const panelContent = (<Flexbox gap={12} width={280}>@@ -210,18 +222,16 @@ const TasksGroupConfig = memo<TasksHeaderProps>(({ options, setOptions }) => {updateSystemStatus({ taskListViewMode: key as TaskViewMode }, 'updateTaskListViewMode')}/>- {viewMode === 'list' && (- <Form- className={styles.form}- items={formItems}- itemsType={'flat'}- size={'small'}- variant={'borderless'}- styles={{- item: { padding: 0 },- }}- />- )}+ <Form+ className={styles.form}+ items={viewMode === 'kanban' ? boardFormItems : formItems}+ itemsType={'flat'}+ size={'small'}+ variant={'borderless'}+ styles={{+ item: { padding: 0 },+ }}+ /></Flexbox>);diff --git a/src/features/AgentTasks/AgentTaskList/kanbanBoardModel.test.ts b/src/features/AgentTasks/AgentTaskList/kanbanBoardModel.test.tsnew file mode 100644index 00000000000..31dbecdd8ad--- /dev/null+++ b/src/features/AgentTasks/AgentTaskList/kanbanBoardModel.test.ts@@ -0,0 +1,94 @@+import { describe, expect, it } from 'vitest';++import type { TaskGroupItem, TaskListItem } from '@/store/task/slices/list/initialState';++import {+ buildKanbanColumns,+ getKanbanTaskPatch,+ moveTaskBetweenKanbanGroups,+ normalizeKanbanGroupBy,+} from './kanbanBoardModel';++const task = (id: string, assigneeAgentId?: string | null): TaskListItem =>+ ({+ assigneeAgentId,+ id,+ identifier: `T-${id}`,+ priority: 0,+ status: 'backlog',+ }) as TaskListItem;++const group = (+ key: string,+ tasks: TaskListItem[],+ assigneeAgentId?: string | null,+): TaskGroupItem =>+ ({+ assigneeAgentId,+ hasMore: false,+ key,+ limit: 50,+ offset: 0,+ tasks,+ total: tasks.length,+ }) as TaskGroupItem;++describe('kanbanBoardModel', () => {+ it('uses assignee and priority as board dimensions and falls back from no grouping', () => {+ expect(normalizeKanbanGroupBy('assignee')).toBe('assignee');+ expect(normalizeKanbanGroupBy('priority')).toBe('priority');+ expect(normalizeKanbanGroupBy('none')).toBe('status');+ });++ it('builds assignee columns including the unassigned group', () => {+ const groups = [+ group('assignee:agent-1', [task('1', 'agent-1')], 'agent-1'),+ group('assignee:unassigned', [task('2', null)], null),+ ];++ const columns = buildKanbanColumns(groups, 'assignee');++ expect(columns.map((column) => column.key).sort()).toEqual(+ ['assignee:unassigned', 'assignee:agent-1'].sort(),+ );+ expect(+ columns.find((column) => column.key === 'assignee:unassigned')?.groupMeta?.assigneeId,+ ).toBeUndefined();+ expect(columns.find((column) => column.key === 'assignee:agent-1')?.groupMeta?.assigneeId).toBe(+ 'agent-1',+ );+ });++ it('patches the task assignee when moving between assignee columns', () => {+ const assignedTask = task('1', 'agent-1');+ const groups = [+ group('assignee:agent-1', [assignedTask], 'agent-1'),+ group('assignee:unassigned', [], null),+ ];+ const targetColumn = buildKanbanColumns(groups, 'assignee').find(+ (column) => column.key === 'assignee:unassigned',+ )!;+ const patch = getKanbanTaskPatch('assignee', targetColumn)!;++ const next = moveTaskBetweenKanbanGroups(groups, assignedTask, targetColumn.key, patch);++ expect(next.find((item) => item.key === 'assignee:agent-1')?.total).toBe(0);+ const unassigned = next.find((item) => item.key === 'assignee:unassigned');+ expect(unassigned?.total).toBe(1);+ expect(unassigned?.tasks[0].assigneeAgentId).toBeNull();+ });++ it('preserves paginated group totals during an optimistic move', () => {+ const assignedTask = task('1', 'agent-1');+ const groups = [+ { ...group('assignee:agent-1', [assignedTask], 'agent-1'), total: 75 },+ { ...group('assignee:agent-2', [], 'agent-2'), total: 63 },+ ];++ const next = moveTaskBetweenKanbanGroups(groups, assignedTask, 'assignee:agent-2', {+ assigneeAgentId: 'agent-2',+ });++ expect(next.map(({ total }) => total)).toEqual([74, 64]);+ });+});diff --git a/src/features/AgentTasks/AgentTaskList/kanbanBoardModel.ts b/src/features/AgentTasks/AgentTaskList/kanbanBoardModel.tsnew file mode 100644index 00000000000..979e6efca8e--- /dev/null+++ b/src/features/AgentTasks/AgentTaskList/kanbanBoardModel.ts@@ -0,0 +1,94 @@+import type { TaskStatus } from '@lobechat/types';++import type {+ TaskGroupItem,+ TaskKanbanGroupBy,+ TaskListItem,+} from '@/store/task/slices/list/initialState';++import type { TaskGroupBy, TaskGroupMeta } from './listViewOptions';+import {+ getTaskAssigneeGroupMeta,+ getTaskPriorityGroupMeta,+ sortGroupEntries,+} from './listViewOptions';++export interface KanbanColumnDefinition {+ droppable: boolean;+ groupMeta?: TaskGroupMeta;+ key: string;+ targetStatus: 'backlog' | 'canceled' | 'completed' | null;+}++export const STATUS_KANBAN_COLUMNS: KanbanColumnDefinition[] = [+ { droppable: true, key: 'backlog', targetStatus: 'backlog' },+ { droppable: false, key: 'running', targetStatus: null },+ { droppable: false, key: 'needsInput', targetStatus: null },+ { droppable: true, key: 'done', targetStatus: 'completed' },+ { droppable: true, key: 'canceled', targetStatus: 'canceled' },+];++export const normalizeKanbanGroupBy = (groupBy: TaskGroupBy): TaskKanbanGroupBy =>+ groupBy === 'assignee' || groupBy === 'priority' ? groupBy : 'status';++export const buildKanbanColumns = (+ taskGroups: TaskGroupItem[],+ groupBy: TaskKanbanGroupBy,+): KanbanColumnDefinition[] => {+ if (groupBy === 'status') return STATUS_KANBAN_COLUMNS;++ const groupEntries = taskGroups.map((group) => {+ const meta =+ groupBy === 'assignee'+ ? getTaskAssigneeGroupMeta(group.assigneeAgentId)+ : getTaskPriorityGroupMeta(group.priority);+ return [meta, group.tasks as TaskListItem[]] as [TaskGroupMeta, TaskListItem[]];+ });++ return sortGroupEntries(groupEntries, groupBy).map(([groupMeta]) => ({+ droppable: true,+ groupMeta,+ key: groupMeta.key,+ targetStatus: null,+ }));+};++export const getKanbanTaskPatch = (+ groupBy: TaskKanbanGroupBy,+ column: KanbanColumnDefinition,+): Partial<TaskListItem> | undefined => {+ if (groupBy === 'assignee' && column.groupMeta?.groupBy === 'assignee') {+ return { assigneeAgentId: column.groupMeta.assigneeId ?? null };+ }+ if (groupBy === 'priority' && column.groupMeta?.groupBy === 'priority') {+ return { priority: column.groupMeta.priority ?? 0 };+ }+ if (groupBy === 'status' && column.targetStatus) {+ return { status: column.targetStatus as TaskStatus };+ }+};++export const moveTaskBetweenKanbanGroups = (+ taskGroups: TaskGroupItem[],+ task: TaskListItem,+ targetColumnKey: string,+ patch: Partial<TaskListItem>,+): TaskGroupItem[] => {+ const patchedTask = { ...task, ...patch };++ return taskGroups.map((group) => {+ const tasks = group.tasks as TaskListItem[];+ const filtered = tasks.filter((item) => item.identifier !== task.identifier);+ const removed = filtered.length < tasks.length;++ if (group.key === targetColumnKey) {+ return {+ ...group,+ tasks: [...filtered, patchedTask],+ total: group.total + (removed ? 0 : 1),+ };+ }++ return removed ? { ...group, tasks: filtered, total: Math.max(0, group.total - 1) } : group;+ });+};diff --git a/src/features/AgentTasks/AgentTaskList/listViewOptions.ts b/src/features/AgentTasks/AgentTaskList/listViewOptions.tsindex 9d599194004..716389e2cc9 100644--- a/src/features/AgentTasks/AgentTaskList/listViewOptions.ts+++ b/src/features/AgentTasks/AgentTaskList/listViewOptions.ts@@ -139,8 +139,7 @@ const getPriorityValue = (task: TaskListItem) => task.priority ?? 0;const getTaskStatusGroup = (task: TaskListItem): NonNullable<TaskGroupMeta['status']> =>TASK_STATUS_TO_GROUP_MAP[task.status] ?? 'backlog';-const getTaskAssigneeMeta = (task: TaskListItem): TaskGroupMeta => {- const agentId = task.assigneeAgentId;+export const getTaskAssigneeGroupMeta = (agentId: string | null | undefined): TaskGroupMeta => {if (!agentId) {return {groupBy: 'assignee',@@ -159,6 +158,25 @@ const getTaskAssigneeMeta = (task: TaskListItem): TaskGroupMeta => {const getTaskAssigneeSortValue = (task: TaskListItem) => task.assigneeAgentId ?? '';+export const getTaskPriorityGroupMeta = (+ priorityValue: number | null | undefined,+): TaskGroupMeta => {+ const priority = priorityValue ?? 0;+ const labelKeyMap: Record<number, string> = {+ 0: 'taskDetail.priority.none',+ 1: 'taskDetail.priority.urgent',+ 2: 'taskDetail.priority.high',+ 3: 'taskDetail.priority.normal',+ 4: 'taskDetail.priority.low',+ };+ return {+ groupBy: 'priority',+ key: `priority:${priority}`,+ label: t(labelKeyMap[priority] ?? labelKeyMap[0], { defaultValue: '', ns: 'chat' }),+ priority,+ };+};+const toTime = (value: Date | string | null | undefined): number => {if (!value) return 0;return value instanceof Date ? value.getTime() : new Date(value).getTime();@@ -231,7 +249,7 @@ export const compareTaskItems = (export const getTaskGroupMeta = (task: TaskListItem, groupBy: TaskGroupBy): TaskGroupMeta => {switch (groupBy) {case 'assignee': {- return getTaskAssigneeMeta(task);+ return getTaskAssigneeGroupMeta(task.assigneeAgentId);}case 'automationMode': {// Automated tasks created before automationMode was introduced are schedules.@@ -244,20 +262,7 @@ export const getTaskGroupMeta = (task: TaskListItem, groupBy: TaskGroupBy): Task};}case 'priority': {- const priority = getPriorityValue(task);- const labelKeyMap: Record<number, string> = {- 0: 'taskDetail.priority.none',- 1: 'taskDetail.priority.urgent',- 2: 'taskDetail.priority.high',- 3: 'taskDetail.priority.normal',- 4: 'taskDetail.priority.low',- };- return {- groupBy: 'priority',- key: `priority:${priority}`,- label: t(labelKeyMap[priority] ?? labelKeyMap[0], { defaultValue: '', ns: 'chat' }),- priority,- };+ return getTaskPriorityGroupMeta(getPriorityValue(task));}case 'status': {const groupedStatus = getTaskStatusGroup(task);diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex df56a4164cc..117b49ee36a 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -283,15 +283,22 @@ export const taskKeys = {(agentKey: string | undefined,visibility: 'all' | 'private' | 'workspace' = 'all',+ groupBy: 'assignee' | 'priority' | 'status' = 'status',+ excludeStatuses?: string,projectId?: string,automated?: boolean,- ) => [- 'task:groupList',- agentKey,- visibility,- ...(projectId ? [projectId] : []),- ...(automated === undefined ? [] : [{ automated }]),- ],+ ) => {+ const hasBoardFilter = groupBy !== 'status' || excludeStatuses !== undefined;+ const key = hasBoardFilter+ ? projectId+ ? ['task:groupList', agentKey, visibility, groupBy, excludeStatuses, projectId]+ : ['task:groupList', agentKey, visibility, groupBy, excludeStatuses]+ : projectId+ ? ['task:groupList', agentKey, visibility, projectId]+ : ['task:groupList', agentKey, visibility];++ return automated === undefined ? key : [...key, { automated }];+ },),/*** The home rail's cross-agent goal roll-up. Scoped by cache scope like thediff --git a/src/services/task.ts b/src/services/task.tsindex 8b69220f568..72cf9229423 100644--- a/src/services/task.ts+++ b/src/services/task.ts@@ -32,7 +32,9 @@ class TaskService {groupList = async (params: {assigneeAgentId?: string;automated?: boolean;- groups: Array<{+ excludeStatuses?: TaskStatus[];+ groupBy?: 'assignee' | 'priority';+ groups?: Array<{key: string;limit?: number;offset?: number;diff --git a/src/store/task/slices/detail/action.test.ts b/src/store/task/slices/detail/action.test.tsindex a903a9379ac..c247b77fc4d 100644--- a/src/store/task/slices/detail/action.test.ts+++ b/src/store/task/slices/detail/action.test.ts@@ -390,6 +390,16 @@ describe('TaskDetailSliceAction', () => {expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-new-parent']);});+ it('should refresh the list after changing priority', async () => {+ const refreshTaskList = vi.fn().mockResolvedValue(undefined);+ useTaskStore.setState({ refreshTaskList } as any);+ vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);++ await useTaskStore.getState().updateTask('T-1', { priority: 2 });++ expect(refreshTaskList).toHaveBeenCalled();+ });+it('should refresh the parent that was patched even if activeTaskId changes mid-flight', async () => {const { mutate } = await import('@/libs/swr');useTaskStore.setState({diff --git a/src/store/task/slices/detail/action.ts b/src/store/task/slices/detail/action.tsindex cc27a30f89a..f3de5432a41 100644--- a/src/store/task/slices/detail/action.ts+++ b/src/store/task/slices/detail/action.ts@@ -406,7 +406,11 @@ export class TaskDetailSliceActionImpl {setStatus: (status) => this.#get().internal_setTaskSaveStatus(id, status),});- if (assigneeAgentId !== undefined || data.parentTaskId !== undefined) {+ if (+ assigneeAgentId !== undefined ||+ data.parentTaskId !== undefined ||+ data.priority !== undefined+ ) {await Promise.all([this.#get().refreshTaskList(), refreshPatchedTargets()]).catch(() => {});}};diff --git a/src/store/task/slices/lifecycle/action.test.ts b/src/store/task/slices/lifecycle/action.test.tsindex 5a5b543eb70..0bc43f75b06 100644--- a/src/store/task/slices/lifecycle/action.test.ts+++ b/src/store/task/slices/lifecycle/action.test.ts@@ -24,6 +24,8 @@ beforeEach(() => {vi.clearAllMocks();useTaskStore.setState({activeTaskId: 'T-1',+ listGroupBy: 'status',+ listGroupExcludeStatuses: undefined,taskDetailMap: { 'T-1': { ...mockDetail } },taskGroups: [],tasks: [],@@ -133,6 +135,31 @@ describe('TaskLifecycleSliceAction', () => {await useTaskStore.getState().updateTaskStatus('T-1', 'completed');});+ it('should preserve assignee grouping when a task status changes', async () => {+ useTaskStore.setState({+ listGroupBy: 'assignee',+ taskGroups: [+ {+ assigneeAgentId: 'agent-1',+ key: 'assignee:agent-1',+ tasks: [{ assigneeAgentId: 'agent-1', identifier: 'T-1', status: 'backlog' }],+ total: 1,+ },+ ] as any,+ tasks: [{ assigneeAgentId: 'agent-1', identifier: 'T-1', status: 'backlog' }] as any,+ });+ vi.mocked(taskService.updateStatus).mockImplementation(async () => {+ expect(useTaskStore.getState().taskGroups[0]).toMatchObject({+ key: 'assignee:agent-1',+ tasks: [expect.objectContaining({ identifier: 'T-1', status: 'completed' })],+ total: 1,+ });+ return { success: true } as any;+ });++ await useTaskStore.getState().updateTaskStatus('T-1', 'completed');+ });+it('should roll list and kanban collections back when the status update fails', async () => {useTaskStore.setState({taskGroups: [diff --git a/src/store/task/slices/lifecycle/action.ts b/src/store/task/slices/lifecycle/action.tsindex 53f4ddf495b..330e0ce0f21 100644--- a/src/store/task/slices/lifecycle/action.ts+++ b/src/store/task/slices/lifecycle/action.ts@@ -203,30 +203,35 @@ export class TaskLifecycleSliceActionImpl {};#patchTaskCollectionsStatus = (id: string, status: TaskStatus): void => {- const { taskGroups, tasks } = this.#get();+ const { listGroupBy, taskGroups, tasks } = this.#get();const listTask = tasks.find((task) => task.identifier === id);const groupedTask = taskGroups.flatMap((group) => group.tasks).find((task) => task.identifier === id);if (!listTask && !groupedTask) return;- const targetGroupKey = taskGroupKeyByStatus[status];const nextTasks = listTask? tasks.map((item) => (item.identifier === id ? { ...item, status } : item)): tasks;const nextTaskGroups = groupedTask- ? taskGroups.map((group) => {- const containsTask = group.tasks.some((item) => item.identifier === id);- const belongsToTarget = group.key === targetGroupKey;- const filteredTasks = group.tasks.filter((item) => item.identifier !== id);- const patchedGroupedTask = { ...groupedTask, status };-- return {+ ? listGroupBy === 'status'+ ? taskGroups.map((group) => {+ const targetGroupKey = taskGroupKeyByStatus[status];+ const containsTask = group.tasks.some((item) => item.identifier === id);+ const belongsToTarget = group.key === targetGroupKey;+ const filteredTasks = group.tasks.filter((item) => item.identifier !== id);+ const patchedGroupedTask = { ...groupedTask, status };++ return {+ ...group,+ tasks: belongsToTarget ? [...filteredTasks, patchedGroupedTask] : filteredTasks,+ total: group.total - (containsTask ? 1 : 0) + (belongsToTarget ? 1 : 0),+ };+ })+ : taskGroups.map((group) => ({...group,- tasks: belongsToTarget ? [...filteredTasks, patchedGroupedTask] : filteredTasks,- total: group.total - (containsTask ? 1 : 0) + (belongsToTarget ? 1 : 0),- };- })+ tasks: group.tasks.map((item) => (item.identifier === id ? { ...item, status } : item)),+ })): taskGroups;this.#set(diff --git a/src/store/task/slices/list/action.test.ts b/src/store/task/slices/list/action.test.tsindex f23e4970267..f4851e4cf6c 100644--- a/src/store/task/slices/list/action.test.ts+++ b/src/store/task/slices/list/action.test.ts@@ -1,3 +1,4 @@+import { renderHook } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';import { useTaskStore } from '../../store';@@ -19,11 +20,16 @@ vi.mock('@/libs/swr', () => ({beforeEach(() => {vi.clearAllMocks();useTaskStore.setState({+ groupListQueryAutomated: undefined,+ isTaskGroupListInit: false,isTaskListInit: false,listAgentId: undefined,+ listGroupBy: 'status',+ listGroupExcludeStatuses: undefined,listQueryAutomated: undefined,listQueryVisibility: 'all',listVisibility: 'all',+ taskGroups: [],tasks: [],tasksTotal: 0,});@@ -75,6 +81,73 @@ describe('TaskListSliceAction', () => {});});+ describe('useFetchTaskGroupList', () => {+ it('keys and requests assignee groups independently from status groups', async () => {+ const { useClientDataSWR } = await import('@/libs/swr');+ const { taskService } = await import('@/services/task');++ renderHook(() =>+ useTaskStore.getState().useFetchTaskGroupList({+ allAgents: true,+ automated: false,+ excludeStatuses: ['completed', 'canceled'],+ groupBy: 'assignee',+ }),+ );++ expect(useClientDataSWR).toHaveBeenCalledWith(+ [+ 'task:groupList',+ '__all__',+ 'all',+ 'assignee',+ 'canceled,completed',+ { automated: false },+ ],+ expect.any(Function),+ expect.any(Object),+ );+ const fetcher = vi.mocked(useClientDataSWR).mock.calls[0][1] as () => unknown;+ await fetcher();+ expect(taskService.groupList).toHaveBeenCalledWith({+ assigneeAgentId: undefined,+ automated: false,+ excludeStatuses: ['completed', 'canceled'],+ groupBy: 'assignee',+ hasGoal: false,+ projectId: undefined,+ visibility: undefined,+ });+ });++ it('resets a changed group query scope after render and gates stale data meanwhile', () => {+ useTaskStore.setState({+ isTaskGroupListInit: true,+ listAgentId: '__all__',+ listGroupBy: 'status',+ listGroupExcludeStatuses: undefined,+ taskGroups: [{ key: 'backlog', tasks: [{ identifier: 'T-1' }], total: 1 }] as any,+ });+ let groupByObservedDuringRender: string | undefined;++ const { result } = renderHook(() => {+ const swr = useTaskStore+ .getState()+ .useFetchTaskGroupList({ allAgents: true, groupBy: 'assignee' });+ groupByObservedDuringRender = useTaskStore.getState().listGroupBy;+ return swr;+ });++ expect(groupByObservedDuringRender).toBe('status');+ expect(result.current.isQueryScopeCurrent).toBe(false);+ expect(useTaskStore.getState()).toMatchObject({+ isTaskGroupListInit: false,+ listGroupBy: 'assignee',+ taskGroups: [],+ });+ });+ });+describe('useFetchTaskList', () => {it('requests only tasks from the selected project', async () => {const { useClientDataSWR } = await import('@/libs/swr');@@ -232,7 +305,9 @@ describe('TaskListSliceAction', () => {const { useClientDataSWR } = await import('@/libs/swr');const { taskService } = await import('@/services/task');- useTaskStore.getState().useFetchTaskGroupList({ allAgents: true, automated: false });+ renderHook(() =>+ useTaskStore.getState().useFetchTaskGroupList({ allAgents: true, automated: false }),+ );expect(useClientDataSWR).toHaveBeenCalledWith(['task:groupList', '__all__', 'all', { automated: false }],diff --git a/src/store/task/slices/list/action.ts b/src/store/task/slices/list/action.tsindex d2f5e34719b..f3485bd1314 100644--- a/src/store/task/slices/list/action.ts+++ b/src/store/task/slices/list/action.ts@@ -1,4 +1,5 @@import type { TaskStatus } from '@lobechat/types';+import { useEffect } from 'react';import { mutate, useClientDataSWR } from '@/libs/swr';import { isScheduledTaskListKey, isTaskListKey, taskKeys } from '@/libs/swr/keys';@@ -6,7 +7,12 @@ import { taskService } from '@/services/task';import type { StoreSetter } from '@/store/types';import type { TaskStore } from '../../store';-import type { TaskGroupItem, TaskListItem, TaskListVisibilityFilter } from './initialState';+import type {+ TaskGroupItem,+ TaskKanbanGroupBy,+ TaskListItem,+ TaskListVisibilityFilter,+} from './initialState';/*** Sentinel used as `listAgentId` when the task list is showing tasks across all agents@@ -76,13 +82,21 @@ export class TaskListSliceActionImpl {}refreshTaskGroupList = async (): Promise<void> => {- const { listAgentId, listVisibility } = this.#get();+ const {+ groupListQueryAutomated,+ listAgentId,+ listGroupBy,+ listGroupExcludeStatuses,+ listVisibility,+ } = this.#get();await mutate(taskKeys.groupList(listAgentId,listVisibility,+ listGroupBy,+ listGroupExcludeStatuses,projectIdFromListKey(listAgentId),- this.#get().groupListQueryAutomated,+ groupListQueryAutomated,),);};@@ -91,7 +105,13 @@ export class TaskListSliceActionImpl {taskService.list(params);refreshTaskList = async (): Promise<void> => {- const { listAgentId, listVisibility } = this.#get();+ const {+ groupListQueryAutomated,+ listAgentId,+ listGroupBy,+ listGroupExcludeStatuses,+ listVisibility,+ } = this.#get();const projectId = projectIdFromListKey(listAgentId);await Promise.all([// Every cached variant of the list — both orderings, any visibility chip@@ -103,8 +123,10 @@ export class TaskListSliceActionImpl {taskKeys.groupList(listAgentId,listVisibility,+ listGroupBy,+ listGroupExcludeStatuses,projectId,- this.#get().groupListQueryAutomated,+ groupListQueryAutomated,),),// A schedule can be attached, changed or removed from any task edit, so@@ -138,37 +160,92 @@ export class TaskListSliceActionImpl {allAgents?: boolean;automated?: boolean;enabled?: boolean;+ excludeStatuses?: readonly TaskStatus[];+ groupBy?: TaskKanbanGroupBy;projectId?: string;} = {},) => {- const { agentId, allAgents = false, automated, enabled = true, projectId } = options;+ const {+ agentId,+ allAgents = false,+ automated,+ enabled = true,+ excludeStatuses,+ groupBy = 'status',+ projectId,+ } = options;const effectiveKey = projectId? `${PROJECT_LIST_KEY_PREFIX}${projectId}`: allAgents? ALL_AGENTS_LIST_KEY: agentId;- if (- effectiveKey &&- (this.#get().listAgentId !== effectiveKey ||- this.#get().groupListQueryAutomated !== automated)- ) {+ const excludeStatusesSignature = excludeStatuses?.length+ ? [...excludeStatuses].sort().join(',')+ : undefined;+ const { groupListQueryAutomated, listAgentId, listGroupBy, listGroupExcludeStatuses } =+ this.#get();+ const isQueryScopeCurrent =+ !effectiveKey ||+ (listAgentId === effectiveKey &&+ groupListQueryAutomated === automated &&+ listGroupBy === groupBy &&+ listGroupExcludeStatuses === excludeStatusesSignature);++ // Reset after render so changing the board dimension never notifies React+ // subscribers while another component is rendering. The caller gates old+ // groups with `isQueryScopeCurrent` until this effect commits the new scope.+ useEffect(() => {+ if (!effectiveKey) return;++ const current = this.#get();+ if (+ current.listAgentId === effectiveKey &&+ current.groupListQueryAutomated === automated &&+ current.listGroupBy === groupBy &&+ current.listGroupExcludeStatuses === excludeStatusesSignature+ ) {+ return;+ }+this.#set(- { ...scopeChangeResetState, groupListQueryAutomated: automated, listAgentId: effectiveKey },+ current.listAgentId !== effectiveKey+ ? {+ ...scopeChangeResetState,+ groupListQueryAutomated: automated,+ listAgentId: effectiveKey,+ listGroupBy: groupBy,+ listGroupExcludeStatuses: excludeStatusesSignature,+ }+ : {+ isTaskGroupListInit: false,+ groupListQueryAutomated: automated,+ listGroupBy: groupBy,+ listGroupExcludeStatuses: excludeStatusesSignature,+ taskGroups: [],+ },false,- 'useFetchTaskGroupList/syncAgentId',+ 'useFetchTaskGroupList/syncQueryScope',);- }+ }, [automated, effectiveKey, excludeStatusesSignature, groupBy]);const listVisibility = this.#get().listVisibility;- return useClientDataSWR(+ const swr = useClientDataSWR(enabled && effectiveKey- ? taskKeys.groupList(effectiveKey, listVisibility, projectId, automated)+ ? taskKeys.groupList(+ effectiveKey,+ listVisibility,+ groupBy,+ excludeStatusesSignature,+ projectId,+ automated,+ ): null,async () => {return taskService.groupList({assigneeAgentId: allAgents ? undefined : agentId,- automated,- groups: DEFAULT_KANBAN_GROUPS,+ ...(automated === undefined ? {} : { automated }),+ excludeStatuses: excludeStatuses?.length ? [...excludeStatuses] : undefined,+ ...(groupBy === 'status' ? { groups: DEFAULT_KANBAN_GROUPS } : { groupBy }),hasGoal: false,projectId,visibility: filterToServerVisibility(listVisibility),@@ -176,6 +253,17 @@ export class TaskListSliceActionImpl {},{onSuccess: (data: { data: TaskGroupItem[] }) => {+ const current = this.#get();+ if (+ current.listAgentId !== effectiveKey ||+ current.groupListQueryAutomated !== automated ||+ current.listGroupBy !== groupBy ||+ current.listGroupExcludeStatuses !== excludeStatusesSignature ||+ current.listVisibility !== listVisibility+ ) {+ return;+ }+this.#set({ isTaskGroupListInit: true, taskGroups: data.data },false,@@ -185,6 +273,8 @@ export class TaskListSliceActionImpl {revalidateOnFocus: false,},);++ return { ...swr, isQueryScopeCurrent };};/**diff --git a/src/store/task/slices/list/initialState.ts b/src/store/task/slices/list/initialState.tsindex 003551df322..79795ff082e 100644--- a/src/store/task/slices/list/initialState.ts+++ b/src/store/task/slices/list/initialState.ts@@ -13,12 +13,17 @@ export type TaskGroupItem = Awaited<ReturnType<typeof taskService.groupList>>['d* Personal mode hides the chip and treats every entry as 'all'.*/export type TaskListVisibilityFilter = 'all' | 'private' | 'workspace';+export type TaskKanbanGroupBy = 'assignee' | 'priority' | 'status';export interface TaskListSliceState {groupListQueryAutomated?: boolean;isTaskGroupListInit: boolean;isTaskListInit: boolean;listAgentId?: string;+ /** Grouping dimension of the task data currently stored in `taskGroups`. */+ listGroupBy: TaskKanbanGroupBy;+ /** Excluded statuses of the current grouped query, as a sorted signature. */+ listGroupExcludeStatuses?: string;/*** Automation filter of the task data currently stored in `tasks` — `false`* for Home's recent block (live schedules excluded server-side), undefined@@ -44,9 +49,10 @@ export interface TaskListSliceState {}export const initialTaskListSliceState: TaskListSliceState = {+ groupListQueryAutomated: undefined,isTaskGroupListInit: false,isTaskListInit: false,- groupListQueryAutomated: undefined,+ listGroupBy: 'status',listQueryVisibility: 'all',listVisibility: 'all',taskGroups: [],