🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(task): filter completed tasks by time window (#21657)
Lobehub Coder1190e4dd0039
diff --git a/apps/server/src/routers/lambda/_helpers/taskListSchemas.test.ts b/apps/server/src/routers/lambda/_helpers/taskListSchemas.test.tsnew file mode 100644index 00000000000..8161a5efc03--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/taskListSchemas.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from 'vitest';++import { groupListSchema, listSchema, resolveClosedAfter } from './taskListSchemas';++const DAY_MS = 24 * 60 * 60 * 1000;++describe('completedWithin', () => {+ it('is accepted by list and groupList, and rejects unknown windows', () => {+ expect(listSchema.parse({ completedWithin: 'week' }).completedWithin).toBe('week');+ expect(+ groupListSchema.parse({ completedWithin: 'day', groupBy: 'priority' }).completedWithin,+ ).toBe('day');+ expect(() => listSchema.parse({ completedWithin: 'year' })).toThrow();+ });++ it('resolves to the model cut relative to now', () => {+ const now = new Date('2026-03-10T12:00:00Z').getTime();++ expect(resolveClosedAfter('day', now)).toEqual(new Date(now - DAY_MS));+ expect(resolveClosedAfter('week', now)).toEqual(new Date(now - 7 * DAY_MS));+ expect(resolveClosedAfter('month', now)).toEqual(new Date(now - 30 * DAY_MS));+ expect(resolveClosedAfter(undefined, now)).toBeUndefined();+ });+});diff --git a/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts b/apps/server/src/routers/lambda/_helpers/taskListSchemas.tsindex b504fd6a743..9907f8f91fa 100644--- a/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts+++ b/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts@@ -1,4 +1,9 @@-import { TASK_STATUSES } from '@lobechat/builtin-tool-task';+import {+ TASK_COMPLETED_WINDOW_MS,+ TASK_COMPLETED_WINDOWS,+ TASK_STATUSES,+ type TaskCompletedWindow,+} from '@lobechat/builtin-tool-task';import { z } from 'zod';export const listSchema = z.object({@@ -10,6 +15,9 @@ export const listSchema = z.object({// misconfigured one cannot), false → its exact complement. Omitted leaves the// set unnarrowed.automated: z.boolean().optional(),+ // 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(),// Archived tasks are user-closed; lists leave them out unless asked.includeArchived: z.boolean().optional(),limit: z.number().min(1).max(100).default(50),@@ -35,6 +43,7 @@ export const groupListSchema = z.object({assigneeAgentId: z.string().optional(),automated: z.boolean().optional(),+ completedWithin: z.enum(TASK_COMPLETED_WINDOWS).optional(),excludeStatuses: z.array(z.enum(TASK_STATUSES)).max(10).optional(),groupBy: z.enum(['agent', 'assignee', 'member', 'priority']).optional(),groups: z@@ -60,3 +69,10 @@ export const groupListSchema = z.refine(({ groupBy, groups }) => Boolean(groupBy) !== Boolean(groups), {message: 'Provide either groups or groupBy',});++/** The model's `closedAfter` cut for a `completedWithin` window. */+export const resolveClosedAfter = (+ completedWithin: TaskCompletedWindow | undefined,+ now = Date.now(),+): Date | undefined =>+ completedWithin ? new Date(now - TASK_COMPLETED_WINDOW_MS[completedWithin]) : undefined;diff --git a/apps/server/src/routers/lambda/task/queries.ts b/apps/server/src/routers/lambda/task/queries.tsindex c86b095473f..53a14e59af6 100644--- a/apps/server/src/routers/lambda/task/queries.ts+++ b/apps/server/src/routers/lambda/task/queries.ts@@ -4,7 +4,7 @@ import { TRPCError } from '@trpc/server';import { UserModel } from '@/database/models/user';import { router } from '@/libs/trpc/lambda';-import { groupListSchema, listSchema } from '../_helpers/taskListSchemas';+import { groupListSchema, listSchema, resolveClosedAfter } from '../_helpers/taskListSchemas';import { idInput, resolveOrThrow, taskProcedure } from './procedures';export const queriesRouter = router({@@ -124,9 +124,10 @@ export const queriesRouter = router({groupList: taskProcedure.input(groupListSchema).query(async ({ input, ctx }) => {try {const model = ctx.taskModel;- const { scope, ...query } = input;+ const { completedWithin, scope, ...query } = input;const groups = await model.groupList({...query,+ closedAfter: resolveClosedAfter(completedWithin),...(scope === 'assigned' ? { assigneeUserId: ctx.userId } : {}),...(scope === 'created' ? { createdByUserId: ctx.userId } : {}),});@@ -143,7 +144,7 @@ export const queriesRouter = router({list: taskProcedure.input(listSchema).query(async ({ input, ctx }) => {try {const model = ctx.taskModel;- const { parentIdentifier, scope, ...query } = input;+ const { completedWithin, parentIdentifier, scope, ...query } = input;let parentTaskId = query.parentTaskId;if (parentIdentifier) {@@ -160,6 +161,7 @@ export const queriesRouter = router({const result = await model.list({...query,+ closedAfter: resolveClosedAfter(completedWithin),...(scope === 'assigned' ? { assigneeUserId: ctx.userId } : {}),...(scope === 'created' ? { createdByUserId: ctx.userId } : {}),parentTaskId,diff --git a/locales/ar/chat.json b/locales/ar/chat.jsonindex c286b1203fd..fce8a23e5fa 100644--- a/locales/ar/chat.json+++ b/locales/ar/chat.json@@ -2514,7 +2514,6 @@"taskList.form.orderCompletedByRecency": "ترتيب المهام المكتملة حسب الأحدث","taskList.form.ordering": "الترتيب","taskList.form.showArchived": "عرض المؤرشف",- "taskList.form.showCompleted": "عرض المكتملة والمُلغاة","taskList.form.showSubTasks": "عرض المهام الفرعية","taskList.form.subGrouping": "التجميع الفرعي","taskList.groupBy.assignee": "المكلّف",diff --git a/locales/bg-BG/chat.json b/locales/bg-BG/chat.jsonindex fff4c76a4b4..3ffc5d3de95 100644--- a/locales/bg-BG/chat.json+++ b/locales/bg-BG/chat.json@@ -2514,7 +2514,6 @@"taskList.form.orderCompletedByRecency": "Подреди завършените задачи по актуалност","taskList.form.ordering": "Подреждане","taskList.form.showArchived": "Покажи архивираните",- "taskList.form.showCompleted": "Покажи завършени и отменени","taskList.form.showSubTasks": "Показване на подзадачи","taskList.form.subGrouping": "Подгрупиране","taskList.groupBy.assignee": "Отговорник",diff --git a/locales/de-DE/chat.json b/locales/de-DE/chat.jsonindex b8248097213..593f37959dc 100644--- a/locales/de-DE/chat.json+++ b/locales/de-DE/chat.json@@ -2514,7 +2514,6 @@"taskList.form.orderCompletedByRecency": "Abgeschlossene Aufgaben nach Aktualität sortieren","taskList.form.ordering": "Sortierung","taskList.form.showArchived": "Archivierte anzeigen",- "taskList.form.showCompleted": "Abgeschlossene & stornierte anzeigen","taskList.form.showSubTasks": "Unteraufgaben anzeigen","taskList.form.subGrouping": "Untergruppierung","taskList.groupBy.assignee": "Zuständige Person",diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 45857531d18..2ecda9a2106 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -2557,6 +2557,11 @@"taskList.assigneeSelector.agentGroup": "Agents","taskList.assigneeSelector.workspaceMemberGroup": "Workspace members","taskList.breadcrumb.task": "Task",+ "taskList.completedTasks.all": "All",+ "taskList.completedTasks.day": "Past day",+ "taskList.completedTasks.month": "Past month",+ "taskList.completedTasks.none": "None",+ "taskList.completedTasks.week": "Past week","taskList.contextMenu.archive": "Archive","taskList.contextMenu.archiveBlocked": "Stop the running task or its schedule/heartbeat before archiving it","taskList.contextMenu.archiveDenied.noEditPermission": "You don't have permission to edit tasks in this workspace. Ask a workspace admin for access.",@@ -2593,12 +2598,12 @@"taskList.emptyHero.greeting": "What should we tackle today?","taskList.emptyHero.templatesTitle": "Templates picked for you","taskList.form.columns": "Columns",+ "taskList.form.completedTasks": "Completed & canceled","taskList.form.grouping": "Grouping","taskList.form.nestedSubTasks": "Nested sub-tasks","taskList.form.orderCompletedByRecency": "Sort completed tasks by recency","taskList.form.ordering": "Ordering","taskList.form.showArchived": "Show archived",- "taskList.form.showCompleted": "Show completed & canceled","taskList.form.showSubTasks": "Show sub-tasks","taskList.form.subGrouping": "Sub-grouping","taskList.groupBy.assignee": "Agent",diff --git a/locales/es-ES/chat.json b/locales/es-ES/chat.jsonindex 30a2823bf30..ac7320ac73f 100644--- a/locales/es-ES/chat.json+++ b/locales/es-ES/chat.json@@ -2514,7 +2514,6 @@"taskList.form.orderCompletedByRecency": "Ordenar tareas completadas por antigüedad","taskList.form.ordering": "Ordenación","taskList.form.showArchived": "Mostrar archivados",- "taskList.form.showCompleted": "Mostrar completadas y canceladas","taskList.form.showSubTasks": "Mostrar subtareas","taskList.form.subGrouping": "Subagrupación","taskList.groupBy.assignee": "Asignado a",diff --git a/locales/fa-IR/chat.json b/locales/fa-IR/chat.jsonindex 82c5bb67cc5..ecb547fa5a0 100644--- a/locales/fa-IR/chat.json+++ b/locales/fa-IR/chat.json@@ -2514,7 +2514,6 @@"taskList.form.orderCompletedByRecency": "مرتبسازی وظایف تکمیلشده بر اساس جدیدترین","taskList.form.ordering": "مرتبسازی","taskList.form.showArchived": "نمایش بایگانی شدهها",- "taskList.form.showCompleted": "نمایش تکمیلشده و لغوشده","taskList.form.showSubTasks": "نمایش زیرکارها","taskList.form.subGrouping": "زیرگروهبندی","taskList.groupBy.assignee": "واگذارشده",diff --git a/locales/fr-FR/chat.json b/locales/fr-FR/chat.jsonindex 0764f6d791d..ff020f4b260 100644--- a/locales/fr-FR/chat.json+++ b/locales/fr-FR/chat.json@@ -2514,7 +2514,6 @@"taskList.form.orderCompletedByRecency": "Trier les tâches terminées par ancienneté","taskList.form.ordering": "Tri","taskList.form.showArchived": "Afficher les archivés",- "taskList.form.showCompleted": "Afficher terminées et annulées","taskList.form.showSubTasks": "Afficher les sous-tâches","taskList.form.subGrouping": "Sous-regroupement","taskList.groupBy.assignee": "Attribué à",diff --git a/locales/it-IT/chat.json b/locales/it-IT/chat.jsonindex cf3b1380731..e6de59050eb 100644--- a/locales/it-IT/chat.json+++ b/locales/it-IT/chat.json@@ -2514,7 +2514,6 @@"taskList.form.orderCompletedByRecency": "Ordina le attività completate per data recente","taskList.form.ordering": "Ordinamento","taskList.form.showArchived": "Mostra archiviati",- "taskList.form.showCompleted": "Mostra completati e annullati","taskList.form.showSubTasks": "Mostra sotto-attività","taskList.form.subGrouping": "Sotto-raggruppamento","taskList.groupBy.assignee": "Assegnatario",diff --git a/locales/ja-JP/chat.json b/locales/ja-JP/chat.jsonindex accdd5ed141..da133e2dd74 100644--- a/locales/ja-JP/chat.json+++ b/locales/ja-JP/chat.json@@ -2514,7 +2514,6 @@"taskList.form.orderCompletedByRecency": "完了タスクを最近順に並べる","taskList.form.ordering": "並び替え","taskList.form.showArchived": "アーカイブ済みを表示",- "taskList.form.showCompleted": "完了・キャンセル済みを表示","taskList.form.showSubTasks": "サブタスクを表示","taskList.form.subGrouping": "サブグループ化","taskList.groupBy.assignee": "担当者",diff --git a/locales/ko-KR/chat.json b/locales/ko-KR/chat.jsonindex 5aebc23ea96..6875f635fa3 100644--- a/locales/ko-KR/chat.json+++ b/locales/ko-KR/chat.json@@ -2514,7 +2514,6 @@"taskList.form.orderCompletedByRecency": "완료된 작업을 최신순으로 정렬","taskList.form.ordering": "정렬","taskList.form.showArchived": "보관된 항목 보기",- "taskList.form.showCompleted": "완료 및 취소된 작업 표시","taskList.form.showSubTasks": "하위 작업 보기","taskList.form.subGrouping": "하위 그룹화","taskList.groupBy.assignee": "담당자",diff --git a/locales/nl-NL/chat.json b/locales/nl-NL/chat.jsonindex 56798572dad..8f40b9de64e 100644--- a/locales/nl-NL/chat.json+++ b/locales/nl-NL/chat.json@@ -2514,7 +2514,6 @@"taskList.form.orderCompletedByRecency": "Voltooide taken sorteren op recentheid","taskList.form.ordering": "Sortering","taskList.form.showArchived": "Gearchiveerde tonen",- "taskList.form.showCompleted": "Voltooide & geannuleerde tonen","taskList.form.showSubTasks": "Toon sub-taken","taskList.form.subGrouping": "Subgroepering","taskList.groupBy.assignee": "Toegewezen aan",diff --git a/locales/pl-PL/chat.json b/locales/pl-PL/chat.jsonindex 69a8585819a..63fe22e33ac 100644--- a/locales/pl-PL/chat.json+++ b/locales/pl-PL/chat.json@@ -2514,7 +2514,6 @@"taskList.form.orderCompletedByRecency": "Sortuj ukończone zadania według najnowszych","taskList.form.ordering": "Sortowanie","taskList.form.showArchived": "Pokaż zarchiwizowane",- "taskList.form.showCompleted": "Pokaż ukończone i anulowane","taskList.form.showSubTasks": "Pokaż podzadania","taskList.form.subGrouping": "Podgrupowanie","taskList.groupBy.assignee": "Przypisany",diff --git a/locales/pt-BR/chat.json b/locales/pt-BR/chat.jsonindex 4090c15b59c..08fe9b82ac8 100644--- a/locales/pt-BR/chat.json+++ b/locales/pt-BR/chat.json@@ -2514,7 +2514,6 @@"taskList.form.orderCompletedByRecency": "Ordenar concluídas por recente","taskList.form.ordering": "Ordenação","taskList.form.showArchived": "Mostrar arquivados",- "taskList.form.showCompleted": "Mostrar concluídas e canceladas","taskList.form.showSubTasks": "Mostrar subtarefas","taskList.form.subGrouping": "Subagrupamento","taskList.groupBy.assignee": "Responsável",diff --git a/locales/ru-RU/chat.json b/locales/ru-RU/chat.jsonindex c219b3917e0..df5dad7b31d 100644--- a/locales/ru-RU/chat.json+++ b/locales/ru-RU/chat.json@@ -2514,7 +2514,6 @@"taskList.form.orderCompletedByRecency": "Сортировать выполненные по давности","taskList.form.ordering": "Сортировка","taskList.form.showArchived": "Показать архивированные",- "taskList.form.showCompleted": "Показать завершённые и отменённые","taskList.form.showSubTasks": "Показать подзадачи","taskList.form.subGrouping": "Доп. группировка","taskList.groupBy.assignee": "Исполнитель",diff --git a/locales/tr-TR/chat.json b/locales/tr-TR/chat.jsonindex 35a30402439..b6d5471104a 100644--- a/locales/tr-TR/chat.json+++ b/locales/tr-TR/chat.json@@ -2514,7 +2514,6 @@"taskList.form.orderCompletedByRecency": "Tamamlanan görevleri yakınlığa göre sırala","taskList.form.ordering": "Sıralama","taskList.form.showArchived": "Arşivlenenleri göster",- "taskList.form.showCompleted": "Tamamlanan ve iptal edilenleri göster","taskList.form.showSubTasks": "Alt görevleri göster","taskList.form.subGrouping": "Alt gruplama","taskList.groupBy.assignee": "Atanan",diff --git a/locales/vi-VN/chat.json b/locales/vi-VN/chat.jsonindex f8597d9cb35..27e790891d6 100644--- a/locales/vi-VN/chat.json+++ b/locales/vi-VN/chat.json@@ -2514,7 +2514,6 @@"taskList.form.orderCompletedByRecency": "Sắp xếp tác vụ đã hoàn thành theo thời gian gần nhất","taskList.form.ordering": "Sắp xếp","taskList.form.showArchived": "Hiển thị đã lưu trữ",- "taskList.form.showCompleted": "Hiện tác vụ đã hoàn thành & đã hủy","taskList.form.showSubTasks": "Hiển thị nhiệm vụ con","taskList.form.subGrouping": "Nhóm phụ","taskList.groupBy.assignee": "Người được giao",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 4882b2653cc..6e604881f99 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -2557,6 +2557,11 @@"taskList.assigneeSelector.agentGroup": "助理","taskList.assigneeSelector.workspaceMemberGroup": "工作区成员","taskList.breadcrumb.task": "任务",+ "taskList.completedTasks.all": "全部",+ "taskList.completedTasks.day": "过去一天",+ "taskList.completedTasks.month": "过去一个月",+ "taskList.completedTasks.none": "不显示",+ "taskList.completedTasks.week": "过去一周","taskList.contextMenu.archive": "归档","taskList.contextMenu.archiveBlocked": "请先停止正在运行的任务,或暂停其定时/心跳,再进行归档","taskList.contextMenu.archiveDenied.noEditPermission": "你在当前工作区没有编辑任务的权限,请联系工作区管理员开通",@@ -2593,12 +2598,12 @@"taskList.emptyHero.greeting": "今天想搞定点什么?","taskList.emptyHero.templatesTitle": "为你推荐的模板","taskList.form.columns": "列",+ "taskList.form.completedTasks": "已完成与已取消","taskList.form.grouping": "分组","taskList.form.nestedSubTasks": "缩进显示子任务","taskList.form.orderCompletedByRecency": "按最近完成排序","taskList.form.ordering": "排序","taskList.form.showArchived": "显示已归档",- "taskList.form.showCompleted": "显示已完成与已取消","taskList.form.showSubTasks": "显示子任务","taskList.form.subGrouping": "子分组","taskList.groupBy.assignee": "助理",diff --git a/locales/zh-TW/chat.json b/locales/zh-TW/chat.jsonindex faae852b382..64bf3e0a629 100644--- a/locales/zh-TW/chat.json+++ b/locales/zh-TW/chat.json@@ -2514,7 +2514,6 @@"taskList.form.orderCompletedByRecency": "依最近完成排序","taskList.form.ordering": "排序方式","taskList.form.showArchived": "顯示已封存",- "taskList.form.showCompleted": "顯示已完成與已取消","taskList.form.showSubTasks": "顯示子任務","taskList.form.subGrouping": "次分組","taskList.groupBy.assignee": "負責人",diff --git a/packages/builtin-tool-task/src/constants.ts b/packages/builtin-tool-task/src/constants.tsindex 3e2768c73df..60e8fdcb35e 100644--- a/packages/builtin-tool-task/src/constants.ts+++ b/packages/builtin-tool-task/src/constants.ts@@ -10,6 +10,19 @@ export const TASK_STATUSES = [export const UNFINISHED_TASK_STATUSES = ['backlog', 'running', 'scheduled', 'paused'] as const;+/** Look-back windows a task list can keep completed and canceled tasks for. */+export const TASK_COMPLETED_WINDOWS = ['day', 'week', 'month'] as const;++export type TaskCompletedWindow = (typeof TASK_COMPLETED_WINDOWS)[number];++const DAY_MS = 24 * 60 * 60 * 1000;++export const TASK_COMPLETED_WINDOW_MS: Record<TaskCompletedWindow, number> = {+ day: DAY_MS,+ month: 30 * DAY_MS,+ week: 7 * DAY_MS,+};+/** Tool result for a create call without a usable `name` (required by the manifest). */export const MISSING_TASK_NAME_ERROR ='Task not created: `name` is required. Pass a short, descriptive name for the task and call again.';diff --git a/packages/builtin-tool-task/src/index.ts b/packages/builtin-tool-task/src/index.tsindex 9f8b8e13e16..33d0dbe7b97 100644--- a/packages/builtin-tool-task/src/index.ts+++ b/packages/builtin-tool-task/src/index.ts@@ -1,4 +1,11 @@-export { MISSING_TASK_NAME_ERROR, TASK_STATUSES, UNFINISHED_TASK_STATUSES } from './constants';+export type { TaskCompletedWindow } from './constants';+export {+ MISSING_TASK_NAME_ERROR,+ TASK_COMPLETED_WINDOW_MS,+ TASK_COMPLETED_WINDOWS,+ TASK_STATUSES,+ UNFINISHED_TASK_STATUSES,+} from './constants';export {DEFAULT_LIST_TASK_LIMIT,normalizeListTasksParams,diff --git a/packages/database/src/models/__tests__/task.closedAfter.test.ts b/packages/database/src/models/__tests__/task.closedAfter.test.tsnew file mode 100644index 00000000000..b606f34ca13--- /dev/null+++ b/packages/database/src/models/__tests__/task.closedAfter.test.ts@@ -0,0 +1,96 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { tasks, users } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { TaskModel } from '../task';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'task-closed-after-test-user-id';+const DAY_MS = 24 * 60 * 60 * 1000;++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }]);+});++afterEach(async () => {+ await serverDB.delete(users);+});++const daysAgo = (days: number) => new Date(Date.now() - days * DAY_MS);++/**+ * An old backlog task, a completed task from each side of a one-week window,+ * and canceled tasks with no `completedAt` dated only by `updatedAt`.+ */+const seed = async (model: TaskModel) => {+ const backlog = await model.create({ instruction: 'Old backlog task' });+ const recentDone = await model.create({ instruction: 'Completed yesterday' });+ const staleDone = await model.create({ instruction: 'Completed last month' });+ const recentCanceled = await model.create({ instruction: 'Canceled yesterday' });+ const staleCanceled = await model.create({ instruction: 'Canceled last month' });++ await serverDB+ .update(tasks)+ .set({ updatedAt: daysAgo(60) })+ .where(eq(tasks.id, backlog.id));+ await serverDB+ .update(tasks)+ .set({ completedAt: daysAgo(1), status: 'completed', updatedAt: daysAgo(1) })+ .where(eq(tasks.id, recentDone.id));+ // updatedAt is recent (e.g. a later edit), but completedAt decides.+ await serverDB+ .update(tasks)+ .set({ completedAt: daysAgo(30), status: 'completed', updatedAt: daysAgo(1) })+ .where(eq(tasks.id, staleDone.id));+ await serverDB+ .update(tasks)+ .set({ completedAt: null, status: 'canceled', updatedAt: daysAgo(1) })+ .where(eq(tasks.id, recentCanceled.id));+ await serverDB+ .update(tasks)+ .set({ completedAt: null, status: 'canceled', updatedAt: daysAgo(30) })+ .where(eq(tasks.id, staleCanceled.id));++ return { backlog, recentCanceled, recentDone, staleCanceled, staleDone };+};++describe('TaskModel closedAfter', () => {+ it('list keeps unfinished tasks and only the tasks closed after the cut', async () => {+ const model = new TaskModel(serverDB, userId);+ const seeded = await seed(model);++ const all = await model.list();+ expect(all.total).toBe(5);++ const windowed = await model.list({ closedAfter: daysAgo(7) });+ expect(windowed.tasks.map((task) => task.id).sort()).toEqual(+ [seeded.backlog.id, seeded.recentCanceled.id, seeded.recentDone.id].sort(),+ );+ // The cut happens before pagination, so `total` counts the same set.+ expect(windowed.total).toBe(3);+ });++ it('groupList narrows the closed columns by the same cut', async () => {+ const model = new TaskModel(serverDB, userId);+ const seeded = await seed(model);+ const groups = [+ { key: 'backlog', statuses: ['backlog'] },+ { key: 'done', statuses: ['completed'] },+ { key: 'canceled', statuses: ['canceled'] },+ ];++ const result = await model.groupList({ closedAfter: daysAgo(7), groups });+ const byKey = new Map(result.map((group) => [group.key, group]));++ expect(byKey.get('backlog')?.tasks.map((task) => task.id)).toEqual([seeded.backlog.id]);+ expect(byKey.get('done')?.tasks.map((task) => task.id)).toEqual([seeded.recentDone.id]);+ expect(byKey.get('done')?.total).toBe(1);+ expect(byKey.get('canceled')?.tasks.map((task) => task.id)).toEqual([seeded.recentCanceled.id]);+ expect(byKey.get('canceled')?.total).toBe(1);+ });+});diff --git a/packages/database/src/models/taskListFilters.ts b/packages/database/src/models/taskListFilters.tsindex ecfca77a0c0..355b31cfdc5 100644--- a/packages/database/src/models/taskListFilters.ts+++ b/packages/database/src/models/taskListFilters.ts@@ -36,11 +36,20 @@ export const RUNNABLE_AUTOMATION = and(*/const LIVE_AUTOMATION = and(RUNNABLE_AUTOMATION, isNull(tasks.archivedAt))!;+/** The statuses `closedAfter` narrows, matching the list's `HIDDEN_WHEN_COMPLETED_STATUSES`. */+const CLOSED_TASK_STATUSES = ['canceled', 'completed'];+export interface TaskListFilterOptions {assigneeAgentId?: string;/** Only tasks assigned to this workspace member. */assigneeUserId?: string;automated?: boolean;+ /**+ * Leave out completed and canceled tasks closed before this time. A closed+ * task without `completedAt` (canceled ones) falls back to `updatedAt`;+ * unfinished tasks are never narrowed.+ */+ closedAfter?: Date;/** Only tasks created by this user. */createdByUserId?: string;/** Archived tasks are user-closed and hidden from every list unless asked for. */@@ -70,6 +79,7 @@ export const buildTaskListFilters = ({assigneeAgentId,assigneeUserId,automated,+ closedAfter,createdByUserId,includeArchived,parentTaskId,@@ -86,6 +96,14 @@ export const buildTaskListFilters = ({// runnable expression NULL for manual tasks, and WHERE would drop them.if (automated === false) conditions.push(sql`${LIVE_AUTOMATION} IS NOT TRUE`);if (!includeArchived) conditions.push(isNull(tasks.archivedAt));+ if (closedAfter) {+ conditions.push(+ or(+ notInArray(tasks.status, CLOSED_TASK_STATUSES),+ sql`coalesce(${tasks.completedAt}, ${tasks.updatedAt}) >= ${closedAfter.toISOString()}`,+ )!,+ );+ }if (projectId) conditions.push(eq(tasks.projectId, projectId));if (visibility) conditions.push(eq(tasks.visibility, visibility));diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 72084d8ceb8..f88f48525a9 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -3006,6 +3006,11 @@ export default {'goalTurn.trigger.takeover': 'Takeover','taskList.activeTasks': 'Active Tasks','taskList.all': 'All tasks',+ 'taskList.completedTasks.all': 'All',+ 'taskList.completedTasks.day': 'Past day',+ 'taskList.completedTasks.month': 'Past month',+ 'taskList.completedTasks.none': 'None',+ 'taskList.completedTasks.week': 'Past week','taskList.archived': 'Archived','taskList.visibility.all': 'All','taskList.visibility.label': 'Visibility',@@ -3014,12 +3019,12 @@ export default {'taskList.emptyHero.greeting': 'What should we tackle today?','taskList.emptyHero.templatesTitle': 'Templates picked for you','taskList.form.columns': 'Columns',+ 'taskList.form.completedTasks': 'Completed & canceled','taskList.form.grouping': 'Grouping','taskList.form.nestedSubTasks': 'Nested sub-tasks','taskList.form.orderCompletedByRecency': 'Sort completed tasks by recency','taskList.form.ordering': 'Ordering','taskList.form.showArchived': 'Show archived',- 'taskList.form.showCompleted': 'Show completed & canceled','taskList.form.showSubTasks': 'Show sub-tasks','taskList.form.subGrouping': 'Sub-grouping','taskList.hiddenCompleted.count_one': '{{count}} task',diff --git a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.test.ts b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.test.tsindex 6d9affd1f7f..eb2dc2b2fef 100644--- a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.test.ts+++ b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.test.ts@@ -18,6 +18,7 @@ import {collapseSubTasks,compareTaskItems,DEFAULT_TASK_LIST_VIEW_OPTIONS,+ isTaskHiddenByCompletedFilter,} from './listViewOptions';import { shouldRenderTaskAgentPanelToggle } from './taskAgentPanelToggle';@@ -80,7 +81,7 @@ describe('AgentTasksPage', () => {).toEqual({...DEFAULT_TASK_LIST_VIEW_OPTIONS,groupBy: 'automationMode',- hideCompleted: false,+ completedTasks: 'all',orderBy: 'updatedAt',orderDirection: 'asc',showSubTasks: true,@@ -101,7 +102,7 @@ describe('AgentTasksPage', () => {getMyTaskViewOptions({...DEFAULT_TASK_LIST_VIEW_OPTIONS,groupBy: 'priority',- hideCompleted: false,+ completedTasks: 'week',orderBy: 'title',orderDirection: 'asc',showSubTasks: false,@@ -109,7 +110,7 @@ describe('AgentTasksPage', () => {).toEqual({...DEFAULT_TASK_LIST_VIEW_OPTIONS,groupBy: 'priority',- hideCompleted: false,+ completedTasks: 'all',orderBy: 'updatedAt',orderDirection: 'asc',showSubTasks: true,@@ -129,6 +130,22 @@ describe('AgentTasksPage', () => {expect(collapseSubTasks([parent, child]).map((t) => t.id)).toEqual(['p']);});+ it('never re-applies the completed window to a page the server already cut', () => {+ // The server counted this row inside the window; a browser clock that is+ // ahead (or a cutoff crossed since the fetch) must not drop it again.+ const options = getMyTaskViewOptions({+ ...DEFAULT_TASK_LIST_VIEW_OPTIONS,+ completedTasks: 'day',+ });+ const justOutside = {+ ...taskUpdatedAt('done', '2026-01-01'),+ completedAt: new Date('2026-01-01T00:00:00Z'),+ status: 'completed',+ } as TaskListItem;+ const now = new Date('2026-01-02T00:00:01Z').getTime();+ expect(isTaskHiddenByCompletedFilter(justOutside, options.completedTasks, now)).toBe(false);+ });+it('renders a page newest-first, like the server paginates it', () => {const options = getMyTaskViewOptions(DEFAULT_TASK_LIST_VIEW_OPTIONS);const newer = taskUpdatedAt('a', '2026-02-01');@@ -170,9 +187,12 @@ describe('AgentTasksPage', () => {expect(pinned.orderBy).toBe('updatedAt');expect(pinned.orderDirection).toBe('asc');expect(pinned.showSubTasks).toBe(true);+ // `completedTasks` stays offered: it takes effect server-side+ // (`getVisibleTaskStatuses` / `getCompletedWithin`), so only the+ // rendered page is told not to cut again.+ expect(pinned.completedTasks).toBe('all');// Not pinned: the panel keeps offering these, and they still take effect.expect(pinned.groupBy).toBe(DEFAULT_TASK_LIST_VIEW_OPTIONS.groupBy);- expect(pinned.hideCompleted).toBe(DEFAULT_TASK_LIST_VIEW_OPTIONS.hideCompleted);expect(pinned.nestedSubTasks).toBe(DEFAULT_TASK_LIST_VIEW_OPTIONS.nestedSubTasks);});});diff --git a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsxindex c215ec4bbf2..7310421ff80 100644--- a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx+++ b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx@@ -36,7 +36,12 @@ import CreateTaskInlineEntry from './CreateTaskInlineEntry';import EmptyState from './EmptyState';import KanbanBoard from './KanbanBoard';import type { TaskListViewOptions } from './listViewOptions';-import { getVisibleTaskStatuses, normalizeTaskListViewOptions } from './listViewOptions';+import {+ getCompletedWithin,+ getVisibleTaskStatuses,+ normalizeTaskListViewOptions,+ toStoredTaskListViewOptions,+} from './listViewOptions';import { shouldRenderTaskAgentPanelToggle } from './taskAgentPanelToggle';import TaskList from './TaskList';import TaskListVisibilityFilter from './TaskListVisibilityFilter';@@ -149,10 +154,13 @@ export const clampCollectionPage = (page: number, total: number): number =>* - every fetched row renders. With `showSubTasks: false` `TaskList` folds a* child away whenever its parent shares the page, which would leave the page* sparse while `total` still counts the hidden rows. Nesting (when enabled)- * still tucks a child under a parent that is on the same page.+ * still tucks a child under a parent that is on the same page. Likewise the+ * `completedTasks` cut is applied server-side before pagination; repeating it+ * on the page with the browser clock could drop rows `total` still counts.* Grouping stays client-side — it only arranges the rows of the current page.*/const PAGINATED_COLLECTION_VIEW = {+ completedTasks: 'all',orderBy: 'updatedAt',orderDirection: 'asc',showSubTasks: true,@@ -164,12 +172,12 @@ export const getScheduledTaskViewOptions = (...viewOptions,...PAGINATED_COLLECTION_VIEW,groupBy: 'automationMode',- hideCompleted: false,});/**- * "My tasks" additionally sends `hideCompleted` as a server status filter- * (`getVisibleTaskStatuses`) rather than applying it to the fetched page.+ * "My tasks" additionally sends `completedTasks` as a server filter+ * (`getVisibleTaskStatuses` / `getCompletedWithin`) rather than applying it to+ * the fetched page.*/export const getMyTaskViewOptions = (viewOptions: TaskListViewOptions): TaskListViewOptions => ({...viewOptions,@@ -279,6 +287,7 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, projectId }) => {});const useFetchMyTaskList = useTaskStore((s) => s.useFetchMyTaskList);const mineSWR = useFetchMyTaskList({+ completedWithin: getCompletedWithin(viewOptions),enabled: isMineCollection && !isMineBoard,limit: COLLECTION_PAGE_SIZE,offset: (collectionPage - 1) * COLLECTION_PAGE_SIZE,@@ -321,7 +330,10 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, projectId }) => {groupBy: normalized.groupBy === 'automationMode' ? 'status' : normalized.groupBy,subGroupBy: normalized.subGroupBy === 'automationMode' ? 'none' : normalized.subGroupBy,};- updateSystemStatus({ taskListViewOptions: next }, 'updateTaskListViewOptions');+ updateSystemStatus(+ { taskListViewOptions: toStoredTaskListViewOptions(next) },+ 'updateTaskListViewOptions',+ );},[updateSystemStatus, viewOptions],);@@ -369,7 +381,7 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, projectId }) => {}, [agentId, canCreateTask, navigate, projectId]);const handleShowHiddenCompleted = useCallback(() => {- setViewOptions((prev) => ({ ...prev, hideCompleted: false }));+ setViewOptions((prev) => ({ ...prev, completedTasks: 'all' }));}, [setViewOptions]);const handleCollectionChange = useCallback(diff --git a/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx b/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsxindex 07f2e2ff7aa..68d6624d9ff 100644--- a/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx+++ b/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx@@ -42,7 +42,7 @@ import {} from './kanbanBoardModel';import KanbanColumn, { COLUMN_I18N_KEYS, COLUMN_STATUS_ICON, COLUMN_WIDTH } from './KanbanColumn';import type { TaskListViewOptions } from './listViewOptions';-import { HIDDEN_WHEN_COMPLETED_STATUSES } from './listViewOptions';+import { getCompletedWithin, HIDDEN_WHEN_COMPLETED_STATUSES } from './listViewOptions';const styles = createStaticStyles(({ css }) => ({board: css`@@ -77,13 +77,15 @@ const KanbanBoard = memo<KanbanBoardProps>((props) => {const { t } = useTranslation('chat');const { allowed: canEditTask } = usePermission('create_content');const groupBy = normalizeKanbanGroupBy(options.groupBy);- const excludeStatuses = options.hideCompleted ? HIDDEN_WHEN_COMPLETED_STATUSES : undefined;+ const excludeStatuses =+ options.completedTasks === 'none' ? HIDDEN_WHEN_COMPLETED_STATUSES : undefined;const useFetchTaskGroupList = useTaskStore((s) => s.useFetchTaskGroupList);// Keep the sync handle for `error` + `mutate` (the error/Retry state) and the// `queryKey` the groups are read by.const { error, isLoading, mutate, queryKey } = useFetchTaskGroupList({...buildKanbanGroupQuery({ agentId, excludeStatuses, groupBy, myTaskScope, projectId }),+ completedWithin: getCompletedWithin(options),includeArchived: options.showArchived,});// Each board query (scope, dimension, filters) is its own store entry, so thediff --git a/src/features/AgentTasks/AgentTaskList/TaskList.tsx b/src/features/AgentTasks/AgentTaskList/TaskList.tsxindex 11082ce9a6c..8a47b840de8 100644--- a/src/features/AgentTasks/AgentTaskList/TaskList.tsx+++ b/src/features/AgentTasks/AgentTaskList/TaskList.tsx@@ -32,7 +32,7 @@ import {collapseSubTasks,compareTaskItems,groupTaskItems,- HIDDEN_WHEN_COMPLETED_STATUSES,+ isTaskHiddenByCompletedFilter,} from './listViewOptions';import TaskGroupLabel from './TaskGroupLabel';import TaskItemSkeleton from './TaskItemSkeleton';@@ -65,8 +65,6 @@ interface TaskListProps {routeScope?: TaskItemRouteScope;}-const HIDDEN_COMPLETED_STATUS_SET = new Set<string>(HIDDEN_WHEN_COMPLETED_STATUSES);-/** Row height the window sizes itself by before it has measured real rows. */const DEFAULT_ROW_HEIGHT = 52;@@ -162,13 +160,13 @@ const TaskList = memo<TaskListProps>((props) => {const effectiveSubGroupBy = groupBy === 'none' ? 'none' : subGroupBy;const unfinishedTasks = useMemo(() =>- options.hideCompleted- ? tasks.filter((task) => !HIDDEN_COMPLETED_STATUS_SET.has(task.status))- : tasks,- [tasks, options.hideCompleted],+ options.completedTasks === 'all'+ ? tasks+ : tasks.filter((task) => !isTaskHiddenByCompletedFilter(task, options.completedTasks)),+ [tasks, options.completedTasks],);// Only the completed/canceled cut feeds the "hidden by display options"- // footer — its "Show" action clears `hideCompleted`, so folding the sub-task+ // footer — its "Show" action resets `completedTasks` to 'all', so folding the sub-task// count in would promise a reveal that toggle doesn't deliver.const hiddenCount = tasks.length - unfinishedTasks.length;const visibleTasks = useMemo(diff --git a/src/features/AgentTasks/AgentTaskList/TasksGroupConfig.tsx b/src/features/AgentTasks/AgentTaskList/TasksGroupConfig.tsxindex e71f053bb03..1306b07b26e 100644--- a/src/features/AgentTasks/AgentTaskList/TasksGroupConfig.tsx+++ b/src/features/AgentTasks/AgentTaskList/TasksGroupConfig.tsx@@ -24,7 +24,13 @@ import { useGlobalStore } from '@/store/global';import type { TaskViewMode } from '@/store/global/initialState';import { systemStatusSelectors } from '@/store/global/selectors';-import type { TaskGroupBy, TaskListViewOptions, TaskOrderBy } from './listViewOptions';+import type {+ TaskCompletedFilter,+ TaskGroupBy,+ TaskListViewOptions,+ TaskOrderBy,+} from './listViewOptions';+import { TASK_COMPLETED_FILTERS } from './listViewOptions';/** A display control the active collection fixes, so it has nothing to change. */export type TaskListPinnedOption = 'ordering' | 'showSubTasks';@@ -113,18 +119,24 @@ const TasksGroupConfig = memo<TasksHeaderProps>(({ options, pinnedOptions, setOplabel: viewMode === 'kanban' ? t('taskList.form.columns') : t('taskList.form.grouping'),} satisfies FormFieldProps;- const showCompletedFormItem = {+ const completedTasksOptions = TASK_COMPLETED_FILTERS.map((value) => ({+ label: t(`taskList.completedTasks.${value}`),+ value,+ }));++ const completedTasksFormItem = {children: (- <Switch- checked={!options.hideCompleted}+ <Select+ options={completedTasksOptions}size={'small'}- onChange={(checked) => {- setOptions((prev) => ({ ...prev, hideCompleted: !checked }));+ style={{ width: 120 }}+ value={options.completedTasks}+ onChange={(value: TaskCompletedFilter) => {+ setOptions((prev) => ({ ...prev, completedTasks: value }));}}/>),- minWidth: undefined,- label: t('taskList.form.showCompleted'),+ label: t('taskList.form.completedTasks'),} satisfies FormFieldProps;const showArchivedFormItem = {@@ -204,7 +216,7 @@ const TasksGroupConfig = memo<TasksHeaderProps>(({ options, pinnedOptions, setOpminWidth: undefined,label: t('taskList.form.orderCompletedByRecency'),},- showCompletedFormItem,+ completedTasksFormItem,showArchivedFormItem,...(isPinned('showSubTasks')? []@@ -243,7 +255,7 @@ const TasksGroupConfig = memo<TasksHeaderProps>(({ options, pinnedOptions, setOp]: []),];- const boardFormItems = [groupingFormItem, showCompletedFormItem, showArchivedFormItem];+ const boardFormItems = [groupingFormItem, completedTasksFormItem, showArchivedFormItem];const panelContent = (<Flexbox gap={12} width={280}>diff --git a/src/features/AgentTasks/AgentTaskList/listViewOptions.test.ts b/src/features/AgentTasks/AgentTaskList/listViewOptions.test.tsindex 3b2eee4e2a6..6ef7839a37b 100644--- a/src/features/AgentTasks/AgentTaskList/listViewOptions.test.ts+++ b/src/features/AgentTasks/AgentTaskList/listViewOptions.test.ts@@ -7,10 +7,13 @@ import {collapseSubTasks,compareTaskItems,DEFAULT_TASK_LIST_VIEW_OPTIONS,+ getCompletedWithin,getVisibleTaskStatuses,groupTaskItems,HIDDEN_WHEN_COMPLETED_STATUSES,+ isTaskHiddenByCompletedFilter,normalizeTaskListViewOptions,+ toStoredTaskListViewOptions,} from './listViewOptions';const task = (id: string, overrides: Partial<TaskListItem> = {}): TaskListItem =>@@ -238,9 +241,92 @@ describe('buildTaskRows', () => {});});+describe('completedTasks', () => {+ it('defaults to hiding completed and canceled tasks', () => {+ expect(normalizeTaskListViewOptions().completedTasks).toBe('none');+ });++ it('migrates the persisted hideCompleted switch it replaces', () => {+ expect(normalizeTaskListViewOptions({ hideCompleted: true }).completedTasks).toBe('none');+ expect(normalizeTaskListViewOptions({ hideCompleted: false }).completedTasks).toBe('all');+ });++ it('prefers a stored completedTasks over a leftover hideCompleted', () => {+ expect(+ normalizeTaskListViewOptions({ completedTasks: 'week', hideCompleted: true }).completedTasks,+ ).toBe('week');+ });++ it('falls back to the default for an unknown value', () => {+ expect(normalizeTaskListViewOptions({ completedTasks: 'year' as never }).completedTasks).toBe(+ 'none',+ );+ });+});++describe('toStoredTaskListViewOptions', () => {+ it('keeps the legacy hideCompleted in step for builds that only read it', () => {+ const stored = (completedTasks: TaskListViewOptions['completedTasks']) =>+ toStoredTaskListViewOptions({ ...DEFAULT_TASK_LIST_VIEW_OPTIONS, completedTasks });++ expect(stored('none').hideCompleted).toBe(true);+ expect(stored('all').hideCompleted).toBe(false);+ expect(stored('week').hideCompleted).toBe(false);+ });++ it('round-trips through normalization to the same choice', () => {+ const options = { ...DEFAULT_TASK_LIST_VIEW_OPTIONS, completedTasks: 'month' as const };+ expect(normalizeTaskListViewOptions(toStoredTaskListViewOptions(options))).toEqual(options);+ });+});++describe('isTaskHiddenByCompletedFilter', () => {+ const now = new Date('2026-03-10T12:00:00Z').getTime();+ const closedDaysAgo = (status: TaskListItem['status'], days: number, field = 'completedAt') =>+ task(`${status}-${days}`, {+ status,+ updatedAt: new Date('2026-01-01'),+ [field]: new Date(now - days * 24 * 60 * 60 * 1000),+ } as Partial<TaskListItem>);++ it('never hides an unfinished task, however old', () => {+ const old = task('old', { status: 'backlog', updatedAt: new Date('2020-01-01') });+ expect(isTaskHiddenByCompletedFilter(old, 'none', now)).toBe(false);+ expect(isTaskHiddenByCompletedFilter(old, 'day', now)).toBe(false);+ });++ it('keeps completed tasks closed within the window and hides older ones', () => {+ expect(isTaskHiddenByCompletedFilter(closedDaysAgo('completed', 3), 'week', now)).toBe(false);+ expect(isTaskHiddenByCompletedFilter(closedDaysAgo('completed', 8), 'week', now)).toBe(true);+ expect(isTaskHiddenByCompletedFilter(closedDaysAgo('completed', 2), 'day', now)).toBe(true);+ expect(isTaskHiddenByCompletedFilter(closedDaysAgo('completed', 20), 'month', now)).toBe(false);+ });++ it('dates a canceled task without completedAt by updatedAt', () => {+ const recent = closedDaysAgo('canceled', 1, 'updatedAt');+ expect(isTaskHiddenByCompletedFilter(recent, 'week', now)).toBe(false);+ const stale = closedDaysAgo('canceled', 10, 'updatedAt');+ expect(isTaskHiddenByCompletedFilter(stale, 'week', now)).toBe(true);+ });++ it('shows every closed task for all and none of them for none', () => {+ const ancient = closedDaysAgo('completed', 400);+ expect(isTaskHiddenByCompletedFilter(ancient, 'all', now)).toBe(false);+ expect(isTaskHiddenByCompletedFilter(closedDaysAgo('completed', 0), 'none', now)).toBe(true);+ });+});++describe('getCompletedWithin', () => {+ it('sends only a windowed choice to the server', () => {+ expect(getCompletedWithin({ completedTasks: 'week' })).toBe('week');+ expect(getCompletedWithin({ completedTasks: 'all' })).toBeUndefined();+ expect(getCompletedWithin({ completedTasks: 'none' })).toBeUndefined();+ });+});+describe('getVisibleTaskStatuses', () => {- it('translates hideCompleted into the server status filter, before pagination', () => {- const statuses = getVisibleTaskStatuses({ hideCompleted: true });+ it('translates completedTasks none into the server status filter, before pagination', () => {+ const statuses = getVisibleTaskStatuses({ completedTasks: 'none' });expect(statuses).toBeDefined();for (const hidden of HIDDEN_WHEN_COMPLETED_STATUSES) expect(statuses).not.toContain(hidden);expect(statuses).toContain('backlog');@@ -248,6 +334,7 @@ describe('getVisibleTaskStatuses', () => {});it('applies no narrowing when completed tasks are shown', () => {- expect(getVisibleTaskStatuses({ hideCompleted: false })).toBeUndefined();+ expect(getVisibleTaskStatuses({ completedTasks: 'all' })).toBeUndefined();+ expect(getVisibleTaskStatuses({ completedTasks: 'week' })).toBeUndefined();});});diff --git a/src/features/AgentTasks/AgentTaskList/listViewOptions.ts b/src/features/AgentTasks/AgentTaskList/listViewOptions.tsindex 5afa1e47152..e7845563e2d 100644--- a/src/features/AgentTasks/AgentTaskList/listViewOptions.ts+++ b/src/features/AgentTasks/AgentTaskList/listViewOptions.ts@@ -1,4 +1,9 @@-import { TASK_STATUSES } from '@lobechat/builtin-tool-task';+import {+ TASK_COMPLETED_WINDOW_MS,+ TASK_COMPLETED_WINDOWS,+ TASK_STATUSES,+ type TaskCompletedWindow,+} from '@lobechat/builtin-tool-task';import type { TaskStatus } from '@lobechat/types';import { t } from 'i18next';@@ -7,10 +12,21 @@ import type { TaskListItem } from '@/store/task/slices/list/initialState';export type TaskGroupBy = 'assignee' | 'automationMode' | 'member' | 'none' | 'priority' | 'status';export type TaskOrderBy = 'assignee' | 'createdAt' | 'priority' | 'status' | 'title' | 'updatedAt';export type TaskOrderDirection = 'asc' | 'desc';+/**+ * Which completed and canceled tasks a list keeps: all of them, none, or only+ * those closed within a look-back window.+ */+export type TaskCompletedFilter = 'all' | 'none' | TaskCompletedWindow;++export const TASK_COMPLETED_FILTERS: readonly TaskCompletedFilter[] = [+ 'all',+ ...TASK_COMPLETED_WINDOWS,+ 'none',+];export interface TaskListViewOptions {+ completedTasks: TaskCompletedFilter;groupBy: TaskGroupBy;- hideCompleted: boolean;/** Indent a shown sub-task under its parent instead of listing it as a peer. */nestedSubTasks: boolean;orderBy: TaskOrderBy;@@ -29,20 +45,44 @@ export const HIDDEN_WHEN_COMPLETED_STATUSES: ReadonlyArray<NonNullable<TaskGroup];/**- * Server-side counterpart of `hideCompleted`: the statuses a paginated list- * has to request so the cut happens before `limit` / `offset` instead of on- * the fetched page (which could otherwise come back empty while older- * unfinished tasks exist). `undefined` means no status narrowing.+ * Server-side counterpart of `completedTasks: 'none'`: the statuses a+ * paginated list has to request so the cut happens before `limit` / `offset`+ * instead of on the fetched page (which could otherwise come back empty while+ * older unfinished tasks exist). `undefined` means no status narrowing.*/export const getVisibleTaskStatuses = (- options: Pick<TaskListViewOptions, 'hideCompleted'>,+ options: Pick<TaskListViewOptions, 'completedTasks'>,): TaskStatus[] | undefined =>- options.hideCompleted+ options.completedTasks === 'none'? TASK_STATUSES.filter((status) => !HIDDEN_COMPLETED_STATUS_SET.has(status)): undefined;+/** Server-side counterpart of a windowed `completedTasks`, sent as `completedWithin`. */+export const getCompletedWithin = (+ options: Pick<TaskListViewOptions, 'completedTasks'>,+): TaskCompletedWindow | undefined =>+ options.completedTasks === 'all' || options.completedTasks === 'none'+ ? undefined+ : options.completedTasks;+const HIDDEN_COMPLETED_STATUS_SET = new Set<string>(HIDDEN_WHEN_COMPLETED_STATUSES);+/**+ * Client-side `completedTasks` cut for a list fetched in full. Mirrors the+ * server's `closedAfter`: a closed task without `completedAt` (a canceled one)+ * is dated by `updatedAt`.+ */+export const isTaskHiddenByCompletedFilter = (+ task: Pick<TaskListItem, 'completedAt' | 'status' | 'updatedAt'>,+ completedTasks: TaskCompletedFilter,+ now = Date.now(),+): boolean => {+ if (completedTasks === 'all' || !HIDDEN_COMPLETED_STATUS_SET.has(task.status)) return false;+ if (completedTasks === 'none') return true;+ const closedAt = toTime(task.completedAt) || toTime(task.updatedAt);+ return closedAt < now - TASK_COMPLETED_WINDOW_MS[completedTasks];+};+export interface TaskGroupMeta {assigneeId?: string;assigneeUserId?: string;@@ -55,8 +95,8 @@ export interface TaskGroupMeta {}export const DEFAULT_TASK_LIST_VIEW_OPTIONS: TaskListViewOptions = {+ completedTasks: 'none',groupBy: 'status',- hideCompleted: true,// Nesting is the default *shape* for sub-tasks, but sub-tasks stay hidden// until asked for: a parent already carries its progress (`3/8`), so listing// its children as peers only pads the list with rows the parent stands for.@@ -86,9 +126,37 @@ const TASK_ORDER_BY_SET = new Set<TaskOrderBy>(['updatedAt',]);const TASK_ORDER_DIRECTION_SET = new Set<TaskOrderDirection>(['asc', 'desc']);+const TASK_COMPLETED_FILTER_SET = new Set<TaskCompletedFilter>(TASK_COMPLETED_FILTERS);++/** View options as persisted, possibly by a release that only had `hideCompleted`. */+export type StoredTaskListViewOptions = Partial<TaskListViewOptions> & {+ /** Replaced by `completedTasks`: `true` → 'none', `false` → 'all'. */+ hideCompleted?: boolean;+};++const normalizeCompletedTasks = (next: StoredTaskListViewOptions): TaskCompletedFilter => {+ if (TASK_COMPLETED_FILTER_SET.has(next.completedTasks as TaskCompletedFilter)) {+ return next.completedTasks as TaskCompletedFilter;+ }+ if (typeof next.hideCompleted === 'boolean') return next.hideCompleted ? 'none' : 'all';+ return DEFAULT_TASK_LIST_VIEW_OPTIONS.completedTasks;+};++/**+ * The shape to persist. Keeps writing the legacy `hideCompleted` beside+ * `completedTasks` so a build that predates the select (e.g. after a+ * rollback) still follows the latest choice; a windowed choice reads as+ * "shown" there, the closest it can express.+ */+export const toStoredTaskListViewOptions = <T extends Pick<TaskListViewOptions, 'completedTasks'>>(+ options: T,+): T & { hideCompleted: boolean } => ({+ ...options,+ hideCompleted: options.completedTasks === 'none',+});export const normalizeTaskListViewOptions = (- value?: Partial<TaskListViewOptions> | null,+ value?: StoredTaskListViewOptions | null,): TaskListViewOptions => {const next = value ?? {};const groupBy = TASK_GROUP_BY_SET.has(next.groupBy as TaskGroupBy)@@ -99,11 +167,8 @@ export const normalizeTaskListViewOptions = (: DEFAULT_TASK_LIST_VIEW_OPTIONS.subGroupBy;return {+ completedTasks: normalizeCompletedTasks(next),groupBy,- hideCompleted:- typeof next.hideCompleted === 'boolean'- ? next.hideCompleted- : DEFAULT_TASK_LIST_VIEW_OPTIONS.hideCompleted,nestedSubTasks:typeof next.nestedSubTasks === 'boolean'? next.nestedSubTasksdiff --git a/src/services/task.ts b/src/services/task.tsindex e444c4cae29..d80a6e9e0bb 100644--- a/src/services/task.ts+++ b/src/services/task.ts@@ -1,3 +1,4 @@+import type { TaskCompletedWindow } from '@lobechat/builtin-tool-task';import type {CheckpointConfig,TaskAutomationMode,@@ -26,6 +27,8 @@ class TaskService {after?: { at: Date | string; seq: number };assigneeAgentId?: string;automated?: boolean;+ /** Keep completed / canceled tasks only when closed within this window. */+ completedWithin?: TaskCompletedWindow;/** Archived tasks are left out unless this is set. */includeArchived?: boolean;orderBy?: 'createdAt' | 'updatedAt';@@ -44,6 +47,7 @@ class TaskService {groupList = async (params: {assigneeAgentId?: string;automated?: boolean;+ completedWithin?: TaskCompletedWindow;excludeStatuses?: TaskStatus[];groupBy?: 'assignee' | 'member' | 'priority';groups?: Array<{diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.tsindex cde159f1383..fc1e6d2f52b 100644--- a/src/store/global/initialState.ts+++ b/src/store/global/initialState.ts@@ -448,8 +448,15 @@ export interface SystemStatus {*/taskListViewMode?: TaskViewMode;taskListViewOptions?: {+ /**+ * Left out of the defaults on purpose: status is deep-merged over the+ * persisted value, so a default here would override the legacy+ * `hideCompleted` it replaces before normalization could migrate it.+ */+ completedTasks?: 'all' | 'day' | 'month' | 'none' | 'week';groupBy: 'assignee' | 'member' | 'none' | 'priority' | 'status';- hideCompleted: boolean;+ /** @deprecated Replaced by `completedTasks`; read once to migrate. */+ hideCompleted?: boolean;nestedSubTasks: boolean;orderBy: 'assignee' | 'createdAt' | 'priority' | 'status' | 'title' | 'updatedAt';orderCompletedByRecency: boolean;@@ -579,7 +586,6 @@ export const INITIAL_STATUS = {recentPageSize: 5,taskListViewOptions: {groupBy: 'status',- hideCompleted: true,nestedSubTasks: true,orderBy: 'updatedAt',orderCompletedByRecency: true,diff --git a/src/store/global/selectors/systemStatus.ts b/src/store/global/selectors/systemStatus.tsindex 51e40873427..92d89b148b4 100644--- a/src/store/global/selectors/systemStatus.ts+++ b/src/store/global/selectors/systemStatus.ts@@ -136,7 +136,6 @@ const pagePageSize = (s: GlobalState): number => s.status.pagePageSize || 20;const taskListViewOptions = (s: GlobalState) =>s.status.taskListViewOptions || {groupBy: 'status',- hideCompleted: true,nestedSubTasks: true,orderBy: 'updatedAt',orderCompletedByRecency: true,diff --git a/src/store/task/slices/list/action.ts b/src/store/task/slices/list/action.tsindex fe0874a9acd..1a037745d6b 100644--- a/src/store/task/slices/list/action.ts+++ b/src/store/task/slices/list/action.ts@@ -1,3 +1,4 @@+import type { TaskCompletedWindow } from '@lobechat/builtin-tool-task';import type { TaskStatus } from '@lobechat/types';import { useMemo } from 'react';@@ -156,6 +157,7 @@ export class TaskListSliceActionImpl {const params = {...(query.agentId ? { assigneeAgentId: query.agentId } : {}),automated: query.automated,+ ...(query.completedWithin && { completedWithin: query.completedWithin }),includeArchived: query.includeArchived,orderBy: query.orderBy,projectId: query.projectId,@@ -172,6 +174,7 @@ export class TaskListSliceActionImpl {taskService.groupList({assigneeAgentId: query.agentId,...(query.automated === undefined ? {} : { automated: query.automated }),+ ...(query.completedWithin && { completedWithin: query.completedWithin }),excludeStatuses: query.excludeStatuses,...(query.groupBy === 'status'? { groups: DEFAULT_KANBAN_GROUPS }@@ -321,6 +324,8 @@ export class TaskListSliceActionImpl {agentId?: string;allAgents?: boolean;automated?: boolean;+ /** Keep completed / canceled cards only when closed within this window. */+ completedWithin?: TaskCompletedWindow;enabled?: boolean;excludeStatuses?: readonly TaskStatus[];groupBy?: TaskKanbanGroupBy;@@ -339,6 +344,7 @@ export class TaskListSliceActionImpl {agentId,allAgents = false,automated,+ completedWithin,enabled = true,excludeStatuses,groupBy = 'status',@@ -354,6 +360,7 @@ export class TaskListSliceActionImpl {? {agentId: allAgents || scope ? undefined : agentId,automated,+ completedWithin,excludeStatuses: excludeStatuses?.length ? [...excludeStatuses].sort() : undefined,groupBy,includeArchived: includeArchived || undefined,@@ -406,22 +413,36 @@ export class TaskListSliceActionImpl {* collection into the other.*/useFetchMyTaskList = (options: {+ /**+ * Server-side look-back for completed / canceled tasks (the "Completed+ * tasks" display option), cut before `limit` / `offset` like `statuses`.+ */+ completedWithin?: TaskCompletedWindow;enabled?: boolean;includeArchived?: boolean;limit?: number;offset?: number;scope: 'assigned' | 'created';/**- * Server-side status narrowing (the `hideCompleted` display option+ * Server-side status narrowing (the "Completed tasks: None" display option* translated by `getVisibleTaskStatuses`). Applied before `limit` /* `offset` so a page can never come back empty while older unfinished* tasks exist; part of the query for the same reason as `scope`.*/statuses?: TaskStatus[];}): TaskCollectionPageResult => {- const { enabled = true, includeArchived, limit, offset, scope, statuses } = options;+ const {+ completedWithin,+ enabled = true,+ includeArchived,+ limit,+ offset,+ scope,+ statuses,+ } = options;return this.#useCollectionPage({+ completedWithin,// Archived rows are a different server page, like the status filter.includeArchived: includeArchived || undefined,limit,diff --git a/src/store/task/slices/list/projection.ts b/src/store/task/slices/list/projection.tsindex dfb35bdffe5..f6749de1eb2 100644--- a/src/store/task/slices/list/projection.ts+++ b/src/store/task/slices/list/projection.ts@@ -1,3 +1,4 @@+import type { TaskCompletedWindow } from '@lobechat/builtin-tool-task';import type { TaskStatus } from '@lobechat/types';import { defineReplica, type ReplicaEntityAdapter, stableQueryKey } from '@/libs/replica';@@ -28,6 +29,8 @@ export interface TaskListQuery {automated?: boolean;/** Every page walked (the Tasks list view), or the first server page. */complete?: boolean;+ /** Completed / canceled tasks closed outside this window are left out server-side. */+ completedWithin?: TaskCompletedWindow;/** 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`. */@@ -52,6 +55,8 @@ export interface TaskListValue {export interface TaskGroupListQuery {agentId?: string;automated?: boolean;+ /** Completed / canceled cards closed outside this window are left out server-side. */+ completedWithin?: TaskCompletedWindow;/** Sorted. */excludeStatuses?: TaskStatus[];groupBy: TaskKanbanGroupBy;@@ -144,7 +149,7 @@ export const taskGroupListEntity: ReplicaEntityAdapter<TaskGroupListValue, TaskGif (!current) return data;let next = fn(current);if (next === current) return data;- // A card whose new status the board hides (`hideCompleted`) leaves it, even+ // A card whose new status the board hides ("Completed tasks: None") leaves it, even// though the server still returns the hidden status's empty column.if (next && data.excludeStatuses?.includes(next.status as TaskStatus)) next = undefined;