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(home): task-shaped task mode, with a scheduled-tasks block (#18173)

Arvin Xu91919550877c
diff --git a/apps/server/src/routers/lambda/task.ts b/apps/server/src/routers/lambda/task.ts
index 19283392339..4cb6f4e20e3 100644
--- a/apps/server/src/routers/lambda/task.ts
+++ b/apps/server/src/routers/lambda/task.ts
@@ -105,9 +105,15 @@ const updateSchema = z.object({
const listSchema = z.object({
assigneeAgentId: z.string().optional(),
+ // true → only tasks whose schedule or heartbeat can still fire (a terminal or
+ // misconfigured one cannot), false → its exact complement. Omitted leaves the
+ // set unnarrowed.
+ automated: z.boolean().optional(),
hasGoal: z.boolean().optional(),
limit: z.number().min(1).max(100).default(50),
offset: z.number().min(0).default(0),
+ // Which timestamp orders the page, newest first. Defaults to creation time.
+ orderBy: z.enum(['createdAt', 'updatedAt']).optional(),
parentIdentifier: z.string().optional(),
parentTaskId: z.string().nullish(),
priorities: z.array(z.number().min(0).max(4)).max(5).optional(),
diff --git a/locales/en-US/home.json b/locales/en-US/home.json
index 2910f9a3c40..2f10cb4d323 100644
--- a/locales/en-US/home.json
+++ b/locales/en-US/home.json
@@ -48,9 +48,10 @@
"dashboard.chat.running": "Running topics",
"dashboard.customize.decrease": "Decrease {{label}}",
"dashboard.customize.entry": "Customize",
- "dashboard.customize.group.decoration": "Decoration",
+ "dashboard.customize.group.agent": "Agent",
"dashboard.customize.group.listSize": "List size",
- "dashboard.customize.group.sections": "Sections",
+ "dashboard.customize.group.rail": "Sidebar",
+ "dashboard.customize.group.task": "Tasks",
"dashboard.customize.increase": "Increase {{label}}",
"dashboard.customize.portrait.desc": "Show your agent portrait beside the top of Home.",
"dashboard.customize.portrait.title": "Portrait decoration",
@@ -60,15 +61,16 @@
"dashboard.customize.preset.minimal.title": "Minimal",
"dashboard.customize.recents.count.title": "Recent threads",
"dashboard.customize.reset": "Reset to defaults",
- "dashboard.customize.tasks.count.title": "Tasks",
+ "dashboard.customize.tasks.count.title": "Recent tasks",
"dashboard.customize.title": "Customize Home",
"dashboard.customize.widget.goals": "Goals",
"dashboard.customize.widget.needsYou": "Needs you",
"dashboard.customize.widget.news": "News",
"dashboard.customize.widget.recents": "Recent threads",
"dashboard.customize.widget.running": "Running",
+ "dashboard.customize.widget.scheduledTasks": "Scheduled tasks",
"dashboard.customize.widget.suggestions": "Suggestions",
- "dashboard.customize.widget.tasks": "Tasks",
+ "dashboard.customize.widget.tasks": "Recent tasks",
"dashboard.customize.widget.unread": "Unread",
"dashboard.empty.plan.description": "Break an outcome into clear next steps",
"dashboard.empty.plan.prompt": "Help me create a practical plan for:",
@@ -95,10 +97,12 @@
"dashboard.placeholder.task": "Describe a task to start right away",
"dashboard.rail.hide": "Hide activity",
"dashboard.rail.show": "Show activity",
+ "dashboard.scheduledTask.title": "Scheduled tasks",
"dashboard.submitFailed": "Could not submit. Your draft has been kept.",
"dashboard.task.empty": "No tasks yet",
- "dashboard.task.title": "Tasks",
+ "dashboard.task.title": "Recent tasks",
"dashboard.task.unsupportedContext": "Task mode does not support attachments or selected context yet. Remove them or switch to Agent mode; your draft has been kept.",
+ "dashboard.task.viewAll": "View all",
"homePromoBanner.cta": "Try now",
"homePromoBanner.dismiss": "Dismiss",
"homePromoBanner.label": "{{model}} is now available",
diff --git a/locales/zh-CN/home.json b/locales/zh-CN/home.json
index 9f5c15b7a41..860d7790535 100644
--- a/locales/zh-CN/home.json
+++ b/locales/zh-CN/home.json
@@ -48,9 +48,10 @@
"dashboard.chat.running": "正在运行",
"dashboard.customize.decrease": "减少{{label}}",
"dashboard.customize.entry": "自定义",
- "dashboard.customize.group.decoration": "装饰",
+ "dashboard.customize.group.agent": "Agent",
"dashboard.customize.group.listSize": "列表条数",
- "dashboard.customize.group.sections": "区块",
+ "dashboard.customize.group.rail": "侧边栏",
+ "dashboard.customize.group.task": "任务",
"dashboard.customize.increase": "增加{{label}}",
"dashboard.customize.portrait.desc": "在首页顶部旁显示你的智能体形象。",
"dashboard.customize.portrait.title": "形象装饰",
@@ -60,15 +61,16 @@
"dashboard.customize.preset.minimal.title": "精简",
"dashboard.customize.recents.count.title": "最近话题",
"dashboard.customize.reset": "恢复默认",
- "dashboard.customize.tasks.count.title": "任务",
+ "dashboard.customize.tasks.count.title": "最近任务",
"dashboard.customize.title": "自定义首页",
"dashboard.customize.widget.goals": "目标",
"dashboard.customize.widget.needsYou": "需要你处理",
"dashboard.customize.widget.news": "今日简报",
"dashboard.customize.widget.recents": "最近话题",
"dashboard.customize.widget.running": "进行中",
+ "dashboard.customize.widget.scheduledTasks": "定时任务",
"dashboard.customize.widget.suggestions": "推荐",
- "dashboard.customize.widget.tasks": "任务",
+ "dashboard.customize.widget.tasks": "最近任务",
"dashboard.customize.widget.unread": "未读",
"dashboard.empty.plan.description": "把目标拆解为清晰、可执行的下一步",
"dashboard.empty.plan.prompt": "帮我为以下目标制定一份切实可行的计划:",
@@ -95,10 +97,12 @@
"dashboard.placeholder.task": "描述要立即开始的任务",
"dashboard.rail.hide": "隐藏动态",
"dashboard.rail.show": "显示动态",
+ "dashboard.scheduledTask.title": "定时任务",
"dashboard.submitFailed": "提交失败,草稿已保留。",
"dashboard.task.empty": "暂无任务",
- "dashboard.task.title": "任务",
+ "dashboard.task.title": "最近任务",
"dashboard.task.unsupportedContext": "任务模式暂不支持附件或已选上下文。请移除它们或切换到 Agent 模式;草稿已保留。",
+ "dashboard.task.viewAll": "查看全部",
"homePromoBanner.cta": "立即体验",
"homePromoBanner.dismiss": "关闭",
"homePromoBanner.label": "{{model}} 现已上线",
diff --git a/packages/database/src/models/__tests__/task.test.ts b/packages/database/src/models/__tests__/task.test.ts
index bda552673a2..529a0f2e7fd 100644
--- a/packages/database/src/models/__tests__/task.test.ts
+++ b/packages/database/src/models/__tests__/task.test.ts
@@ -1,5 +1,5 @@
// @vitest-environment node
-import { eq } from 'drizzle-orm';
+import { eq, sql } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
@@ -341,6 +341,95 @@ describe('TaskModel', () => {
expect(total).toBe(5);
expect(tasks).toHaveLength(2);
});
+
+ // The tick services refuse these three shapes, so a roll-up that lists them
+ // as schedules is listing things that will never fire — and in a bounded
+ // list they push out the ones that will.
+ it('should leave out automation the runtime would refuse to fire', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const live = await model.create({
+ automationMode: 'schedule',
+ instruction: 'Nightly digest',
+ schedulePattern: '0 9 * * *',
+ });
+ const noPattern = await model.create({
+ automationMode: 'schedule',
+ instruction: 'Schedule with its pattern cleared',
+ });
+ const noInterval = await model.create({
+ automationMode: 'heartbeat',
+ heartbeatInterval: 0,
+ instruction: 'Heartbeat with its interval cleared',
+ });
+ const done = await model.create({
+ automationMode: 'schedule',
+ instruction: 'Completed but still carries its cron',
+ schedulePattern: '0 9 * * *',
+ });
+ await model.updateStatus(done.id, 'completed');
+
+ const automated = await model.list({ automated: true });
+ expect(automated.tasks.map((t) => t.id)).toEqual([live.id]);
+
+ // Complementary, so nothing falls into neither bucket.
+ const manual = await model.list({ automated: false });
+ expect(manual.tasks.map((t) => t.id).sort()).toEqual(
+ [noPattern.id, noInterval.id, done.id].sort(),
+ );
+ });
+
+ it('should order by last activity when asked, not by creation', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const older = await model.create({ instruction: 'Created first, touched last' });
+ const newer = await model.create({ instruction: 'Created second, never touched' });
+
+ // Stamp `updated_at` rather than letting `update()` do it. Inserts take
+ // their timestamp from Postgres `now()` while `update()` writes a Node
+ // `new Date()`, so asserting on a real edit races the database clock
+ // against the host's — which is stable enough to pass alone and flips
+ // under a loaded full-suite run. The column under test is the ORDER BY,
+ // not who wrote the value.
+ const stamp = async (id: string, iso: string) => {
+ await serverDB.execute(sql`update tasks set updated_at = ${iso} where id = ${id}`);
+ };
+ await stamp(newer.id, '2026-01-01T00:00:00Z');
+ await stamp(older.id, '2026-06-01T00:00:00Z');
+
+ const order = async (params: Parameters<TaskModel['list']>[0]) => {
+ const { tasks: rows } = await model.list(params);
+ // Only these two rows: the assertion is about their relative order.
+ return rows.map((t) => t.id).filter((id) => id === older.id || id === newer.id);
+ };
+
+ expect(await order({})).toEqual([newer.id, older.id]);
+ expect(await order({ orderBy: 'updatedAt' })).toEqual([older.id, newer.id]);
+ });
+
+ it('should split automated tasks from manual ones', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const cron = await model.create({
+ automationMode: 'schedule',
+ instruction: 'Nightly digest',
+ schedulePattern: '0 9 * * *',
+ });
+ const heartbeat = await model.create({
+ automationMode: 'heartbeat',
+ heartbeatInterval: 3600,
+ instruction: 'Keep watching',
+ });
+ const manual = await model.create({ instruction: 'One-off' });
+
+ const automated = await model.list({ automated: true });
+ expect(automated.total).toBe(2);
+ expect(automated.tasks.map((t) => t.id).sort()).toEqual([cron.id, heartbeat.id].sort());
+
+ const notAutomated = await model.list({ automated: false });
+ expect(notAutomated.total).toBe(1);
+ expect(notAutomated.tasks[0].id).toBe(manual.id);
+
+ // Omitting the flag must not narrow anything.
+ expect((await model.list()).total).toBe(3);
+ });
});
describe('groupList', () => {
diff --git a/packages/database/src/models/task.ts b/packages/database/src/models/task.ts
index 2c342fa506a..6d502160ddd 100644
--- a/packages/database/src/models/task.ts
+++ b/packages/database/src/models/task.ts
@@ -12,6 +12,7 @@ import {
and,
desc,
eq,
+ gt,
gte,
inArray,
isNotNull,
@@ -58,6 +59,32 @@ import { buildWorkspaceWhere } from '../utils/workspace';
* workspace_id IS NULL` for all four helpers — visibility is inert because
* everything personal is implicitly owner-only.
*/
+/**
+ * A task the automation runtime would still act on.
+ *
+ * `automation_mode` alone does not mean "this fires". The tick services refuse
+ * to run on exactly these grounds — `scheduleTick` skips a schedule with no
+ * cron pattern, `heartbeatTick` skips a heartbeat with no positive interval,
+ * and both skip a task that has reached a terminal status. A row that keeps its
+ * mode after being completed, canceled or stripped of its pattern is a
+ * leftover, not a schedule, and listing it as one lets dead entries crowd real
+ * ones out of a bounded roll-up.
+ *
+ * Kept as one expression so the `automated` filter's two sides stay exact
+ * complements and no row falls into neither bucket.
+ */
+const RUNNABLE_AUTOMATION = and(
+ notInArray(tasks.status, ['canceled', 'completed', 'failed']),
+ or(
+ and(
+ eq(tasks.automationMode, 'schedule'),
+ isNotNull(tasks.schedulePattern),
+ ne(tasks.schedulePattern, ''),
+ ),
+ and(eq(tasks.automationMode, 'heartbeat'), gt(tasks.heartbeatInterval, 0)),
+ ),
+)!;
+
export class TaskModel {
private readonly userId: string;
private readonly db: LobeChatDatabase;
@@ -599,9 +626,21 @@ export class TaskModel {
async list(options?: {
assigneeAgentId?: string;
+ /**
+ * Narrow to tasks that still run on their own — see {@link RUNNABLE_AUTOMATION}
+ * for what "still" rules out. `false` is its exact complement.
+ */
+ automated?: boolean;
hasGoal?: boolean;
limit?: number;
offset?: number;
+ /**
+ * Which timestamp the (bounded) result is ordered by, newest first.
+ * `createdAt` is the default because most callers want a stable list;
+ * a surface that calls itself "recent" wants `updatedAt`, or its page
+ * would omit the task that just moved in favour of a newer, idle one.
+ */
+ orderBy?: 'createdAt' | 'updatedAt';
parentTaskId?: string | null;
priorities?: number[];
statuses?: string[];
@@ -617,10 +656,12 @@ export class TaskModel {
priorities,
parentTaskId,
assigneeAgentId,
+ automated,
hasGoal,
visibility,
limit = 50,
offset = 0,
+ orderBy = 'createdAt',
} = options || {};
const conditions = [this.ownership()];
@@ -628,6 +669,12 @@ export class TaskModel {
if (statuses?.length) conditions.push(inArray(tasks.status, statuses));
if (priorities?.length) conditions.push(inArray(tasks.priority, priorities));
if (assigneeAgentId) conditions.push(eq(tasks.assigneeAgentId, assigneeAgentId));
+ if (automated === true) conditions.push(RUNNABLE_AUTOMATION);
+ // `IS NOT TRUE`, not `NOT (…)`: a manual task has a NULL `automation_mode`,
+ // so the predicate evaluates to NULL rather than false, and `NOT NULL` is
+ // still NULL — which WHERE drops. That would make `automated: false` return
+ // nothing at all for exactly the rows it is meant to return.
+ if (automated === false) conditions.push(sql`${RUNNABLE_AUTOMATION} IS NOT TRUE`);
if (hasGoal === true) conditions.push(sql`COALESCE(${tasks.config} ->> 'goal', '') <> ''`);
if (hasGoal === false) conditions.push(sql`COALESCE(${tasks.config} ->> 'goal', '') = ''`);
if (visibility) conditions.push(eq(tasks.visibility, visibility));
@@ -649,7 +696,7 @@ export class TaskModel {
.select()
.from(tasks)
.where(where)
- .orderBy(desc(tasks.createdAt))
+ .orderBy(desc(orderBy === 'updatedAt' ? tasks.updatedAt : tasks.createdAt))
.limit(limit)
.offset(offset);
diff --git a/packages/locales/src/default/home.ts b/packages/locales/src/default/home.ts
index 3d15e64a329..78d051ea4d0 100644
--- a/packages/locales/src/default/home.ts
+++ b/packages/locales/src/default/home.ts
@@ -53,9 +53,10 @@ export default {
'dashboard.chat.running': 'Running topics',
'dashboard.customize.decrease': 'Decrease {{label}}',
'dashboard.customize.entry': 'Customize',
- 'dashboard.customize.group.decoration': 'Decoration',
'dashboard.customize.group.listSize': 'List size',
- 'dashboard.customize.group.sections': 'Sections',
+ 'dashboard.customize.group.agent': 'Agent',
+ 'dashboard.customize.group.rail': 'Sidebar',
+ 'dashboard.customize.group.task': 'Tasks',
'dashboard.customize.increase': 'Increase {{label}}',
'dashboard.customize.portrait.desc': 'Show your agent portrait beside the top of Home.',
'dashboard.customize.portrait.title': 'Portrait decoration',
@@ -65,15 +66,16 @@ export default {
'dashboard.customize.preset.minimal.title': 'Minimal',
'dashboard.customize.recents.count.title': 'Recent threads',
'dashboard.customize.reset': 'Reset to defaults',
- 'dashboard.customize.tasks.count.title': 'Tasks',
+ 'dashboard.customize.tasks.count.title': 'Recent tasks',
'dashboard.customize.title': 'Customize Home',
'dashboard.customize.widget.goals': 'Goals',
'dashboard.customize.widget.needsYou': 'Needs you',
'dashboard.customize.widget.news': 'News',
'dashboard.customize.widget.recents': 'Recent threads',
'dashboard.customize.widget.running': 'Running',
+ 'dashboard.customize.widget.scheduledTasks': 'Scheduled tasks',
'dashboard.customize.widget.suggestions': 'Suggestions',
- 'dashboard.customize.widget.tasks': 'Tasks',
+ 'dashboard.customize.widget.tasks': 'Recent tasks',
'dashboard.customize.widget.unread': 'Unread',
'dashboard.empty.plan.description': 'Break an outcome into clear next steps',
'dashboard.empty.plan.prompt': 'Help me create a practical plan for:',
@@ -101,9 +103,11 @@ export default {
'dashboard.placeholder.task': 'Describe a task to start right away',
'dashboard.rail.hide': 'Hide activity',
'dashboard.rail.show': 'Show activity',
+ 'dashboard.scheduledTask.title': 'Scheduled tasks',
'dashboard.submitFailed': 'Could not submit. Your draft has been kept.',
'dashboard.task.empty': 'No tasks yet',
- 'dashboard.task.title': 'Tasks',
+ 'dashboard.task.title': 'Recent tasks',
+ 'dashboard.task.viewAll': 'View all',
'dashboard.task.unsupportedContext':
'Task mode does not support attachments or selected context yet. Remove them or switch to Agent mode; your draft has been kept.',
'inbox.author.scheduled': 'Scheduled',
diff --git a/src/features/Home/CustomizeModal/Content.tsx b/src/features/Home/CustomizeModal/Content.tsx
index 8ad45af8809..14b6b894cde 100644
--- a/src/features/Home/CustomizeModal/Content.tsx
+++ b/src/features/Home/CustomizeModal/Content.tsx
@@ -10,7 +10,7 @@ import { useTranslation } from 'react-i18next';
import CountStepper from './components/CountStepper';
import PresetBar from './components/PresetBar';
import SettingRow from './components/SettingRow';
-import { HOME_COUNT_MAX, HOME_COUNT_MIN, HOME_WIDGET_KEYS } from './config';
+import { HOME_COUNT_MAX, HOME_COUNT_MIN, HOME_WIDGET_GROUPS } from './config';
import { useHomeCustomization } from './useHomeCustomization';
const styles = createStaticStyles(({ css, cssVar }) => ({
@@ -73,36 +73,42 @@ const CustomizeModalContent = memo(() => {
<PresetBar value={preset} onChange={applyPreset} />
</SettingRow>
- <Flexbox gap={12}>
- <Text fontSize={12} type={'secondary'} weight={600}>
- {t('dashboard.customize.group.decoration')}
- </Text>
- <SettingRow
- description={t('dashboard.customize.portrait.desc')}
- title={t('dashboard.customize.portrait.title')}
- >
- <Switch
- aria-label={t('dashboard.customize.portrait.title')}
- checked={showPortrait}
- onChange={togglePortrait}
- />
- </SettingRow>
- </Flexbox>
+ {/* No heading: the groups below name parts of the page, and a heading
+ over this single row would promise a category that has one member
+ and no page to point at. Its own label and description say enough. */}
+ <SettingRow
+ description={t('dashboard.customize.portrait.desc')}
+ title={t('dashboard.customize.portrait.title')}
+ >
+ <Switch
+ aria-label={t('dashboard.customize.portrait.title')}
+ checked={showPortrait}
+ size={'small'}
+ onChange={togglePortrait}
+ />
+ </SettingRow>
- <Flexbox gap={12}>
- <Text fontSize={12} type={'secondary'} weight={600}>
- {t('dashboard.customize.group.sections')}
- </Text>
- {HOME_WIDGET_KEYS.map((key) => (
- <SettingRow key={key} title={t(`dashboard.customize.widget.${key}`)}>
- <Switch
- aria-label={t(`dashboard.customize.widget.${key}`)}
- checked={!isWidgetHidden(key)}
- onChange={() => toggleWidget(key)}
- />
- </SettingRow>
- ))}
- </Flexbox>
+ {HOME_WIDGET_GROUPS.map((group) => (
+ <Flexbox gap={12} key={group.key}>
+ <Text fontSize={12} type={'secondary'} weight={600}>
+ {t(`dashboard.customize.group.${group.key}`)}
+ </Text>
+ {group.widgets.map((key) => (
+ <SettingRow key={key} title={t(`dashboard.customize.widget.${key}`)}>
+ <Switch
+ aria-label={t(`dashboard.customize.widget.${key}`)}
+ checked={!isWidgetHidden(key)}
+ // The scheduled block is the second half of the task overview,
+ // so there is nothing for it to switch on while the first half
+ // is off.
+ disabled={key === 'scheduledTasks' && isWidgetHidden('tasks')}
+ size={'small'}
+ onChange={() => toggleWidget(key)}
+ />
+ </SettingRow>
+ ))}
+ </Flexbox>
+ ))}
<Flexbox gap={12}>
<Text fontSize={12} type={'secondary'} weight={600}>
diff --git a/src/features/Home/CustomizeModal/config.ts b/src/features/Home/CustomizeModal/config.ts
index c44d673a4e3..8af6f9f0da3 100644
--- a/src/features/Home/CustomizeModal/config.ts
+++ b/src/features/Home/CustomizeModal/config.ts
@@ -11,11 +11,40 @@ export const HOME_INBOX_WIDGET_KEYS = [
'suggestions',
] as const;
-export const HOME_WIDGET_KEYS = [...HOME_INBOX_WIDGET_KEYS, 'recents', 'tasks'] as const;
+export const HOME_WIDGET_KEYS = [
+ ...HOME_INBOX_WIDGET_KEYS,
+ 'recents',
+ 'tasks',
+ 'scheduledTasks',
+] as const;
export type HomeInboxWidgetKey = (typeof HOME_INBOX_WIDGET_KEYS)[number];
export type HomeWidgetKey = (typeof HOME_WIDGET_KEYS)[number];
+/**
+ * A flat list of nine switches makes the reader hold the whole page in their
+ * head to find one section. The grouping that lets you find one without
+ * reading them all is **where the section sits on Home** — you already know
+ * which part of the page you want less of, so the panel is read by pointing at
+ * it rather than by recalling a category name.
+ *
+ * That makes membership a fact about the page, not a taste call: the main
+ * column carries the agent feeds and the two task blocks, and the rail carries
+ * goals, running, news and suggestions (`RAIL_INBOX_PROPS` hides needs-you and
+ * unread from the rail; `ownsRailSections` decides the rest). A widget that
+ * moves columns must move groups with it.
+ *
+ * The order inside each group follows the page top-down, so scanning the panel
+ * and scanning Home walk the same path.
+ */
+export const HOME_WIDGET_GROUPS = [
+ { key: 'agent', widgets: ['recents', 'unread', 'needsYou'] },
+ { key: 'task', widgets: ['tasks', 'scheduledTasks'] },
+ { key: 'rail', widgets: ['goals', 'running', 'news', 'suggestions'] },
+] as const satisfies ReadonlyArray<{ key: string; widgets: readonly HomeWidgetKey[] }>;
+
+export type HomeWidgetGroupKey = (typeof HOME_WIDGET_GROUPS)[number]['key'];
+
export const HOME_CUSTOMIZE_DEFAULTS = {
hiddenHomeWidgets: [] as string[],
homeRecentsCount: 8,
@@ -54,8 +83,19 @@ interface HomeVisibilityState {
showPortrait: boolean;
}
+/**
+ * `scheduledTasks` rides on `tasks`: the two are one task overview split in
+ * half, so switching the main list off must not leave the other half standing
+ * under a different heading. It also keeps settings saved before this key
+ * existed meaningful — a stored "minimal" selection lists every widget that
+ * existed then, and without this fallback those pages would silently grow a
+ * section back and drop out of their preset.
+ */
+export const isHomeWidgetHidden = (key: HomeWidgetKey, hiddenWidgets: string[]): boolean =>
+ hiddenWidgets.includes(key) || (key === 'scheduledTasks' && hiddenWidgets.includes('tasks'));
+
const hiddenKeySet = ({ hiddenWidgets }: HomeVisibilityState): Set<string> =>
- new Set(HOME_WIDGET_KEYS.filter((key) => hiddenWidgets.includes(key)));
+ new Set(HOME_WIDGET_KEYS.filter((key) => isHomeWidgetHidden(key, hiddenWidgets)));
export const resolveHomePreset = (state: HomeVisibilityState): HomePresetKey | undefined => {
const hidden = hiddenKeySet(state);
@@ -75,7 +115,8 @@ export const resolveHomePreset = (state: HomeVisibilityState): HomePresetKey | u
// dashboard: the greeting and the composer become one centered block. Derived
// from the switches rather than stored, so it can never disagree with them.
export const isHomeMinimalLayout = (state: HomeVisibilityState): boolean =>
- !state.showPortrait && HOME_WIDGET_KEYS.every((key) => state.hiddenWidgets.includes(key));
+ !state.showPortrait &&
+ HOME_WIDGET_KEYS.every((key) => isHomeWidgetHidden(key, state.hiddenWidgets));
// An error banner covers every widget whose content it reports on, not just the
// one it is named after: the topic feed powers unread AND running, and the briefs
diff --git a/src/features/Home/CustomizeModal/useHomeCustomization.test.ts b/src/features/Home/CustomizeModal/useHomeCustomization.test.ts
index dc5179f2b70..27187477e49 100644
--- a/src/features/Home/CustomizeModal/useHomeCustomization.test.ts
+++ b/src/features/Home/CustomizeModal/useHomeCustomization.test.ts
@@ -2,8 +2,10 @@ import { describe, expect, it } from 'vitest';
import {
HOME_PRESETS,
+ HOME_WIDGET_GROUPS,
HOME_WIDGET_KEYS,
isHomeMinimalLayout,
+ isHomeWidgetHidden,
isWidgetSectionVisible,
resolveHomePreset,
} from './config';
@@ -98,6 +100,54 @@ describe('isHomeMinimalLayout', () => {
});
});
+describe('HOME_WIDGET_GROUPS', () => {
+ const grouped = HOME_WIDGET_GROUPS.flatMap((group) => group.widgets);
+
+ it('gives every widget exactly one group, so none can fall out of the panel', () => {
+ expect([...grouped].sort()).toEqual([...HOME_WIDGET_KEYS].sort());
+ });
+
+ // The groups name where a section sits on Home, so membership is a fact about
+ // the page rather than a taste call. `RAIL_INBOX_PROPS` keeps needs-you and
+ // unread out of the rail, and `ownsRailSections` gives running / news /
+ // suggestions to it; goals renders in the rail card. Move a section between
+ // columns and this test is the thing that says the panel now lies.
+ it.each([
+ ['agent', ['recents', 'unread', 'needsYou']],
+ ['task', ['tasks', 'scheduledTasks']],
+ ['rail', ['goals', 'running', 'news', 'suggestions']],
+ ])('groups %s by where those sections render on Home', (key, widgets) => {
+ expect(HOME_WIDGET_GROUPS.find((group) => group.key === key)?.widgets).toEqual(widgets);
+ });
+});
+
+describe('isHomeWidgetHidden', () => {
+ // Everything a minimal-preset page stored before the scheduled block existed.
+ const LEGACY_ALL_HIDDEN = HOME_WIDGET_KEYS.filter((key) => key !== 'scheduledTasks');
+
+ it('hides the scheduled block along with the task list it belongs to', () => {
+ expect(isHomeWidgetHidden('scheduledTasks', ['tasks'])).toBe(true);
+ });
+
+ it('lets the scheduled block be switched off on its own', () => {
+ expect(isHomeWidgetHidden('scheduledTasks', ['scheduledTasks'])).toBe(true);
+ expect(isHomeWidgetHidden('tasks', ['scheduledTasks'])).toBe(false);
+ });
+
+ it('leaves both on when neither is listed', () => {
+ expect(isHomeWidgetHidden('scheduledTasks', ['news'])).toBe(false);
+ });
+
+ it('does not grow a section back onto a page saved before the key existed', () => {
+ expect(resolveHomePreset({ hiddenWidgets: LEGACY_ALL_HIDDEN, showPortrait: false })).toBe(
+ 'minimal',
+ );
+ expect(isHomeMinimalLayout({ hiddenWidgets: LEGACY_ALL_HIDDEN, showPortrait: false })).toBe(
+ true,
+ );
+ });
+});
+
describe('isWidgetSectionVisible', () => {
it('hides a loading section governed by a hidden widget', () => {
expect(isWidgetSectionVisible('needsYou-loading', ['needsYou'])).toBe(false);
diff --git a/src/features/Home/CustomizeModal/useHomeCustomization.ts b/src/features/Home/CustomizeModal/useHomeCustomization.ts
index 310c2191b55..f0162d62009 100644
--- a/src/features/Home/CustomizeModal/useHomeCustomization.ts
+++ b/src/features/Home/CustomizeModal/useHomeCustomization.ts
@@ -11,6 +11,7 @@ import {
type HomePresetKey,
type HomeWidgetKey,
isHomeMinimalLayout,
+ isHomeWidgetHidden,
resolveHomePreset,
} from './config';
@@ -99,7 +100,7 @@ export const useHomeCustomization = (): HomeCustomization => {
}, [updateSystemStatus]);
const isWidgetHidden = useCallback(
- (key: HomeWidgetKey) => hiddenWidgets.includes(key),
+ (key: HomeWidgetKey) => isHomeWidgetHidden(key, hiddenWidgets),
[hiddenWidgets],
);
diff --git a/src/features/Home/HomeModeContent.tsx b/src/features/Home/HomeModeContent.tsx
index 8f11b180967..d4602e4fd61 100644
--- a/src/features/Home/HomeModeContent.tsx
+++ b/src/features/Home/HomeModeContent.tsx
@@ -10,7 +10,9 @@ import { useTranslation } from 'react-i18next';
import { useWorkspaceMemberProfiles } from '@/business/client/hooks/useWorkspaceMemberProfiles';
import AsyncError from '@/components/AsyncError';
+import AssigneeAvatar from '@/features/AgentTasks/features/AssigneeAvatar';
import TaskStatusIcon from '@/features/AgentTasks/features/TaskStatusIcon';
+import TaskTriggerTag from '@/features/AgentTasks/features/TaskTriggerTag';
import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';
import { useAgentDisplayMeta } from '@/features/AgentTasks/shared/useAgentDisplayMeta';
import HomeInbox from '@/features/HomeInbox';
@@ -31,6 +33,7 @@ import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { useTaskStore } from '@/store/task';
import { taskListSelectors } from '@/store/task/selectors';
+import type { TaskListItem } from '@/store/task/slices/list/initialState';
import { useUserStore } from '@/store/user';
import { authSelectors, userProfileSelectors } from '@/store/user/slices/auth/selectors';
import { markdownToTxt } from '@/utils/markdownToTxt';
@@ -38,6 +41,7 @@ import { markdownToTxt } from '@/utils/markdownToTxt';
import GroupBlock from './components/GroupBlock';
import { homeType } from './components/homeType';
import Time from './components/Time';
+import { isHomeWidgetHidden } from './CustomizeModal/config';
import EmptySuggestions from './EmptySuggestions';
import { resolveHomeChatContentState } from './homeChatContentState';
import type { HomeMode } from './types';
@@ -52,6 +56,18 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
padding-block: 16px;
color: ${cssVar.colorTextTertiary};
`,
+ blockAction: css`
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ text-decoration: none;
+
+ &:hover {
+ color: ${cssVar.colorText};
+ }
+ `,
+ identifier: css`
+ flex: none;
+ `,
row: css`
border-radius: ${cssVar.borderRadiusLG};
color: inherit;
@@ -99,6 +115,8 @@ interface RowProps {
href: string;
icon: ReactNode;
title: ReactNode;
+ /** Sits on the title's own line, after it — an identifier, a badge. */
+ titleExtra?: ReactNode;
trailing?: ReactNode;
}
@@ -113,22 +131,51 @@ const TASK_STATUSES = new Set<TaskStatus>([
]);
export const HOME_TOPIC_RECENT_LIMIT = 15;
+const FLEX_MIN_WIDTH_0 = { minWidth: 0 };
+
export const resolveRecentsBadgeCount = (fetched: number, shown: number): number | undefined =>
Math.min(fetched, shown) || undefined;
+/**
+ * The one line a task row shows under its name. `instruction` is what the task
+ * was actually asked to do, so it is the line worth reading; `description` is
+ * the summary that only some tasks carry. Both are markdown, and a row is one
+ * line — its syntax markers are just noise here.
+ *
+ * A task created straight from the composer takes its name from its
+ * instruction, so the two would print the same sentence twice. When they agree,
+ * the row keeps the name alone rather than repeating it in a quieter colour.
+ */
+export const resolveTaskSummaryLine = (
+ { description, instruction }: { description?: string | null; instruction?: string | null },
+ title: string,
+): string | undefined => {
+ const raw = instruction?.trim() || description?.trim();
+ if (!raw) return undefined;
+
+ const line = markdownToTxt(raw).replaceAll(/\s+/g, ' ').trim();
+
+ return !line || line === title.trim() ? undefined : line;
+};
+
const normalizeTaskStatus = (status: string): TaskStatus =>
TASK_STATUSES.has(status as TaskStatus) ? (status as TaskStatus) : 'backlog';
-const Row = memo<RowProps>(({ description, href, icon, title, trailing }) => (
+const Row = memo<RowProps>(({ description, href, icon, title, titleExtra, trailing }) => (
<WorkspaceLink className={cx(styles.rowBox, styles.row)} to={href}>
<Flexbox horizontal align={'flex-start'} gap={12}>
<Flexbox flex={'none'} paddingBlock={3}>
{icon}
</Flexbox>
<Flexbox className={styles.rowText} gap={3}>
- <Text ellipsis className={homeType.itemTitle}>
- {title}
- </Text>
+ {/* The name takes the space and truncates; anything after it keeps its
+ full width, so an identifier stays readable however long the name is. */}
+ <Flexbox horizontal align={'center'} gap={8} style={FLEX_MIN_WIDTH_0}>
+ <Text ellipsis className={homeType.itemTitle}>
+ {title}
+ </Text>
+ {titleExtra}
+ </Flexbox>
{description && (
<Text className={cx(homeType.supporting, styles.description)}>{description}</Text>
)}
@@ -238,37 +285,143 @@ const LoadingRows = memo<{ avatarSize?: number; withTime?: boolean }>(
),
);
+/**
+ * A task in the home list carries the same right-hand read as the Tasks page:
+ * how it is triggered, who runs it, when it last moved. Without that a task row
+ * is indistinguishable from a topic row, and the section reads as another feed
+ * rather than as work with an owner.
+ */
+const TaskRow = memo<{ task: TaskListItem }>(({ task }) => {
+ const title = task.name?.trim() || task.identifier;
+ const description = useMemo(() => resolveTaskSummaryLine(task, title), [task, title]);
+
+ return (
+ <Row
+ description={description}
+ href={taskDetailPath(task.identifier)}
+ icon={<TaskStatusIcon size={16} status={normalizeTaskStatus(task.status)} />}
+ title={title}
+ // The identifier is how the task is referred to everywhere else, so it
+ // belongs beside the name rather than in the sentence slot below it.
+ titleExtra={
+ title === task.identifier ? undefined : (
+ <Text className={cx(homeType.meta, styles.identifier)}>{task.identifier}</Text>
+ )
+ }
+ trailing={
+ <Flexbox horizontal align={'center'} flex={'none'} gap={8}>
+ <TaskTriggerTag
+ automationMode={task.automationMode}
+ heartbeatInterval={task.heartbeatInterval}
+ schedulePattern={task.schedulePattern}
+ scheduleTimezone={task.scheduleTimezone}
+ />
+ <AssigneeAvatar agentId={task.assigneeAgentId} size={20} />
+ <Time date={task.updatedAt || task.createdAt} />
+ </Flexbox>
+ }
+ />
+ );
+});
+
const TaskContent = memo(() => {
const { t } = useTranslation('home');
const useFetchTaskList = useTaskStore((s) => s.useFetchTaskList);
// Home is an overview, not a continuation of the Task page's last-used
- // filter. It must always show the complete task set.
- const tasksSWR = useFetchTaskList({ allAgents: true, visibility: 'all' });
+ // filter. It must always show the complete task set — ordered by activity,
+ // because this block calls itself "recent" and prints the same timestamp.
+ const tasksSWR = useFetchTaskList({ allAgents: true, orderBy: 'updatedAt', visibility: 'all' });
const tasks = useTaskStore(taskListSelectors.taskList);
const tasksTotal = useTaskStore(taskListSelectors.taskListTotal);
const tasksInit = useTaskStore(taskListSelectors.isTaskListInit);
const taskCount = useGlobalStore(systemStatusSelectors.homeTaskCount);
+ const shown = tasks.slice(0, taskCount);
return (
- <GroupBlock count={tasksTotal || undefined} title={t('dashboard.task.title')}>
+ <GroupBlock
+ actionAlwaysVisible
+ count={resolveRecentsBadgeCount(tasks.length, taskCount)}
+ title={t('dashboard.task.title')}
+ // The block shows the most recent slice, so the rest needs somewhere to
+ // be: the badge counts what is on screen and this carries the remainder
+ // to the full list, instead of a badge claiming a total you cannot reach.
+ action={
+ tasksTotal > shown.length ? (
+ <WorkspaceLink className={styles.blockAction} to={'/tasks'}>
+ {t('dashboard.task.viewAll')}
+ </WorkspaceLink>
+ ) : undefined
+ }
+ >
{tasksSWR.error && !tasksInit ? (
<AsyncError error={tasksSWR.error} variant={'inline'} onRetry={tasksSWR.mutate} />
) : !tasksInit ? (
- <LoadingRows avatarSize={16} />
+ <LoadingRows withTime avatarSize={16} />
) : tasks.length === 0 ? (
<Text className={styles.empty}>{t('dashboard.task.empty')}</Text>
) : (
<Flexbox gap={4}>
- {tasks.slice(0, taskCount).map((task) => (
- <Row
- description={task.description || task.identifier}
- href={taskDetailPath(task.identifier)}
- icon={<TaskStatusIcon size={16} status={normalizeTaskStatus(task.status)} />}
- key={task.identifier}
- title={task.name || task.identifier}
- />
+ {shown.map((task) => (
+ <TaskRow key={task.identifier} task={task} />
+ ))}
+ </Flexbox>
+ )}
+ </GroupBlock>
+ );
+});
+
+/**
+ * The tasks that run without anyone pressing anything. They are the part of the
+ * task set that keeps moving while you are away, so they get their own block
+ * under the recent ones instead of being scattered through a list ordered by
+ * when they last happened to tick.
+ */
+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);
+
+ // 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
+ // exists once something is actually scheduled — the loading skeleton aside,
+ // which has to hold its place until the answer arrives.
+ //
+ // A failed first fetch is NOT that case: hiding it would make an unreachable
+ // list look exactly like an account with no schedules, and someone whose
+ // automations are running would read a confidently incomplete page. The block
+ // stays and says so, with a retry.
+ const failedFirstLoad = Boolean(scheduledSWR.error) && !scheduledInit;
+ if (scheduledInit && scheduled.length === 0) return null;
+
+ const shown = scheduled.slice(0, taskCount);
+
+ return (
+ <GroupBlock
+ actionAlwaysVisible
+ count={failedFirstLoad ? undefined : resolveRecentsBadgeCount(scheduled.length, taskCount)}
+ title={t('dashboard.scheduledTask.title')}
+ action={
+ !failedFirstLoad && scheduledTotal > shown.length ? (
+ <WorkspaceLink className={styles.blockAction} to={'/tasks'}>
+ {t('dashboard.task.viewAll')}
+ </WorkspaceLink>
+ ) : undefined
+ }
+ >
+ {failedFirstLoad ? (
+ <AsyncError error={scheduledSWR.error} variant={'inline'} onRetry={scheduledSWR.mutate} />
+ ) : scheduledInit ? (
+ <Flexbox gap={4}>
+ {shown.map((task) => (
+ <TaskRow key={task.identifier} task={task} />
))}
</Flexbox>
+ ) : (
+ <LoadingRows withTime avatarSize={16} />
)}
</GroupBlock>
);
@@ -283,6 +436,7 @@ const HomeModeContent = memo<HomeModeContentProps>(({ inlineRail, mode, onSugges
const hiddenWidgets = useGlobalStore(systemStatusSelectors.hiddenHomeWidgets);
const recentsHidden = hiddenWidgets.includes('recents');
const tasksHidden = hiddenWidgets.includes('tasks');
+ const scheduledTasksHidden = isHomeWidgetHidden('scheduledTasks', hiddenWidgets);
const cacheScope = useCacheScope();
// One page-level mine/team scope, shared by the inbox sections and Recent
@@ -406,7 +560,17 @@ const HomeModeContent = memo<HomeModeContentProps>(({ inlineRail, mode, onSugges
if (!isLogin) return null;
if (mode === 'task') {
- if (!inlineRail) return tasksHidden ? null : <TaskContent />;
+ // Recent tasks answer "what is going on"; the scheduled block answers "what
+ // will happen without me" — the second question only makes sense after the
+ // first, so it always sits underneath.
+ const taskBlocks = (
+ <>
+ {!tasksHidden && <TaskContent />}
+ {!scheduledTasksHidden && <ScheduledTaskContent />}
+ </>
+ );
+
+ if (!inlineRail) return <Flexbox gap={32}>{taskBlocks}</Flexbox>;
// The rail's sections sit beside task mode while it is open, so a folded
// rail must not take them away here either: in flight and what happened
@@ -415,7 +579,7 @@ const HomeModeContent = memo<HomeModeContentProps>(({ inlineRail, mode, onSugges
return (
<Flexbox gap={32}>
<HomeInbox hideNeedsYou hideUnread inlineRail variant={'main'} />
- {!tasksHidden && <TaskContent />}
+ {taskBlocks}
<Recommendations variant={'main'} />
</Flexbox>
);
diff --git a/src/features/Home/InputArea/ModeSelect.tsx b/src/features/Home/InputArea/ModeSelect.tsx
index fa57c9437cb..6a9e7b2c899 100644
--- a/src/features/Home/InputArea/ModeSelect.tsx
+++ b/src/features/Home/InputArea/ModeSelect.tsx
@@ -1,7 +1,7 @@
import { Flexbox, Icon } from '@lobehub/ui';
import { Button, Popover } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
-import { ChevronDownIcon, InfinityIcon, MessageCircleIcon } from 'lucide-react';
+import { ChevronDownIcon, InfinityIcon, ListTodoIcon } from 'lucide-react';
import { memo, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -94,9 +94,13 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
}));
+// Task mode carries the same glyph as the sidebar's Tasks entry: picking it
+// here and opening that page are two doors onto one thing, so they must not
+// look like two different features. Agent mode keeps the infinity mark, which
+// is the product's own sign for the open-ended, keeps-going side of the pair.
const MODES = [
- { icon: MessageCircleIcon, key: 'chat' },
- { icon: InfinityIcon, key: 'task' },
+ { icon: InfinityIcon, key: 'chat' },
+ { icon: ListTodoIcon, key: 'task' },
] as const;
interface ModeSelectProps {
diff --git a/src/features/Home/__tests__/taskSummaryLine.test.ts b/src/features/Home/__tests__/taskSummaryLine.test.ts
new file mode 100644
index 00000000000..85208d3375a
--- /dev/null
+++ b/src/features/Home/__tests__/taskSummaryLine.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveTaskSummaryLine } from '../HomeModeContent';
+
+describe('resolveTaskSummaryLine', () => {
+ it('reads the instruction, which is what the task was asked to do', () => {
+ expect(
+ resolveTaskSummaryLine(
+ { description: '一句摘要', instruction: '扫描依赖漏洞并汇总高危项' },
+ '每日依赖安全周检',
+ ),
+ ).toBe('扫描依赖漏洞并汇总高危项');
+ });
+
+ it('falls back to the description when there is no instruction', () => {
+ expect(resolveTaskSummaryLine({ description: '一句摘要', instruction: ' ' }, '任务名')).toBe(
+ '一句摘要',
+ );
+ });
+
+ it('flattens markdown and whitespace into a single line', () => {
+ expect(
+ resolveTaskSummaryLine({ instruction: '# 标题\n\n- **第一步**\n- 第二步' }, '任务名'),
+ ).toBe('标题 第一步 第二步');
+ });
+
+ // A task created from the composer takes its name from its instruction, so
+ // printing both would say the same sentence twice in two colours.
+ it('drops the line when it only repeats the title', () => {
+ expect(resolveTaskSummaryLine({ instruction: '写一首诗' }, '写一首诗')).toBeUndefined();
+ expect(resolveTaskSummaryLine({ instruction: ' 写一首诗 ' }, '写一首诗')).toBeUndefined();
+ });
+
+ it('has nothing to show when both sources are empty', () => {
+ expect(
+ resolveTaskSummaryLine({ description: null, instruction: null }, '任务名'),
+ ).toBeUndefined();
+ });
+});
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 78532114a1f..5d675e37566 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -280,8 +280,23 @@ export const taskKeys = {
homeGoals: def('task:homeGoals', (scope: string) => ['task:homeGoals', scope]),
list: def(
'task:list',
+ (
+ agentKey: string | undefined,
+ visibility: 'all' | 'private' | 'workspace' = 'all',
+ // Part of the key, not a detail: Home orders by activity while the Tasks
+ // page orders by creation, and they read the same store field.
+ orderBy: 'createdAt' | 'updatedAt' = 'createdAt',
+ ) => ['task:list', agentKey, visibility, orderBy],
+ ),
+ /**
+ * Home's automated-task roll-up: the tasks that fire on a schedule or a
+ * heartbeat. Kept off `list` because it is a different result set entirely —
+ * sharing the key would let one section's fetch overwrite the other's.
+ */
+ scheduledList: def(
+ 'task:scheduledList',
(agentKey: string | undefined, visibility: 'all' | 'private' | 'workspace' = 'all') => [
- 'task:list',
+ 'task:scheduledList',
agentKey,
visibility,
],
diff --git a/src/services/task.ts b/src/services/task.ts
index 5e4d9e78daa..573f200530a 100644
--- a/src/services/task.ts
+++ b/src/services/task.ts
@@ -11,7 +11,9 @@ class TaskService {
list = async (params: {
assigneeAgentId?: string;
+ automated?: boolean;
hasGoal?: boolean;
+ orderBy?: 'createdAt' | 'updatedAt';
limit?: number;
offset?: number;
parentIdentifier?: string;
diff --git a/src/store/task/selectors/listSelectors.ts b/src/store/task/selectors/listSelectors.ts
index c8192aa2fca..072fb75768c 100644
--- a/src/store/task/selectors/listSelectors.ts
+++ b/src/store/task/selectors/listSelectors.ts
@@ -7,6 +7,12 @@ 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 viewMode = (s: TaskStoreState) => s.viewMode;
const listVisibility = (s: TaskStoreState) => s.listVisibility;
@@ -47,11 +53,14 @@ 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 ca5f81c87f1..60896435172 100644
--- a/src/store/task/slices/list/action.test.ts
+++ b/src/store/task/slices/list/action.test.ts
@@ -65,7 +65,23 @@ describe('TaskListSliceAction', () => {
await useTaskStore.getState().refreshTaskList();
- expect(mutate).toHaveBeenCalledWith(['task:list', 'agt_1', 'private']);
+ expect(mutate).toHaveBeenCalledWith(['task:list', 'agt_1', 'private', 'createdAt']);
+ });
+
+ // Home reads the same list under a different ordering. An edit is exactly
+ // what moves a task in that ordering, so refreshing one and not the other
+ // leaves Home showing a stale order with no way to notice.
+ it('should invalidate both orderings of the list', async () => {
+ const { mutate } = await import('@/libs/swr');
+ useTaskStore.setState({
+ listAgentId: 'agt_1',
+ listQueryVisibility: 'private',
+ listVisibility: 'private',
+ });
+
+ await useTaskStore.getState().refreshTaskList();
+
+ expect(mutate).toHaveBeenCalledWith(['task:list', 'agt_1', 'private', 'updatedAt']);
});
});
@@ -77,7 +93,23 @@ describe('TaskListSliceAction', () => {
useTaskStore.getState().useFetchTaskList({ allAgents: true, visibility: 'all' });
expect(useClientDataSWR).toHaveBeenCalledWith(
- ['task:list', '__all__', 'all'],
+ ['task:list', '__all__', 'all', 'createdAt'],
+ expect.any(Function),
+ expect.any(Object),
+ );
+ });
+
+ // Without the ordering in the key, Home and the Tasks page share one cache
+ // entry and whichever mounts first decides the other's order.
+ it('keys the cache by ordering so two surfaces cannot serve each other stale order', async () => {
+ const { useClientDataSWR } = await import('@/libs/swr');
+
+ useTaskStore
+ .getState()
+ .useFetchTaskList({ allAgents: true, orderBy: 'updatedAt', visibility: 'all' });
+
+ expect(useClientDataSWR).toHaveBeenCalledWith(
+ ['task:list', '__all__', 'all', 'updatedAt'],
expect.any(Function),
expect.any(Object),
);
diff --git a/src/store/task/slices/list/action.ts b/src/store/task/slices/list/action.ts
index 285f6532865..f4bd3b85810 100644
--- a/src/store/task/slices/list/action.ts
+++ b/src/store/task/slices/list/action.ts
@@ -85,8 +85,15 @@ export class TaskListSliceActionImpl {
refreshTaskList = async (): Promise<void> => {
const { listAgentId, listQueryVisibility, listVisibility } = this.#get();
await Promise.all([
- mutate(taskKeys.list(listAgentId, listQueryVisibility)),
+ // Both orderings of the same list: the Tasks page holds the createdAt
+ // entry and Home the updatedAt one, and an edit invalidates both — an
+ // edit is exactly what moves a task in the updatedAt ordering.
+ mutate(taskKeys.list(listAgentId, listQueryVisibility, 'createdAt')),
+ mutate(taskKeys.list(listAgentId, listQueryVisibility, 'updatedAt')),
mutate(taskKeys.groupList(listAgentId, listVisibility)),
+ // 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)),
]);
};
@@ -154,16 +161,55 @@ 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`.
+ */
+ useFetchScheduledTaskList = (options: { enabled?: boolean; limit?: number } = {}) => {
+ const { enabled = true, limit } = options;
+
+ return useClientDataSWR(
+ enabled ? taskKeys.scheduledList(ALL_AGENTS_LIST_KEY) : 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,
+ },
+ );
+ };
+
useFetchTaskList = (
options: {
agentId?: string;
allAgents?: boolean;
enabled?: boolean;
+ /**
+ * Newest-first by creation unless a caller asks otherwise. A block that
+ * calls itself "recent" and prints `updatedAt` has to order by it too, or
+ * the task that just moved falls off the page in favour of a newer idle
+ * one. Part of the cache key: the Tasks page and Home read the same
+ * `tasks` field and must not serve each other's ordering.
+ */
+ orderBy?: 'createdAt' | 'updatedAt';
/** Override the Task page's persisted filter for embedded consumers. */
visibility?: TaskListVisibilityFilter;
} = {},
) => {
- const { agentId, allAgents = false, enabled = true, visibility } = options;
+ const { agentId, allAgents = false, enabled = true, orderBy, visibility } = options;
const effectiveKey = allAgents ? ALL_AGENTS_LIST_KEY : agentId;
const listVisibility = visibility ?? this.#get().listVisibility;
const { listAgentId, listQueryVisibility } = this.#get();
@@ -184,11 +230,12 @@ export class TaskListSliceActionImpl {
}
return useClientDataSWR(
- enabled && effectiveKey ? taskKeys.list(effectiveKey, listVisibility) : null,
+ enabled && effectiveKey ? taskKeys.list(effectiveKey, listVisibility, orderBy) : null,
async ([, id]: [string, string]) => {
return this.fetchTaskList({
...(allAgents ? {} : { assigneeAgentId: id }),
hasGoal: false,
+ orderBy,
visibility: filterToServerVisibility(listVisibility),
});
},
diff --git a/src/store/task/slices/list/initialState.ts b/src/store/task/slices/list/initialState.ts
index 851a99147a2..5e49a0a9e11 100644
--- a/src/store/task/slices/list/initialState.ts
+++ b/src/store/task/slices/list/initialState.ts
@@ -17,6 +17,7 @@ export type TaskViewMode = 'kanban' | 'list';
export type TaskListVisibilityFilter = 'all' | 'private' | 'workspace';
export interface TaskListSliceState {
+ isScheduledTaskListInit: boolean;
isTaskGroupListInit: boolean;
isTaskListInit: boolean;
listAgentId?: string;
@@ -25,6 +26,9 @@ 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;
@@ -32,10 +36,13 @@ export interface TaskListSliceState {
}
export const initialTaskListSliceState: TaskListSliceState = {
+ isScheduledTaskListInit: false,
isTaskGroupListInit: false,
isTaskListInit: false,
listQueryVisibility: 'all',
listVisibility: 'all',
+ scheduledTasks: [],
+ scheduledTasksTotal: 0,
taskGroups: [],
tasks: [],
tasksTotal: 0,