🤯 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
♻️ refactor(tasks): streamline database list queries (#18618)
Arvin Xu452a0896b28b
diff --git a/packages/database/src/models/__tests__/task.test.ts b/packages/database/src/models/__tests__/task.test.tsindex db5fdd76cfe..e2cd5f7b790 100644--- a/packages/database/src/models/__tests__/task.test.ts+++ b/packages/database/src/models/__tests__/task.test.ts@@ -524,6 +524,19 @@ describe('TaskModel', () => {expect(backlogP2.offset).toBe(2);});+ it('should not double-count duplicate statuses in a group', async () => {+ const model = new TaskModel(serverDB, userId);+ await model.create({ instruction: 'Backlog task' });++ const [group] = await model.groupList({+ groups: [{ key: 'backlog', statuses: ['backlog', 'backlog'] }],+ });++ expect(group.total).toBe(1);+ expect(group.tasks).toHaveLength(1);+ expect(group.hasMore).toBe(false);+ });+it('should filter root tasks only (parentTaskId null)', async () => {const model = new TaskModel(serverDB, userId);const parent = await model.create({ instruction: 'Parent' });diff --git a/packages/database/src/models/task.ts b/packages/database/src/models/task.tsindex 503248698af..11c7114e3d2 100644--- a/packages/database/src/models/task.ts+++ b/packages/database/src/models/task.ts@@ -95,6 +95,29 @@ const HAS_GOAL = sql`EXISTS (WHERE ${goals.subjectType} = 'task' AND ${goals.subjectId} = ${tasks.id})`;+interface TaskListFilterOptions {+ assigneeAgentId?: string;+ automated?: boolean;+ hasGoal?: boolean;+ parentTaskId?: string | null;+ projectId?: string;+ visibility?: 'private' | 'public';+}++interface TaskListOptions extends TaskListFilterOptions {+ limit?: number;+ offset?: number;+ orderBy?: 'createdAt' | 'updatedAt';+ priorities?: number[];+ statuses?: string[];+}++interface TaskRunStats extends Record<string, unknown> {+ root_id: string;+ total_run_cost: number;+ total_run_duration: number;+}+export class TaskModel {private readonly userId: string;private readonly db: LobeChatDatabase;@@ -162,6 +185,35 @@ export class TaskModel {: sql`${prefix}created_by_user_id = ${this.userId} AND ${prefix}workspace_id IS NULL`;};+ private buildListConditions = ({+ assigneeAgentId,+ automated,+ hasGoal,+ parentTaskId,+ projectId,+ visibility,+ }: TaskListFilterOptions): SQL[] => {+ const conditions = [this.ownership()];++ if (assigneeAgentId) conditions.push(eq(tasks.assigneeAgentId, assigneeAgentId));+ if (automated === true) conditions.push(RUNNABLE_AUTOMATION);+ // `IS NOT TRUE`, not `NOT (…)`: nullable automation fields make the+ // runnable expression NULL for manual tasks, and WHERE would drop them.+ if (automated === false) conditions.push(sql`${RUNNABLE_AUTOMATION} IS NOT TRUE`);+ if (hasGoal === true) conditions.push(HAS_GOAL);+ if (hasGoal === false) conditions.push(sql`NOT ${HAS_GOAL}`);+ if (projectId) conditions.push(eq(tasks.projectId, projectId));+ if (visibility) conditions.push(eq(tasks.visibility, visibility));++ if (parentTaskId === null) {+ conditions.push(isNull(tasks.parentTaskId));+ } else if (parentTaskId) {+ conditions.push(eq(tasks.parentTaskId, parentTaskId));+ }++ return conditions;+ };+/*** Look up a task's visibility so child-row inserts (deps, docs, topics) can* mirror it without forcing every call site to know the value. Defaults to@@ -537,23 +589,16 @@ export class TaskModel {// ========== Query ==========- async groupList(options: {- assigneeAgentId?: string;- automated?: boolean;- groups: Array<{- key: string;- limit?: number;- offset?: number;- statuses: string[];- }>;- parentTaskId?: string | null;- /** Only return tasks carrying a bound goal entity (`goals` row). */- hasGoal?: boolean;- projectId?: string;- /** Same semantics as `list({ visibility })` — UI narrowing on top of the- * already ownership-filtered set. */- visibility?: 'private' | 'public';- }): Promise<+ async groupList(+ options: TaskListFilterOptions & {+ groups: Array<{+ key: string;+ limit?: number;+ offset?: number;+ statuses: string[];+ }>;+ },+ ): Promise<Array<{hasMore: boolean;key: string;@@ -563,99 +608,59 @@ export class TaskModel {total: number;}>> {- const { groups, assigneeAgentId, automated, hasGoal, parentTaskId, projectId, visibility } =- options;-- const baseConditions = [this.ownership()];- if (assigneeAgentId) baseConditions.push(eq(tasks.assigneeAgentId, assigneeAgentId));- if (automated === true) baseConditions.push(RUNNABLE_AUTOMATION);- if (automated === false) baseConditions.push(sql`${RUNNABLE_AUTOMATION} IS NOT TRUE`);- if (hasGoal === true) baseConditions.push(HAS_GOAL);- if (hasGoal === false) baseConditions.push(sql`NOT ${HAS_GOAL}`);- if (projectId) baseConditions.push(eq(tasks.projectId, projectId));- if (visibility) baseConditions.push(eq(tasks.visibility, visibility));- if (parentTaskId === null) {- baseConditions.push(isNull(tasks.parentTaskId));- } else if (parentTaskId) {- baseConditions.push(eq(tasks.parentTaskId, parentTaskId));- }+ const { groups } = options;+ const baseConditions = this.buildListConditions(options);+ const normalizedGroups = groups.map((group) => ({+ ...group,+ statuses: Array.from(new Set(group.statuses)),+ }));- // Collect all statuses for a single aggregated count query- const allStatuses = Array.from(new Set(groups.flatMap((g) => g.statuses)));- const countResult = await this.db+ 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);- const countByStatus: Record<string, number> = {};- for (const row of countResult) {- countByStatus[row.status] = Number(row.count);- }-- // Query each group's tasks in parallel- const results = await Promise.all(- groups.map(async (group) => {- const limit = group.limit ?? 50;- const offset = group.offset ?? 0;+ const groupQueries = normalizedGroups.map(async (group) => {+ const limit = group.limit ?? 50;+ const offset = group.offset ?? 0;- const groupTasks = await this.db- .select()- .from(tasks)- .where(and(...baseConditions, inArray(tasks.status, group.statuses)))- .orderBy(desc(tasks.createdAt))- .limit(limit)- .offset(offset);-- const total = group.statuses.reduce((sum, s) => sum + (countByStatus[s] || 0), 0);-- return {- hasMore: offset + groupTasks.length < total,- key: group.key,- limit,- offset,- tasks: groupTasks,- total,- };- }),- );+ const groupTasks = await this.db+ .select()+ .from(tasks)+ .where(and(...baseConditions, inArray(tasks.status, group.statuses)))+ .orderBy(desc(tasks.createdAt))+ .limit(limit)+ .offset(offset);++ return {+ key: group.key,+ 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);++ return {+ ...group,+ hasMore: group.offset + group.tasks.length < total,+ total,+ };+ });const taskIds = Array.from(new Set(results.flatMap((group) => group.tasks.map(({ id }) => id))),);- const runStats =- taskIds.length === 0- ? []- : (- await this.db.execute<{- root_id: string;- total_run_cost: number;- total_run_duration: number;- }>(sql`- WITH RECURSIVE goal_tree AS (- SELECT ${tasks.id} AS root_id, ${tasks.id} AS task_id- FROM ${tasks}- WHERE ${inArray(tasks.id, taskIds)} AND ${this.ownership()}- UNION ALL- SELECT goal_tree.root_id, child.id- FROM ${tasks} child- JOIN goal_tree ON child.parent_task_id = goal_tree.task_id- WHERE ${this.ownershipSql('child')}- )- SELECT- goal_tree.root_id,- coalesce(sum(${topics.totalCost}), 0) AS total_run_cost,- coalesce(- sum(extract(epoch from (${topics.completedAt} - ${taskTopics.createdAt})) * 1000)- filter (where ${topics.completedAt} is not null),- 0- ) AS total_run_duration- FROM goal_tree- LEFT JOIN ${taskTopics} ON ${taskTopics.taskId} = goal_tree.task_id- LEFT JOIN ${topics} ON ${topics.id} = ${taskTopics.topicId}- GROUP BY goal_tree.root_id- `)- ).rows;+ const [runStats, goalByTaskId] = await Promise.all([+ this.runStatsByTaskIds(taskIds),+ this.goalsByTaskIds(taskIds),+ ]);const runStatsByTaskId = new Map(runStats.map((stats) => [stats.root_id,@@ -666,8 +671,6 @@ export class TaskModel {]),);- const goalByTaskId = await this.goalsByTaskIds(taskIds);-return results.map((group) => ({...group,tasks: group.tasks.map((task) => ({@@ -691,84 +694,60 @@ export class TaskModel {return new Map(rows.map((row) => [row.subjectId!, row]));}- async list(options?: {- assigneeAgentId?: string;- /**- * Narrow to tasks that still run on their own — see {@link RUNNABLE_AUTOMATION}- * for what "still" rules out. `false` is its exact complement.- */- automated?: boolean;- hasGoal?: boolean;- limit?: number;- offset?: number;- /**- * Which timestamp the (bounded) result is ordered by, newest first.- * `createdAt` is the default because most callers want a stable list;- * a surface that calls itself "recent" wants `updatedAt`, or its page- * would omit the task that just moved in favour of a newer, idle one.- */- orderBy?: 'createdAt' | 'updatedAt';- parentTaskId?: string | null;- priorities?: number[];- projectId?: string;- statuses?: string[];- /**- * UI-side narrowing of the (already ownership-filtered) result set.- * Undefined means "no extra filter" (= "All" in the chip). Security is- * still enforced by `ownership()`; this is a view preference.- */- visibility?: 'private' | 'public';- }): Promise<{ tasks: TaskItem[]; total: number }> {- const {- statuses,- priorities,- parentTaskId,- assigneeAgentId,- automated,- hasGoal,- projectId,- visibility,- limit = 50,- offset = 0,- orderBy = 'createdAt',- } = options || {};+ private async runStatsByTaskIds(taskIds: string[]): Promise<TaskRunStats[]> {+ if (taskIds.length === 0) return [];- const conditions = [this.ownership()];+ const result = await this.db.execute<TaskRunStats>(sql`+ WITH RECURSIVE goal_tree AS (+ SELECT ${tasks.id} AS root_id, ${tasks.id} AS task_id+ FROM ${tasks}+ WHERE ${inArray(tasks.id, taskIds)} AND ${this.ownership()}+ UNION ALL+ SELECT goal_tree.root_id, child.id+ FROM ${tasks} child+ JOIN goal_tree ON child.parent_task_id = goal_tree.task_id+ WHERE ${this.ownershipSql('child')}+ )+ SELECT+ goal_tree.root_id,+ coalesce(sum(${topics.totalCost}), 0) AS total_run_cost,+ coalesce(+ sum(extract(epoch from (${topics.completedAt} - ${taskTopics.createdAt})) * 1000)+ filter (where ${topics.completedAt} is not null),+ 0+ ) AS total_run_duration+ FROM goal_tree+ LEFT JOIN ${taskTopics} ON ${taskTopics.taskId} = goal_tree.task_id+ LEFT JOIN ${topics} ON ${topics.id} = ${taskTopics.topicId}+ GROUP BY goal_tree.root_id+ `);++ return result.rows;+ }++ async list(options: TaskListOptions = {}): Promise<{ tasks: TaskItem[]; total: number }> {+ const { statuses, priorities, limit = 50, offset = 0, orderBy = 'createdAt' } = options;++ const conditions = this.buildListConditions(options);if (statuses?.length) conditions.push(inArray(tasks.status, statuses));if (priorities?.length) conditions.push(inArray(tasks.priority, priorities));- if (assigneeAgentId) conditions.push(eq(tasks.assigneeAgentId, assigneeAgentId));- if (automated === true) conditions.push(RUNNABLE_AUTOMATION);- // `IS NOT TRUE`, not `NOT (…)`: a manual task has a NULL `automation_mode`,- // so the predicate evaluates to NULL rather than false, and `NOT NULL` is- // still NULL — which WHERE drops. That would make `automated: false` return- // nothing at all for exactly the rows it is meant to return.- if (automated === false) conditions.push(sql`${RUNNABLE_AUTOMATION} IS NOT TRUE`);- if (hasGoal === true) conditions.push(HAS_GOAL);- if (hasGoal === false) conditions.push(sql`NOT ${HAS_GOAL}`);- if (projectId) conditions.push(eq(tasks.projectId, projectId));- if (visibility) conditions.push(eq(tasks.visibility, visibility));-- if (parentTaskId === null) {- conditions.push(isNull(tasks.parentTaskId));- } else if (parentTaskId) {- conditions.push(eq(tasks.parentTaskId, parentTaskId));- }const where = and(...conditions);- const countResult = await this.db+ const countQuery = this.db.select({ count: sql<number>`count(*)` }).from(tasks).where(where);- const taskList = await this.db+ const taskListQuery = this.db.select().from(tasks).where(where).orderBy(desc(orderBy === 'updatedAt' ? tasks.updatedAt : tasks.createdAt)).limit(limit).offset(offset);+ const [countResult, taskList] = await Promise.all([countQuery, taskListQuery]);return { tasks: taskList, total: Number(countResult[0].count) };}diff --git a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.test.ts b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.test.tsindex fd5fa62091f..b901b6c3644 100644--- a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.test.ts+++ b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.test.ts@@ -2,10 +2,12 @@ import { describe, expect, it } from 'vitest';import {clampScheduledPage,+ getScheduledTaskViewOptions,getTaskCreateActionBehavior,getTaskPageHeaderVisibility,resolveTaskCollection,} from './AgentTasksPage';+import { DEFAULT_TASK_LIST_VIEW_OPTIONS } from './listViewOptions';import { shouldRenderTaskAgentPanelToggle } from './taskAgentPanelToggle';describe('AgentTasksPage', () => {@@ -20,6 +22,26 @@ describe('AgentTasksPage', () => {});});+ describe('getScheduledTaskViewOptions', () => {+ it('keeps client sorting aligned with the updatedAt-desc server pagination', () => {+ expect(+ getScheduledTaskViewOptions({+ ...DEFAULT_TASK_LIST_VIEW_OPTIONS,+ orderBy: 'title',+ orderDirection: 'asc',+ showSubTasks: true,+ }),+ ).toEqual({+ ...DEFAULT_TASK_LIST_VIEW_OPTIONS,+ groupBy: 'automationMode',+ hideCompleted: false,+ orderBy: 'updatedAt',+ orderDirection: 'desc',+ showSubTasks: true,+ });+ });+ });+describe('resolveTaskCollection', () => {it('opens the scheduled collection from its addressable URL', () => {expect(resolveTaskCollection(new URLSearchParams('collection=scheduled'))).toBe('scheduled');diff --git a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsxindex b70d8c16d06..9c2787dd2d9 100644--- a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx+++ b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx@@ -90,6 +90,16 @@ export const resolveTaskCollection = (searchParams: URLSearchParams): TaskCollecexport const clampScheduledPage = (page: number, total: number): number =>Math.min(page, Math.max(1, Math.ceil(total / SCHEDULED_TASK_PAGE_SIZE)));+export const getScheduledTaskViewOptions = (+ viewOptions: TaskListViewOptions,+): TaskListViewOptions => ({+ ...viewOptions,+ groupBy: 'automationMode',+ hideCompleted: false,+ orderBy: 'updatedAt',+ orderDirection: 'desc',+});+const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, projectId }) => {const { t } = useTranslation('chat');const navigate = useWorkspaceAwareNavigate();@@ -133,7 +143,7 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, projectId }) => {const rawViewOptions = useGlobalStore(systemStatusSelectors.taskListViewOptions);const viewOptions = useMemo(() => normalizeTaskListViewOptions(rawViewOptions), [rawViewOptions]);const scheduledViewOptions = useMemo(- () => ({ ...viewOptions, groupBy: 'automationMode' as const, hideCompleted: false }),+ () => getScheduledTaskViewOptions(viewOptions),[viewOptions],);useEffect(() => {