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(tasks): separate scheduled task view (#18586)

Arvin Xu6d504480a271
diff --git a/apps/server/src/routers/lambda/task.ts b/apps/server/src/routers/lambda/task.ts
index d279dced6fc..4013bbfe514 100644
--- a/apps/server/src/routers/lambda/task.ts
+++ b/apps/server/src/routers/lambda/task.ts
@@ -139,6 +139,7 @@ const listSchema = z.object({
const groupListSchema = z.object({
assigneeAgentId: z.string().optional(),
+ automated: z.boolean().optional(),
groups: z
.array(
z.object({
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index f9018dd14dc..7098c866631 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1513,8 +1513,10 @@
"taskList.form.showSubTasks": "Show sub-tasks",
"taskList.form.subGrouping": "Sub-grouping",
"taskList.groupBy.assignee": "Assignee",
+ "taskList.groupBy.heartbeat": "Heartbeat",
"taskList.groupBy.none": "No grouping",
"taskList.groupBy.priority": "Priority",
+ "taskList.groupBy.schedule": "Schedule",
"taskList.groupBy.status": "Status",
"taskList.hiddenCompleted.count_one": "{{count}} task",
"taskList.hiddenCompleted.count_other": "{{count}} tasks",
@@ -1536,6 +1538,8 @@
"taskList.orderBy.status": "Status",
"taskList.orderBy.title": "Title",
"taskList.orderBy.updatedAt": "Updated at",
+ "taskList.scheduled.empty": "No scheduled tasks yet",
+ "taskList.scheduled.title": "Scheduled tasks",
"taskList.title": "Tasks",
"taskList.unassigned": "Unassigned",
"taskList.unassignedHint": "Lobe AI will run this task when no assignee is set",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index e68daff6a01..7679759fbab 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1513,8 +1513,10 @@
"taskList.form.showSubTasks": "显示子任务",
"taskList.form.subGrouping": "子分组",
"taskList.groupBy.assignee": "负责人",
+ "taskList.groupBy.heartbeat": "心跳",
"taskList.groupBy.none": "不分组",
"taskList.groupBy.priority": "优先级",
+ "taskList.groupBy.schedule": "定时",
"taskList.groupBy.status": "状态",
"taskList.hiddenCompleted.count_one": "{{count}} 个任务",
"taskList.hiddenCompleted.count_other": "{{count}} 个任务",
@@ -1536,6 +1538,8 @@
"taskList.orderBy.status": "状态",
"taskList.orderBy.title": "标题",
"taskList.orderBy.updatedAt": "更新时间",
+ "taskList.scheduled.empty": "暂无定时任务",
+ "taskList.scheduled.title": "定时任务",
"taskList.title": "任务",
"taskList.unassigned": "未分配",
"taskList.unassignedHint": "未分配时将由 Lobe AI 执行该任务",
diff --git a/packages/database/src/models/__tests__/task.test.ts b/packages/database/src/models/__tests__/task.test.ts
index cf21f083a58..db5fdd76cfe 100644
--- a/packages/database/src/models/__tests__/task.test.ts
+++ b/packages/database/src/models/__tests__/task.test.ts
@@ -567,6 +567,24 @@ describe('TaskModel', () => {
expect(result[0].tasks).toHaveLength(1);
});
+ it('should exclude runnable automation from ordinary kanban groups', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const manual = await model.create({ instruction: 'Manual task' });
+ await model.create({
+ automationMode: 'schedule',
+ instruction: 'Scheduled task',
+ schedulePattern: '0 9 * * *',
+ });
+
+ const [group] = await model.groupList({
+ automated: false,
+ groups: [{ key: 'backlog', statuses: ['backlog'] }],
+ });
+
+ expect(group.tasks.map((task) => task.id)).toEqual([manual.id]);
+ expect(group.total).toBe(1);
+ });
+
it('should filter tasks by their bound goal entity', async () => {
const model = new TaskModel(serverDB, userId);
diff --git a/packages/database/src/models/task.ts b/packages/database/src/models/task.ts
index e1aa2adb335..503248698af 100644
--- a/packages/database/src/models/task.ts
+++ b/packages/database/src/models/task.ts
@@ -539,6 +539,7 @@ export class TaskModel {
async groupList(options: {
assigneeAgentId?: string;
+ automated?: boolean;
groups: Array<{
key: string;
limit?: number;
@@ -562,10 +563,13 @@ export class TaskModel {
total: number;
}>
> {
- const { groups, assigneeAgentId, hasGoal, parentTaskId, projectId, visibility } = options;
+ const { groups, assigneeAgentId, automated, hasGoal, parentTaskId, projectId, visibility } =
+ options;
const baseConditions = [this.ownership()];
if (assigneeAgentId) baseConditions.push(eq(tasks.assigneeAgentId, assigneeAgentId));
+ if (automated === true) baseConditions.push(RUNNABLE_AUTOMATION);
+ if (automated === false) baseConditions.push(sql`${RUNNABLE_AUTOMATION} IS NOT TRUE`);
if (hasGoal === true) baseConditions.push(HAS_GOAL);
if (hasGoal === false) baseConditions.push(sql`NOT ${HAS_GOAL}`);
if (projectId) baseConditions.push(eq(tasks.projectId, projectId));
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 169f5fab476..54eebd4dcd6 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1805,8 +1805,10 @@ export default {
'taskList.hiddenCompleted.show': 'Show',
'taskList.hiddenCompleted.suffix': 'hidden by display options',
'taskList.groupBy.assignee': 'Assignee',
+ 'taskList.groupBy.heartbeat': 'Heartbeat',
'taskList.groupBy.none': 'No grouping',
'taskList.groupBy.priority': 'Priority',
+ 'taskList.groupBy.schedule': 'Schedule',
'taskList.groupBy.status': 'Status',
'taskList.orderBy.assignee': 'Assignee',
'taskList.orderBy.createdAt': 'Created at',
@@ -1814,6 +1816,8 @@ export default {
'taskList.orderBy.status': 'Status',
'taskList.orderBy.title': 'Title',
'taskList.orderBy.updatedAt': 'Updated at',
+ 'taskList.scheduled.empty': 'No scheduled tasks yet',
+ 'taskList.scheduled.title': 'Scheduled tasks',
'taskList.title': 'Tasks',
'taskList.unassigned': 'Unassigned',
'taskList.unassignedHint': 'Lobe AI will run this task when no assignee is set',
diff --git a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.test.ts b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.test.ts
index 22722415d02..fd5fa62091f 100644
--- a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.test.ts
+++ b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.test.ts
@@ -1,9 +1,36 @@
import { describe, expect, it } from 'vitest';
-import { getTaskCreateActionBehavior, getTaskPageHeaderVisibility } from './AgentTasksPage';
+import {
+ clampScheduledPage,
+ getTaskCreateActionBehavior,
+ getTaskPageHeaderVisibility,
+ resolveTaskCollection,
+} from './AgentTasksPage';
import { shouldRenderTaskAgentPanelToggle } from './taskAgentPanelToggle';
describe('AgentTasksPage', () => {
+ describe('clampScheduledPage', () => {
+ it('moves a stale last page back into range when the result total shrinks', () => {
+ expect(clampScheduledPage(2, 50)).toBe(1);
+ expect(clampScheduledPage(3, 51)).toBe(2);
+ });
+
+ it('keeps the first page valid for an empty result', () => {
+ expect(clampScheduledPage(1, 0)).toBe(1);
+ });
+ });
+
+ describe('resolveTaskCollection', () => {
+ it('opens the scheduled collection from its addressable URL', () => {
+ expect(resolveTaskCollection(new URLSearchParams('collection=scheduled'))).toBe('scheduled');
+ });
+
+ it('falls back to ordinary tasks for absent or unknown values', () => {
+ expect(resolveTaskCollection(new URLSearchParams())).toBe('tasks');
+ expect(resolveTaskCollection(new URLSearchParams('collection=unknown'))).toBe('tasks');
+ });
+ });
+
describe('getTaskCreateActionBehavior', () => {
it('should allow workspace viewers to reopen the collapsed inline entry in list view', () => {
expect(
diff --git a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
index 5bd92d84cc7..b70d8c16d06 100644
--- a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
+++ b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
@@ -1,6 +1,10 @@
import { ActionIcon, Flexbox } from '@lobehub/ui';
+import { TabsIndicator, TabsList, TabsRoot, TabsTab } from '@lobehub/ui/base-ui';
+import { Pagination } from 'antd';
import { Plus } from 'lucide-react';
-import { memo, useCallback, useMemo } from 'react';
+import { memo, useCallback, useEffect, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useSearchParams } from 'react-router';
import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
import NavHeader from '@/features/NavHeader';
@@ -77,15 +81,34 @@ interface AgentTasksPageProps {
projectId?: string;
}
+type TaskCollection = 'scheduled' | 'tasks';
+const SCHEDULED_TASK_PAGE_SIZE = 50;
+
+export const resolveTaskCollection = (searchParams: URLSearchParams): TaskCollection =>
+ searchParams.get('collection') === 'scheduled' ? 'scheduled' : 'tasks';
+
+export const clampScheduledPage = (page: number, total: number): number =>
+ Math.min(page, Math.max(1, Math.ceil(total / SCHEDULED_TASK_PAGE_SIZE)));
+
const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, projectId }) => {
+ const { t } = useTranslation('chat');
const navigate = useWorkspaceAwareNavigate();
const isMobile = useIsMobile();
const { allowed: canCreateTask, reason } = usePermission('create_content');
const viewMode = useGlobalStore(systemStatusSelectors.taskListViewMode);
+ const [searchParams, setSearchParams] = useSearchParams();
+ const [scheduledPage, setScheduledPage] = useState(1);
+ const canSwitchCollection = !agentId && !projectId;
+ const collection = canSwitchCollection ? resolveTaskCollection(searchParams) : 'tasks';
+ const isScheduledCollection = canSwitchCollection && collection === 'scheduled';
const useFetchTaskList = useTaskStore((s) => s.useFetchTaskList);
// Keep the SWR handle only for `error` + `mutate` (the error/Retry state).
const { error, isLoading, mutate } = useFetchTaskList(
- projectId ? { projectId, visibility: 'all' } : agentId ? { agentId } : { allAgents: true },
+ projectId
+ ? { projectId, visibility: 'all' }
+ : agentId
+ ? { agentId }
+ : { allAgents: true, automated: false },
);
// Drive the loading/empty boundary off the store's own init flag, NOT SWR's
// per-key `data`. On a scope (agent ↔ all) or visibility switch the store
@@ -98,8 +121,25 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, projectId }) => {
// failed first load, so we surface loading only while there's no error (below).
const isTaskListInit = useTaskStore(taskListSelectors.isTaskListInit);
const isEmptyHero = useTaskStore(taskListSelectors.isListEmpty);
+ const useFetchScheduledTaskList = useTaskStore((s) => s.useFetchScheduledTaskList);
+ const scheduledSWR = useFetchScheduledTaskList({
+ enabled: isScheduledCollection,
+ limit: SCHEDULED_TASK_PAGE_SIZE,
+ offset: (scheduledPage - 1) * SCHEDULED_TASK_PAGE_SIZE,
+ });
+ const scheduledTasks = scheduledSWR.data?.data ?? [];
+ const scheduledTasksTotal = scheduledSWR.data?.total ?? 0;
+ const isScheduledTaskListInit = scheduledSWR.data !== undefined;
const rawViewOptions = useGlobalStore(systemStatusSelectors.taskListViewOptions);
const viewOptions = useMemo(() => normalizeTaskListViewOptions(rawViewOptions), [rawViewOptions]);
+ const scheduledViewOptions = useMemo(
+ () => ({ ...viewOptions, groupBy: 'automationMode' as const, hideCompleted: false }),
+ [viewOptions],
+ );
+ useEffect(() => {
+ if (!isScheduledTaskListInit) return;
+ setScheduledPage((page) => clampScheduledPage(page, scheduledTasksTotal));
+ }, [isScheduledTaskListInit, scheduledTasksTotal]);
const inlineCollapsed = useGlobalStore(systemStatusSelectors.taskCreateInlineCollapsed);
const [showTaskAgentPanel, toggleTaskAgentPanel] = useGlobalStore((s) => [
systemStatusSelectors.showTaskAgentPanel(s),
@@ -109,7 +149,12 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, projectId }) => {
const routeScope = agentId ? 'agent' : 'global';
const setViewOptions = useCallback(
(updater: (prev: TaskListViewOptions) => TaskListViewOptions) => {
- const next = normalizeTaskListViewOptions(updater(viewOptions));
+ const normalized = normalizeTaskListViewOptions(updater(viewOptions));
+ const next = {
+ ...normalized,
+ groupBy: normalized.groupBy === 'automationMode' ? 'status' : normalized.groupBy,
+ subGroupBy: normalized.subGroupBy === 'automationMode' ? 'none' : normalized.subGroupBy,
+ };
updateSystemStatus({ taskListViewOptions: next }, 'updateTaskListViewOptions');
},
[updateSystemStatus, viewOptions],
@@ -146,16 +191,46 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, projectId }) => {
setViewOptions((prev) => ({ ...prev, hideCompleted: false }));
}, [setViewOptions]);
- const headerVisibility = getTaskPageHeaderVisibility({ agentId, isEmptyHero, isMobile });
+ const handleCollectionChange = useCallback(
+ (value: string) => {
+ const next = new URLSearchParams(searchParams);
+ if (value === 'scheduled') {
+ next.set('collection', 'scheduled');
+ } else {
+ next.delete('collection');
+ }
+ setScheduledPage(1);
+ setSearchParams(next, { replace: true });
+ },
+ [searchParams, setSearchParams],
+ );
+
+ const headerVisibility = getTaskPageHeaderVisibility({
+ agentId,
+ isEmptyHero: isScheduledCollection ? false : isEmptyHero,
+ isMobile,
+ });
+
+ const collectionTabs = canSwitchCollection ? (
+ <TabsRoot size={'small'} value={collection} onValueChange={handleCollectionChange}>
+ <TabsList>
+ <TabsIndicator />
+ <TabsTab value={'tasks'}>{t('taskList.title')}</TabsTab>
+ <TabsTab value={'scheduled'}>{t('taskList.scheduled.title')}</TabsTab>
+ </TabsList>
+ </TabsRoot>
+ ) : (
+ <Breadcrumb />
+ );
return (
<Flexbox flex={1} height={'100%'}>
<NavHeader
- left={headerVisibility.showBreadcrumb ? <Breadcrumb /> : undefined}
+ left={headerVisibility.showBreadcrumb || canSwitchCollection ? collectionTabs : undefined}
right={
<Flexbox horizontal align={'center'} gap={4}>
- {!agentId && !projectId && <TaskListVisibilityFilter />}
- {(inlineCollapsed || viewMode === 'kanban') && (
+ {!isScheduledCollection && !agentId && !projectId && <TaskListVisibilityFilter />}
+ {!isScheduledCollection && (inlineCollapsed || viewMode === 'kanban') && (
<ActionIcon
disabled={createActionBehavior.disabled}
icon={Plus}
@@ -164,7 +239,7 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, projectId }) => {
onClick={handleCreateTask}
/>
)}
- {headerVisibility.showViewOptions && (
+ {!isScheduledCollection && headerVisibility.showViewOptions && (
<TasksGroupConfig options={viewOptions} setOptions={setViewOptions} />
)}
{headerVisibility.showTaskAgentPanelToggle && (
@@ -183,7 +258,37 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, projectId }) => {
},
}}
/>
- {isEmptyHero ? (
+ {isScheduledCollection ? (
+ <WideScreenContainer
+ fullWidth
+ gap={16}
+ paddingBlock={16}
+ paddingInline={16}
+ wrapperStyle={{ flex: 1, overflowY: 'auto' }}
+ >
+ <TaskList
+ data={isScheduledTaskListInit || undefined}
+ emptyDescription={t('taskList.scheduled.empty')}
+ error={scheduledSWR.error}
+ isLoading={scheduledSWR.isLoading || (!isScheduledTaskListInit && !scheduledSWR.error)}
+ items={scheduledTasks}
+ options={scheduledViewOptions}
+ routeScope={routeScope}
+ onRetry={() => scheduledSWR.mutate()}
+ />
+ {(scheduledTasksTotal > SCHEDULED_TASK_PAGE_SIZE || scheduledPage > 1) && (
+ <Flexbox horizontal justify={'center'} paddingBlock={8}>
+ <Pagination
+ current={scheduledPage}
+ pageSize={SCHEDULED_TASK_PAGE_SIZE}
+ showSizeChanger={false}
+ total={scheduledTasksTotal}
+ onChange={setScheduledPage}
+ />
+ </Flexbox>
+ )}
+ </WideScreenContainer>
+ ) : isEmptyHero ? (
<EmptyState agentId={agentId} projectId={projectId} />
) : viewMode === 'kanban' ? (
<Flexbox flex={1} style={{ overflowX: 'auto', overflowY: 'hidden' }}>
diff --git a/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx b/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx
index dc632ff51f0..80a1d65691a 100644
--- a/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx
+++ b/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx
@@ -91,7 +91,7 @@ const KanbanBoard = memo<KanbanBoardProps>(({ agentId, projectId, routeScope })
const useFetchTaskGroupList = useTaskStore((s) => s.useFetchTaskGroupList);
// Keep the SWR handle only for `error` + `mutate` (the error/Retry state).
const { error, isLoading, mutate } = useFetchTaskGroupList(
- projectId ? { projectId } : agentId ? { agentId } : { allAgents: true },
+ projectId ? { projectId } : agentId ? { agentId } : { allAgents: true, automated: false },
);
// Drive the loading/empty boundary off the store's own init flag, NOT SWR's
// per-key `data`. On a scope or visibility switch the store resets
diff --git a/src/features/AgentTasks/AgentTaskList/TaskList.tsx b/src/features/AgentTasks/AgentTaskList/TaskList.tsx
index 433ee876aec..5ba9558d2eb 100644
--- a/src/features/AgentTasks/AgentTaskList/TaskList.tsx
+++ b/src/features/AgentTasks/AgentTaskList/TaskList.tsx
@@ -1,13 +1,14 @@
import { Accordion, AccordionItem, Block, Center, Empty, Flexbox, Icon, Text } from '@lobehub/ui';
import { Divider } from 'antd';
import { cssVar } from 'antd-style';
-import { ClipboardCheckIcon, UserRound } from 'lucide-react';
+import { CalendarClock, ClipboardCheckIcon, HeartPulse, UserRound } from 'lucide-react';
import { Fragment, memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import AsyncBoundary from '@/components/AsyncBoundary';
import { useTaskStore } from '@/store/task';
import { taskListSelectors } from '@/store/task/selectors';
+import type { TaskListItem } from '@/store/task/slices/list/initialState';
import type { TaskItemRouteScope } from '../features/AgentTaskItem';
import AgentTaskItem from '../features/AgentTaskItem';
@@ -24,9 +25,8 @@ import {
buildTaskRows,
collapseSubTasks,
compareTaskItems,
- getTaskGroupMeta,
+ groupTaskItems,
HIDDEN_WHEN_COMPLETED_STATUSES,
- sortGroupEntries,
} from './listViewOptions';
import TaskItemSkeleton from './TaskItemSkeleton';
import TaskRowIndent from './TaskRowIndent';
@@ -39,10 +39,13 @@ interface TaskListProps {
* on a scope/visibility switch and never disagrees with the empty signal.
*/
data?: unknown;
+ emptyDescription?: string;
/** Thrown error from the list SWR — surfaced as a failure state, not a skeleton. */
error?: unknown;
/** First-load / retry in flight (SWR `isLoading`). */
isLoading?: boolean;
+ /** Optional list source for alternate task collections such as scheduled tasks. */
+ items?: TaskListItem[];
onRetry?: () => void;
onShowHiddenCompleted?: () => void;
options: TaskListViewOptions;
@@ -81,7 +84,13 @@ const PRIORITY_ICON_MAP = {
4: PriorityLowIcon,
} as const;
-const TASK_GROUP_BY_VALUES = new Set<TaskGroupBy>(['assignee', 'none', 'priority', 'status']);
+const TASK_GROUP_BY_VALUES = new Set<TaskGroupBy>([
+ 'assignee',
+ 'automationMode',
+ 'none',
+ 'priority',
+ 'status',
+]);
const normalizeGroupBy = (value: TaskGroupBy | string | undefined, fallback: TaskGroupBy) => {
if (!value) return fallback;
@@ -113,6 +122,16 @@ const renderGroupPrefix = (group: TaskGroupMeta) => {
);
}
+ if (group.groupBy === 'automationMode') {
+ return (
+ <Icon
+ color={cssVar.colorTextDescription}
+ icon={group.automationMode === 'heartbeat' ? HeartPulse : CalendarClock}
+ size={16}
+ />
+ );
+ }
+
if (group.groupBy === 'status') {
const status = group.status ?? 'backlog';
@@ -142,9 +161,11 @@ const renderGroupTitle = (group: TaskGroupMeta, count: number, sub?: boolean) =>
);
const TaskList = memo<TaskListProps>((props) => {
- const { data, error, isLoading, onRetry, onShowHiddenCompleted, options, routeScope } = props;
+ const { data, error, isLoading, items, onRetry, onShowHiddenCompleted, options, routeScope } =
+ props;
const { t } = useTranslation('chat');
- const tasks = useTaskStore(taskListSelectors.taskList);
+ const storeTasks = useTaskStore(taskListSelectors.taskList);
+ const tasks = items ?? storeTasks;
const groupBy = normalizeGroupBy(options.groupBy, 'status');
const subGroupBy = normalizeGroupBy(options.subGroupBy, 'none');
const effectiveSubGroupBy = groupBy === 'none' ? 'none' : subGroupBy;
@@ -179,24 +200,7 @@ const TaskList = memo<TaskListProps>((props) => {
const subGroupOrderDirection =
options.orderBy === effectiveSubGroupBy ? options.orderDirection : undefined;
- const primaryGroupMap = new Map<string, { items: typeof visibleTasks; meta: TaskGroupMeta }>();
- for (const task of sortedTasks) {
- const primaryGroup = getTaskGroupMeta(task, groupBy);
- if (!primaryGroup?.key) continue;
- const bucket = primaryGroupMap.get(primaryGroup.key);
-
- if (bucket) {
- bucket.items.push(task);
- } else {
- primaryGroupMap.set(primaryGroup.key, { items: [task], meta: primaryGroup });
- }
- }
-
- const primaryGroups = sortGroupEntries(
- [...primaryGroupMap.values()].map((group) => [group.meta, group.items]),
- groupBy,
- primaryGroupOrderDirection,
- );
+ const primaryGroups = groupTaskItems(sortedTasks, groupBy, primaryGroupOrderDirection);
return primaryGroups.map(([meta, groupedTasks]) => {
if (effectiveSubGroupBy === 'none') {
@@ -208,32 +212,17 @@ const TaskList = memo<TaskListProps>((props) => {
};
}
- const subGroupMap = new Map<string, { items: typeof visibleTasks; meta: TaskGroupMeta }>();
- for (const task of groupedTasks) {
- const subGroup = getTaskGroupMeta(task, effectiveSubGroupBy);
- if (!subGroup?.key) continue;
- const bucket = subGroupMap.get(subGroup.key);
-
- if (bucket) {
- bucket.items.push(task);
- } else {
- subGroupMap.set(subGroup.key, { items: [task], meta: subGroup });
- }
- }
-
return {
count: groupedTasks.length,
meta,
rows: toRows(groupedTasks),
- subGroups: sortGroupEntries(
- [...subGroupMap.values()].map((group) => [group.meta, group.items]),
- effectiveSubGroupBy,
- subGroupOrderDirection,
- ).map(([subMeta, subItems]) => ({
- count: subItems.length,
- meta: subMeta,
- rows: toRows(subItems),
- })),
+ subGroups: groupTaskItems(groupedTasks, effectiveSubGroupBy, subGroupOrderDirection).map(
+ ([subMeta, subItems]) => ({
+ count: subItems.length,
+ meta: subMeta,
+ rows: toRows(subItems),
+ }),
+ ),
};
});
}, [effectiveSubGroupBy, groupBy, nested, options, taskById, visibleTasks]);
@@ -251,7 +240,10 @@ const TaskList = memo<TaskListProps>((props) => {
const emptyState = (
<Center height={'80vh'} width={'100%'}>
- <Empty description={t('taskList.empty')} icon={ClipboardCheckIcon} />
+ <Empty
+ description={props.emptyDescription ?? t('taskList.empty')}
+ icon={ClipboardCheckIcon}
+ />
</Center>
);
diff --git a/src/features/AgentTasks/AgentTaskList/listViewOptions.test.ts b/src/features/AgentTasks/AgentTaskList/listViewOptions.test.ts
index 535f10bbcf9..e83e6730ff3 100644
--- a/src/features/AgentTasks/AgentTaskList/listViewOptions.test.ts
+++ b/src/features/AgentTasks/AgentTaskList/listViewOptions.test.ts
@@ -7,6 +7,7 @@ import {
collapseSubTasks,
compareTaskItems,
DEFAULT_TASK_LIST_VIEW_OPTIONS,
+ groupTaskItems,
normalizeTaskListViewOptions,
} from './listViewOptions';
@@ -50,6 +51,29 @@ describe('normalizeTaskListViewOptions', () => {
});
});
+describe('automation mode grouping', () => {
+ it('groups scheduled and heartbeat tasks separately with schedule first', () => {
+ const schedule = task('schedule', { automationMode: 'schedule' });
+ const heartbeat = task('heartbeat', { automationMode: 'heartbeat' });
+ expect(
+ groupTaskItems([heartbeat, schedule], 'automationMode').map(([group, items]) => [
+ group.automationMode,
+ items.map((item) => item.id),
+ ]),
+ ).toEqual([
+ ['schedule', ['schedule']],
+ ['heartbeat', ['heartbeat']],
+ ]);
+ });
+
+ it('does not create an empty automation group', () => {
+ const heartbeat = task('heartbeat', { automationMode: 'heartbeat' });
+ const groups = groupTaskItems([heartbeat], 'automationMode');
+
+ expect(groups.map(([group]) => group.key)).toEqual(['automationMode:heartbeat']);
+ });
+});
+
describe('collapseSubTasks', () => {
it('drops a sub-task whose parent is already listed', () => {
const items = [task('parent'), task('child', { parentTaskId: 'parent' })];
diff --git a/src/features/AgentTasks/AgentTaskList/listViewOptions.ts b/src/features/AgentTasks/AgentTaskList/listViewOptions.ts
index 9ef332681b6..9d599194004 100644
--- a/src/features/AgentTasks/AgentTaskList/listViewOptions.ts
+++ b/src/features/AgentTasks/AgentTaskList/listViewOptions.ts
@@ -2,7 +2,7 @@ import { t } from 'i18next';
import type { TaskListItem } from '@/store/task/slices/list/initialState';
-export type TaskGroupBy = 'assignee' | 'none' | 'priority' | 'status';
+export type TaskGroupBy = 'assignee' | 'automationMode' | 'none' | 'priority' | 'status';
export type TaskOrderBy = 'assignee' | 'createdAt' | 'priority' | 'status' | 'title' | 'updatedAt';
export type TaskOrderDirection = 'asc' | 'desc';
@@ -26,6 +26,7 @@ export const HIDDEN_WHEN_COMPLETED_STATUSES: ReadonlyArray<NonNullable<TaskGroup
export interface TaskGroupMeta {
assigneeId?: string;
+ automationMode?: 'heartbeat' | 'schedule';
groupBy: TaskGroupBy;
key: string;
label: string;
@@ -47,7 +48,13 @@ export const DEFAULT_TASK_LIST_VIEW_OPTIONS: TaskListViewOptions = {
subGroupBy: 'none',
};
-const TASK_GROUP_BY_SET = new Set<TaskGroupBy>(['assignee', 'none', 'priority', 'status']);
+const TASK_GROUP_BY_SET = new Set<TaskGroupBy>([
+ 'assignee',
+ 'automationMode',
+ 'none',
+ 'priority',
+ 'status',
+]);
const TASK_ORDER_BY_SET = new Set<TaskOrderBy>([
'assignee',
'createdAt',
@@ -226,6 +233,16 @@ export const getTaskGroupMeta = (task: TaskListItem, groupBy: TaskGroupBy): Task
case 'assignee': {
return getTaskAssigneeMeta(task);
}
+ case 'automationMode': {
+ // Automated tasks created before automationMode was introduced are schedules.
+ const automationMode = task.automationMode === 'heartbeat' ? 'heartbeat' : 'schedule';
+ return {
+ automationMode,
+ groupBy: 'automationMode',
+ key: `automationMode:${automationMode}`,
+ label: t(`taskList.groupBy.${automationMode}`, { ns: 'chat' }),
+ };
+ }
case 'priority': {
const priority = getPriorityValue(task);
const labelKeyMap: Record<number, string> = {
@@ -272,6 +289,9 @@ export const getTaskGroupMeta = (task: TaskListItem, groupBy: TaskGroupBy): Task
const getGroupRank = (group: TaskGroupMeta, groupBy: TaskGroupBy): number => {
switch (groupBy) {
+ case 'automationMode': {
+ return group.automationMode === 'schedule' ? 0 : 1;
+ }
case 'priority': {
if (group.priority === undefined) return Number.MAX_SAFE_INTEGER;
return PRIORITY_RANK_MAP[group.priority] ?? Number.MAX_SAFE_INTEGER;
@@ -304,6 +324,31 @@ export const sortGroupEntries = (
});
};
+export const groupTaskItems = (
+ items: TaskListItem[],
+ groupBy: TaskGroupBy,
+ orderDirection?: TaskOrderDirection,
+): Array<[TaskGroupMeta, TaskListItem[]]> => {
+ const groups = new Map<string, { items: TaskListItem[]; meta: TaskGroupMeta }>();
+
+ for (const task of items) {
+ const meta = getTaskGroupMeta(task, groupBy);
+ const bucket = groups.get(meta.key);
+
+ if (bucket) {
+ bucket.items.push(task);
+ } else {
+ groups.set(meta.key, { items: [task], meta });
+ }
+ }
+
+ return sortGroupEntries(
+ [...groups.values()].map((group) => [group.meta, group.items]),
+ groupBy,
+ orderDirection,
+ );
+};
+
/** Depth cap — guards a malformed parent chain from recursing without end. */
const MAX_NEST_DEPTH = 8;
diff --git a/src/features/Home/HomeModeContent.tsx b/src/features/Home/HomeModeContent.tsx
index fbab02a2e26..ca5b5c81b59 100644
--- a/src/features/Home/HomeModeContent.tsx
+++ b/src/features/Home/HomeModeContent.tsx
@@ -417,11 +417,11 @@ const TaskContent = memo(() => {
const ScheduledTaskContent = memo(() => {
const { t } = useTranslation('home');
const useFetchScheduledTaskList = useTaskStore((s) => s.useFetchScheduledTaskList);
- const scheduledSWR = useFetchScheduledTaskList();
- const scheduled = useTaskStore(taskListSelectors.scheduledTaskList);
- const scheduledTotal = useTaskStore(taskListSelectors.scheduledTaskListTotal);
- const scheduledInit = useTaskStore(taskListSelectors.isScheduledTaskListInit);
const taskCount = useGlobalStore(systemStatusSelectors.homeTaskCount);
+ const scheduledSWR = useFetchScheduledTaskList({ limit: taskCount });
+ const scheduled = scheduledSWR.data?.data ?? [];
+ const scheduledTotal = scheduledSWR.data?.total ?? 0;
+ const scheduledInit = scheduledSWR.data !== undefined;
// Automation is opt-in and most accounts have none. An empty block would be a
// permanent reminder of a feature you did not ask for, so the section only
@@ -444,7 +444,7 @@ const ScheduledTaskContent = memo(() => {
title={t('dashboard.scheduledTask.title')}
action={
!failedFirstLoad && scheduledTotal > shown.length ? (
- <WorkspaceLink className={styles.blockAction} to={'/tasks'}>
+ <WorkspaceLink className={styles.blockAction} to={'/tasks?collection=scheduled'}>
{t('dashboard.task.viewAll')}
</WorkspaceLink>
) : undefined
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 3a6de94cf98..df56a4164cc 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -273,6 +273,9 @@ export const recentKeys = {
export const isTaskListKey = (key: unknown): boolean =>
Array.isArray(key) && key[0] === 'task:list';
+export const isScheduledTaskListKey = (key: unknown): boolean =>
+ Array.isArray(key) && key[0] === 'task:scheduledList';
+
export const taskKeys = {
detail: def('task:detail', (taskId: string) => ['task:detail', taskId]),
groupList: def(
@@ -281,10 +284,14 @@ export const taskKeys = {
agentKey: string | undefined,
visibility: 'all' | 'private' | 'workspace' = 'all',
projectId?: string,
- ) =>
- projectId
- ? ['task:groupList', agentKey, visibility, projectId]
- : ['task:groupList', agentKey, visibility],
+ automated?: boolean,
+ ) => [
+ 'task:groupList',
+ agentKey,
+ visibility,
+ ...(projectId ? [projectId] : []),
+ ...(automated === undefined ? [] : [{ automated }]),
+ ],
),
/**
* The home rail's cross-agent goal roll-up. Scoped by cache scope like the
@@ -333,10 +340,16 @@ export const taskKeys = {
*/
scheduledList: def(
'task:scheduledList',
- (agentKey: string | undefined, visibility: 'all' | 'private' | 'workspace' = 'all') => [
+ (
+ agentKey: string | undefined,
+ visibility: 'all' | 'private' | 'workspace' = 'all',
+ limit?: number,
+ offset?: number,
+ ) => [
'task:scheduledList',
agentKey,
visibility,
+ ...(limit === undefined && offset === undefined ? [] : [{ limit, offset }]),
],
),
/**
diff --git a/src/services/task.ts b/src/services/task.ts
index 6f316f997ac..8b69220f568 100644
--- a/src/services/task.ts
+++ b/src/services/task.ts
@@ -31,6 +31,7 @@ class TaskService {
groupList = async (params: {
assigneeAgentId?: string;
+ automated?: boolean;
groups: Array<{
key: string;
limit?: number;
diff --git a/src/store/task/selectors/listSelectors.ts b/src/store/task/selectors/listSelectors.ts
index 30070f8f7ee..2bcc9cd4282 100644
--- a/src/store/task/selectors/listSelectors.ts
+++ b/src/store/task/selectors/listSelectors.ts
@@ -7,12 +7,6 @@ const taskListTotal = (s: TaskStoreState) => s.tasksTotal;
const isTaskListInit = (s: TaskStoreState) => s.isTaskListInit;
-const scheduledTaskList = (s: TaskStoreState): TaskListItem[] => s.scheduledTasks;
-
-const scheduledTaskListTotal = (s: TaskStoreState) => s.scheduledTasksTotal;
-
-const isScheduledTaskListInit = (s: TaskStoreState) => s.isScheduledTaskListInit;
-
const listVisibility = (s: TaskStoreState) => s.listVisibility;
const statusDisplayMap: Record<string, string> = {
@@ -51,14 +45,11 @@ export const taskListSelectors = {
doneTasks,
getDisplayStatus,
isListEmpty,
- isScheduledTaskListInit,
isTaskGroupListInit,
isTaskListInit,
listVisibility,
needsInputTasks,
runningTasks,
- scheduledTaskList,
- scheduledTaskListTotal,
taskGroupByKey,
taskGroups,
taskList,
diff --git a/src/store/task/slices/list/action.test.ts b/src/store/task/slices/list/action.test.ts
index f44958d4b5a..f23e4970267 100644
--- a/src/store/task/slices/list/action.test.ts
+++ b/src/store/task/slices/list/action.test.ts
@@ -5,6 +5,7 @@ import { useTaskStore } from '../../store';
// Mock task service
vi.mock('@/services/task', () => ({
taskService: {
+ groupList: vi.fn(),
list: vi.fn(),
},
}));
@@ -22,6 +23,7 @@ beforeEach(() => {
listAgentId: undefined,
listQueryAutomated: undefined,
listQueryVisibility: 'all',
+ listVisibility: 'all',
tasks: [],
tasksTotal: 0,
});
@@ -225,6 +227,58 @@ describe('TaskListSliceAction', () => {
});
});
+ describe('useFetchTaskGroupList', () => {
+ it('passes the ordinary-task automation filter through the kanban query', async () => {
+ const { useClientDataSWR } = await import('@/libs/swr');
+ const { taskService } = await import('@/services/task');
+
+ useTaskStore.getState().useFetchTaskGroupList({ allAgents: true, automated: false });
+
+ expect(useClientDataSWR).toHaveBeenCalledWith(
+ ['task:groupList', '__all__', 'all', { automated: false }],
+ expect.any(Function),
+ expect.any(Object),
+ );
+ const fetcher = vi.mocked(useClientDataSWR).mock.calls[0][1] as () => Promise<unknown>;
+ await fetcher();
+ expect(taskService.groupList).toHaveBeenCalledWith(
+ expect.objectContaining({ automated: false }),
+ );
+ });
+ });
+
+ describe('useFetchScheduledTaskList', () => {
+ it('keys and requests the selected scheduled-task page', async () => {
+ const { useClientDataSWR } = await import('@/libs/swr');
+ const { taskService } = await import('@/services/task');
+
+ useTaskStore.getState().useFetchScheduledTaskList({ limit: 50, offset: 50 });
+
+ expect(useClientDataSWR).toHaveBeenCalledWith(
+ ['task:scheduledList', '__all__', 'all', { limit: 50, offset: 50 }],
+ expect.any(Function),
+ expect.any(Object),
+ );
+ const fetcher = vi.mocked(useClientDataSWR).mock.calls[0][1] as () => Promise<unknown>;
+ await fetcher();
+ expect(taskService.list).toHaveBeenCalledWith(
+ expect.objectContaining({ automated: true, limit: 50, offset: 50 }),
+ );
+ });
+
+ it('keeps concurrent consumers isolated by their SWR keys', async () => {
+ const { useClientDataSWR } = await import('@/libs/swr');
+
+ useTaskStore.getState().useFetchScheduledTaskList({ limit: 5 });
+ useTaskStore.getState().useFetchScheduledTaskList({ limit: 50, offset: 50 });
+
+ expect(vi.mocked(useClientDataSWR).mock.calls.map(([key]) => key)).toEqual([
+ ['task:scheduledList', '__all__', 'all', { limit: 5, offset: undefined }],
+ ['task:scheduledList', '__all__', 'all', { limit: 50, offset: 50 }],
+ ]);
+ });
+ });
+
describe('setListVisibility', () => {
it('should update visibility filter and reset list state', async () => {
useTaskStore.setState({
diff --git a/src/store/task/slices/list/action.ts b/src/store/task/slices/list/action.ts
index 206b9a51458..d2f5e34719b 100644
--- a/src/store/task/slices/list/action.ts
+++ b/src/store/task/slices/list/action.ts
@@ -1,7 +1,7 @@
import type { TaskStatus } from '@lobechat/types';
import { mutate, useClientDataSWR } from '@/libs/swr';
-import { isTaskListKey, taskKeys } from '@/libs/swr/keys';
+import { isScheduledTaskListKey, isTaskListKey, taskKeys } from '@/libs/swr/keys';
import { taskService } from '@/services/task';
import type { StoreSetter } from '@/store/types';
@@ -78,7 +78,12 @@ export class TaskListSliceActionImpl {
refreshTaskGroupList = async (): Promise<void> => {
const { listAgentId, listVisibility } = this.#get();
await mutate(
- taskKeys.groupList(listAgentId, listVisibility, projectIdFromListKey(listAgentId)),
+ taskKeys.groupList(
+ listAgentId,
+ listVisibility,
+ projectIdFromListKey(listAgentId),
+ this.#get().groupListQueryAutomated,
+ ),
);
};
@@ -94,10 +99,17 @@ export class TaskListSliceActionImpl {
// boundaries (touching reorders `updatedAt`, scheduling flips the
// automation filter), so they are invalidated by root, not enumerated.
mutate(isTaskListKey),
- mutate(taskKeys.groupList(listAgentId, listVisibility, projectId)),
+ mutate(
+ taskKeys.groupList(
+ listAgentId,
+ listVisibility,
+ projectId,
+ this.#get().groupListQueryAutomated,
+ ),
+ ),
// A schedule can be attached, changed or removed from any task edit, so
// the automated roll-up has to be revalidated alongside the main list.
- mutate(taskKeys.scheduledList(ALL_AGENTS_LIST_KEY)),
+ mutate(isScheduledTaskListKey),
]);
};
@@ -124,19 +136,24 @@ export class TaskListSliceActionImpl {
options: {
agentId?: string;
allAgents?: boolean;
+ automated?: boolean;
enabled?: boolean;
projectId?: string;
} = {},
) => {
- const { agentId, allAgents = false, enabled = true, projectId } = options;
+ const { agentId, allAgents = false, automated, enabled = true, projectId } = options;
const effectiveKey = projectId
? `${PROJECT_LIST_KEY_PREFIX}${projectId}`
: allAgents
? ALL_AGENTS_LIST_KEY
: agentId;
- if (effectiveKey && this.#get().listAgentId !== effectiveKey) {
+ if (
+ effectiveKey &&
+ (this.#get().listAgentId !== effectiveKey ||
+ this.#get().groupListQueryAutomated !== automated)
+ ) {
this.#set(
- { ...scopeChangeResetState, listAgentId: effectiveKey },
+ { ...scopeChangeResetState, groupListQueryAutomated: automated, listAgentId: effectiveKey },
false,
'useFetchTaskGroupList/syncAgentId',
);
@@ -144,10 +161,13 @@ export class TaskListSliceActionImpl {
const listVisibility = this.#get().listVisibility;
return useClientDataSWR(
- enabled && effectiveKey ? taskKeys.groupList(effectiveKey, listVisibility, projectId) : null,
+ enabled && effectiveKey
+ ? taskKeys.groupList(effectiveKey, listVisibility, projectId, automated)
+ : null,
async () => {
return taskService.groupList({
assigneeAgentId: allAgents ? undefined : agentId,
+ automated,
groups: DEFAULT_KANBAN_GROUPS,
hasGoal: false,
projectId,
@@ -168,33 +188,25 @@ export class TaskListSliceActionImpl {
};
/**
- * The automated-task roll-up behind Home's "Scheduled" section. Always
- * cross-agent and unnarrowed by visibility: Home is an overview, not a
- * continuation of the Task page's filter chip — so it needs neither the
- * agent scope nor the visibility argument the main list carries, and its
- * own state fields keep it from colliding with `tasks`.
+ * The automated-task roll-up behind Home's "Scheduled" section. Each caller
+ * consumes its own SWR result because Home and the paginated Tasks page can
+ * coexist in Electron with different limits and offsets.
*/
- useFetchScheduledTaskList = (options: { enabled?: boolean; limit?: number } = {}) => {
- const { enabled = true, limit } = options;
-
+ useFetchScheduledTaskList = (
+ options: { enabled?: boolean; limit?: number; offset?: number } = {},
+ ) => {
+ const { enabled = true, limit, offset } = options;
return useClientDataSWR(
- enabled ? taskKeys.scheduledList(ALL_AGENTS_LIST_KEY) : null,
+ enabled ? taskKeys.scheduledList(ALL_AGENTS_LIST_KEY, 'all', limit, offset) : null,
async () =>
- this.fetchTaskList({ automated: true, hasGoal: false, limit, orderBy: 'updatedAt' }),
- {
- onSuccess: (data: { data: TaskListItem[]; total: number }) => {
- this.#set(
- {
- isScheduledTaskListInit: true,
- scheduledTasks: data.data,
- scheduledTasksTotal: data.total,
- },
- false,
- 'useFetchScheduledTaskList/onSuccess',
- );
- },
- revalidateOnFocus: false,
- },
+ this.fetchTaskList({
+ automated: true,
+ hasGoal: false,
+ limit,
+ offset,
+ orderBy: 'updatedAt',
+ }),
+ { revalidateOnFocus: false },
);
};
diff --git a/src/store/task/slices/list/initialState.ts b/src/store/task/slices/list/initialState.ts
index 28e67ab0c09..003551df322 100644
--- a/src/store/task/slices/list/initialState.ts
+++ b/src/store/task/slices/list/initialState.ts
@@ -15,7 +15,7 @@ export type TaskGroupItem = Awaited<ReturnType<typeof taskService.groupList>>['d
export type TaskListVisibilityFilter = 'all' | 'private' | 'workspace';
export interface TaskListSliceState {
- isScheduledTaskListInit: boolean;
+ groupListQueryAutomated?: boolean;
isTaskGroupListInit: boolean;
isTaskListInit: boolean;
listAgentId?: string;
@@ -38,22 +38,17 @@ export interface TaskListSliceState {
/** Defaults to 'all' so the Tasks top entry shows every visible task
* (private + workspace-shared) without narrowing. */
listVisibility: TaskListVisibilityFilter;
- /** Tasks driven by a schedule or heartbeat — a separate query from `tasks`. */
- scheduledTasks: TaskListItem[];
- scheduledTasksTotal: number;
taskGroups: TaskGroupItem[];
tasks: TaskListItem[];
tasksTotal: number;
}
export const initialTaskListSliceState: TaskListSliceState = {
- isScheduledTaskListInit: false,
isTaskGroupListInit: false,
isTaskListInit: false,
+ groupListQueryAutomated: undefined,
listQueryVisibility: 'all',
listVisibility: 'all',
- scheduledTasks: [],
- scheduledTasksTotal: 0,
taskGroups: [],
tasks: [],
tasksTotal: 0,