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): Linear-style filters on the Tasks page (#22083)

Rdmclin24b0b029da149
diff --git a/apps/server/src/routers/lambda/_helpers/taskListSchemas.test.ts b/apps/server/src/routers/lambda/_helpers/taskListSchemas.test.ts
index 8161a5efc03..323ba130e69 100644
--- a/apps/server/src/routers/lambda/_helpers/taskListSchemas.test.ts
+++ b/apps/server/src/routers/lambda/_helpers/taskListSchemas.test.ts
@@ -22,3 +22,44 @@ describe('completedWithin', () => {
expect(resolveClosedAfter(undefined, now)).toBeUndefined();
});
});
+
+describe('filter', () => {
+ const filter = {
+ agent: { operator: 'isNot', values: ['agt_1', '__none__'] },
+ completedAt: { operator: 'before', window: 'quarter' },
+ content: ' menu ',
+ priority: { operator: 'is', values: [0, 2] },
+ status: { operator: 'is', values: ['backlog'] },
+ } as const;
+
+ it('is accepted by list and groupList', () => {
+ expect(listSchema.parse({ filter }).filter).toEqual({ ...filter, content: 'menu' });
+ expect(groupListSchema.parse({ filter, groupBy: 'priority' }).filter?.status).toEqual(
+ filter.status,
+ );
+ });
+
+ it('rejects malformed conditions', () => {
+ expect(() =>
+ listSchema.parse({ filter: { status: { operator: 'is', values: ['done'] } } }),
+ ).toThrow();
+ expect(() =>
+ listSchema.parse({ filter: { priority: { operator: 'is', values: [5] } } }),
+ ).toThrow();
+ expect(() =>
+ listSchema.parse({ filter: { status: { operator: 'is', values: [] } } }),
+ ).toThrow();
+ expect(() =>
+ listSchema.parse({ filter: { createdAt: { operator: 'within', window: 'year' } } }),
+ ).toThrow();
+ expect(() =>
+ listSchema.parse({ filter: { status: { operator: 'contains', values: ['backlog'] } } }),
+ ).toThrow();
+ });
+
+ it('does not let a creator condition ask for "nobody"', () => {
+ expect(() =>
+ listSchema.parse({ filter: { creator: { operator: 'is', values: ['__none__'] } } }),
+ ).toThrow();
+ });
+});
diff --git a/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts b/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts
index efe21796250..30694a2cd2b 100644
--- a/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts
+++ b/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts
@@ -4,8 +4,48 @@ import {
TASK_STATUSES,
type TaskCompletedWindow,
} from '@lobechat/builtin-tool-task';
+import {
+ TASK_LIST_FILTER_CONTENT_MAX_LENGTH,
+ TASK_LIST_FILTER_DATE_OPERATORS,
+ TASK_LIST_FILTER_DATE_WINDOWS,
+ TASK_LIST_FILTER_MAX_VALUES,
+ TASK_LIST_FILTER_NONE,
+ TASK_LIST_FILTER_OPERATORS,
+} from '@lobechat/types';
import { z } from 'zod';
+const filterSet = <T extends z.ZodTypeAny>(value: T) =>
+ z.object({
+ operator: z.enum(TASK_LIST_FILTER_OPERATORS),
+ values: z.array(value).min(1).max(TASK_LIST_FILTER_MAX_VALUES),
+ });
+
+const filterDate = z.object({
+ operator: z.enum(TASK_LIST_FILTER_DATE_OPERATORS),
+ window: z.enum(TASK_LIST_FILTER_DATE_WINDOWS),
+});
+
+const filterId = z.string().min(1).max(255);
+
+/**
+ * The Tasks page filter (`TaskListFilter` in `@lobechat/types`). Ids may hold
+ * `TASK_LIST_FILTER_NONE` for "no agent / member / project"; a creator is
+ * never missing, so that set takes member ids and `agent:<id>` agent creators. Ownership is still enforced by
+ * the model, so a filter can only narrow what the caller may already see.
+ */
+export const taskListFilterSchema = z.object({
+ agent: filterSet(filterId).optional(),
+ assignee: filterSet(filterId).optional(),
+ completedAt: filterDate.optional(),
+ content: z.string().trim().max(TASK_LIST_FILTER_CONTENT_MAX_LENGTH).optional(),
+ createdAt: filterDate.optional(),
+ creator: filterSet(filterId.refine((id) => id !== TASK_LIST_FILTER_NONE)).optional(),
+ priority: filterSet(z.number().int().min(0).max(4)).optional(),
+ project: filterSet(filterId).optional(),
+ status: filterSet(z.enum(TASK_STATUSES)).optional(),
+ updatedAt: filterDate.optional(),
+});
+
export const listSchema = z.object({
// Keyset cursor — rows strictly after this `(orderBy timestamp, seq)` position
// in newest-first order. Stable under concurrent inserts/deletes, unlike `offset`.
@@ -18,6 +58,8 @@ export const listSchema = z.object({
// Keep completed and canceled tasks only when closed within this look-back
// window. Relative, so a client's query stays the same as time passes.
completedWithin: z.enum(TASK_COMPLETED_WINDOWS).optional(),
+ // The Tasks page filter; narrows on top of every other option.
+ filter: taskListFilterSchema.optional(),
// Archived tasks are user-closed; lists leave them out unless asked.
includeArchived: z.boolean().optional(),
limit: z.number().min(1).max(100).default(50),
@@ -45,6 +87,7 @@ export const groupListSchema = z
automated: z.boolean().optional(),
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', 'member', 'priority']).optional(),
groups: z
.array(
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 54d255abb05..888881dc69b 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2693,6 +2693,43 @@
"taskList.empty": "No tasks yet",
"taskList.emptyHero.greeting": "What should we tackle today?",
"taskList.emptyHero.templatesTitle": "Templates picked for you",
+ "taskList.filter.add": "Add filter",
+ "taskList.filter.clear": "Clear",
+ "taskList.filter.clearAll": "Clear filters",
+ "taskList.filter.contentContains": "Content contains “{{text}}”",
+ "taskList.filter.empty": "No tasks match the current filters",
+ "taskList.filter.field.agent": "Agent",
+ "taskList.filter.field.assignee": "Assignee",
+ "taskList.filter.field.completedAt": "Completed",
+ "taskList.filter.field.content": "Content",
+ "taskList.filter.field.createdAt": "Created",
+ "taskList.filter.field.creator": "Creator",
+ "taskList.filter.field.dates": "Dates",
+ "taskList.filter.field.priority": "Priority",
+ "taskList.filter.field.project": "Project",
+ "taskList.filter.field.status": "Status",
+ "taskList.filter.field.updatedAt": "Updated",
+ "taskList.filter.me": "Me",
+ "taskList.filter.noAgent": "No agent",
+ "taskList.filter.noProject": "No project",
+ "taskList.filter.operator.before": "is older than",
+ "taskList.filter.operator.contains": "contains",
+ "taskList.filter.operator.is": "is",
+ "taskList.filter.operator.isAnyOf": "is any of",
+ "taskList.filter.operator.isNoneOf": "is none of",
+ "taskList.filter.operator.isNot": "is not",
+ "taskList.filter.operator.within": "is within",
+ "taskList.filter.remove": "Remove filter",
+ "taskList.filter.searchPlaceholder": "Add filter…",
+ "taskList.filter.unknownValue": "Unknown",
+ "taskList.filter.untitledAgent": "Untitled agent",
+ "taskList.filter.untitledProject": "Untitled project",
+ "taskList.filter.valueCount_one": "{{count}} value",
+ "taskList.filter.valueCount_other": "{{count}} values",
+ "taskList.filter.window.day": "Past day",
+ "taskList.filter.window.month": "Past month",
+ "taskList.filter.window.quarter": "Past 3 months",
+ "taskList.filter.window.week": "Past week",
"taskList.form.columns": "Columns",
"taskList.form.completedTasks": "Completed & canceled",
"taskList.form.grouping": "Grouping",
diff --git a/locales/en-US/hotkey.json b/locales/en-US/hotkey.json
index 707919492d2..7c2577f16f1 100644
--- a/locales/en-US/hotkey.json
+++ b/locales/en-US/hotkey.json
@@ -27,6 +27,8 @@
"openChatSettings.title": "Open Chat Settings",
"openHotkeyHelper.desc": "View instructions for all keyboard shortcuts",
"openHotkeyHelper.title": "Open Hotkey Help",
+ "openTaskFilter.desc": "Open the filter menu on the Tasks page",
+ "openTaskFilter.title": "Filter Tasks",
"prevTab.desc": "Cycle to the previous tab in the Desktop app; wraps around to the last tab at the beginning",
"prevTab.title": "Previous Tab",
"regenerateMessage.desc": "Regenerate the last message",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index e0384e5b381..3cdc3a6189a 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2693,6 +2693,43 @@
"taskList.empty": "暂无任务",
"taskList.emptyHero.greeting": "今天想搞定点什么?",
"taskList.emptyHero.templatesTitle": "为你推荐的模板",
+ "taskList.filter.add": "添加筛选",
+ "taskList.filter.clear": "清除",
+ "taskList.filter.clearAll": "清除筛选",
+ "taskList.filter.contentContains": "内容包含“{{text}}”",
+ "taskList.filter.empty": "没有符合当前筛选条件的任务",
+ "taskList.filter.field.agent": "执行助理",
+ "taskList.filter.field.assignee": "负责人",
+ "taskList.filter.field.completedAt": "完成时间",
+ "taskList.filter.field.content": "内容",
+ "taskList.filter.field.createdAt": "创建时间",
+ "taskList.filter.field.creator": "创建者",
+ "taskList.filter.field.dates": "日期",
+ "taskList.filter.field.priority": "优先级",
+ "taskList.filter.field.project": "项目",
+ "taskList.filter.field.status": "状态",
+ "taskList.filter.field.updatedAt": "更新时间",
+ "taskList.filter.me": "我",
+ "taskList.filter.noAgent": "无执行助理",
+ "taskList.filter.noProject": "无项目",
+ "taskList.filter.operator.before": "早于",
+ "taskList.filter.operator.contains": "包含",
+ "taskList.filter.operator.is": "是",
+ "taskList.filter.operator.isAnyOf": "是其中之一",
+ "taskList.filter.operator.isNoneOf": "不是其中任何一个",
+ "taskList.filter.operator.isNot": "不是",
+ "taskList.filter.operator.within": "在",
+ "taskList.filter.remove": "移除筛选",
+ "taskList.filter.searchPlaceholder": "添加筛选…",
+ "taskList.filter.unknownValue": "未知",
+ "taskList.filter.untitledAgent": "未命名助理",
+ "taskList.filter.untitledProject": "未命名项目",
+ "taskList.filter.valueCount_one": "{{count}} 项",
+ "taskList.filter.valueCount_other": "{{count}} 项",
+ "taskList.filter.window.day": "过去 1 天",
+ "taskList.filter.window.month": "过去 1 个月",
+ "taskList.filter.window.quarter": "过去 3 个月",
+ "taskList.filter.window.week": "过去 1 周",
"taskList.form.columns": "列",
"taskList.form.completedTasks": "已完成与已取消",
"taskList.form.grouping": "分组",
diff --git a/locales/zh-CN/hotkey.json b/locales/zh-CN/hotkey.json
index 599c7a7783b..e9236455e4f 100644
--- a/locales/zh-CN/hotkey.json
+++ b/locales/zh-CN/hotkey.json
@@ -27,6 +27,8 @@
"openChatSettings.title": "打开会话设置",
"openHotkeyHelper.desc": "查看所有快捷键的使用说明",
"openHotkeyHelper.title": "打开快捷键帮助",
+ "openTaskFilter.desc": "在任务页打开筛选菜单",
+ "openTaskFilter.title": "筛选任务",
"prevTab.desc": "在桌面端标签页之间反向循环切换,到达开头后跳回最后一个标签页",
"prevTab.title": "上一个标签页",
"regenerateMessage.desc": "重新生成最后一条消息",
diff --git a/packages/const/src/hotkeys.ts b/packages/const/src/hotkeys.ts
index 79a1329bc2a..b92cb2fac03 100644
--- a/packages/const/src/hotkeys.ts
+++ b/packages/const/src/hotkeys.ts
@@ -51,6 +51,7 @@ export const HotkeyEnum = {
OpenChatSettings: 'openChatSettings',
PrevTab: 'prevTab',
OpenHotkeyHelper: 'openHotkeyHelper',
+ OpenTaskFilter: 'openTaskFilter',
RegenerateMessage: 'regenerateMessage',
SaveDocument: 'saveDocument',
SaveTopic: 'saveTopic',
@@ -149,6 +150,12 @@ export const HOTKEYS_REGISTRATION: HotkeyRegistration = [
keys: combineKeys([KeyEnum.Alt, 'f']),
scopes: [HotkeyScopeEnum.Global],
},
+ {
+ group: HotkeyGroupEnum.Essential,
+ id: HotkeyEnum.OpenTaskFilter,
+ keys: 'f',
+ scopes: [HotkeyScopeEnum.Global],
+ },
// Chat
{
group: HotkeyGroupEnum.Conversation,
diff --git a/packages/database/src/models/__tests__/task.filter.test.ts b/packages/database/src/models/__tests__/task.filter.test.ts
new file mode 100644
index 00000000000..d5dd6900d90
--- /dev/null
+++ b/packages/database/src/models/__tests__/task.filter.test.ts
@@ -0,0 +1,225 @@
+// @vitest-environment node
+import {
+ matchesTaskListFilter,
+ TASK_LIST_FILTER_NONE,
+ type TaskListFilter,
+ toTaskListFilterAgentCreator,
+} from '@lobechat/types';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { agents, projects, tasks, users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { TaskModel } from '../task';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'task-filter-test-user-id';
+const otherUserId = 'task-filter-test-other-user-id';
+const DAY_MS = 24 * 60 * 60 * 1000;
+const NOW = Date.now();
+const daysAgo = (days: number) => new Date(NOW - days * DAY_MS);
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await serverDB.insert(agents).values([
+ { id: 'agt_filter_a', slug: 'agt_filter_a', userId },
+ { id: 'agt_filter_b', slug: 'agt_filter_b', userId },
+ ]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+});
+
+/**
+ * Five tasks spread over every filterable dimension:
+ * - `alpha` backlog, urgent, agent A, member self, project P, created 2 days ago
+ * - `beta` running, high, agent B, member other, no project, created 20 days ago
+ * - `gamma` completed 3 days ago, priority NULL, no agent, no member, project P
+ * - `delta` completed 60 days ago, low, agent A, created 120 days ago by agent A
+ * - `literal` backlog, no priority, its name holds `100%_done`
+ */
+const seed = async () => {
+ const model = new TaskModel(serverDB, userId);
+ const [project] = await serverDB
+ .insert(projects)
+ .values({ name: 'P', userId })
+ .returning({ id: projects.id });
+
+ const alpha = await model.create({
+ assigneeAgentId: 'agt_filter_a',
+ assigneeUserId: userId,
+ instruction: 'Build the alpha filter menu',
+ name: 'Alpha',
+ priority: 1,
+ projectId: project.id,
+ });
+ const beta = await model.create({
+ assigneeAgentId: 'agt_filter_b',
+ assigneeUserId: otherUserId,
+ instruction: 'Beta work',
+ name: 'Beta',
+ priority: 2,
+ });
+ const gamma = await model.create({
+ instruction: 'Gamma work',
+ name: 'Gamma',
+ projectId: project.id,
+ });
+ const delta = await model.create({
+ assigneeAgentId: 'agt_filter_a',
+ instruction: 'Delta work',
+ name: 'Delta',
+ priority: 4,
+ });
+ const literal = await model.create({ instruction: 'Literal work', name: 'Ship 100%_done' });
+
+ await serverDB
+ .update(tasks)
+ .set({ createdAt: daysAgo(2), updatedAt: daysAgo(1) })
+ .where(eq(tasks.id, alpha.id));
+ await serverDB
+ .update(tasks)
+ .set({ createdAt: daysAgo(20), status: 'running', updatedAt: daysAgo(10) })
+ .where(eq(tasks.id, beta.id));
+ await serverDB
+ .update(tasks)
+ .set({
+ completedAt: daysAgo(3),
+ createdAt: daysAgo(5),
+ priority: null,
+ status: 'completed',
+ updatedAt: daysAgo(3),
+ })
+ .where(eq(tasks.id, gamma.id));
+ await serverDB
+ .update(tasks)
+ .set({
+ completedAt: daysAgo(60),
+ createdAt: daysAgo(120),
+ createdByAgentId: 'agt_filter_a',
+ status: 'completed',
+ updatedAt: daysAgo(60),
+ })
+ .where(eq(tasks.id, delta.id));
+
+ return { alpha, beta, delta, gamma, literal, model, projectId: project.id };
+};
+
+const ids = (rows: { id: string }[]) => rows.map((row) => row.id).sort();
+
+describe('TaskModel list filter', () => {
+ it('narrows by each field and agrees with the JS mirror', async () => {
+ const { alpha, beta, delta, gamma, literal, model, projectId } = await seed();
+ const all = [alpha, beta, gamma, delta, literal];
+
+ const cases: Array<[TaskListFilter, { id: string }[]]> = [
+ [{ status: { operator: 'is', values: ['completed'] } }, [gamma, delta]],
+ [{ status: { operator: 'isNot', values: ['completed', 'running'] } }, [alpha, literal]],
+ // A NULL priority counts as "no priority".
+ [{ priority: { operator: 'is', values: [0] } }, [gamma, literal]],
+ [{ priority: { operator: 'isNot', values: [0, 4] } }, [alpha, beta]],
+ [{ agent: { operator: 'is', values: ['agt_filter_a'] } }, [alpha, delta]],
+ [
+ { agent: { operator: 'is', values: ['agt_filter_b', TASK_LIST_FILTER_NONE] } },
+ [beta, gamma, literal],
+ ],
+ // "is not A" keeps the unassigned rows…
+ [{ agent: { operator: 'isNot', values: ['agt_filter_a'] } }, [beta, gamma, literal]],
+ // …and excluding "none" drops exactly them.
+ [{ agent: { operator: 'isNot', values: [TASK_LIST_FILTER_NONE] } }, [alpha, beta, delta]],
+ [{ assignee: { operator: 'is', values: [otherUserId] } }, [beta]],
+ [{ assignee: { operator: 'is', values: [TASK_LIST_FILTER_NONE] } }, [gamma, delta, literal]],
+ // A member still finds the tasks their agents created for them…
+ [{ creator: { operator: 'is', values: [userId] } }, all],
+ [{ creator: { operator: 'isNot', values: [userId] } }, []],
+ // …and the agent value finds only what that agent created; NULL agents stay in `isNot`.
+ [
+ { creator: { operator: 'isNot', values: [toTaskListFilterAgentCreator('agt_filter_a')] } },
+ [alpha, beta, gamma, literal],
+ ],
+ [
+ { creator: { operator: 'is', values: [toTaskListFilterAgentCreator('agt_filter_a')] } },
+ [delta],
+ ],
+ [
+ {
+ creator: {
+ operator: 'is',
+ values: [userId, toTaskListFilterAgentCreator('agt_filter_a')],
+ },
+ },
+ all,
+ ],
+ [{ project: { operator: 'is', values: [projectId] } }, [alpha, gamma]],
+ [{ project: { operator: 'isNot', values: [projectId, TASK_LIST_FILTER_NONE] } }, []],
+ [{ createdAt: { operator: 'within', window: 'week' } }, [alpha, gamma, literal]],
+ [{ createdAt: { operator: 'before', window: 'quarter' } }, [delta]],
+ [{ updatedAt: { operator: 'before', window: 'week' } }, [beta, delta]],
+ // Unfinished tasks have no completedAt and match neither side.
+ [{ completedAt: { operator: 'within', window: 'week' } }, [gamma]],
+ [{ completedAt: { operator: 'before', window: 'month' } }, [delta]],
+ [{ content: 'ALPHA FILTER' }, [alpha]],
+ [{ content: 'work' }, [beta, gamma, delta, literal]],
+ // LIKE wildcards in the text are literal.
+ [{ content: '100%_' }, [literal]],
+ [{ content: '%' }, [literal]],
+ [{ content: '_' }, [literal]],
+ // Fields are ANDed.
+ [
+ {
+ agent: { operator: 'is', values: ['agt_filter_a'] },
+ status: { operator: 'is', values: ['completed'] },
+ },
+ [delta],
+ ],
+ ];
+
+ const rows = await model.list({ limit: 100 });
+ for (const [filter, expected] of cases) {
+ const result = await model.list({ filter, limit: 100, now: NOW });
+ expect(ids(result.tasks), JSON.stringify(filter)).toEqual(ids(expected));
+ expect(result.total, JSON.stringify(filter)).toBe(expected.length);
+ expect(
+ ids(rows.tasks.filter((task) => matchesTaskListFilter(task, filter, NOW))),
+ `JS mirror of ${JSON.stringify(filter)}`,
+ ).toEqual(ids(expected));
+ }
+ });
+
+ it('applies the filter to every groupList shape', async () => {
+ const { alpha, delta, model } = await seed();
+ const filter: TaskListFilter = { agent: { operator: 'is', values: ['agt_filter_a'] } };
+
+ const statusGroups = await model.groupList({
+ filter,
+ groups: [
+ { key: 'backlog', statuses: ['backlog'] },
+ { key: 'done', statuses: ['completed'] },
+ ],
+ });
+ const byKey = new Map(statusGroups.map((group) => [group.key, group]));
+ expect(ids(byKey.get('backlog')!.tasks)).toEqual([alpha.id]);
+ expect(byKey.get('backlog')!.total).toBe(1);
+ expect(ids(byKey.get('done')!.tasks)).toEqual([delta.id]);
+
+ const priorityGroups = await model.groupList({ filter, groupBy: 'priority' });
+ const priorityTasks = priorityGroups.flatMap((group) => group.tasks);
+ expect(ids(priorityTasks)).toEqual(ids([alpha, delta]));
+
+ const agentGroups = await model.groupList({ filter, groupBy: 'agent' });
+ expect(ids(agentGroups.flatMap((group) => group.tasks))).toEqual(ids([alpha, delta]));
+ });
+
+ it('cannot widen ownership: another user sees nothing of these tasks', async () => {
+ await seed();
+ const other = new TaskModel(serverDB, otherUserId);
+ const result = await other.list({
+ filter: { assignee: { operator: 'is', values: [otherUserId] } },
+ });
+ expect(result.tasks).toEqual([]);
+ });
+});
diff --git a/packages/database/src/models/taskListFilters.ts b/packages/database/src/models/taskListFilters.ts
index 355b31cfdc5..56056ef1c56 100644
--- a/packages/database/src/models/taskListFilters.ts
+++ b/packages/database/src/models/taskListFilters.ts
@@ -1,4 +1,29 @@
-import { and, eq, gt, isNotNull, isNull, ne, notInArray, or, type SQL, sql } from 'drizzle-orm';
+import {
+ resolveTaskListFilterDateCutoff,
+ TASK_LIST_FILTER_AGENT_CREATOR_PREFIX,
+ TASK_LIST_FILTER_NONE,
+ type TaskListFilter,
+ type TaskListFilterDate,
+ type TaskListFilterSet,
+} from '@lobechat/types';
+import {
+ and,
+ eq,
+ gt,
+ gte,
+ ilike,
+ inArray,
+ isNotNull,
+ isNull,
+ lt,
+ ne,
+ not,
+ notInArray,
+ or,
+ SQL,
+ sql,
+} from 'drizzle-orm';
+import type { PgColumn } from 'drizzle-orm/pg-core';
import { tasks } from '../schemas/task';
@@ -52,8 +77,12 @@ export interface TaskListFilterOptions {
closedAfter?: Date;
/** Only tasks created by this user. */
createdByUserId?: string;
+ /** The Tasks page filter (status, priority, agent, member, project, dates, content). */
+ filter?: TaskListFilter;
/** Archived tasks are user-closed and hidden from every list unless asked for. */
includeArchived?: boolean;
+ /** Clock the filter's relative date windows resolve against; tests pin it. */
+ now?: number;
parentTaskId?: string | null;
projectId?: string;
visibility?: 'private' | 'public';
@@ -81,7 +110,9 @@ export const buildTaskListFilters = ({
automated,
closedAfter,
createdByUserId,
+ filter,
includeArchived,
+ now,
parentTaskId,
projectId,
visibility,
@@ -113,5 +144,100 @@ export const buildTaskListFilters = ({
conditions.push(eq(tasks.parentTaskId, parentTaskId));
}
+ if (filter) conditions.push(...buildTaskFilterConditions(filter, now));
+
return conditions;
};
+
+/**
+ * One value-set condition. `TASK_LIST_FILTER_NONE` stands for NULL, and
+ * `isNot` keeps the NULL rows unless "none" itself is excluded — "agent is
+ * not A" still lists the unassigned tasks, as `matchesTaskListFilter` does.
+ */
+const buildSetCondition = (
+ column: PgColumn | SQL,
+ set: TaskListFilterSet<number | string> | undefined,
+): SQL | undefined => {
+ if (!set || set.values.length === 0) return undefined;
+ const includesNone = set.values.includes(TASK_LIST_FILTER_NONE);
+ const values = set.values.filter((value) => value !== TASK_LIST_FILTER_NONE);
+ // inArray overloads a column and an SQL expression separately; it rejects the union.
+ const matchesValue =
+ values.length === 0
+ ? undefined
+ : column instanceof SQL
+ ? inArray(column, values)
+ : inArray(column, values);
+ const matchesNone = includesNone ? isNull(column) : undefined;
+
+ if (set.operator === 'isNot') {
+ // NOT IN is NULL for a NULL column, so the NULL side is decided explicitly.
+ const notValue = matchesValue ? or(isNull(column), not(matchesValue)) : undefined;
+ return includesNone ? and(isNotNull(column), ...(notValue ? [notValue] : [])) : notValue;
+ }
+ return or(...[matchesValue, matchesNone].filter((c): c is SQL => !!c));
+};
+
+/**
+ * Member values match `created_by_user_id`, `agent:<id>` values match
+ * `created_by_agent_id`; a task matches when either side does, so a member
+ * still finds the tasks their agents created. Mirrors `matchesTaskListFilter`.
+ */
+const buildCreatorCondition = (set: TaskListFilterSet<string> | undefined): SQL | undefined => {
+ if (!set || set.values.length === 0) return undefined;
+ const userIds = set.values.filter(
+ (value) => !value.startsWith(TASK_LIST_FILTER_AGENT_CREATOR_PREFIX),
+ );
+ const agentIds = set.values
+ .filter((value) => value.startsWith(TASK_LIST_FILTER_AGENT_CREATOR_PREFIX))
+ .map((value) => value.slice(TASK_LIST_FILTER_AGENT_CREATOR_PREFIX.length));
+ const matches = or(
+ ...[
+ userIds.length > 0 ? inArray(tasks.createdByUserId, userIds) : undefined,
+ agentIds.length > 0 ? inArray(tasks.createdByAgentId, agentIds) : undefined,
+ ].filter((condition): condition is SQL => !!condition),
+ )!;
+ // `created_by_agent_id` is NULL on member-made tasks; coalesce keeps NOT from
+ // turning that NULL into "unknown" and dropping the row.
+ return set.operator === 'isNot' ? not(sql`coalesce(${matches}, false)`) : matches;
+};
+
+/** A NULL timestamp (an unfinished task's `completedAt`) matches neither side. */
+const buildDateCondition = (
+ column: PgColumn,
+ date: TaskListFilterDate | undefined,
+ now?: number,
+): SQL | undefined => {
+ if (!date) return undefined;
+ const cutoff = resolveTaskListFilterDateCutoff(date.window, now);
+ return date.operator === 'before' ? lt(column, cutoff) : gte(column, cutoff);
+};
+
+/** `%`, `_` and the escape character itself are literal in a content search. */
+const escapeLikePattern = (value: string) => value.replaceAll(/[%\\_]/g, (char) => `\\${char}`);
+
+export const buildTaskFilterConditions = (filter: TaskListFilter, now?: number): SQL[] => {
+ const content = filter.content?.trim();
+ const pattern = content ? `%${escapeLikePattern(content)}%` : undefined;
+
+ return [
+ buildSetCondition(tasks.status, filter.status),
+ // A missing priority is "no priority" (0), the same bucket the UI shows it in.
+ buildSetCondition(sql`coalesce(${tasks.priority}, 0)`, filter.priority),
+ buildSetCondition(tasks.assigneeAgentId, filter.agent),
+ buildSetCondition(tasks.assigneeUserId, filter.assignee),
+ buildCreatorCondition(filter.creator),
+ buildSetCondition(tasks.projectId, filter.project),
+ buildDateCondition(tasks.createdAt, filter.createdAt, now),
+ buildDateCondition(tasks.updatedAt, filter.updatedAt, now),
+ buildDateCondition(tasks.completedAt, filter.completedAt, now),
+ pattern
+ ? or(
+ ilike(tasks.name, pattern),
+ ilike(tasks.identifier, pattern),
+ ilike(tasks.description, pattern),
+ ilike(tasks.instruction, pattern),
+ )
+ : undefined,
+ ].filter((condition): condition is SQL => !!condition);
+};
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 2ec1035f2d4..40285ba07fc 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -3127,6 +3127,43 @@ export default {
'taskList.empty': 'No tasks yet',
'taskList.emptyHero.greeting': 'What should we tackle today?',
'taskList.emptyHero.templatesTitle': 'Templates picked for you',
+ 'taskList.filter.add': 'Add filter',
+ 'taskList.filter.clear': 'Clear',
+ 'taskList.filter.clearAll': 'Clear filters',
+ 'taskList.filter.contentContains': 'Content contains “{{text}}”',
+ 'taskList.filter.empty': 'No tasks match the current filters',
+ 'taskList.filter.field.agent': 'Agent',
+ 'taskList.filter.field.assignee': 'Assignee',
+ 'taskList.filter.field.completedAt': 'Completed',
+ 'taskList.filter.field.content': 'Content',
+ 'taskList.filter.field.createdAt': 'Created',
+ 'taskList.filter.field.creator': 'Creator',
+ 'taskList.filter.field.dates': 'Dates',
+ 'taskList.filter.field.priority': 'Priority',
+ 'taskList.filter.field.project': 'Project',
+ 'taskList.filter.field.status': 'Status',
+ 'taskList.filter.field.updatedAt': 'Updated',
+ 'taskList.filter.me': 'Me',
+ 'taskList.filter.noAgent': 'No agent',
+ 'taskList.filter.noProject': 'No project',
+ 'taskList.filter.operator.before': 'is older than',
+ 'taskList.filter.operator.contains': 'contains',
+ 'taskList.filter.operator.is': 'is',
+ 'taskList.filter.operator.isAnyOf': 'is any of',
+ 'taskList.filter.operator.isNoneOf': 'is none of',
+ 'taskList.filter.operator.isNot': 'is not',
+ 'taskList.filter.operator.within': 'is within',
+ 'taskList.filter.remove': 'Remove filter',
+ 'taskList.filter.searchPlaceholder': 'Add filter…',
+ 'taskList.filter.unknownValue': 'Unknown',
+ 'taskList.filter.untitledAgent': 'Untitled agent',
+ 'taskList.filter.untitledProject': 'Untitled project',
+ 'taskList.filter.valueCount_one': '{{count}} value',
+ 'taskList.filter.valueCount_other': '{{count}} values',
+ 'taskList.filter.window.day': 'Past day',
+ 'taskList.filter.window.month': 'Past month',
+ 'taskList.filter.window.quarter': 'Past 3 months',
+ 'taskList.filter.window.week': 'Past week',
'taskList.form.columns': 'Columns',
'taskList.form.completedTasks': 'Completed & canceled',
'taskList.form.grouping': 'Grouping',
diff --git a/packages/locales/src/default/hotkey.ts b/packages/locales/src/default/hotkey.ts
index 2a60db55cd1..8f649aee01b 100644
--- a/packages/locales/src/default/hotkey.ts
+++ b/packages/locales/src/default/hotkey.ts
@@ -46,6 +46,8 @@ export default {
'switchAgent.title': 'Quick Switch Agent',
'switchTab.desc': 'Jump to a specific tab by its position (1–9) in the Desktop app tab bar',
'switchTab.title': 'Switch to Tab by Number',
+ 'openTaskFilter.desc': 'Open the filter menu on the Tasks page',
+ 'openTaskFilter.title': 'Filter Tasks',
'toggleFavorite.desc': 'Add the open page to the Favorites section of the sidebar, or remove it',
'toggleFavorite.title': 'Add to / Remove from Favorites',
'toggleLeftPanel.desc': 'Show or hide the left panel',
diff --git a/packages/prompts/src/prompts/task/buildTaskListPrompt.test.ts b/packages/prompts/src/prompts/task/buildTaskListPrompt.test.ts
index 9ca035d3ee3..f71f4634ded 100644
--- a/packages/prompts/src/prompts/task/buildTaskListPrompt.test.ts
+++ b/packages/prompts/src/prompts/task/buildTaskListPrompt.test.ts
@@ -84,4 +84,19 @@ describe('buildTaskListPrompt', () => {
expect(result).toContain('Default Lobe AI agent id: agt_inbox');
expect(result).toContain('Do not use it as a listTasks filter');
});
+
+ it('tells the agent the list is narrowed by a filter', () => {
+ const result = buildTaskListPrompt(
+ {
+ filtered: true,
+ tasks: [{ identifier: 'T-1', name: 'Write chapter 1', priority: 2, status: 'running' }],
+ total: 1,
+ },
+ NOW,
+ );
+ expect(result).toContain('with a filter applied');
+ expect(result).toContain('not every task');
+ expect(result).toContain('tasks outside the filter are not listed here');
+ expect(result).not.toContain('listTasks');
+ });
});
diff --git a/packages/prompts/src/prompts/task/buildTaskListPrompt.ts b/packages/prompts/src/prompts/task/buildTaskListPrompt.ts
index b5aad9e3348..c447c628cb1 100644
--- a/packages/prompts/src/prompts/task/buildTaskListPrompt.ts
+++ b/packages/prompts/src/prompts/task/buildTaskListPrompt.ts
@@ -4,6 +4,8 @@ import type { TaskManagerPromptDefaults } from './taskManagerDefaults';
import { buildTaskManagerDefaultsBlock } from './taskManagerDefaults';
export interface BuildTaskListPromptInput extends TaskManagerPromptDefaults {
+ /** The user narrowed the list with the page's filter, so it is not every task. */
+ filtered?: boolean;
tasks: Array<TaskSummary & { createdAt?: string | Date }>;
total: number;
}
@@ -12,12 +14,14 @@ export interface BuildTaskListPromptInput extends TaskManagerPromptDefaults {
* Task list prompt for Task Manager conversational reference.
*/
export const buildTaskListPrompt = (input: BuildTaskListPromptInput, now?: Date): string => {
- const { tasks, total } = input;
+ const { filtered, tasks, total } = input;
const shown = tasks.length;
const lines: string[] = [
'<task_list>',
- `<hint>The user is currently viewing the tasks list page. These are the ${shown} task(s) displayed in the UI. Do NOT call listTasks to re-fetch them.</hint>`,
+ filtered
+ ? `<hint>The user is currently viewing the tasks list page with a filter applied. These are the ${shown} task(s) matching that filter, not every task; tasks outside the filter are not listed here.</hint>`
+ : `<hint>The user is currently viewing the tasks list page. These are the ${shown} task(s) displayed in the UI. Do NOT call listTasks to re-fetch them.</hint>`,
...buildTaskManagerDefaultsBlock(input),
];
diff --git a/packages/types/src/hotkey.ts b/packages/types/src/hotkey.ts
index 1f2fd136742..53ac85347c2 100644
--- a/packages/types/src/hotkey.ts
+++ b/packages/types/src/hotkey.ts
@@ -10,6 +10,7 @@ export type HotkeyId =
| 'openChatSettings'
| 'prevTab'
| 'openHotkeyHelper'
+ | 'openTaskFilter'
| 'regenerateMessage'
| 'saveDocument'
| 'saveTopic'
diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.ts
index bc74d31ccd7..6844ef9a907 100644
--- a/packages/types/src/task/index.ts
+++ b/packages/types/src/task/index.ts
@@ -3,6 +3,7 @@ import type { ChatFileItem } from '../message/ui/chat';
export * from './archive';
export * from './execution';
+export * from './listFilter';
// ── Task type aliases ──
diff --git a/packages/types/src/task/listFilter.test.ts b/packages/types/src/task/listFilter.test.ts
new file mode 100644
index 00000000000..e5d7c8cf72c
--- /dev/null
+++ b/packages/types/src/task/listFilter.test.ts
@@ -0,0 +1,188 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ countTaskListFilterConditions,
+ matchesTaskListFilter,
+ normalizeTaskListFilter,
+ TASK_LIST_FILTER_NONE,
+ type TaskListFilterTarget,
+ toTaskListFilterAgentCreator,
+} from './listFilter';
+
+const NOW = new Date('2026-11-01T12:00:00Z').getTime();
+const DAY_MS = 24 * 60 * 60 * 1000;
+const daysAgo = (days: number) => new Date(NOW - days * DAY_MS);
+
+const task = (overrides: Partial<TaskListFilterTarget> = {}): TaskListFilterTarget => ({
+ assigneeAgentId: 'agt_a',
+ assigneeUserId: 'user_a',
+ completedAt: null,
+ createdAt: daysAgo(3),
+ createdByUserId: 'user_creator',
+ description: null,
+ identifier: 'T-12',
+ instruction: 'Ship the filter menu',
+ name: 'Task filter',
+ priority: 2,
+ projectId: 'proj_a',
+ status: 'backlog',
+ updatedAt: daysAgo(1),
+ ...overrides,
+});
+
+describe('normalizeTaskListFilter', () => {
+ it('returns undefined for missing or empty filters', () => {
+ expect(normalizeTaskListFilter(undefined)).toBeUndefined();
+ expect(normalizeTaskListFilter({})).toBeUndefined();
+ expect(
+ normalizeTaskListFilter({ content: ' ', status: { operator: 'is', values: [] } }),
+ ).toBeUndefined();
+ });
+
+ it('dedupes and sorts values so equal filters share one key', () => {
+ const a = normalizeTaskListFilter({
+ priority: { operator: 'is', values: [3, 1, 3] },
+ status: { operator: 'isNot', values: ['running', 'backlog'] },
+ });
+ const b = normalizeTaskListFilter({
+ status: { operator: 'isNot', values: ['backlog', 'running', 'backlog'] },
+ priority: { operator: 'is', values: [1, 3] },
+ });
+ expect(a).toEqual({
+ priority: { operator: 'is', values: [1, 3] },
+ status: { operator: 'isNot', values: ['backlog', 'running'] },
+ });
+ expect(JSON.stringify(a)).toBe(JSON.stringify(b));
+ });
+
+ it('trims content and drops unknown date windows', () => {
+ expect(
+ normalizeTaskListFilter({
+ content: ' menu ',
+ createdAt: { operator: 'within', window: 'decade' as never },
+ }),
+ ).toEqual({ content: 'menu' });
+ });
+
+ it('counts the active conditions', () => {
+ expect(countTaskListFilterConditions(undefined)).toBe(0);
+ expect(
+ countTaskListFilterConditions({
+ content: 'x',
+ status: { operator: 'is', values: ['backlog'] },
+ }),
+ ).toBe(2);
+ });
+});
+
+describe('matchesTaskListFilter', () => {
+ it('passes everything without a filter', () => {
+ expect(matchesTaskListFilter(task(), undefined, NOW)).toBe(true);
+ });
+
+ it('matches an agent-created task by its member and by its agent', () => {
+ const byAgent = task({ createdByAgentId: 'agt_writer' });
+ const byMember = { operator: 'is' as const, values: ['user_creator'] };
+ const byWriter = {
+ operator: 'is' as const,
+ values: [toTaskListFilterAgentCreator('agt_writer')],
+ };
+
+ expect(matchesTaskListFilter(task(), { creator: byMember }, NOW)).toBe(true);
+ expect(matchesTaskListFilter(byAgent, { creator: byMember }, NOW)).toBe(true);
+ expect(matchesTaskListFilter(byAgent, { creator: byWriter }, NOW)).toBe(true);
+ expect(matchesTaskListFilter(task(), { creator: byWriter }, NOW)).toBe(false);
+ expect(
+ matchesTaskListFilter(task(), { creator: { ...byWriter, operator: 'isNot' } }, NOW),
+ ).toBe(true);
+ expect(
+ matchesTaskListFilter(byAgent, { creator: { ...byMember, operator: 'isNot' } }, NOW),
+ ).toBe(false);
+ });
+
+ it('matches value sets with is / isNot', () => {
+ expect(
+ matchesTaskListFilter(task(), { status: { operator: 'is', values: ['backlog'] } }, NOW),
+ ).toBe(true);
+ expect(
+ matchesTaskListFilter(task(), { status: { operator: 'isNot', values: ['backlog'] } }, NOW),
+ ).toBe(false);
+ expect(
+ matchesTaskListFilter(task(), { priority: { operator: 'is', values: [1, 2] } }, NOW),
+ ).toBe(true);
+ });
+
+ it('treats a missing priority as "no priority" (0)', () => {
+ expect(
+ matchesTaskListFilter(
+ task({ priority: null }),
+ { priority: { operator: 'is', values: [0] } },
+ NOW,
+ ),
+ ).toBe(true);
+ });
+
+ it('matches the "none" sentinel against missing ids', () => {
+ const unassigned = task({ assigneeAgentId: null, projectId: null });
+ expect(
+ matchesTaskListFilter(
+ unassigned,
+ { agent: { operator: 'is', values: [TASK_LIST_FILTER_NONE] } },
+ NOW,
+ ),
+ ).toBe(true);
+ // "is not A" keeps the unassigned rows…
+ expect(
+ matchesTaskListFilter(unassigned, { agent: { operator: 'isNot', values: ['agt_a'] } }, NOW),
+ ).toBe(true);
+ // …unless "none" itself is excluded.
+ expect(
+ matchesTaskListFilter(
+ unassigned,
+ { project: { operator: 'isNot', values: [TASK_LIST_FILTER_NONE] } },
+ NOW,
+ ),
+ ).toBe(false);
+ });
+
+ it('ANDs fields together', () => {
+ expect(
+ matchesTaskListFilter(
+ task(),
+ {
+ agent: { operator: 'is', values: ['agt_a'] },
+ status: { operator: 'is', values: ['running'] },
+ },
+ NOW,
+ ),
+ ).toBe(false);
+ });
+
+ it('resolves relative date windows', () => {
+ expect(
+ matchesTaskListFilter(task(), { createdAt: { operator: 'within', window: 'week' } }, NOW),
+ ).toBe(true);
+ expect(
+ matchesTaskListFilter(task(), { createdAt: { operator: 'before', window: 'week' } }, NOW),
+ ).toBe(false);
+ expect(
+ matchesTaskListFilter(task(), { createdAt: { operator: 'within', window: 'day' } }, NOW),
+ ).toBe(false);
+ });
+
+ it('never matches a date condition on a missing timestamp', () => {
+ expect(
+ matchesTaskListFilter(task(), { completedAt: { operator: 'within', window: 'month' } }, NOW),
+ ).toBe(false);
+ expect(
+ matchesTaskListFilter(task(), { completedAt: { operator: 'before', window: 'month' } }, NOW),
+ ).toBe(false);
+ });
+
+ it('searches name, identifier, description and instruction case-insensitively', () => {
+ expect(matchesTaskListFilter(task(), { content: 'FILTER' }, NOW)).toBe(true);
+ expect(matchesTaskListFilter(task(), { content: 't-12' }, NOW)).toBe(true);
+ expect(matchesTaskListFilter(task(), { content: 'ship the' }, NOW)).toBe(true);
+ expect(matchesTaskListFilter(task(), { content: 'billing' }, NOW)).toBe(false);
+ });
+});
diff --git a/packages/types/src/task/listFilter.ts b/packages/types/src/task/listFilter.ts
new file mode 100644
index 00000000000..47fb6df1483
--- /dev/null
+++ b/packages/types/src/task/listFilter.ts
@@ -0,0 +1,249 @@
+import type { TaskStatus } from './index';
+
+/**
+ * The Tasks page filter (Linear-style "Add Filter"): a set of independent
+ * conditions, one per field. Values inside one field are OR-ed, fields are
+ * AND-ed with each other and with the page's own scope / display options.
+ *
+ * The server turns it into SQL (`buildTaskListFilters` in
+ * `packages/database/src/models/taskListFilters.ts`); `matchesTaskListFilter`
+ * below mirrors that SQL in JS so a locally edited row that no longer matches
+ * leaves the list before the refetch lands. Keep the two in step.
+ */
+
+/** Stands for "no value" (no agent / no member / no project) inside a value set. */
+export const TASK_LIST_FILTER_NONE = '__none__';
+
+/**
+ * Prefix of an agent inside the `creator` set, so member and agent ids share
+ * one value set. A member value matches every task that member created,
+ * including those their agents created for them; an agent value matches the
+ * tasks that agent created.
+ */
+export const TASK_LIST_FILTER_AGENT_CREATOR_PREFIX = 'agent:';
+
+export const toTaskListFilterAgentCreator = (agentId: string) =>
+ `${TASK_LIST_FILTER_AGENT_CREATOR_PREFIX}${agentId}`;
+
+export const TASK_LIST_FILTER_OPERATORS = ['is', 'isNot'] as const;
+export type TaskListFilterOperator = (typeof TASK_LIST_FILTER_OPERATORS)[number];
+
+export interface TaskListFilterSet<T extends number | string = string> {
+ operator: TaskListFilterOperator;
+ values: T[];
+}
+
+/** Relative look-back windows, so a stored filter keeps meaning "recent" as time passes. */
+export const TASK_LIST_FILTER_DATE_WINDOWS = ['day', 'week', 'month', 'quarter'] as const;
+export type TaskListFilterDateWindow = (typeof TASK_LIST_FILTER_DATE_WINDOWS)[number];
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+export const TASK_LIST_FILTER_DATE_WINDOW_MS: Record<TaskListFilterDateWindow, number> = {
+ day: DAY_MS,
+ month: 30 * DAY_MS,
+ quarter: 90 * DAY_MS,
+ week: 7 * DAY_MS,
+};
+
+/** `within` → on or after the cut-off, `before` → strictly older than it. */
+export const TASK_LIST_FILTER_DATE_OPERATORS = ['within', 'before'] as const;
+export type TaskListFilterDateOperator = (typeof TASK_LIST_FILTER_DATE_OPERATORS)[number];
+
+export interface TaskListFilterDate {
+ operator: TaskListFilterDateOperator;
+ window: TaskListFilterDateWindow;
+}
+
+export const TASK_LIST_FILTER_SET_FIELDS = [
+ 'status',
+ 'priority',
+ 'agent',
+ 'assignee',
+ 'creator',
+ 'project',
+] as const;
+export type TaskListFilterSetField = (typeof TASK_LIST_FILTER_SET_FIELDS)[number];
+
+export const TASK_LIST_FILTER_DATE_FIELDS = ['createdAt', 'updatedAt', 'completedAt'] as const;
+export type TaskListFilterDateField = (typeof TASK_LIST_FILTER_DATE_FIELDS)[number];
+
+export type TaskListFilterField = TaskListFilterDateField | TaskListFilterSetField | 'content';
+
+export interface TaskListFilter {
+ /** Executor agent (`assigneeAgentId`); may hold `TASK_LIST_FILTER_NONE`. */
+ agent?: TaskListFilterSet<string>;
+ /** Member assignee (`assigneeUserId`); may hold `TASK_LIST_FILTER_NONE`. */
+ assignee?: TaskListFilterSet<string>;
+ completedAt?: TaskListFilterDate;
+ /** Case-insensitive substring of the name, identifier, description or instruction. */
+ content?: string;
+ createdAt?: TaskListFilterDate;
+ /**
+ * Member ids match `createdByUserId`; `agent:<id>` values
+ * (`toTaskListFilterAgentCreator`) match `createdByAgentId`.
+ */
+ creator?: TaskListFilterSet<string>;
+ /** `priority`, a missing one counting as 0 ("no priority"). */
+ priority?: TaskListFilterSet<number>;
+ /** `projectId`; may hold `TASK_LIST_FILTER_NONE`. */
+ project?: TaskListFilterSet<string>;
+ status?: TaskListFilterSet<TaskStatus>;
+ updatedAt?: TaskListFilterDate;
+}
+
+/** Longest `content` the filter keeps; anything past it is trimmed. */
+export const TASK_LIST_FILTER_CONTENT_MAX_LENGTH = 200;
+/** Most values one field may hold; `task.list` / `task.groupList` reject more. */
+export const TASK_LIST_FILTER_MAX_VALUES = 100;
+
+const sortValues = <T extends number | string>(values: T[]): T[] =>
+ [...new Set(values)].sort((a, b) =>
+ typeof a === 'number' && typeof b === 'number' ? a - b : String(a).localeCompare(String(b)),
+ );
+
+const normalizeSet = <T extends number | string>(
+ set: TaskListFilterSet<T> | undefined,
+): TaskListFilterSet<T> | undefined => {
+ if (!set || !Array.isArray(set.values) || set.values.length === 0) return undefined;
+ return {
+ operator: set.operator === 'isNot' ? 'isNot' : 'is',
+ values: sortValues(set.values),
+ };
+};
+
+const normalizeDate = (date: TaskListFilterDate | undefined): TaskListFilterDate | undefined => {
+ if (!date || !(TASK_LIST_FILTER_DATE_WINDOWS as readonly string[]).includes(date.window)) {
+ return undefined;
+ }
+ return { operator: date.operator === 'before' ? 'before' : 'within', window: date.window };
+};
+
+/**
+ * Canonical form: empty conditions dropped, value sets de-duplicated and
+ * sorted, so the same filter is always one query key. `undefined` when
+ * nothing is left — an empty filter and no filter are the same query.
+ */
+export const normalizeTaskListFilter = (
+ filter: TaskListFilter | null | undefined,
+): TaskListFilter | undefined => {
+ if (!filter) return undefined;
+ const content = filter.content?.trim().slice(0, TASK_LIST_FILTER_CONTENT_MAX_LENGTH);
+ const next: TaskListFilter = {
+ agent: normalizeSet(filter.agent),
+ assignee: normalizeSet(filter.assignee),
+ completedAt: normalizeDate(filter.completedAt),
+ content: content || undefined,
+ createdAt: normalizeDate(filter.createdAt),
+ creator: normalizeSet(filter.creator),
+ priority: normalizeSet(filter.priority),
+ project: normalizeSet(filter.project),
+ status: normalizeSet(filter.status),
+ updatedAt: normalizeDate(filter.updatedAt),
+ };
+ const entries = Object.entries(next).filter(([, value]) => value !== undefined);
+ return entries.length > 0 ? (Object.fromEntries(entries) as TaskListFilter) : undefined;
+};
+
+/** Number of active conditions, for the header badge. */
+export const countTaskListFilterConditions = (filter: TaskListFilter | undefined): number =>
+ filter ? Object.values(normalizeTaskListFilter(filter) ?? {}).length : 0;
+
+export const resolveTaskListFilterDateCutoff = (
+ window: TaskListFilterDateWindow,
+ now = Date.now(),
+): Date => new Date(now - TASK_LIST_FILTER_DATE_WINDOW_MS[window]);
+
+/** The row fields `matchesTaskListFilter` reads. */
+export interface TaskListFilterTarget {
+ assigneeAgentId?: string | null;
+ assigneeUserId?: string | null;
+ completedAt?: Date | string | null;
+ createdAt?: Date | string | null;
+ createdByAgentId?: string | null;
+ createdByUserId?: string | null;
+ description?: string | null;
+ identifier?: string | null;
+ instruction?: string | null;
+ name?: string | null;
+ priority?: number | null;
+ projectId?: string | null;
+ status: string;
+ updatedAt?: Date | string | null;
+}
+
+const matchesSet = <T extends number | string>(
+ set: TaskListFilterSet<T> | undefined,
+ value: T | null | undefined,
+ noneValue?: T,
+): boolean => {
+ if (!set || set.values.length === 0) return true;
+ const key = value ?? noneValue;
+ const included = key !== undefined && set.values.includes(key);
+ return set.operator === 'isNot' ? !included : included;
+};
+
+/** A task matches a creator value through its member or through its agent. */
+const matchesCreator = (
+ set: TaskListFilterSet<string> | undefined,
+ task: TaskListFilterTarget,
+): boolean => {
+ if (!set || set.values.length === 0) return true;
+ const included =
+ (!!task.createdByUserId && set.values.includes(task.createdByUserId)) ||
+ (!!task.createdByAgentId &&
+ set.values.includes(toTaskListFilterAgentCreator(task.createdByAgentId)));
+ return set.operator === 'isNot' ? !included : included;
+};
+
+const toTime = (value: Date | string | null | undefined): number | undefined => {
+ if (!value) return undefined;
+ const time = new Date(value).getTime();
+ return Number.isNaN(time) ? undefined : time;
+};
+
+const matchesDate = (
+ date: TaskListFilterDate | undefined,
+ value: Date | string | null | undefined,
+ now: number,
+): boolean => {
+ if (!date) return true;
+ const time = toTime(value);
+ // A missing timestamp (an unfinished task's `completedAt`) matches neither side.
+ if (time === undefined) return false;
+ const cutoff = resolveTaskListFilterDateCutoff(date.window, now).getTime();
+ return date.operator === 'before' ? time < cutoff : time >= cutoff;
+};
+
+const matchesContent = (content: string | undefined, task: TaskListFilterTarget): boolean => {
+ if (!content) return true;
+ const needle = content.toLowerCase();
+ return [task.name, task.identifier, task.description, task.instruction].some(
+ (field) => !!field && field.toLowerCase().includes(needle),
+ );
+};
+
+/**
+ * JS mirror of the server's SQL for `filter`. Rows the server already
+ * filtered always pass; it only drops a row whose local copy has changed
+ * since (a priority edited, an assignee swapped) until the refetch lands.
+ */
+export const matchesTaskListFilter = (
+ task: TaskListFilterTarget,
+ filter: TaskListFilter | undefined,
+ now = Date.now(),
+): boolean => {
+ if (!filter) return true;
+ return (
+ matchesSet(filter.status, task.status as TaskStatus) &&
+ matchesSet(filter.priority, task.priority ?? 0) &&
+ matchesSet(filter.agent, task.assigneeAgentId, TASK_LIST_FILTER_NONE) &&
+ matchesSet(filter.assignee, task.assigneeUserId, TASK_LIST_FILTER_NONE) &&
+ matchesCreator(filter.creator, task) &&
+ matchesSet(filter.project, task.projectId, TASK_LIST_FILTER_NONE) &&
+ matchesDate(filter.createdAt, task.createdAt, now) &&
+ matchesDate(filter.updatedAt, task.updatedAt, now) &&
+ matchesDate(filter.completedAt, task.completedAt, now) &&
+ matchesContent(filter.content, task)
+ );
+};
diff --git a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
index 87a7473d83b..347ba448182 100644
--- a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
+++ b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
@@ -34,6 +34,14 @@ import Breadcrumb from '../shared/Breadcrumb';
import { taskDetailPath } from '../shared/taskDetailPath';
import CreateTaskInlineEntry from './CreateTaskInlineEntry';
import EmptyState from './EmptyState';
+import {
+ pickOfferedTaskFilter,
+ TaskFilterBar,
+ TaskFilterButton,
+ taskListFilterScopeKey,
+ useTaskFilterFields,
+ useTaskListFilter,
+} from './filter';
import KanbanBoard from './KanbanBoard';
import type { TaskListViewOptions } from './listViewOptions';
import {
@@ -229,6 +237,22 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, proj
// gated off while it is up.
const isBoardView = resolveTaskCollectionView(collection, viewMode) === 'board';
const isMineBoard = isMineCollection && isBoardView;
+ // The Linear-style filter is kept per list scope (workspace + page) and
+ // applied server-side by every collection, so paginated pages and board
+ // columns count only the matching tasks.
+ const filterFields = useTaskFilterFields({ agentId, projectId });
+ const [storedFilter, setFilter] = useTaskListFilter(
+ taskListFilterScopeKey({ agentId, projectId, workspaceId: activeWorkspaceId }),
+ );
+ const filter = useMemo(
+ () =>
+ pickOfferedTaskFilter(
+ storedFilter,
+ filterFields.map((field) => field.key),
+ ),
+ [filterFields, storedFilter],
+ );
+ const hasFilter = !!filter;
const rawViewOptions = useGlobalStore(systemStatusSelectors.taskListViewOptions);
const viewOptions = useMemo(() => normalizeTaskListViewOptions(rawViewOptions), [rawViewOptions]);
const useFetchTaskList = useTaskStore((s) => s.useFetchTaskList);
@@ -252,6 +276,7 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, proj
automated: false,
complete: isListView,
enabled: isOrdinaryCollection,
+ filter,
includeArchived: viewOptions.showArchived,
});
// Drive the loading/empty boundary off the store entry of this exact query:
@@ -261,10 +286,13 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, proj
const setActiveTaskListKey = useTaskStore((s) => s.setActiveTaskListKey);
// The task manager agent reads this page's list as "the viewed list".
useEffect(() => {
- setActiveTaskListKey(queryKey);
+ setActiveTaskListKey(queryKey, hasFilter);
return () => setActiveTaskListKey(undefined);
- }, [queryKey, setActiveTaskListKey]);
- const isEmptyHero = useTaskStore(taskListSelectors.isListEmpty(queryKey));
+ }, [hasFilter, queryKey, setActiveTaskListKey]);
+ // An empty result under a filter is "nothing matches", not a fresh
+ // workspace: keep the header (and the way out of the filter) on screen.
+ const isListEmpty = useTaskStore(taskListSelectors.isListEmpty(queryKey));
+ const isEmptyHero = isListEmpty && !hasFilter;
// The empty hero hides the view options, and with them "Show archived". When
// only archived tasks remain, keep the options reachable so they can come back.
const { queryKey: archivedProbeKey } = useFetchTaskList({
@@ -283,6 +311,7 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, proj
const scheduledSWR = useFetchScheduledTaskList({
agentId,
enabled: isScheduledCollection,
+ filter,
limit: COLLECTION_PAGE_SIZE,
offset: (collectionPage - 1) * COLLECTION_PAGE_SIZE,
projectId,
@@ -291,6 +320,7 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, proj
const mineSWR = useFetchMyTaskList({
completedWithin: getCompletedWithin(viewOptions),
enabled: isMineCollection && !isMineBoard,
+ filter,
limit: COLLECTION_PAGE_SIZE,
offset: (collectionPage - 1) * COLLECTION_PAGE_SIZE,
includeArchived: viewOptions.showArchived,
@@ -313,6 +343,10 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, proj
[viewOptions],
);
const myTaskViewOptions = useMemo(() => getMyTaskViewOptions(viewOptions), [viewOptions]);
+ const filterKey = JSON.stringify(filter ?? null);
+ useEffect(() => {
+ setCollectionPage(1);
+ }, [filterKey]);
useEffect(() => {
if (!isCollectionListInit) return;
setCollectionPage((page) => clampCollectionPage(page, collectionTasksTotal));
@@ -382,6 +416,12 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, proj
});
}, [agentId, canCreateTask, navigate, projectId]);
+ const handleClearFilter = useCallback(() => setFilter(() => undefined), [setFilter]);
+ const filterEmptyAction = hasFilter ? (
+ <Button onClick={handleClearFilter}>{t('taskList.filter.clearAll')}</Button>
+ ) : undefined;
+ const filterEmptyDescription = hasFilter ? t('taskList.filter.empty') : undefined;
+
const handleShowHiddenCompleted = useCallback(() => {
setViewOptions((prev) => ({ ...prev, completedTasks: 'all' }));
}, [setViewOptions]);
@@ -457,6 +497,9 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, proj
left={headerLeft}
right={
<Flexbox horizontal align={'center'} gap={4}>
+ {(headerVisibility.showViewOptions || hasFilter) && (
+ <TaskFilterButton fields={filterFields} filter={filter} setFilter={setFilter} />
+ )}
{isOrdinaryCollection && !agentId && !projectId && <TaskListVisibilityFilter />}
{isOrdinaryCollection && headerActions}
{isOrdinaryCollection && (inlineCollapsed || viewMode === 'kanban') && (
@@ -500,17 +543,22 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, proj
},
}}
/>
+ <TaskFilterBar fields={filterFields} filter={filter} setFilter={setFilter} />
{isMineBoard ? (
<Flexbox flex={1} style={{ overflowX: 'auto', overflowY: 'hidden' }}>
<KanbanBoard
+ filter={filter}
myTaskScope={myTaskScope}
options={viewOptions}
routeScope={routeScope}
- emptyDescription={t(
- myTaskScope === 'created'
- ? 'taskList.mine.emptyCreated'
- : 'taskList.mine.emptyAssigned',
- )}
+ emptyDescription={
+ filterEmptyDescription ??
+ t(
+ myTaskScope === 'created'
+ ? 'taskList.mine.emptyCreated'
+ : 'taskList.mine.emptyAssigned',
+ )
+ }
/>
</Flexbox>
) : !isOrdinaryCollection ? (
@@ -524,25 +572,28 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, proj
<TaskList
data={isCollectionListInit || undefined}
error={collectionSWR.error}
+ filter={filter}
isLoading={collectionSWR.isLoading || (!isCollectionListInit && !collectionSWR.error)}
items={collectionTasks}
options={isMineCollection ? myTaskViewOptions : scheduledViewOptions}
routeScope={routeScope}
emptyAction={
- showScheduledEmptyCreate ? (
+ filterEmptyAction ??
+ (showScheduledEmptyCreate ? (
<Button icon={Plus} onClick={handleCreateScheduledTask}>
{t('createTask.submitScheduled')}
</Button>
- ) : undefined
+ ) : undefined)
}
emptyDescription={
- isMineCollection
+ filterEmptyDescription ??
+ (isMineCollection
? t(
myTaskScope === 'created'
? 'taskList.mine.emptyCreated'
: 'taskList.mine.emptyAssigned',
)
- : t('taskList.scheduled.empty')
+ : t('taskList.scheduled.empty'))
}
selectionScope={[
collection,
@@ -571,6 +622,8 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, proj
<Flexbox flex={1} style={{ overflowX: 'auto', overflowY: 'hidden' }}>
<KanbanBoard
agentId={agentId}
+ emptyDescription={filterEmptyDescription}
+ filter={filter}
options={viewOptions}
projectId={projectId}
routeScope={routeScope}
@@ -593,7 +646,10 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, proj
)}
<TaskList
data={isTaskListInit || undefined}
+ emptyAction={filterEmptyAction}
+ emptyDescription={filterEmptyDescription}
error={error}
+ filter={filter}
isLoading={isLoading || (!isTaskListInit && !error)}
options={viewOptions}
queryKey={queryKey}
diff --git a/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx b/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx
index 68d6624d9ff..cf1b63dcbc4 100644
--- a/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx
+++ b/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx
@@ -9,6 +9,7 @@ import {
useSensor,
useSensors,
} from '@dnd-kit/core';
+import { matchesTaskListFilter, type TaskListFilter } from '@lobechat/types';
import { Center, createStaticStyles, Empty, Flexbox } from '@lobehub/ui';
import { ClipboardCheckIcon } from 'lucide-react';
import { memo, useCallback, useMemo, useState } from 'react';
@@ -61,6 +62,8 @@ interface KanbanBoardProps {
agentId?: string;
/** Overrides the generic "no tasks" copy with the collection's own line. */
emptyDescription?: string;
+ /** The page filter: sent with the board query and re-applied to edited cards. */
+ filter?: TaskListFilter;
/**
* "My tasks" board: narrows the server groups to the caller's own slice of
* the workspace, matching what that tab's list view fetches — including its
@@ -73,7 +76,7 @@ interface KanbanBoardProps {
}
const KanbanBoard = memo<KanbanBoardProps>((props) => {
- const { agentId, emptyDescription, myTaskScope, options, projectId, routeScope } = props;
+ const { agentId, emptyDescription, filter, myTaskScope, options, projectId, routeScope } = props;
const { t } = useTranslation('chat');
const { allowed: canEditTask } = usePermission('create_content');
const groupBy = normalizeKanbanGroupBy(options.groupBy);
@@ -86,12 +89,27 @@ const KanbanBoard = memo<KanbanBoardProps>((props) => {
const { error, isLoading, mutate, queryKey } = useFetchTaskGroupList({
...buildKanbanGroupQuery({ agentId, excludeStatuses, groupBy, myTaskScope, projectId }),
completedWithin: getCompletedWithin(options),
+ 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 currentTaskGroups = useTaskStore(taskListSelectors.taskGroups(queryKey));
+ const storedTaskGroups = useTaskStore(taskListSelectors.taskGroups(queryKey));
+ // Cards edited out of the filter leave their column before the refetch lands.
+ const currentTaskGroups = useMemo(() => {
+ if (!filter) return storedTaskGroups;
+ return storedTaskGroups.map((group) => {
+ const tasks = group.tasks.filter((task) => matchesTaskListFilter(task, filter));
+ return tasks.length === group.tasks.length
+ ? group
+ : {
+ ...group,
+ tasks,
+ total: Math.max(0, group.total - (group.tasks.length - tasks.length)),
+ };
+ });
+ }, [filter, storedTaskGroups]);
const updateTask = useTaskStore((s) => s.updateTask);
const runTask = useTaskStore((s) => s.runTask);
const refreshTaskList = useTaskStore((s) => s.refreshTaskList);
diff --git a/src/features/AgentTasks/AgentTaskList/TaskList.tsx b/src/features/AgentTasks/AgentTaskList/TaskList.tsx
index ba25c7a5ce9..4b90e1f215f 100644
--- a/src/features/AgentTasks/AgentTaskList/TaskList.tsx
+++ b/src/features/AgentTasks/AgentTaskList/TaskList.tsx
@@ -1,3 +1,4 @@
+import { matchesTaskListFilter, type TaskListFilter } from '@lobechat/types';
import {
AccordionHeader,
AccordionItem,
@@ -58,6 +59,11 @@ interface TaskListProps {
emptyDescription?: string;
/** Thrown error from the list SWR — surfaced as a failure state, not a skeleton. */
error?: unknown;
+ /**
+ * The page filter the rows were fetched with. Re-applied locally so a row
+ * edited out of it (priority changed, assignee swapped) leaves at once.
+ */
+ filter?: TaskListFilter;
/** First-load / retry in flight (SWR `isLoading`). */
isLoading?: boolean;
/** Optional list source for alternate task collections such as scheduled tasks. */
@@ -150,6 +156,7 @@ const TaskList = memo<TaskListProps>((props) => {
const {
data,
error,
+ filter,
isLoading,
items,
onRetry,
@@ -161,7 +168,12 @@ const TaskList = memo<TaskListProps>((props) => {
const { t } = useTranslation('chat');
const storeTasks = useTaskStore(taskListSelectors.taskList(queryKey));
const storeTasksTotal = useTaskStore(taskListSelectors.taskListTotal(queryKey));
- const tasks = items ?? storeTasks;
+ const sourceTasks = items ?? storeTasks;
+ const tasks = useMemo(
+ () =>
+ filter ? sourceTasks.filter((task) => matchesTaskListFilter(task, filter)) : sourceTasks,
+ [filter, sourceTasks],
+ );
// The store list is fetched in full up to a ceiling; past it the server's
// `total` still counts every task, so say the list is a subset rather than
// let the missing rows vanish silently. Alternate collections (`items`)
diff --git a/src/features/AgentTasks/AgentTaskList/filter/TaskFilterBar.tsx b/src/features/AgentTasks/AgentTaskList/filter/TaskFilterBar.tsx
new file mode 100644
index 00000000000..fb60df428c4
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskList/filter/TaskFilterBar.tsx
@@ -0,0 +1,318 @@
+'use client';
+
+import {
+ TASK_LIST_FILTER_DATE_WINDOWS,
+ type TaskListFilter,
+ type TaskListFilterDateField,
+ type TaskListFilterSet,
+} from '@lobechat/types';
+import {
+ Button,
+ cssVar as cssVarJs,
+ type DropdownItem,
+ DropdownMenu,
+ Flexbox,
+ Icon,
+} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { TextSearchIcon, XIcon } from 'lucide-react';
+import type { KeyboardEvent, ReactNode } from 'react';
+import { memo, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import {
+ isTaskFilterValueSelected,
+ removeTaskFilterField,
+ setTaskFilterContent,
+ setTaskFilterDateWindow,
+ showsTaskFilterValuesInline,
+ taskFilterSetOperatorKey,
+ type TaskFilterValue,
+ toggleTaskFilterOperator,
+ toggleTaskFilterValue,
+} from './taskFilterState';
+import type { TaskFilterFieldDef, TaskFilterSetFieldDef } from './useTaskFilterFields';
+
+const styles = stylex.create({
+ bar: {
+ flexWrap: 'wrap',
+ paddingBlockEnd: 8,
+ paddingBlockStart: 4,
+ paddingInline: 16,
+ },
+ chip: {
+ alignItems: 'stretch',
+ backgroundColor: cssVar.colorBgContainer,
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: 6,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ color: cssVar.colorText,
+ display: 'inline-flex',
+ fontSize: 12,
+ height: 26,
+ lineHeight: '24px',
+ overflow: 'hidden',
+ },
+ contentInput: {
+ backgroundColor: 'transparent',
+ borderStyle: 'none',
+ color: cssVar.colorText,
+ fontSize: 12,
+ outline: 'none',
+ paddingBlock: 0,
+ paddingInline: 8,
+ width: 140,
+ },
+ secondary: {
+ color: cssVar.colorTextSecondary,
+ },
+ segment: {
+ alignItems: 'center',
+ borderInlineEndColor: cssVar.colorBorderSecondary,
+ borderInlineEndStyle: 'solid',
+ borderInlineEndWidth: { 'default': 1, ':last-child': 0 },
+ display: 'inline-flex',
+ gap: 6,
+ paddingInline: 8,
+ whiteSpace: 'nowrap',
+ },
+ segmentButton: {
+ backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillTertiary },
+ cursor: 'pointer',
+ transitionDuration: cssVar.motionDurationMid,
+ transitionProperty: 'background-color',
+ },
+});
+
+/** Content typed into the chip is committed after this pause, like a search box. */
+const CONTENT_COMMIT_DELAY_MS = 400;
+
+interface TaskFilterBarProps {
+ fields: TaskFilterFieldDef[];
+ filter?: TaskListFilter;
+ setFilter: (updater: (prev: TaskListFilter | undefined) => TaskListFilter | undefined) => void;
+}
+
+const Segment = ({
+ children,
+ onClick,
+ secondary,
+ title,
+}: {
+ children: ReactNode;
+ onClick?: () => void;
+ secondary?: boolean;
+ title?: string;
+}) => (
+ <span
+ role={onClick ? 'button' : undefined}
+ tabIndex={onClick ? 0 : undefined}
+ title={title}
+ {...stylex.props(
+ styles.segment,
+ !!onClick && styles.segmentButton,
+ secondary && styles.secondary,
+ )}
+ onClick={onClick}
+ onKeyDown={
+ onClick
+ ? (event) => {
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault();
+ onClick();
+ }
+ }
+ : undefined
+ }
+ >
+ {children}
+ </span>
+);
+
+const ContentInput = memo<{ onCommit: (value: string) => void; value: string }>(
+ ({ onCommit, value }) => {
+ const [draft, setDraft] = useState(value);
+
+ useEffect(() => setDraft(value), [value]);
+ useEffect(() => {
+ if (draft.trim() === value) return;
+ const timer = setTimeout(() => onCommit(draft), CONTENT_COMMIT_DELAY_MS);
+ return () => clearTimeout(timer);
+ }, [draft, onCommit, value]);
+
+ return (
+ <input
+ {...stylex.props(styles.contentInput)}
+ value={draft}
+ onBlur={() => draft.trim() !== value && onCommit(draft)}
+ onChange={(event) => setDraft(event.target.value)}
+ onKeyDown={(event: KeyboardEvent<HTMLInputElement>) => {
+ if (event.key === 'Enter') onCommit(draft);
+ }}
+ />
+ );
+ },
+);
+
+ContentInput.displayName = 'TaskFilterContentInput';
+
+/**
+ * The active filter as Linear-style chips under the header:
+ * `[field] [operator] [values] [×]`. The operator flips on click, the values
+ * reopen the value menu, × drops the condition; "Clear" drops them all.
+ */
+const TaskFilterBar = memo<TaskFilterBarProps>(({ fields, filter, setFilter }) => {
+ const { t } = useTranslation('chat');
+
+ if (!filter) return null;
+
+ const removeButton = (field: Parameters<typeof removeTaskFilterField>[1]) => (
+ <Segment
+ title={t('taskList.filter.remove')}
+ onClick={() => setFilter((prev) => removeTaskFilterField(prev, field))}
+ >
+ <Icon icon={XIcon} size={12} />
+ </Segment>
+ );
+
+ const renderSetChip = (field: TaskFilterSetFieldDef) => {
+ const set = filter[field.key] as TaskListFilterSet<TaskFilterValue> | undefined;
+ if (!set) return null;
+ const selected = set.values.map(
+ (value) =>
+ field.options.find((option) => option.value === value) ?? {
+ // A value whose option is gone (a deleted agent, a member who left)
+ // still renders, so it can be seen and removed.
+ icon: undefined,
+ label: t('taskList.filter.unknownValue'),
+ value,
+ },
+ );
+ const summary = showsTaskFilterValuesInline(selected.length)
+ ? selected.map((option) => option.label).join(', ')
+ : t('taskList.filter.valueCount', { count: selected.length });
+ const valueItems: DropdownItem[] = field.options.map((option) => ({
+ checked: isTaskFilterValueSelected(filter, field.key, option.value),
+ closeOnClick: false,
+ icon: option.icon,
+ key: `${field.key}:${option.value}`,
+ label: option.label,
+ onCheckedChange: () =>
+ setFilter((prev) => toggleTaskFilterValue(prev, field.key, option.value)),
+ type: 'checkbox' as const,
+ }));
+
+ return (
+ <span
+ {...stylex.props(styles.chip)}
+ data-testid={`task-filter-chip-${field.key}`}
+ key={field.key}
+ >
+ <Segment>
+ <Icon color={cssVarJs.colorTextSecondary} icon={field.icon} size={14} />
+ {field.label}
+ </Segment>
+ <Segment
+ secondary
+ onClick={() => setFilter((prev) => toggleTaskFilterOperator(prev, field.key))}
+ >
+ {t(taskFilterSetOperatorKey(set.operator, set.values.length))}
+ </Segment>
+ <DropdownMenu items={valueItems}>
+ <span
+ {...stylex.props(styles.segment, styles.segmentButton)}
+ role={'button'}
+ tabIndex={0}
+ >
+ {showsTaskFilterValuesInline(selected.length) &&
+ selected.map((option) => (
+ <span key={String(option.value)} style={{ display: 'inline-flex' }}>
+ {option.icon}
+ </span>
+ ))}
+ {summary}
+ </span>
+ </DropdownMenu>
+ {removeButton(field.key)}
+ </span>
+ );
+ };
+
+ const renderDateChip = (field: {
+ icon: TaskFilterFieldDef['icon'];
+ key: TaskListFilterDateField;
+ label: string;
+ }) => {
+ const date = filter[field.key];
+ if (!date) return null;
+ const windowItems: DropdownItem[] = TASK_LIST_FILTER_DATE_WINDOWS.map((window) => ({
+ checked: date.window === window,
+ key: `${field.key}:${window}`,
+ label: t(`taskList.filter.window.${window}`),
+ onCheckedChange: () => setFilter((prev) => setTaskFilterDateWindow(prev, field.key, window)),
+ type: 'checkbox' as const,
+ }));
+
+ return (
+ <span
+ {...stylex.props(styles.chip)}
+ data-testid={`task-filter-chip-${field.key}`}
+ key={field.key}
+ >
+ <Segment>
+ <Icon color={cssVarJs.colorTextSecondary} icon={field.icon} size={14} />
+ {field.label}
+ </Segment>
+ <Segment
+ secondary
+ onClick={() => setFilter((prev) => toggleTaskFilterOperator(prev, field.key))}
+ >
+ {t(
+ date.operator === 'before'
+ ? 'taskList.filter.operator.before'
+ : 'taskList.filter.operator.within',
+ )}
+ </Segment>
+ <DropdownMenu items={windowItems}>
+ <span
+ {...stylex.props(styles.segment, styles.segmentButton)}
+ role={'button'}
+ tabIndex={0}
+ >
+ {t(`taskList.filter.window.${date.window}`)}
+ </span>
+ </DropdownMenu>
+ {removeButton(field.key)}
+ </span>
+ );
+ };
+
+ return (
+ <Flexbox horizontal align={'center'} {...stylex.props(styles.bar)} gap={6}>
+ {fields.map((field) => (field.kind === 'set' ? renderSetChip(field) : renderDateChip(field)))}
+ {filter.content && (
+ <span {...stylex.props(styles.chip)} data-testid={'task-filter-chip-content'}>
+ <Segment>
+ <Icon color={cssVarJs.colorTextSecondary} icon={TextSearchIcon} size={14} />
+ {t('taskList.filter.field.content')}
+ </Segment>
+ <Segment secondary>{t('taskList.filter.operator.contains')}</Segment>
+ <ContentInput
+ value={filter.content}
+ onCommit={(value) => setFilter((prev) => setTaskFilterContent(prev, value))}
+ />
+ {removeButton('content')}
+ </span>
+ )}
+ <Button size={'small'} type={'text'} onClick={() => setFilter(() => undefined)}>
+ {t('taskList.filter.clear')}
+ </Button>
+ </Flexbox>
+ );
+});
+
+TaskFilterBar.displayName = 'TaskFilterBar';
+
+export default TaskFilterBar;
diff --git a/src/features/AgentTasks/AgentTaskList/filter/TaskFilterButton.tsx b/src/features/AgentTasks/AgentTaskList/filter/TaskFilterButton.tsx
new file mode 100644
index 00000000000..651b9f83194
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskList/filter/TaskFilterButton.tsx
@@ -0,0 +1,216 @@
+'use client';
+
+import { HotkeyEnum } from '@lobechat/const/hotkeys';
+import { TASK_LIST_FILTER_DATE_WINDOWS, type TaskListFilter } from '@lobechat/types';
+import {
+ ActionIcon,
+ cssVar as cssVarJs,
+ type DropdownItem,
+ DropdownMenu,
+ Hotkey,
+ Icon,
+} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { CalendarIcon, ListFilterIcon, TextSearchIcon } from 'lucide-react';
+import type { KeyboardEvent } from 'react';
+import { memo, useCallback, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
+import { useHotkeyById } from '@/hooks/useHotkeys/useHotkeyById';
+import { useUserStore } from '@/store/user';
+import { settingsSelectors } from '@/store/user/selectors';
+
+import {
+ isTaskFilterValueSelected,
+ setTaskFilterContent,
+ setTaskFilterDateWindow,
+ toggleTaskFilterValue,
+} from './taskFilterState';
+import type { TaskFilterDateFieldDef, TaskFilterFieldDef } from './useTaskFilterFields';
+
+const styles = stylex.create({
+ search: {
+ alignItems: 'center',
+ display: 'flex',
+ gap: 8,
+ paddingBlock: 6,
+ paddingInline: 12,
+ },
+ searchInput: {
+ 'backgroundColor': 'transparent',
+ 'borderStyle': 'none',
+ 'color': cssVar.colorText,
+ 'flex': '1',
+ 'fontSize': 14,
+ 'minWidth': 0,
+ 'outline': 'none',
+ 'padding': 0,
+ '::placeholder': {
+ color: cssVar.colorTextQuaternary,
+ },
+ },
+});
+
+interface TaskFilterButtonProps {
+ fields: TaskFilterFieldDef[];
+ filter?: TaskListFilter;
+ setFilter: (updater: (prev: TaskListFilter | undefined) => TaskListFilter | undefined) => void;
+}
+
+const matches = (text: string, query: string) => text.toLowerCase().includes(query);
+
+/**
+ * The header's "Add filter" entry, after Linear: a searchable menu of fields,
+ * each opening its values as checkboxes. Typing searches values across every
+ * field at once and offers a content search for the typed text.
+ */
+const TaskFilterButton = memo<TaskFilterButtonProps>(({ fields, filter, setFilter }) => {
+ const { t } = useTranslation('chat');
+ const [open, setOpen] = useState(false);
+ const [search, setSearch] = useState('');
+
+ const handleOpenChange = useCallback((next: boolean) => {
+ setOpen(next);
+ if (!next) setSearch('');
+ }, []);
+
+ const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.OpenTaskFilter));
+ // A bare key: typing in a field must not open the menu. Live only while the Tasks page is mounted.
+ useHotkeyById(HotkeyEnum.OpenTaskFilter, () => handleOpenChange(true), {
+ enableOnContentEditable: false,
+ enableOnFormTags: false,
+ enabled: true,
+ });
+
+ const query = search.trim().toLowerCase();
+
+ const items = useMemo<DropdownItem[]>(() => {
+ const dateWindowItems = (field: TaskFilterDateFieldDef): DropdownItem[] =>
+ TASK_LIST_FILTER_DATE_WINDOWS.map((window) => ({
+ checked: filter?.[field.key]?.window === window,
+ closeOnClick: false,
+ key: `${field.key}:${window}`,
+ label: t(`taskList.filter.window.${window}`),
+ onCheckedChange: () =>
+ setFilter((prev) => setTaskFilterDateWindow(prev, field.key, window)),
+ type: 'checkbox' as const,
+ }));
+
+ const fieldItem = (field: TaskFilterFieldDef): DropdownItem => ({
+ children:
+ field.kind === 'date'
+ ? dateWindowItems(field)
+ : field.options.map((option) => ({
+ checked: isTaskFilterValueSelected(filter, field.key, option.value),
+ closeOnClick: false,
+ icon: option.icon,
+ key: `${field.key}:${option.value}`,
+ label: option.label,
+ onCheckedChange: () =>
+ setFilter((prev) => toggleTaskFilterValue(prev, field.key, option.value)),
+ type: 'checkbox' as const,
+ })),
+ icon: <Icon color={cssVarJs.colorTextSecondary} icon={field.icon} size={16} />,
+ key: field.key,
+ label: field.label,
+ type: 'submenu' as const,
+ });
+
+ const setFields = fields.filter((field) => field.kind === 'set');
+ const dateFields = fields.filter(
+ (field): field is TaskFilterDateFieldDef => field.kind === 'date',
+ );
+
+ if (!query) {
+ return [
+ ...setFields.map(fieldItem),
+ { key: 'divider-dates', type: 'divider' as const },
+ {
+ children: dateFields.map(fieldItem),
+ icon: <Icon color={cssVarJs.colorTextSecondary} icon={CalendarIcon} size={16} />,
+ key: 'dates',
+ label: t('taskList.filter.field.dates'),
+ type: 'submenu' as const,
+ },
+ ];
+ }
+
+ const contentItem: DropdownItem = {
+ icon: <Icon color={cssVarJs.colorTextSecondary} icon={TextSearchIcon} size={16} />,
+ key: 'content',
+ label: t('taskList.filter.contentContains', { text: search.trim() }),
+ onClick: () => {
+ setFilter((prev) => setTaskFilterContent(prev, search));
+ handleOpenChange(false);
+ },
+ };
+ const matchedFields = fields.filter((field) => matches(field.label, query)).map(fieldItem);
+ const matchedValues: DropdownItem[] = setFields.flatMap((field) =>
+ field.kind === 'set'
+ ? field.options
+ .filter((option) => matches(option.label, query))
+ .map((option) => ({
+ checked: isTaskFilterValueSelected(filter, field.key, option.value),
+ closeOnClick: false,
+ icon: option.icon,
+ key: `match:${field.key}:${option.value}`,
+ label: `${field.label}: ${option.label}`,
+ onCheckedChange: () =>
+ setFilter((prev) => toggleTaskFilterValue(prev, field.key, option.value)),
+ type: 'checkbox' as const,
+ }))
+ : [],
+ );
+
+ return [
+ contentItem,
+ ...(matchedFields.length > 0 || matchedValues.length > 0
+ ? [{ key: 'divider-matches', type: 'divider' as const }]
+ : []),
+ ...matchedFields,
+ ...matchedValues,
+ ];
+ }, [fields, filter, handleOpenChange, query, search, setFilter, t]);
+
+ const handleSearchKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
+ // Keep typing in the box: the menu would treat letters as typeahead.
+ if (event.key !== 'Escape' && event.key !== 'ArrowDown') event.stopPropagation();
+ };
+
+ return (
+ <DropdownMenu
+ items={items}
+ open={open}
+ placement={'bottomRight'}
+ popupProps={{ style: { minWidth: 260 } }}
+ header={
+ <div {...stylex.props(styles.search)}>
+ <input
+ autoFocus
+ {...stylex.props(styles.searchInput)}
+ placeholder={t('taskList.filter.searchPlaceholder')}
+ value={search}
+ onChange={(event) => setSearch(event.target.value)}
+ onKeyDown={handleSearchKeyDown}
+ />
+ <Hotkey keys={hotkey} />
+ </div>
+ }
+ onOpenChange={handleOpenChange}
+ >
+ <ActionIcon
+ active={open}
+ icon={ListFilterIcon}
+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}
+ title={t('taskList.filter.add')}
+ tooltipProps={{ hotkey }}
+ />
+ </DropdownMenu>
+ );
+});
+
+TaskFilterButton.displayName = 'TaskFilterButton';
+
+export default TaskFilterButton;
diff --git a/src/features/AgentTasks/AgentTaskList/filter/agentFilterOption.test.ts b/src/features/AgentTasks/AgentTaskList/filter/agentFilterOption.test.ts
new file mode 100644
index 00000000000..9d73ed41b00
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskList/filter/agentFilterOption.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest';
+
+import AgentAvatar from '@/components/AgentAvatar';
+
+import { toAgentFilterOption } from './agentFilterOption';
+
+describe('toAgentFilterOption', () => {
+ it('renders an agent without its own avatar through AgentAvatar, seeded by its id', () => {
+ const option = toAgentFilterOption({ id: 'agt_coder', label: 'Coder Agent' });
+
+ expect(option.icon.type).toBe(AgentAvatar);
+ expect(option.icon.props).toMatchObject({ agentId: 'agt_coder', name: 'Coder Agent' });
+ expect(option.value).toBe('agt_coder');
+ });
+
+ it('keeps the icon while overriding the value, as the creator field does', () => {
+ const option = toAgentFilterOption(
+ { avatar: '🤖', id: 'agt_coder', label: 'Coder Agent' },
+ 'agent:agt_coder',
+ );
+
+ expect(option.icon.props).toMatchObject({ agentId: 'agt_coder', avatar: '🤖' });
+ expect(option.value).toBe('agent:agt_coder');
+ });
+});
diff --git a/src/features/AgentTasks/AgentTaskList/filter/agentFilterOption.tsx b/src/features/AgentTasks/AgentTaskList/filter/agentFilterOption.tsx
new file mode 100644
index 00000000000..a6970e7ddb4
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskList/filter/agentFilterOption.tsx
@@ -0,0 +1,33 @@
+import AgentAvatar from '@/components/AgentAvatar';
+
+import type { TaskFilterValue } from './taskFilterState';
+
+export const AGENT_OPTION_ICON_SIZE = 16;
+
+interface AgentFilterOptionInput {
+ avatar?: string | null;
+ backgroundColor?: string | null;
+ id: string;
+ label: string;
+}
+
+/**
+ * One agent in a filter menu. `AgentAvatar` draws the generated character for
+ * an agent with no avatar of its own; a plain `Avatar` would leave it blank.
+ */
+export const toAgentFilterOption = (
+ { avatar, backgroundColor, id, label }: AgentFilterOptionInput,
+ value: TaskFilterValue = id,
+) => ({
+ icon: (
+ <AgentAvatar
+ agentId={id}
+ avatar={avatar ?? undefined}
+ background={backgroundColor ?? undefined}
+ name={label}
+ size={AGENT_OPTION_ICON_SIZE}
+ />
+ ),
+ label,
+ value,
+});
diff --git a/src/features/AgentTasks/AgentTaskList/filter/index.ts b/src/features/AgentTasks/AgentTaskList/filter/index.ts
new file mode 100644
index 00000000000..b5d6249889b
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskList/filter/index.ts
@@ -0,0 +1,5 @@
+export { default as TaskFilterBar } from './TaskFilterBar';
+export { default as TaskFilterButton } from './TaskFilterButton';
+export { pickOfferedTaskFilter, taskListFilterScopeKey } from './taskFilterState';
+export { useTaskFilterFields } from './useTaskFilterFields';
+export { useTaskListFilter } from './useTaskListFilter';
diff --git a/src/features/AgentTasks/AgentTaskList/filter/taskFilterState.test.ts b/src/features/AgentTasks/AgentTaskList/filter/taskFilterState.test.ts
new file mode 100644
index 00000000000..f3cc5917ebe
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskList/filter/taskFilterState.test.ts
@@ -0,0 +1,148 @@
+import { TASK_LIST_FILTER_MAX_VALUES } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import {
+ MAX_STORED_TASK_LIST_FILTERS,
+ pickOfferedTaskFilter,
+ removeTaskFilterField,
+ setTaskFilterContent,
+ setTaskFilterDateWindow,
+ showsTaskFilterValuesInline,
+ taskFilterSetOperatorKey,
+ taskListFilterScopeKey,
+ toggleTaskFilterOperator,
+ toggleTaskFilterValue,
+ upsertTaskListFilterEntry,
+} from './taskFilterState';
+
+describe('taskListFilterScopeKey', () => {
+ it('keys filters by workspace and page scope', () => {
+ expect(taskListFilterScopeKey({})).toBe('personal:global');
+ expect(taskListFilterScopeKey({ workspaceId: 'ws_1' })).toBe('ws_1:global');
+ expect(taskListFilterScopeKey({ agentId: 'agt_1', workspaceId: 'ws_1' })).toBe(
+ 'ws_1:agent:agt_1',
+ );
+ // A project page is scoped by the project even when an agent is known.
+ expect(taskListFilterScopeKey({ agentId: 'agt_1', projectId: 'proj_1' })).toBe(
+ 'personal:project:proj_1',
+ );
+ });
+});
+
+describe('upsertTaskListFilterEntry', () => {
+ it('adds, replaces and removes a scope entry', () => {
+ const added = upsertTaskListFilterEntry([], 'a', {
+ status: { operator: 'is', values: ['backlog'] },
+ });
+ expect(added).toEqual([
+ { filter: { status: { operator: 'is', values: ['backlog'] } }, scope: 'a' },
+ ]);
+
+ const replaced = upsertTaskListFilterEntry(added, 'a', { content: 'x' });
+ expect(replaced).toEqual([{ filter: { content: 'x' }, scope: 'a' }]);
+
+ expect(upsertTaskListFilterEntry(replaced, 'a', undefined)).toEqual([]);
+ expect(upsertTaskListFilterEntry(replaced, 'a', {})).toEqual([]);
+ });
+
+ it('keeps only the most recently touched scopes', () => {
+ let entries = upsertTaskListFilterEntry([], 'first', { content: 'x' });
+ for (let i = 0; i < MAX_STORED_TASK_LIST_FILTERS; i++) {
+ entries = upsertTaskListFilterEntry(entries, `scope-${i}`, { content: 'x' });
+ }
+ expect(entries).toHaveLength(MAX_STORED_TASK_LIST_FILTERS);
+ expect(entries.some((entry) => entry.scope === 'first')).toBe(false);
+ });
+});
+
+describe('filter editing', () => {
+ it('toggles values in and out, starting a new condition as "is"', () => {
+ const one = toggleTaskFilterValue(undefined, 'status', 'running');
+ expect(one).toEqual({ status: { operator: 'is', values: ['running'] } });
+
+ const two = toggleTaskFilterValue(one, 'status', 'backlog');
+ expect(two).toEqual({ status: { operator: 'is', values: ['backlog', 'running'] } });
+
+ expect(
+ toggleTaskFilterValue(toggleTaskFilterValue(two, 'status', 'backlog'), 'status', 'running'),
+ ).toBeUndefined();
+ });
+
+ it('stops adding values at the list query limit but still removes them', () => {
+ const values = Array.from({ length: TASK_LIST_FILTER_MAX_VALUES }, (_, i) => `agt_${i}`);
+ const full = { agent: { operator: 'is' as const, values } };
+ expect(toggleTaskFilterValue(full, 'agent', 'agt_extra')).toBe(full);
+ expect(toggleTaskFilterValue(full, 'agent', 'agt_0')?.agent?.values).toHaveLength(
+ TASK_LIST_FILTER_MAX_VALUES - 1,
+ );
+ });
+
+ it('keeps the operator when values change', () => {
+ const negated = toggleTaskFilterOperator(
+ toggleTaskFilterValue(undefined, 'priority', 1),
+ 'priority',
+ );
+ expect(toggleTaskFilterValue(negated, 'priority', 2)).toEqual({
+ priority: { operator: 'isNot', values: [1, 2] },
+ });
+ });
+
+ it('flips date operators and keeps them when the window changes', () => {
+ const within = setTaskFilterDateWindow(undefined, 'createdAt', 'week');
+ expect(within).toEqual({ createdAt: { operator: 'within', window: 'week' } });
+
+ const before = toggleTaskFilterOperator(within, 'createdAt');
+ expect(setTaskFilterDateWindow(before, 'createdAt', 'month')).toEqual({
+ createdAt: { operator: 'before', window: 'month' },
+ });
+ });
+
+ it('sets and clears content', () => {
+ expect(setTaskFilterContent(undefined, ' menu ')).toEqual({ content: 'menu' });
+ expect(setTaskFilterContent({ content: 'menu' }, '')).toBeUndefined();
+ });
+
+ it('removes one field and leaves the rest', () => {
+ expect(
+ removeTaskFilterField(
+ { content: 'menu', status: { operator: 'is', values: ['backlog'] } },
+ 'status',
+ ),
+ ).toEqual({ content: 'menu' });
+ });
+});
+
+describe('pickOfferedTaskFilter', () => {
+ it('drops conditions on fields the page does not offer, keeping content', () => {
+ expect(
+ pickOfferedTaskFilter(
+ {
+ assignee: { operator: 'is', values: ['user_1'] },
+ content: 'menu',
+ status: { operator: 'is', values: ['backlog'] },
+ },
+ ['status', 'priority'],
+ ),
+ ).toEqual({ content: 'menu', status: { operator: 'is', values: ['backlog'] } });
+ });
+
+ it('returns undefined when nothing offered is left', () => {
+ expect(
+ pickOfferedTaskFilter({ assignee: { operator: 'is', values: ['user_1'] } }, ['status']),
+ ).toBeUndefined();
+ });
+});
+
+describe('set chip display', () => {
+ it('reads the operator as plural once several values are picked', () => {
+ expect(taskFilterSetOperatorKey('is', 1)).toBe('taskList.filter.operator.is');
+ expect(taskFilterSetOperatorKey('is', 2)).toBe('taskList.filter.operator.isAnyOf');
+ expect(taskFilterSetOperatorKey('isNot', 1)).toBe('taskList.filter.operator.isNot');
+ expect(taskFilterSetOperatorKey('isNot', 3)).toBe('taskList.filter.operator.isNoneOf');
+ });
+
+ it('lists up to two values inline and collapses more into a count', () => {
+ expect(showsTaskFilterValuesInline(2)).toBe(true);
+ expect(showsTaskFilterValuesInline(3)).toBe(false);
+ });
+});
diff --git a/src/features/AgentTasks/AgentTaskList/filter/taskFilterState.ts b/src/features/AgentTasks/AgentTaskList/filter/taskFilterState.ts
new file mode 100644
index 00000000000..c28a656cd6b
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskList/filter/taskFilterState.ts
@@ -0,0 +1,173 @@
+import {
+ normalizeTaskListFilter,
+ TASK_LIST_FILTER_MAX_VALUES,
+ type TaskListFilter,
+ type TaskListFilterDate,
+ type TaskListFilterDateField,
+ type TaskListFilterDateWindow,
+ type TaskListFilterField,
+ type TaskListFilterSet,
+ type TaskListFilterSetField,
+} from '@lobechat/types';
+
+/** Value type of one set field (priority holds numbers, the rest strings). */
+export type TaskFilterValue = number | string;
+
+export interface TaskListFilterEntry {
+ filter: TaskListFilter;
+ scope: string;
+}
+
+/** Oldest scopes are dropped past this, so visiting many agents cannot grow the status blob forever. */
+export const MAX_STORED_TASK_LIST_FILTERS = 50;
+
+/**
+ * Which list a filter belongs to. Each agent / project page keeps its own, and
+ * the workspace is part of the key because the values (members, agents,
+ * projects) only exist inside one workspace.
+ */
+export const taskListFilterScopeKey = ({
+ agentId,
+ projectId,
+ workspaceId,
+}: {
+ agentId?: string;
+ projectId?: string;
+ workspaceId?: string | null;
+}): string => {
+ const space = workspaceId || 'personal';
+ if (projectId) return `${space}:project:${projectId}`;
+ if (agentId) return `${space}:agent:${agentId}`;
+ return `${space}:global`;
+};
+
+/**
+ * The stored list with `scope` set to `filter` (or removed when the filter is
+ * empty). The touched scope moves to the end, so trimming keeps the most
+ * recently used ones.
+ */
+export const upsertTaskListFilterEntry = (
+ entries: readonly TaskListFilterEntry[],
+ scope: string,
+ filter: TaskListFilter | undefined,
+): TaskListFilterEntry[] => {
+ const rest = entries.filter((entry) => entry.scope !== scope);
+ const normalized = normalizeTaskListFilter(filter);
+ const next = normalized ? [...rest, { filter: normalized, scope }] : rest;
+ return next.slice(-MAX_STORED_TASK_LIST_FILTERS);
+};
+
+const getSet = (
+ filter: TaskListFilter | undefined,
+ field: TaskListFilterSetField,
+): TaskListFilterSet<TaskFilterValue> | undefined =>
+ filter?.[field] as TaskListFilterSet<TaskFilterValue> | undefined;
+
+export const isTaskFilterValueSelected = (
+ filter: TaskListFilter | undefined,
+ field: TaskListFilterSetField,
+ value: TaskFilterValue,
+): boolean => !!getSet(filter, field)?.values.includes(value);
+
+/**
+ * Add or remove one value; a new condition starts as "is". Adding past
+ * `TASK_LIST_FILTER_MAX_VALUES` is ignored, since the list query would reject it.
+ */
+export const toggleTaskFilterValue = (
+ filter: TaskListFilter | undefined,
+ field: TaskListFilterSetField,
+ value: TaskFilterValue,
+): TaskListFilter | undefined => {
+ const current = getSet(filter, field);
+ const values = current?.values ?? [];
+ if (!values.includes(value) && values.length >= TASK_LIST_FILTER_MAX_VALUES) return filter;
+ const nextValues = values.includes(value)
+ ? values.filter((item) => item !== value)
+ : [...values, value];
+ return normalizeTaskListFilter({
+ ...filter,
+ [field]: { operator: current?.operator ?? 'is', values: nextValues },
+ });
+};
+
+/** Flip "is" ↔ "is not" (sets) or "within" ↔ "before" (dates). */
+export const toggleTaskFilterOperator = (
+ filter: TaskListFilter | undefined,
+ field: TaskListFilterDateField | TaskListFilterSetField,
+): TaskListFilter | undefined => {
+ const condition = filter?.[field];
+ if (!filter || !condition) return filter;
+ if ('window' in condition) {
+ const date = condition as TaskListFilterDate;
+ return normalizeTaskListFilter({
+ ...filter,
+ [field]: { ...date, operator: date.operator === 'within' ? 'before' : 'within' },
+ });
+ }
+ const set = condition as TaskListFilterSet<TaskFilterValue>;
+ return normalizeTaskListFilter({
+ ...filter,
+ [field]: { ...set, operator: set.operator === 'is' ? 'isNot' : 'is' },
+ });
+};
+
+/** Pick a date window, keeping the current operator. */
+export const setTaskFilterDateWindow = (
+ filter: TaskListFilter | undefined,
+ field: TaskListFilterDateField,
+ window: TaskListFilterDateWindow,
+): TaskListFilter | undefined =>
+ normalizeTaskListFilter({
+ ...filter,
+ [field]: { operator: filter?.[field]?.operator ?? 'within', window },
+ });
+
+export const setTaskFilterContent = (
+ filter: TaskListFilter | undefined,
+ content: string,
+): TaskListFilter | undefined => normalizeTaskListFilter({ ...filter, content });
+
+export const removeTaskFilterField = (
+ filter: TaskListFilter | undefined,
+ field: TaskListFilterField,
+): TaskListFilter | undefined => {
+ if (!filter) return undefined;
+ const { [field]: _removed, ...rest } = filter;
+ return normalizeTaskListFilter(rest);
+};
+
+/**
+ * The part of a stored filter this page can show and edit. A condition on a
+ * field the page does not offer (a member field once the page has no member
+ * directory) would narrow the list with no chip to clear it, so it is ignored.
+ */
+export const pickOfferedTaskFilter = (
+ filter: TaskListFilter | undefined,
+ offeredFields: readonly TaskListFilterField[],
+): TaskListFilter | undefined => {
+ if (!filter) return undefined;
+ const offered = new Set<TaskListFilterField>([...offeredFields, 'content']);
+ return normalizeTaskListFilter(
+ Object.fromEntries(
+ Object.entries(filter).filter(([field]) => offered.has(field as TaskListFilterField)),
+ ) as TaskListFilter,
+ );
+};
+
+/** Chips list at most this many value labels inline; more collapse into a count. */
+export const MAX_INLINE_TASK_FILTER_VALUES = 2;
+
+/** Whether a chip shows its value labels inline rather than a count. */
+export const showsTaskFilterValuesInline = (count: number): boolean =>
+ count <= MAX_INLINE_TASK_FILTER_VALUES;
+
+/** i18n key of a set chip's operator: "is" / "is not" read as "is any of" / "is none of" for several values. */
+export const taskFilterSetOperatorKey = (
+ operator: TaskListFilterSet<TaskFilterValue>['operator'],
+ count: number,
+) => {
+ const many = count > 1;
+ if (operator === 'isNot')
+ return many ? 'taskList.filter.operator.isNoneOf' : 'taskList.filter.operator.isNot';
+ return many ? 'taskList.filter.operator.isAnyOf' : 'taskList.filter.operator.is';
+};
diff --git a/src/features/AgentTasks/AgentTaskList/filter/useTaskFilterFields.tsx b/src/features/AgentTasks/AgentTaskList/filter/useTaskFilterFields.tsx
new file mode 100644
index 00000000000..8ec033bf909
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskList/filter/useTaskFilterFields.tsx
@@ -0,0 +1,300 @@
+import { TASK_STATUSES } from '@lobechat/builtin-tool-task';
+import { DEFAULT_INBOX_AVATAR } from '@lobechat/const';
+import {
+ agentDisplayName,
+ TASK_LIST_FILTER_NONE,
+ type TaskListFilterDateField,
+ type TaskListFilterSetField,
+ toTaskListFilterAgentCreator,
+} from '@lobechat/types';
+import { Avatar, Icon } from '@lobehub/ui';
+import isEqual from 'fast-deep-equal';
+import type { LucideIcon } from 'lucide-react';
+import {
+ BotIcon,
+ CalendarCheckIcon,
+ CalendarClockIcon,
+ CalendarPlusIcon,
+ CircleDashedIcon,
+ FolderClosedIcon,
+ SignalHighIcon,
+ UserRoundIcon,
+ UserRoundPenIcon,
+} from 'lucide-react';
+import type { ReactNode } from 'react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { useFetchWorkspaceMembers } from '@/business/client/hooks/useFetchWorkspaceMembers';
+import { useWorkspaceMembers } from '@/business/client/hooks/useWorkspaceMembers';
+import UserAvatar from '@/components/UserAvatar';
+import { useFetchAgentList } from '@/hooks/useFetchAgentList';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
+import { useHomeStore } from '@/store/home';
+import { homeAgentListSelectors } from '@/store/home/selectors';
+import { useCurrentProjectList, useProjectStore } from '@/store/project';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+import { PRIORITY_META } from '../../features/TaskPriorityTag';
+import TaskStatusIcon from '../../features/TaskStatusIcon';
+import { UnassignedAssigneeIcon } from '../../features/UnassignedAssigneeIcon';
+import { hasWorkspaceMemberDirectory } from '../../shared/memberAssigneeMode';
+import { toAgentFilterOption } from './agentFilterOption';
+import type { TaskFilterValue } from './taskFilterState';
+
+export interface TaskFilterOption {
+ icon?: ReactNode;
+ label: string;
+ value: TaskFilterValue;
+}
+
+export interface TaskFilterSetFieldDef {
+ icon: LucideIcon;
+ key: TaskListFilterSetField;
+ kind: 'set';
+ label: string;
+ options: TaskFilterOption[];
+}
+
+export interface TaskFilterDateFieldDef {
+ icon: LucideIcon;
+ key: TaskListFilterDateField;
+ kind: 'date';
+ label: string;
+}
+
+export type TaskFilterFieldDef = TaskFilterDateFieldDef | TaskFilterSetFieldDef;
+
+/** Menu order of the priorities: the way the board lays them out, "no priority" last. */
+const PRIORITY_ORDER = [1, 2, 3, 4, 0];
+
+const OPTION_ICON_SIZE = 16;
+
+interface UseTaskFilterFieldsParams {
+ /** The page is one agent's list, so the agent field would only ever hold that agent. */
+ agentId?: string;
+ /** The page is one project's list; same reason for the project field. */
+ projectId?: string;
+}
+
+/**
+ * Everything the "Add filter" menu and the filter chips can offer on this
+ * page, with display labels and icons for each value. Assignee and creator
+ * list the workspace members, or just the signed-in user in personal mode;
+ * the creator field also lists the agents. A member value also matches the
+ * tasks their agents created for them; an agent value narrows to that agent.
+ */
+export const useTaskFilterFields = ({
+ agentId,
+ projectId,
+}: UseTaskFilterFieldsParams): TaskFilterFieldDef[] => {
+ const { t } = useTranslation('chat');
+ const activeWorkspaceId = useActiveWorkspaceId();
+ const hasMembers = hasWorkspaceMemberDirectory(activeWorkspaceId);
+
+ useFetchAgentList();
+ const sidebarAgents = useHomeStore(homeAgentListSelectors.allAgents, isEqual);
+ const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
+ const inboxMeta = useAgentStore((s) =>
+ inboxAgentId ? agentSelectors.getAgentMetaById(inboxAgentId)(s) : undefined,
+ );
+
+ useFetchWorkspaceMembers();
+ const members = useWorkspaceMembers();
+ const selfUserId = useUserStore(userProfileSelectors.userId);
+ const selfAvatar = useUserStore(userProfileSelectors.userAvatar);
+ const selfName = useUserStore(userProfileSelectors.displayUserName);
+
+ const useFetchProjectList = useProjectStore((s) => s.useFetchProjectList);
+ useFetchProjectList(!projectId);
+ const projects = useCurrentProjectList();
+
+ return useMemo(() => {
+ const statusField: TaskFilterSetFieldDef = {
+ icon: CircleDashedIcon,
+ key: 'status',
+ kind: 'set',
+ label: t('taskList.filter.field.status'),
+ options: TASK_STATUSES.map((status) => ({
+ icon: <TaskStatusIcon size={OPTION_ICON_SIZE} status={status} />,
+ label: t(`taskDetail.status.${status}`),
+ value: status,
+ })),
+ };
+
+ const priorityField: TaskFilterSetFieldDef = {
+ icon: SignalHighIcon,
+ key: 'priority',
+ kind: 'set',
+ label: t('taskList.filter.field.priority'),
+ options: PRIORITY_ORDER.map((level) => {
+ const meta = PRIORITY_META[level];
+ const PriorityIcon = meta.icon;
+ return {
+ icon: <PriorityIcon size={OPTION_ICON_SIZE} />,
+ label: t(`taskDetail.${meta.labelKey}` as never, { defaultValue: meta.label }),
+ value: level,
+ };
+ }),
+ };
+
+ const agentOptions: TaskFilterOption[] = [
+ {
+ icon: <UnassignedAssigneeIcon kind={'agent'} size={OPTION_ICON_SIZE} />,
+ label: t('taskList.filter.noAgent'),
+ value: TASK_LIST_FILTER_NONE,
+ },
+ ];
+ const seenAgents = new Set<string>();
+ if (inboxAgentId) {
+ seenAgents.add(inboxAgentId);
+ agentOptions.push(
+ toAgentFilterOption({
+ avatar: inboxMeta?.avatar || DEFAULT_INBOX_AVATAR,
+ backgroundColor: inboxMeta?.backgroundColor,
+ id: inboxAgentId,
+ label: agentDisplayName(inboxMeta, t('inbox.title')),
+ }),
+ );
+ }
+ for (const agent of sidebarAgents) {
+ if (agent.type !== 'agent' || seenAgents.has(agent.id)) continue;
+ seenAgents.add(agent.id);
+ agentOptions.push(
+ toAgentFilterOption({
+ avatar: typeof agent.avatar === 'string' ? agent.avatar : undefined,
+ backgroundColor: agent.backgroundColor,
+ id: agent.id,
+ label: agentDisplayName(agent, t('taskList.filter.untitledAgent')),
+ }),
+ );
+ }
+ const agentField: TaskFilterSetFieldDef = {
+ icon: BotIcon,
+ key: 'agent',
+ kind: 'set',
+ label: t('taskList.filter.field.agent'),
+ options: agentOptions,
+ };
+
+ const memberOptions: TaskFilterOption[] = hasMembers
+ ? members.map((member) => {
+ const name =
+ member.user?.fullName || member.user?.username || member.user?.email || member.userId;
+ return {
+ icon: <UserAvatar avatar={member.user?.avatar} name={name} size={OPTION_ICON_SIZE} />,
+ label: name,
+ value: member.userId,
+ };
+ })
+ : selfUserId
+ ? [
+ {
+ icon: <UserAvatar avatar={selfAvatar} name={selfName} size={OPTION_ICON_SIZE} />,
+ label: selfName || t('taskList.filter.me'),
+ value: selfUserId,
+ },
+ ]
+ : [];
+ const assigneeField: TaskFilterSetFieldDef = {
+ icon: UserRoundIcon,
+ key: 'assignee',
+ kind: 'set',
+ label: t('taskList.filter.field.assignee'),
+ options: [
+ {
+ icon: <UnassignedAssigneeIcon kind={'human'} size={OPTION_ICON_SIZE} />,
+ label: t('taskList.unassigned'),
+ value: TASK_LIST_FILTER_NONE,
+ },
+ ...memberOptions,
+ ],
+ };
+ const creatorField: TaskFilterSetFieldDef = {
+ icon: UserRoundPenIcon,
+ key: 'creator',
+ kind: 'set',
+ label: t('taskList.filter.field.creator'),
+ options: [
+ ...memberOptions,
+ // Same agents as the agent field, minus "no agent": every task has a creator.
+ ...agentOptions
+ .filter((option) => option.value !== TASK_LIST_FILTER_NONE)
+ .map((option) => ({
+ ...option,
+ value: toTaskListFilterAgentCreator(String(option.value)),
+ })),
+ ],
+ };
+
+ const projectField: TaskFilterSetFieldDef = {
+ icon: FolderClosedIcon,
+ key: 'project',
+ kind: 'set',
+ label: t('taskList.filter.field.project'),
+ options: [
+ {
+ icon: <Icon icon={FolderClosedIcon} size={OPTION_ICON_SIZE} />,
+ label: t('taskList.filter.noProject'),
+ value: TASK_LIST_FILTER_NONE,
+ },
+ ...projects.map((project) => ({
+ icon: project.avatar ? (
+ <Avatar avatar={project.avatar} size={OPTION_ICON_SIZE} />
+ ) : (
+ <Icon icon={FolderClosedIcon} size={OPTION_ICON_SIZE} />
+ ),
+ label: project.name || t('taskList.filter.untitledProject'),
+ value: project.id,
+ })),
+ ],
+ };
+
+ const dateFields: TaskFilterDateFieldDef[] = [
+ {
+ icon: CalendarPlusIcon,
+ key: 'createdAt',
+ kind: 'date',
+ label: t('taskList.filter.field.createdAt'),
+ },
+ {
+ icon: CalendarClockIcon,
+ key: 'updatedAt',
+ kind: 'date',
+ label: t('taskList.filter.field.updatedAt'),
+ },
+ {
+ icon: CalendarCheckIcon,
+ key: 'completedAt',
+ kind: 'date',
+ label: t('taskList.filter.field.completedAt'),
+ },
+ ];
+
+ return [
+ statusField,
+ priorityField,
+ ...(agentId ? [] : [agentField]),
+ assigneeField,
+ creatorField,
+ ...(projectId ? [] : [projectField]),
+ ...dateFields,
+ ];
+ }, [
+ agentId,
+ hasMembers,
+ inboxAgentId,
+ inboxMeta,
+ members,
+ projectId,
+ projects,
+ selfAvatar,
+ selfName,
+ selfUserId,
+ sidebarAgents,
+ t,
+ ]);
+};
diff --git a/src/features/AgentTasks/AgentTaskList/filter/useTaskListFilter.ts b/src/features/AgentTasks/AgentTaskList/filter/useTaskListFilter.ts
new file mode 100644
index 00000000000..8cc18274f18
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskList/filter/useTaskListFilter.ts
@@ -0,0 +1,32 @@
+import type { TaskListFilter } from '@lobechat/types';
+import { useCallback } from 'react';
+
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+
+import { upsertTaskListFilterEntry } from './taskFilterState';
+
+/**
+ * The persisted filter of one Tasks page scope (`taskListFilterScopeKey`) and
+ * its setter. The setter takes an updater so rapid edits (several values
+ * checked in one open menu) build on the latest stored filter.
+ */
+export const useTaskListFilter = (scope: string) => {
+ const filter = useGlobalStore(systemStatusSelectors.taskListFilter(scope));
+ const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
+
+ const setFilter = useCallback(
+ (updater: (prev: TaskListFilter | undefined) => TaskListFilter | undefined) => {
+ const state = useGlobalStore.getState();
+ const entries = systemStatusSelectors.taskListFilters(state);
+ const prev = systemStatusSelectors.taskListFilter(scope)(state);
+ updateSystemStatus(
+ { taskListFilters: upsertTaskListFilterEntry(entries, scope, updater(prev)) },
+ 'updateTaskListFilter',
+ );
+ },
+ [scope, updateSystemStatus],
+ );
+
+ return [filter, setFilter] as const;
+};
diff --git a/src/services/task.ts b/src/services/task.ts
index cd1b18f1b38..2be854f69b9 100644
--- a/src/services/task.ts
+++ b/src/services/task.ts
@@ -4,6 +4,7 @@ import type {
TaskAutomationMode,
TaskInstructionSynthesis,
TaskIntentAnalysis,
+ TaskListFilter,
TaskStatus,
} from '@lobechat/types';
@@ -29,6 +30,8 @@ class TaskService {
automated?: boolean;
/** Keep completed / canceled tasks only when closed within this window. */
completedWithin?: TaskCompletedWindow;
+ /** The Tasks page filter, applied server-side before paging. */
+ filter?: TaskListFilter;
/** Archived tasks are left out unless this is set. */
includeArchived?: boolean;
orderBy?: 'createdAt' | 'updatedAt';
@@ -49,6 +52,7 @@ class TaskService {
automated?: boolean;
completedWithin?: TaskCompletedWindow;
excludeStatuses?: TaskStatus[];
+ filter?: TaskListFilter;
groupBy?: 'assignee' | 'member' | 'priority';
groups?: Array<{
key: string;
diff --git a/src/store/chat/slices/agentRun/actions/transports/viewedTaskPrompt.test.ts b/src/store/chat/slices/agentRun/actions/transports/viewedTaskPrompt.test.ts
index 9ee12730b4d..0682c352aff 100644
--- a/src/store/chat/slices/agentRun/actions/transports/viewedTaskPrompt.test.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/viewedTaskPrompt.test.ts
@@ -38,6 +38,32 @@ describe('buildViewedTaskPrompt', () => {
});
});
+describe('buildViewedTaskPrompt for the task list', () => {
+ const listContext = { viewedTask: { type: 'list' as const } };
+
+ const viewList = (filtered: boolean) =>
+ useTaskStore.setState({
+ activeTaskListFiltered: filtered,
+ activeTaskListKey: 'list',
+ taskListMap: {
+ list: {
+ items: [{ identifier: 'T-1', name: 'Fix menu', priority: 2, status: 'running' }],
+ total: 1,
+ },
+ } as any,
+ });
+
+ it('tells the agent a filtered list is not every task', () => {
+ viewList(true);
+ expect(buildViewedTaskPrompt(listContext)).toContain('with a filter applied');
+ });
+
+ it('keeps the plain list hint without a filter', () => {
+ viewList(false);
+ expect(buildViewedTaskPrompt(listContext)).toContain('Do NOT call listTasks');
+ });
+});
+
describe('withHeteroContext', () => {
beforeEach(() => {
useTaskStore.setState({ taskDetailMap: { 'T-858': taskDetail } });
diff --git a/src/store/chat/slices/agentRun/actions/transports/viewedTaskPrompt.ts b/src/store/chat/slices/agentRun/actions/transports/viewedTaskPrompt.ts
index 1510122c9dd..33035f8fe7c 100644
--- a/src/store/chat/slices/agentRun/actions/transports/viewedTaskPrompt.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/viewedTaskPrompt.ts
@@ -25,6 +25,7 @@ export const buildViewedTaskPrompt = (
const tasks = viewedList?.items ?? [];
return buildTaskListPrompt({
defaultAssigneeAgentId,
+ filtered: taskState.activeTaskListFiltered,
tasks,
total: viewedList?.total || tasks.length,
});
diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.ts
index 5d5d2a10d5d..5123d25fc1a 100644
--- a/src/store/global/initialState.ts
+++ b/src/store/global/initialState.ts
@@ -1,3 +1,4 @@
+import { type TaskListFilter } from '@lobechat/types';
import { type NavigateFunction } from 'react-router';
import { type LocaleMode } from '@/types/locale';
@@ -458,6 +459,13 @@ export interface SystemStatus {
* Whether the right-side "Hidden columns" panel on the Kanban board is collapsed.
*/
taskKanbanHiddenPanelCollapsed?: boolean;
+ /**
+ * Tasks page filters, one entry per list scope (workspace + global / agent /
+ * project page). An array, not a map: status is deep-merged on write, which
+ * could never drop a removed condition from a nested object, while arrays
+ * are replaced whole.
+ */
+ taskListFilters?: { filter: TaskListFilter; scope: string }[];
/**
* Display mode for the tasks page. Persisted so a manually selected board or
* list view survives navigation and page reloads.
diff --git a/src/store/global/selectors/systemStatus.ts b/src/store/global/selectors/systemStatus.ts
index 7c3ab976003..cefa6174ec4 100644
--- a/src/store/global/selectors/systemStatus.ts
+++ b/src/store/global/selectors/systemStatus.ts
@@ -155,6 +155,13 @@ const taskListViewOptions = (s: GlobalState) =>
subGroupBy: 'none',
};
+const EMPTY_TASK_LIST_FILTERS: NonNullable<GlobalState['status']['taskListFilters']> = [];
+
+const taskListFilters = (s: GlobalState) => s.status.taskListFilters ?? EMPTY_TASK_LIST_FILTERS;
+
+const taskListFilter = (scope: string) => (s: GlobalState) =>
+ taskListFilters(s).find((entry) => entry.scope === scope)?.filter;
+
const taskListViewMode = (s: GlobalState) => s.status.taskListViewMode ?? 'list';
// Default the inline composer to collapsed so a populated task list keeps the
@@ -573,6 +580,8 @@ export const systemStatusSelectors = {
taskKanbanHiddenColumns,
taskKanbanHiddenPanelCollapsed,
taskListViewMode,
+ taskListFilter,
+ taskListFilters,
taskListViewOptions,
sidebarExpandedKeys,
agentSidebarSections,
diff --git a/src/store/task/slices/list/action.ts b/src/store/task/slices/list/action.ts
index 4accaf4f34f..818562d1307 100644
--- a/src/store/task/slices/list/action.ts
+++ b/src/store/task/slices/list/action.ts
@@ -1,5 +1,5 @@
import type { TaskCompletedWindow } from '@lobechat/builtin-tool-task';
-import type { TaskStatus } from '@lobechat/types';
+import { normalizeTaskListFilter, type TaskListFilter, type TaskStatus } from '@lobechat/types';
import { useMemo } from 'react';
import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';
@@ -63,6 +63,8 @@ export const TASK_COLLECTION_PAGE_SIZE = 50;
export interface ScheduledTaskListOptions {
agentId?: string;
+ /** The Tasks page filter; Home's roll-up sends none. */
+ filter?: TaskListFilter;
limit?: number;
offset?: number;
projectId?: string;
@@ -75,12 +77,14 @@ export interface ScheduledTaskListOptions {
*/
export const scheduledTaskListQuery = ({
agentId,
+ filter,
limit,
offset,
projectId,
}: ScheduledTaskListOptions): TaskListQuery => ({
agentId: projectId ? undefined : agentId,
automated: true,
+ filter: normalizeTaskListFilter(filter),
limit,
offset,
orderBy: 'updatedAt',
@@ -158,6 +162,7 @@ export class TaskListSliceActionImpl {
...(query.agentId ? { assigneeAgentId: query.agentId } : {}),
automated: query.automated,
...(query.completedWithin && { completedWithin: query.completedWithin }),
+ ...(query.filter && { filter: query.filter }),
includeArchived: query.includeArchived,
orderBy: query.orderBy,
projectId: query.projectId,
@@ -176,6 +181,7 @@ export class TaskListSliceActionImpl {
...(query.automated === undefined ? {} : { automated: query.automated }),
...(query.completedWithin && { completedWithin: query.completedWithin }),
excludeStatuses: query.excludeStatuses,
+ ...(query.filter && { filter: query.filter }),
...(query.groupBy === 'status'
? { groups: DEFAULT_KANBAN_GROUPS }
: { groupBy: query.groupBy }),
@@ -259,9 +265,15 @@ export class TaskListSliceActionImpl {
apply: (value: TaskGroupListValue) => TaskGroupListValue,
) => this.#taskGroupList.beginOptimistic(queryKey, apply);
- setActiveTaskListKey = (queryKey?: string): void => {
- if (this.#get().activeTaskListKey === queryKey) return;
- this.#set({ activeTaskListKey: queryKey }, false, 'setActiveTaskListKey');
+ setActiveTaskListKey = (queryKey?: string, filtered?: boolean): void => {
+ const state = this.#get();
+ if (state.activeTaskListKey === queryKey && !!state.activeTaskListFiltered === !!filtered)
+ return;
+ this.#set(
+ { activeTaskListFiltered: !!queryKey && !!filtered, activeTaskListKey: queryKey },
+ false,
+ 'setActiveTaskListKey',
+ );
};
refreshTaskGroupList = async (): Promise<void> => {
@@ -328,6 +340,8 @@ export class TaskListSliceActionImpl {
completedWithin?: TaskCompletedWindow;
enabled?: boolean;
excludeStatuses?: readonly TaskStatus[];
+ /** The Tasks page filter; part of the key. */
+ filter?: TaskListFilter;
groupBy?: TaskKanbanGroupBy;
includeArchived?: boolean;
projectId?: string;
@@ -347,6 +361,7 @@ export class TaskListSliceActionImpl {
completedWithin,
enabled = true,
excludeStatuses,
+ filter,
groupBy = 'status',
includeArchived,
projectId,
@@ -362,6 +377,7 @@ export class TaskListSliceActionImpl {
automated,
completedWithin,
excludeStatuses: excludeStatuses?.length ? [...excludeStatuses].sort() : undefined,
+ filter: normalizeTaskListFilter(filter),
groupBy,
includeArchived: includeArchived || undefined,
projectId,
@@ -419,6 +435,8 @@ export class TaskListSliceActionImpl {
*/
completedWithin?: TaskCompletedWindow;
enabled?: boolean;
+ /** The Tasks page filter, applied before `limit` / `offset`. */
+ filter?: TaskListFilter;
includeArchived?: boolean;
limit?: number;
offset?: number;
@@ -434,6 +452,7 @@ export class TaskListSliceActionImpl {
const {
completedWithin,
enabled = true,
+ filter,
includeArchived,
limit,
offset,
@@ -443,6 +462,7 @@ export class TaskListSliceActionImpl {
return this.#useCollectionPage(
{
completedWithin,
+ filter: normalizeTaskListFilter(filter),
// Archived rows are a different server page, like the status filter.
includeArchived: includeArchived || undefined,
limit,
@@ -478,6 +498,8 @@ export class TaskListSliceActionImpl {
*/
complete?: boolean;
enabled?: boolean;
+ /** The Tasks page filter, applied server-side; part of the key. */
+ filter?: TaskListFilter;
/** Include archived tasks (the "Show archived" option); part of the key. */
includeArchived?: boolean;
/**
@@ -505,6 +527,7 @@ export class TaskListSliceActionImpl {
automated,
complete = false,
enabled = true,
+ filter,
includeArchived,
orderBy,
projectId,
@@ -519,6 +542,7 @@ export class TaskListSliceActionImpl {
agentId: allAgents || projectId ? undefined : agentId,
automated,
complete: complete || undefined,
+ filter: normalizeTaskListFilter(filter),
includeArchived: includeArchived || undefined,
orderBy,
projectId,
diff --git a/src/store/task/slices/list/initialState.ts b/src/store/task/slices/list/initialState.ts
index 6a7399f675f..817acb249fd 100644
--- a/src/store/task/slices/list/initialState.ts
+++ b/src/store/task/slices/list/initialState.ts
@@ -19,6 +19,8 @@ export type TaskListVisibilityFilter = 'all' | 'private' | 'workspace';
export type TaskKanbanGroupBy = 'assignee' | 'member' | 'priority' | 'status';
export interface TaskListSliceState {
+ /** The viewed list is narrowed by the page's filter, so it is not every task. */
+ activeTaskListFiltered?: boolean;
/**
* The list the Tasks page is showing (`taskListMap` key) — what the task
* manager agent sees as "the viewed list".
diff --git a/src/store/task/slices/list/projection.ts b/src/store/task/slices/list/projection.ts
index 8a7017f9c1c..854725de49b 100644
--- a/src/store/task/slices/list/projection.ts
+++ b/src/store/task/slices/list/projection.ts
@@ -1,5 +1,5 @@
import type { TaskCompletedWindow } from '@lobechat/builtin-tool-task';
-import type { TaskStatus } from '@lobechat/types';
+import type { TaskListFilter, TaskStatus } from '@lobechat/types';
import { defineReplica, type ReplicaEntityAdapter, stableQueryKey } from '@/libs/replica';
import type { taskService } from '@/services/task';
@@ -31,6 +31,8 @@ export interface TaskListQuery {
complete?: boolean;
/** Completed / canceled tasks closed outside this window are left out server-side. */
completedWithin?: TaskCompletedWindow;
+ /** The Tasks page filter, normalized (`normalizeTaskListFilter`) so equal filters share an entry. */
+ filter?: TaskListFilter;
/** Archived tasks are hidden unless the "Show archived" option is on. */
includeArchived?: boolean;
/** One server page of a paginated collection (scheduled / "My tasks"); ignored by `complete`. */
@@ -59,6 +61,8 @@ export interface TaskGroupListQuery {
completedWithin?: TaskCompletedWindow;
/** Sorted. */
excludeStatuses?: TaskStatus[];
+ /** Normalized, like `TaskListQuery.filter`. */
+ filter?: TaskListFilter;
groupBy: TaskKanbanGroupBy;
includeArchived?: boolean;
projectId?: string;