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): show scheduled tasks as a schedule table grouped by health (#23661)

AmAzing-e7474360fa6b
diff --git a/apps/server/src/routers/lambda/__tests__/integration/task.recentRuns.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/task.recentRuns.integration.test.ts
new file mode 100644
index 00000000000..25cbef65b83
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/integration/task.recentRuns.integration.test.ts
@@ -0,0 +1,88 @@
+// @vitest-environment node
+import { type LobeChatDatabase } from '@lobechat/database';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { BriefModel } from '@/database/models/brief';
+import { TaskTopicModel } from '@/database/models/taskTopic';
+
+import { taskRouter } from '../../task';
+import { cleanupTestUser, createTestContext, createTestTopic, createTestUser } from './setup';
+
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return testDB;
+ }),
+}));
+
+vi.mock('@/server/modules/ModelRuntime', () => ({
+ initModelRuntimeFromDB: vi.fn(),
+}));
+
+describe('Task Router list recentRuns', () => {
+ let serverDB: LobeChatDatabase;
+ let userId: string;
+ let caller: ReturnType<typeof taskRouter.createCaller>;
+
+ beforeEach(async () => {
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ userId = await createTestUser(serverDB);
+ caller = taskRouter.createCaller(createTestContext(userId));
+ });
+
+ afterEach(async () => {
+ await cleanupTestUser(serverDB, userId);
+ });
+
+ const createScheduled = async (instruction: string) =>
+ (
+ await caller.create({
+ automationMode: 'schedule',
+ instruction,
+ schedulePattern: '0 9 * * *',
+ scheduleTimezone: 'UTC',
+ })
+ ).data;
+
+ it('attaches the latest runs and the awaiting-human flag when asked', async () => {
+ const digest = await createScheduled('Daily digest');
+ const blocked = await createScheduled('Blocked on a question');
+
+ const topicModel = new TaskTopicModel(serverDB, userId);
+ for (const seq of [1, 2, 3]) {
+ const topicId = await createTestTopic(serverDB, userId);
+ await topicModel.add(digest.id, topicId, { seq, trigger: 'schedule' });
+ await topicModel.updateStatus(digest.id, topicId, seq === 2 ? 'failed' : 'completed');
+ }
+ await new BriefModel(serverDB, userId).create({
+ priority: 'urgent',
+ summary: 'Which channel?',
+ taskId: blocked.id,
+ title: 'Needs an answer',
+ type: 'decision',
+ });
+
+ const list = await caller.list({ automated: true, recentRuns: 2 });
+ const byId = new Map(list.data.map((task) => [task.id, task]));
+
+ expect(byId.get(digest.id)?.recentRuns?.map((run) => [run.seq, run.status])).toEqual([
+ [3, 'completed'],
+ [2, 'failed'],
+ ]);
+ expect(byId.get(digest.id)?.awaitingHuman).toBe(false);
+ expect(byId.get(blocked.id)?.recentRuns).toEqual([]);
+ expect(byId.get(blocked.id)?.awaitingHuman).toBe(true);
+ });
+
+ it('leaves both fields off rows of a list that did not ask', async () => {
+ await createScheduled('Daily digest');
+
+ const list = await caller.list({ automated: true });
+
+ expect(list.data).toHaveLength(1);
+ expect(list.data[0]).not.toHaveProperty('recentRuns');
+ expect(list.data[0]).not.toHaveProperty('awaitingHuman');
+ });
+});
diff --git a/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts b/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts
index e0467c0d9c5..f1523d978ef 100644
--- a/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts
+++ b/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts
@@ -74,6 +74,10 @@ export const listSchema = z.object({
parentTaskId: z.string().trim().min(1).nullish(),
priorities: z.array(z.number().min(0).max(4)).max(5).optional(),
projectId: z.string().optional(),
+ // Attach each row's latest N runs (`recentRuns`) and whether an unresolved
+ // urgent brief holds its automation back (`awaitingHuman`). Opt-in: only the
+ // scheduled tasks table reads them, and they cost two extra queries.
+ recentRuns: z.number().int().min(1).max(10).optional(),
// "My tasks" narrowing: 'assigned' → tasks whose member assignee is the
// caller, 'created' → tasks the caller created. Always resolved against
// `ctx.userId` so the endpoint never filters by an arbitrary member.
diff --git a/apps/server/src/routers/lambda/task/queries.ts b/apps/server/src/routers/lambda/task/queries.ts
index 414e2aeda4f..0c29c808913 100644
--- a/apps/server/src/routers/lambda/task/queries.ts
+++ b/apps/server/src/routers/lambda/task/queries.ts
@@ -169,7 +169,7 @@ export const queriesRouter = router({
list: taskProcedure.input(listSchema).query(async ({ input, ctx }) => {
try {
const model = ctx.taskModel;
- const { completedWithin, parentIdentifier, scope, ...query } = input;
+ const { completedWithin, parentIdentifier, recentRuns, scope, ...query } = input;
const parentRef = query.parentTaskId !== undefined ? query.parentTaskId : parentIdentifier;
const parentTaskId =
typeof parentRef === 'string'
@@ -190,11 +190,18 @@ export const queriesRouter = router({
const assigneeUserIds = [
...new Set(result.tasks.map((t) => t.assigneeUserId).filter((id): id is string => !!id)),
];
- const [agents, users] = await Promise.all([
+ const taskIds = result.tasks.map((t) => t.id);
+ const [agents, users, runsByTaskId, awaitingHumanTaskIds] = await Promise.all([
assigneeIds.length > 0 ? ctx.agentModel.getAgentAvatarsByIds(assigneeIds) : [],
assigneeUserIds.length > 0
? UserModel.getDisplayInfoByIds(ctx.serverDB, assigneeUserIds)
: [],
+ recentRuns ? ctx.taskTopicModel.findRecentRunsByTaskIds(taskIds, recentRuns) : undefined,
+ // Same rule the schedule and heartbeat ticks skip on: an urgent brief
+ // that is not an error is a question only the user can answer.
+ recentRuns
+ ? ctx.briefModel.findTaskIdsWithUnresolvedUrgent(taskIds, { excludeTypes: ['error'] })
+ : undefined,
]);
const agentMap = new Map(agents.map((a) => [a.id, a]));
const userMap = new Map(users.map((u) => [u.id, u]));
@@ -225,7 +232,13 @@ export const queriesRouter = router({
});
}
}
- return { ...task, participants };
+ if (!runsByTaskId || !awaitingHumanTaskIds) return { ...task, participants };
+ return {
+ ...task,
+ awaitingHuman: awaitingHumanTaskIds.has(task.id),
+ participants,
+ recentRuns: runsByTaskId.get(task.id) ?? [],
+ };
});
return { data, success: true, total: result.total };
diff --git a/apps/server/src/services/taskLifecycle/index.ts b/apps/server/src/services/taskLifecycle/index.ts
index 8839ee9b33b..d035701a0c6 100644
--- a/apps/server/src/services/taskLifecycle/index.ts
+++ b/apps/server/src/services/taskLifecycle/index.ts
@@ -25,7 +25,11 @@ import type {
TaskSchedulerContext,
TaskTopicHandoff,
} from '@lobechat/types';
-import { DEFAULT_BRIEF_ACTIONS, RequestTrigger } from '@lobechat/types';
+import {
+ DEFAULT_BRIEF_ACTIONS,
+ RequestTrigger,
+ TASK_AUTOMATION_FAILURE_FUSE,
+} from '@lobechat/types';
import debug from 'debug';
import {
@@ -74,12 +78,8 @@ const log = debug('task-lifecycle');
const TERMINAL_STATUSES = new Set(['canceled', 'completed', 'failed']);
const isTerminal = (status: string) => TERMINAL_STATUSES.has(status);
-// Consecutive automation-tick 'error' reasons after which we pause the task /
-// stop re-arming and let the urgent brief surface for human attention. A single
-// transient upstream hiccup (429 / network / upstream 500) must NOT permanently
-// stop a recurring task — only this many *consecutive* failures do. Hardcoded
-// for now; move to task.config later if it needs to be tunable per-task.
-const AUTOMATION_FAILURE_FUSE = 3;
+// Hardcoded for now; move to task.config later if it needs to be tunable per-task.
+const AUTOMATION_FAILURE_FUSE = TASK_AUTOMATION_FAILURE_FUSE;
export interface TopicCompleteParams {
/** Structured terminal error type (e.g. `InsufficientBudgetForModel`) from the
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 21d878e48bc..b15042e23b6 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -3065,7 +3065,34 @@
"taskList.orderBy.status": "Status",
"taskList.orderBy.title": "Title",
"taskList.orderBy.updatedAt": "Updated at",
+ "taskList.scheduled.columns.assignee": "Assignee",
+ "taskList.scheduled.columns.cadence": "Frequency",
+ "taskList.scheduled.columns.nextRun": "Next run",
+ "taskList.scheduled.columns.recentRuns": "Recent runs",
+ "taskList.scheduled.columns.task": "Task",
"taskList.scheduled.empty": "No scheduled tasks yet",
+ "taskList.scheduled.group.attention": "Needs attention",
+ "taskList.scheduled.group.running": "Running",
+ "taskList.scheduled.group.scheduled": "Scheduled",
+ "taskList.scheduled.runs.none": "No runs yet",
+ "taskList.scheduled.runs.outcome.canceled": "Canceled",
+ "taskList.scheduled.runs.outcome.failed": "Failed",
+ "taskList.scheduled.runs.outcome.interrupted": "Interrupted",
+ "taskList.scheduled.runs.outcome.running": "Running",
+ "taskList.scheduled.runs.outcome.succeeded": "Succeeded",
+ "taskList.scheduled.runs.tooltip": "Run #{{seq}} · {{outcome}} · {{time}}",
+ "taskList.scheduled.state.awaitingHuman": "Waiting for your reply",
+ "taskList.scheduled.state.awaitingHuman.hint": "Runs are skipped until you answer the question on this task",
+ "taskList.scheduled.state.awaitingReview": "Pending review",
+ "taskList.scheduled.state.awaitingReview.hint": "Open the task to review its latest result",
+ "taskList.scheduled.state.nextRunUnknown": "Schedule can’t be read",
+ "taskList.scheduled.state.overrun": "Running for {{duration}}, not finished",
+ "taskList.scheduled.state.overrun.hint": "Later runs are skipped until this run ends",
+ "taskList.scheduled.state.running": "Running · {{duration}}",
+ "taskList.scheduled.state.runningNoDuration": "Running",
+ "taskList.scheduled.state.stopped.hint": "It won’t run again until a run succeeds. Open the task to see the error, then run it now",
+ "taskList.scheduled.state.stopped_one": "Stopped after {{count}} failed run",
+ "taskList.scheduled.state.stopped_other": "Stopped after {{count}} failed runs",
"taskList.scheduled.title": "Scheduled tasks",
"taskList.subtaskProgress.loadFailed": "Couldn't load sub-tasks. Click the progress badge to retry.",
"taskList.title": "Tasks",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 236b9a92153..664c0958f4a 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -3065,7 +3065,34 @@
"taskList.orderBy.status": "状态",
"taskList.orderBy.title": "标题",
"taskList.orderBy.updatedAt": "更新时间",
+ "taskList.scheduled.columns.assignee": "执行者",
+ "taskList.scheduled.columns.cadence": "频率",
+ "taskList.scheduled.columns.nextRun": "下次运行",
+ "taskList.scheduled.columns.recentRuns": "最近运行",
+ "taskList.scheduled.columns.task": "任务",
"taskList.scheduled.empty": "暂无定时任务",
+ "taskList.scheduled.group.attention": "需要处理",
+ "taskList.scheduled.group.running": "运行中",
+ "taskList.scheduled.group.scheduled": "已排期",
+ "taskList.scheduled.runs.none": "尚未运行",
+ "taskList.scheduled.runs.outcome.canceled": "已取消",
+ "taskList.scheduled.runs.outcome.failed": "失败",
+ "taskList.scheduled.runs.outcome.interrupted": "中断",
+ "taskList.scheduled.runs.outcome.running": "运行中",
+ "taskList.scheduled.runs.outcome.succeeded": "成功",
+ "taskList.scheduled.runs.tooltip": "第 {{seq}} 次运行 · {{outcome}} · {{time}}",
+ "taskList.scheduled.state.awaitingHuman": "等待你的回复",
+ "taskList.scheduled.state.awaitingHuman.hint": "回答这个任务上的问题之前,不会继续运行",
+ "taskList.scheduled.state.awaitingReview": "待审阅",
+ "taskList.scheduled.state.awaitingReview.hint": "打开任务,审阅最近一次的结果",
+ "taskList.scheduled.state.nextRunUnknown": "无法读取排期",
+ "taskList.scheduled.state.overrun": "已运行 {{duration}},仍未结束",
+ "taskList.scheduled.state.overrun.hint": "这次运行结束之前,后续排期不会触发",
+ "taskList.scheduled.state.running": "运行中 · {{duration}}",
+ "taskList.scheduled.state.runningNoDuration": "运行中",
+ "taskList.scheduled.state.stopped.hint": "运行成功一次之前不会再触发。打开任务查看错误,然后立即运行",
+ "taskList.scheduled.state.stopped_one": "连续失败 {{count}} 次,已停止",
+ "taskList.scheduled.state.stopped_other": "连续失败 {{count}} 次,已停止",
"taskList.scheduled.title": "定时任务",
"taskList.subtaskProgress.loadFailed": "无法加载子任务,请点击进度标签重试。",
"taskList.title": "任务",
diff --git a/packages/database/src/models/__tests__/brief.test.ts b/packages/database/src/models/__tests__/brief.test.ts
index 326228f18c1..0e736d11135 100644
--- a/packages/database/src/models/__tests__/brief.test.ts
+++ b/packages/database/src/models/__tests__/brief.test.ts
@@ -612,6 +612,46 @@ describe('BriefModel', () => {
});
});
+ describe('findTaskIdsWithUnresolvedUrgent', () => {
+ it('names only the tasks held back by an unresolved, non-excluded urgent brief', async () => {
+ await serverDB.insert(tasks).values(
+ ['waiting', 'answered', 'errored', 'normal'].map((key, index) => ({
+ createdByUserId: userId,
+ id: `task-batch-${key}`,
+ identifier: `TASK-BATCH-${index}`,
+ instruction: 'do work',
+ seq: 10 + index,
+ status: 'scheduled',
+ })),
+ );
+
+ const model = new BriefModel(serverDB, userId);
+ const brief = (taskId: string, priority: string, type: string) =>
+ model.create({ priority, summary: 's', taskId, title: 't', type });
+ await brief('task-batch-waiting', 'urgent', 'decision');
+ // Two briefs on one task still name it once.
+ await brief('task-batch-waiting', 'urgent', 'decision');
+ const answered = await brief('task-batch-answered', 'urgent', 'decision');
+ await model.resolve(answered.id);
+ await brief('task-batch-errored', 'urgent', 'error');
+ await brief('task-batch-normal', 'normal', 'decision');
+
+ const ids = [
+ 'task-batch-waiting',
+ 'task-batch-answered',
+ 'task-batch-errored',
+ 'task-batch-normal',
+ ];
+ expect(await model.findTaskIdsWithUnresolvedUrgent(ids, { excludeTypes: ['error'] })).toEqual(
+ new Set(['task-batch-waiting']),
+ );
+ expect(await model.findTaskIdsWithUnresolvedUrgent(ids)).toEqual(
+ new Set(['task-batch-waiting', 'task-batch-errored']),
+ );
+ expect(await model.findTaskIdsWithUnresolvedUrgent([])).toEqual(new Set());
+ });
+ });
+
describe('findByCronJobId', () => {
it('should return briefs for a cron job ordered newest first', async () => {
await serverDB.insert(agents).values({ id: 'agent-cron', title: 'Cron Agent', userId });
diff --git a/packages/database/src/models/__tests__/taskTopic.recentRuns.test.ts b/packages/database/src/models/__tests__/taskTopic.recentRuns.test.ts
new file mode 100644
index 00000000000..96241956e56
--- /dev/null
+++ b/packages/database/src/models/__tests__/taskTopic.recentRuns.test.ts
@@ -0,0 +1,91 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { topics, users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { TaskModel } from '../task';
+import { TaskTopicModel } from '../taskTopic';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'task-recent-runs-user';
+const otherUserId = 'task-recent-runs-other-user';
+
+const createTopic = async (id: string, uid = userId) => {
+ await serverDB.insert(topics).values({ id, userId: uid }).onConflictDoNothing();
+ return id;
+};
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+});
+
+describe('TaskTopicModel.findRecentRunsByTaskIds', () => {
+ it('returns the latest runs of each task, newest first, capped per task', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const topicModel = new TaskTopicModel(serverDB, userId);
+ const daily = await taskModel.create({ instruction: 'Daily digest' });
+ const hourly = await taskModel.create({ instruction: 'Hourly check' });
+ const idle = await taskModel.create({ instruction: 'Never ran' });
+
+ for (const seq of [1, 2, 3, 4]) {
+ const topicId = await createTopic(`tpc_daily_${seq}`);
+ await topicModel.add(daily.id, topicId, { seq, trigger: 'schedule' });
+ await topicModel.updateStatus(daily.id, topicId, seq === 3 ? 'failed' : 'completed');
+ }
+ await topicModel.add(hourly.id, await createTopic('tpc_hourly_1'), {
+ seq: 1,
+ trigger: 'heartbeat',
+ });
+
+ const runs = await topicModel.findRecentRunsByTaskIds([daily.id, hourly.id, idle.id], 3);
+
+ // Capped at 3 per task: the cap is per task, not across the whole page.
+ expect(runs.get(daily.id)?.map((run) => [run.seq, run.status])).toEqual([
+ [4, 'completed'],
+ [3, 'failed'],
+ [2, 'completed'],
+ ]);
+ // Settling a run stamps its topic; that is the run's finish time.
+ expect(runs.get(daily.id)?.[0]).toMatchObject({
+ completedAt: expect.any(Date),
+ topicId: 'tpc_daily_4',
+ trigger: 'schedule',
+ });
+ expect(runs.get(hourly.id)).toMatchObject([
+ { completedAt: null, seq: 1, status: 'running', trigger: 'heartbeat' },
+ ]);
+ expect(runs.has(idle.id)).toBe(false);
+ });
+
+ it('leaves out runs of tasks the caller cannot read', async () => {
+ const mine = await new TaskModel(serverDB, userId).create({ instruction: 'Mine' });
+ const theirs = await new TaskModel(serverDB, otherUserId).create({ instruction: 'Theirs' });
+ await new TaskTopicModel(serverDB, userId).add(mine.id, await createTopic('tpc_mine'), {
+ seq: 1,
+ });
+ await new TaskTopicModel(serverDB, otherUserId).add(
+ theirs.id,
+ await createTopic('tpc_theirs', otherUserId),
+ { seq: 1 },
+ );
+
+ const runs = await new TaskTopicModel(serverDB, userId).findRecentRunsByTaskIds(
+ [mine.id, theirs.id],
+ 5,
+ );
+
+ expect([...runs.keys()]).toEqual([mine.id]);
+ });
+
+ it('reads nothing for an empty page', async () => {
+ const runs = await new TaskTopicModel(serverDB, userId).findRecentRunsByTaskIds([], 5);
+ expect(runs.size).toBe(0);
+ });
+});
diff --git a/packages/database/src/models/brief.ts b/packages/database/src/models/brief.ts
index 6b61d31c83b..fa5aea22f01 100644
--- a/packages/database/src/models/brief.ts
+++ b/packages/database/src/models/brief.ts
@@ -284,6 +284,35 @@ export class BriefModel {
return rows.length > 0;
}
+ /**
+ * Which of `taskIds` have an unresolved urgent brief — the batch form of
+ * {@link hasUnresolvedUrgentByTask}, for lists that mark the tasks whose
+ * automation is held back until the user answers.
+ */
+ async findTaskIdsWithUnresolvedUrgent(
+ taskIds: string[],
+ options?: { excludeTypes?: string[] },
+ ): Promise<Set<string>> {
+ if (taskIds.length === 0) return new Set();
+
+ const excludeTypes = options?.excludeTypes ?? [];
+ const conditions = [
+ this.ownership(),
+ inArray(briefs.taskId, taskIds),
+ eq(briefs.priority, 'urgent'),
+ isNull(briefs.resolvedAt),
+ ];
+ if (excludeTypes.length > 0) {
+ conditions.push(notInArray(briefs.type, excludeTypes));
+ }
+
+ const rows = await this.db
+ .selectDistinct({ taskId: briefs.taskId })
+ .from(briefs)
+ .where(and(...conditions));
+ return new Set(rows.map((row) => row.taskId).filter((id): id is string => !!id));
+ }
+
async findByCronJobId(cronJobId: string): Promise<BriefItem[]> {
return this.db
.select()
diff --git a/packages/database/src/models/taskTopic.ts b/packages/database/src/models/taskTopic.ts
index 66a4c5fd500..9c528e8f3b6 100644
--- a/packages/database/src/models/taskTopic.ts
+++ b/packages/database/src/models/taskTopic.ts
@@ -3,8 +3,8 @@ import {
QUOTA_LIMITED_RUN_STATUS,
TRANSIENT_FAILED_RUN_STATUS,
} from '@lobechat/const/goal';
-import type { BriefDecision, TaskTopicHandoff } from '@lobechat/types';
-import { and, count, desc, eq, gte, inArray, ne, sql } from 'drizzle-orm';
+import type { BriefDecision, TaskRecentRun, TaskTopicHandoff } from '@lobechat/types';
+import { and, count, desc, eq, gte, inArray, lte, ne, sql } from 'drizzle-orm';
import { alias } from 'drizzle-orm/pg-core';
import { agentOperations } from '../schemas/agentOperations';
@@ -517,6 +517,62 @@ export class TaskTopicModel {
.where(and(inArray(taskTopics.taskId, taskIds), this.ownership()));
}
+ /**
+ * The latest `limit` runs of each task, newest first within a task.
+ *
+ * Use when:
+ * - A task list shows each row's recent outcomes (the scheduled tasks table)
+ *
+ * Expects:
+ * - `taskIds` already scoped to tasks the caller may read; run rows are
+ * still narrowed by their own visibility
+ */
+ async findRecentRunsByTaskIds(
+ taskIds: string[],
+ limit: number,
+ ): Promise<Map<string, TaskRecentRun[]>> {
+ const runsByTaskId = new Map<string, TaskRecentRun[]>();
+ if (taskIds.length === 0 || limit <= 0) return runsByTaskId;
+
+ const ranked = this.db
+ .select({
+ createdAt: taskTopics.createdAt,
+ rank: sql<number>`row_number() over (partition by ${taskTopics.taskId} order by ${taskTopics.seq} desc)`.as(
+ 'run_rank',
+ ),
+ seq: taskTopics.seq,
+ status: taskTopics.status,
+ taskId: taskTopics.taskId,
+ topicId: taskTopics.topicId,
+ trigger: taskTopics.trigger,
+ })
+ .from(taskTopics)
+ .where(and(inArray(taskTopics.taskId, taskIds), this.ownership()))
+ .as('ranked_task_runs');
+
+ const rows = await this.db
+ .select({
+ completedAt: topics.completedAt,
+ createdAt: ranked.createdAt,
+ seq: ranked.seq,
+ status: ranked.status,
+ taskId: ranked.taskId,
+ topicId: ranked.topicId,
+ trigger: ranked.trigger,
+ })
+ .from(ranked)
+ .leftJoin(topics, eq(ranked.topicId, topics.id))
+ .where(lte(ranked.rank, limit))
+ .orderBy(ranked.taskId, desc(ranked.seq));
+
+ for (const { taskId, ...run } of rows) {
+ const runs = runsByTaskId.get(taskId) ?? [];
+ runs.push(run);
+ runsByTaskId.set(taskId, runs);
+ }
+ return runsByTaskId;
+ }
+
async findRunningByTaskIds(taskIds: string[]): Promise<TaskTopicItem[]> {
if (taskIds.length === 0) return [];
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 8d6776f58c2..a1481edf201 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -3545,7 +3545,36 @@ export default {
'taskList.mine.emptyAssigned': 'No tasks assigned to you yet',
'taskList.mine.emptyCreated': "You haven't created any tasks yet",
'taskList.mine.title': 'My tasks',
+ 'taskList.scheduled.columns.assignee': 'Assignee',
+ 'taskList.scheduled.columns.cadence': 'Frequency',
+ 'taskList.scheduled.columns.nextRun': 'Next run',
+ 'taskList.scheduled.columns.recentRuns': 'Recent runs',
+ 'taskList.scheduled.columns.task': 'Task',
'taskList.scheduled.empty': 'No scheduled tasks yet',
+ 'taskList.scheduled.group.attention': 'Needs attention',
+ 'taskList.scheduled.group.running': 'Running',
+ 'taskList.scheduled.group.scheduled': 'Scheduled',
+ 'taskList.scheduled.runs.none': 'No runs yet',
+ 'taskList.scheduled.runs.outcome.canceled': 'Canceled',
+ 'taskList.scheduled.runs.outcome.failed': 'Failed',
+ 'taskList.scheduled.runs.outcome.interrupted': 'Interrupted',
+ 'taskList.scheduled.runs.outcome.running': 'Running',
+ 'taskList.scheduled.runs.outcome.succeeded': 'Succeeded',
+ 'taskList.scheduled.runs.tooltip': 'Run #{{seq}} · {{outcome}} · {{time}}',
+ 'taskList.scheduled.state.awaitingHuman': 'Waiting for your reply',
+ 'taskList.scheduled.state.awaitingHuman.hint':
+ 'Runs are skipped until you answer the question on this task',
+ 'taskList.scheduled.state.awaitingReview': 'Pending review',
+ 'taskList.scheduled.state.awaitingReview.hint': 'Open the task to review its latest result',
+ 'taskList.scheduled.state.nextRunUnknown': 'Schedule can’t be read',
+ 'taskList.scheduled.state.overrun': 'Running for {{duration}}, not finished',
+ 'taskList.scheduled.state.overrun.hint': 'Later runs are skipped until this run ends',
+ 'taskList.scheduled.state.running': 'Running · {{duration}}',
+ 'taskList.scheduled.state.runningNoDuration': 'Running',
+ 'taskList.scheduled.state.stopped_one': 'Stopped after {{count}} failed run',
+ 'taskList.scheduled.state.stopped_other': 'Stopped after {{count}} failed runs',
+ 'taskList.scheduled.state.stopped.hint':
+ 'It won’t run again until a run succeeds. Open the task to see the error, then run it now',
'taskList.scheduled.title': 'Scheduled tasks',
'taskList.subtaskProgress.loadFailed':
"Couldn't load sub-tasks. Click the progress badge to retry.",
diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.ts
index 67a68d812ee..a4f6fe814a8 100644
--- a/packages/types/src/task/index.ts
+++ b/packages/types/src/task/index.ts
@@ -252,9 +252,18 @@ export interface TaskTopicHandoff {
// ── Task context (runtime state pockets stored in tasks.context JSONB) ──
+/**
+ * Consecutive automation-tick failures after which a recurring task stops: a
+ * schedule is paused, a heartbeat is no longer re-armed. One transient upstream
+ * hiccup (429 / network / upstream 500) must not stop a recurring task for
+ * good; only this many in a row do. Shared so the scheduled tasks table reads
+ * "stopped" off the same number the lifecycle acts on.
+ */
+export const TASK_AUTOMATION_FAILURE_FUSE = 3;
+
export interface TaskSchedulerContext {
// Count of consecutive automation-tick 'error' reasons since the last 'done'.
- // When it hits the fuse threshold (currently 3) we pause the task / stop
+ // When it hits `TASK_AUTOMATION_FAILURE_FUSE` we pause the task / stop
// re-arming until the user resolves the urgent brief. Manual "run now"
// failures do NOT touch this counter.
consecutiveFailures?: number;
@@ -392,8 +401,32 @@ export interface TaskItem {
workspaceId: string | null;
}
+/**
+ * One run of a task as a list row shows it: enough to draw the outcome strip
+ * of a recurring task and to open the run, nothing more.
+ */
+export interface TaskRecentRun {
+ /** When the run's topic finished; null while it is still going. */
+ completedAt: Date | null;
+ createdAt: Date;
+ seq: number;
+ /** `task_topics.status`: 'running', 'completed', 'failed', 'timeout', 'canceled', … */
+ status: string;
+ topicId: string | null;
+ /** Null for runs recorded before the trigger was tracked. */
+ trigger: TaskRunTrigger | null;
+}
+
export type TaskListItem = TaskItem & {
+ /**
+ * The task has an unresolved urgent brief, so its schedule and heartbeat
+ * ticks are skipped until the user answers. Only set when the list was asked
+ * for `recentRuns`.
+ */
+ awaitingHuman?: boolean;
participants: TaskParticipant[];
+ /** Latest runs, newest first. Only set when the list was asked for `recentRuns`. */
+ recentRuns?: TaskRecentRun[];
};
export interface NewTask {
diff --git a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
index c1c82c5ef75..3abfed65c91 100644
--- a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
+++ b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
@@ -25,13 +25,17 @@ import type { TaskViewMode } from '@/store/global/initialState';
import { systemStatusSelectors } from '@/store/global/selectors';
import { useTaskStore } from '@/store/task';
import { taskLabelSelectors, taskListSelectors } from '@/store/task/selectors';
-import { TASK_COLLECTION_PAGE_SIZE } from '@/store/task/slices/list/action';
+import {
+ SCHEDULED_TASK_RECENT_RUNS,
+ TASK_COLLECTION_PAGE_SIZE,
+} from '@/store/task/slices/list/action';
import { useHeaderActionSize } from '@/styles/density';
import { isMobileSurface } from '@/utils/mobileSurface';
import { AgentGoalsAndTasksTabs } from '../AgentGoalsAndTasksTabs';
import { createTaskModal } from '../CreateTaskModal';
import { useTaskProjectList } from '../features/useTaskProjectList';
+import { ScheduledTaskTable } from '../ScheduledTaskTable';
import Breadcrumb from '../shared/Breadcrumb';
import { taskDetailPath } from '../shared/taskDetailPath';
import { TaskListOriginContext } from '../shared/taskListOrigin';
@@ -201,9 +205,9 @@ const PAGINATED_COLLECTION_VIEW = {
} as const;
/**
- * The scheduled tab is a plain list: no group headers, since each row already
- * states its own rhythm (the schedule or heartbeat chip). A stored grouping
- * belongs to the ordinary list and is set aside here.
+ * The scheduled tab renders its own table (`ScheduledTaskTable`), sectioned by
+ * what each schedule is doing. A stored grouping belongs to the ordinary list
+ * and is set aside here.
*/
export const getScheduledTaskViewOptions = (
viewOptions: TaskListViewOptions,
@@ -216,8 +220,8 @@ export const getScheduledTaskViewOptions = (
/**
* Whether a collection's project groups need the project list to be told apart.
- * Judged on what the collection renders: the scheduled tab is an ungrouped
- * list, so a stored `project` must not hold it behind the project request.
+ * Judged on what the collection renders: the scheduled tab never groups by
+ * project, so a stored `project` must not hold it behind the project request.
*/
export const collectionGroupsByProject = (
collection: TaskCollection,
@@ -250,7 +254,8 @@ export const PAGINATED_COLLECTION_PINNED_OPTIONS = ['ordering', 'showSubTasks']
* because every collection that is offered the list/board switch has to answer
* it: "My tasks" rendered its list unconditionally while still showing the
* switch, so picking Board did nothing at all. The scheduled tab is the one
- * collection with no switch (its config entry is hidden), so it stays a list.
+ * collection with no switch (its config entry is hidden), so it never shows a
+ * board; its 'list' is the schedule table.
*/
export const resolveTaskCollectionView = (
collection: TaskCollection,
@@ -400,6 +405,7 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, proj
limit: COLLECTION_PAGE_SIZE,
offset: (collectionPage - 1) * COLLECTION_PAGE_SIZE,
projectId,
+ recentRuns: SCHEDULED_TASK_RECENT_RUNS,
});
const useFetchMyTaskList = useTaskStore((s) => s.useFetchMyTaskList);
const mineSWR = useFetchMyTaskList({
@@ -423,10 +429,13 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, proj
// button would only duplicate it.
const showScheduledEmptyCreate =
isScheduledCollection && canCreateTask && isCollectionListInit && collectionTasksTotal === 0;
- const scheduledViewOptions = useMemo(
- () => getScheduledTaskViewOptions(viewOptions),
- [viewOptions],
- );
+ const collectionSelectionScope = [
+ collection,
+ isMineCollection ? myTaskScope : '',
+ collectionPage,
+ agentId ?? '',
+ projectId ?? '',
+ ].join(':');
const myTaskViewOptions = useMemo(() => getMyTaskViewOptions(viewOptions), [viewOptions]);
const filterKey = JSON.stringify(filter ?? null);
useEffect(() => {
@@ -704,46 +713,56 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, proj
paddingInline={16}
wrapperStyle={{ flex: 1, overflowY: 'auto' }}
>
- <TaskList
- data={isCollectionListInit || undefined}
- error={collectionSWR.error ?? projectListError}
- filter={filter}
- hideProject={!!projectId}
- items={collectionTasks}
- options={isMineCollection ? myTaskViewOptions : scheduledViewOptions}
- routeScope={routeScope}
- emptyAction={
- filterEmptyAction ??
- (showScheduledEmptyCreate ? (
- <Button icon={Plus} onClick={handleCreateScheduledTask}>
- {t('createTask.submitScheduled')}
- </Button>
- ) : undefined)
- }
- emptyDescription={
- filterEmptyDescription ??
- (isMineCollection
- ? t(
- myTaskScope === 'created'
- ? 'taskList.mine.emptyCreated'
- : 'taskList.mine.emptyAssigned',
- )
- : t('taskList.scheduled.empty'))
- }
- isLoading={
- collectionSWR.isLoading ||
- isProjectListPending ||
- (!isCollectionListInit && !collectionSWR.error)
- }
- selectionScope={[
- collection,
- isMineCollection ? myTaskScope : '',
- collectionPage,
- agentId ?? '',
- projectId ?? '',
- ].join(':')}
- onRetry={() => (projectListError ? retryProjects() : collectionSWR.mutate())}
- />
+ {isScheduledCollection ? (
+ <ScheduledTaskTable
+ data={isCollectionListInit || undefined}
+ emptyDescription={filterEmptyDescription}
+ error={collectionSWR.error}
+ filter={filter}
+ hideProject={!!projectId}
+ routeScope={routeScope}
+ selectionScope={collectionSelectionScope}
+ tasks={collectionTasks}
+ emptyAction={
+ filterEmptyAction ??
+ (showScheduledEmptyCreate ? (
+ <Button icon={Plus} onClick={handleCreateScheduledTask}>
+ {t('createTask.submitScheduled')}
+ </Button>
+ ) : undefined)
+ }
+ isLoading={
+ collectionSWR.isLoading || (!isCollectionListInit && !collectionSWR.error)
+ }
+ onRetry={() => collectionSWR.mutate()}
+ />
+ ) : (
+ <TaskList
+ data={isCollectionListInit || undefined}
+ emptyAction={filterEmptyAction}
+ error={collectionSWR.error ?? projectListError}
+ filter={filter}
+ hideProject={!!projectId}
+ items={collectionTasks}
+ options={myTaskViewOptions}
+ routeScope={routeScope}
+ selectionScope={collectionSelectionScope}
+ emptyDescription={
+ filterEmptyDescription ??
+ t(
+ myTaskScope === 'created'
+ ? 'taskList.mine.emptyCreated'
+ : 'taskList.mine.emptyAssigned',
+ )
+ }
+ isLoading={
+ collectionSWR.isLoading ||
+ isProjectListPending ||
+ (!isCollectionListInit && !collectionSWR.error)
+ }
+ onRetry={() => (projectListError ? retryProjects() : collectionSWR.mutate())}
+ />
+ )}
{(collectionTasksTotal > COLLECTION_PAGE_SIZE || collectionPage > 1) && (
<Flexbox horizontal justify={'center'} paddingBlock={8}>
<Pagination
diff --git a/src/features/AgentTasks/AgentTaskList/TaskList.tsx b/src/features/AgentTasks/AgentTaskList/TaskList.tsx
index d8661b7cdd1..48f0ee788f3 100644
--- a/src/features/AgentTasks/AgentTaskList/TaskList.tsx
+++ b/src/features/AgentTasks/AgentTaskList/TaskList.tsx
@@ -16,7 +16,7 @@ import {
import * as stylex from '@stylexjs/stylex';
import { ClipboardCheckIcon, Plus } from 'lucide-react';
import type { ReactNode } from 'react';
-import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { memo, useCallback, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { Components } from 'react-virtuoso';
import { Virtuoso } from 'react-virtuoso';
@@ -46,11 +46,8 @@ import {
normalizeTaskGroupBy,
} from './listViewOptions';
import SelectableTaskRow, { selectableTaskItemClassName } from './selection/SelectableTaskRow';
-import { useTaskSelectionStore } from './selection/store';
import TaskBulkActionBar from './selection/TaskBulkActionBar';
-import { isEditableTarget } from './selection/taskSelectionModel';
-import { useTaskBatchUndo } from './selection/undo/useTaskBatchUndo';
-import { useSelectionScope } from './selection/useSelectionScope';
+import { useTaskListSelection } from './selection/useTaskListSelection';
import TaskGroupLabel from './TaskGroupLabel';
import TaskItemSkeleton from './TaskItemSkeleton';
import type { TaskListGroupEntry, TaskListVirtualItem } from './taskListVirtualModel';
@@ -334,63 +331,11 @@ const TaskList = memo<TaskListProps>((props) => {
return [...ids];
}, [groupedTaskEntries]);
const listRef = useRef<HTMLDivElement>(null);
- const selectableIdsRef = useRef(selectableIds);
- selectableIdsRef.current = selectableIds;
- const getSelectionOrder = useCallback(() => selectableIdsRef.current, []);
-
- // A selection never outlives the rows it names: prune on every list change,
- // and drop it when this list (or its collection) goes away.
- useEffect(() => {
- useTaskSelectionStore.getState().prune(new Set(selectableIds));
- }, [selectableIds]);
- const selectionScope = props.selectionScope ?? (items ? 'items' : (queryKey ?? ''));
- useSelectionScope(selectionScope);
- const { undoLast } = useTaskBatchUndo();
- const undoLastRef = useRef(undoLast);
- useEffect(() => {
- undoLastRef.current = undoLast;
- }, [undoLast]);
-
- useEffect(() => {
- const onKeyDown = (event: KeyboardEvent) => {
- if (event.defaultPrevented || isEditableTarget(event.target)) return;
- // Only when nothing else holds focus, or focus is on the list itself:
- // ⌘A over a side panel's text keeps selecting that text, and Esc inside
- // a drawer or popover stays theirs.
- const target = event.target as Node | null;
- const onList = !!target && !!listRef.current?.contains(target);
- if (target !== document.body && !onList) return;
- const selection = useTaskSelectionStore.getState();
- if (
- event.key.toLowerCase() === 'a' &&
- (event.metaKey || event.ctrlKey) &&
- !event.shiftKey &&
- !event.altKey
- ) {
- if (selectableIdsRef.current.length === 0) return;
- event.preventDefault();
- selection.selectAll(selectableIdsRef.current);
- return;
- }
- // ⌘/Ctrl+Z: undo the most recent batch action (session-wide stack, so it
- // still works after its toast is gone). Shift+⌘Z is left to the page.
- if (
- event.key.toLowerCase() === 'z' &&
- (event.metaKey || event.ctrlKey) &&
- !event.shiftKey &&
- !event.altKey
- ) {
- if (undoLastRef.current()) event.preventDefault();
- return;
- }
- if (event.key === 'Escape' && selection.selectedIds.length > 0 && !selection.progress) {
- event.preventDefault();
- selection.clear();
- }
- };
- window.addEventListener('keydown', onKeyDown);
- return () => window.removeEventListener('keydown', onKeyDown);
- }, []);
+ const { getSelectionOrder } = useTaskListSelection({
+ listRef,
+ scope: props.selectionScope ?? (items ? 'items' : (queryKey ?? '')),
+ selectableIds,
+ });
const virtualItems = useMemo(
() =>
diff --git a/src/features/AgentTasks/AgentTaskList/selection/useTaskListSelection.ts b/src/features/AgentTasks/AgentTaskList/selection/useTaskListSelection.ts
new file mode 100644
index 00000000000..cba7e221fe2
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskList/selection/useTaskListSelection.ts
@@ -0,0 +1,91 @@
+import { type RefObject, useCallback, useEffect, useRef } from 'react';
+
+import { useTaskSelectionStore } from './store';
+import { isEditableTarget } from './taskSelectionModel';
+import { useTaskBatchUndo } from './undo/useTaskBatchUndo';
+import { useSelectionScope } from './useSelectionScope';
+
+interface UseTaskListSelectionOptions {
+ /** The list's root element: ⌘A / Esc act only when focus is on it or on nothing. */
+ listRef: RefObject<HTMLElement | null>;
+ /**
+ * Identity of the collection the rows belong to (tab, sub-scope, page,
+ * owner). The selection is dropped whenever it changes.
+ */
+ scope: string;
+ /** Selectable ids in display order, top to bottom. */
+ selectableIds: readonly string[];
+}
+
+/**
+ * Everything a task list owes the shared selection store: prune the selection
+ * to the rows on screen, drop it when the list changes identity, and handle
+ * ⌘/Ctrl+A (select all), ⌘/Ctrl+Z (undo the last batch action) and Esc (clear).
+ *
+ * @returns the stable getter rows pass to `SelectableTaskRow` for Shift+click ranges
+ */
+export const useTaskListSelection = ({
+ listRef,
+ scope,
+ selectableIds,
+}: UseTaskListSelectionOptions) => {
+ const selectableIdsRef = useRef(selectableIds);
+ selectableIdsRef.current = selectableIds;
+ const getSelectionOrder = useCallback(() => selectableIdsRef.current, []);
+
+ // A selection never outlives the rows it names: prune on every list change,
+ // and drop it when this list (or its collection) goes away.
+ useEffect(() => {
+ useTaskSelectionStore.getState().prune(new Set(selectableIds));
+ }, [selectableIds]);
+ useSelectionScope(scope);
+
+ const { undoLast } = useTaskBatchUndo();
+ const undoLastRef = useRef(undoLast);
+ useEffect(() => {
+ undoLastRef.current = undoLast;
+ }, [undoLast]);
+
+ useEffect(() => {
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.defaultPrevented || isEditableTarget(event.target)) return;
+ // Only when nothing else holds focus, or focus is on the list itself:
+ // ⌘A over a side panel's text keeps selecting that text, and Esc inside
+ // a drawer or popover stays theirs.
+ const target = event.target as Node | null;
+ const onList = !!target && !!listRef.current?.contains(target);
+ if (target !== document.body && !onList) return;
+ const selection = useTaskSelectionStore.getState();
+ if (
+ event.key.toLowerCase() === 'a' &&
+ (event.metaKey || event.ctrlKey) &&
+ !event.shiftKey &&
+ !event.altKey
+ ) {
+ if (selectableIdsRef.current.length === 0) return;
+ event.preventDefault();
+ selection.selectAll(selectableIdsRef.current);
+ return;
+ }
+ // ⌘/Ctrl+Z: undo the most recent batch action (session-wide stack, so it
+ // still works after its toast is gone). Shift+⌘Z is left to the page.
+ if (
+ event.key.toLowerCase() === 'z' &&
+ (event.metaKey || event.ctrlKey) &&
+ !event.shiftKey &&
+ !event.altKey
+ ) {
+ if (undoLastRef.current()) event.preventDefault();
+ return;
+ }
+ if (event.key === 'Escape' && selection.selectedIds.length > 0 && !selection.progress) {
+ event.preventDefault();
+ selection.clear();
+ }
+ };
+ window.addEventListener('keydown', onKeyDown);
+ return () => window.removeEventListener('keydown', onKeyDown);
+ }, [listRef]);
+
+ return { getSelectionOrder };
+};
diff --git a/src/features/AgentTasks/ScheduledTaskTable/RecentRuns.tsx b/src/features/AgentTasks/ScheduledTaskTable/RecentRuns.tsx
new file mode 100644
index 00000000000..ff99fad91ae
--- /dev/null
+++ b/src/features/AgentTasks/ScheduledTaskTable/RecentRuns.tsx
@@ -0,0 +1,110 @@
+import type { TaskRecentRun } from '@lobechat/types';
+import { Flexbox, Text, Tooltip } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { useTranslation } from 'react-i18next';
+
+import { resolveRunOutcome, type RunOutcome } from './scheduleState';
+import { formatRelativeToNow, formatRunMoment } from './scheduleText';
+
+const styles = stylex.create({
+ dot: {
+ borderRadius: '50%',
+ flexShrink: 0,
+ height: 8,
+ width: 8,
+ },
+ // A run still in flight has no outcome to fill the dot with.
+ running: {
+ borderColor: cssVar.colorWarning,
+ borderStyle: 'solid',
+ borderWidth: 2,
+ },
+});
+
+const outcomeStyles = stylex.create({
+ canceled: { backgroundColor: cssVar.colorTextQuaternary },
+ failed: { backgroundColor: cssVar.colorError },
+ interrupted: { backgroundColor: cssVar.colorWarning },
+ running: { backgroundColor: 'transparent' },
+ succeeded: { backgroundColor: cssVar.colorSuccess },
+});
+
+const OUTCOME_LABEL_KEYS = {
+ canceled: 'taskList.scheduled.runs.outcome.canceled',
+ failed: 'taskList.scheduled.runs.outcome.failed',
+ interrupted: 'taskList.scheduled.runs.outcome.interrupted',
+ running: 'taskList.scheduled.runs.outcome.running',
+ succeeded: 'taskList.scheduled.runs.outcome.succeeded',
+} as const satisfies Record<RunOutcome, string>;
+
+interface RecentRunsProps {
+ now: Date;
+ /** Newest first, as the list returns them. */
+ runs?: TaskRecentRun[];
+}
+
+/**
+ * The last few runs of a recurring task as an outcome strip, oldest to newest,
+ * followed by when the latest one happened. The strip answers "has this been
+ * going well" without opening the task.
+ */
+export const RecentRuns = ({ now, runs }: RecentRunsProps) => {
+ const { t, i18n } = useTranslation('chat');
+
+ if (!runs || runs.length === 0) {
+ return (
+ <Text fontSize={12} type={'secondary'}>
+ {t('taskList.scheduled.runs.none')}
+ </Text>
+ );
+ }
+
+ const locale = i18n.language;
+ const dateTimeFormat = t('taskSchedule.nextRun.format');
+ const chronological = runs.toReversed();
+ const latest = runs[0];
+ const outcomes = chronological.map((run) => t(OUTCOME_LABEL_KEYS[resolveRunOutcome(run.status)]));
+
+ return (
+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ aria-label={outcomes.join(', ')}
+ flex={'none'}
+ gap={4}
+ role={'img'}
+ >
+ {chronological.map((run, index) => {
+ const outcome = resolveRunOutcome(run.status);
+ return (
+ <Tooltip
+ key={run.seq}
+ title={t('taskList.scheduled.runs.tooltip', {
+ outcome: outcomes[index],
+ seq: run.seq,
+ time: formatRunMoment(run.completedAt ?? run.createdAt, {
+ dateTimeFormat,
+ locale,
+ now,
+ }),
+ })}
+ >
+ <span
+ {...stylex.props(
+ styles.dot,
+ outcomeStyles[outcome],
+ outcome === 'running' && styles.running,
+ )}
+ />
+ </Tooltip>
+ );
+ })}
+ </Flexbox>
+ <Text ellipsis fontSize={12} style={{ minWidth: 0 }} type={'secondary'}>
+ {formatRelativeToNow(latest.completedAt ?? latest.createdAt, now, locale)}
+ </Text>
+ </Flexbox>
+ );
+};
diff --git a/src/features/AgentTasks/ScheduledTaskTable/ScheduleStateCell.tsx b/src/features/AgentTasks/ScheduledTaskTable/ScheduleStateCell.tsx
new file mode 100644
index 00000000000..b2f43179716
--- /dev/null
+++ b/src/features/AgentTasks/ScheduledTaskTable/ScheduleStateCell.tsx
@@ -0,0 +1,93 @@
+import { Flexbox, Text, Tooltip } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import { useTranslation } from 'react-i18next';
+
+import type { ScheduleState } from './scheduleState';
+import { formatElapsed, formatRelativeToNow, formatRunMoment } from './scheduleText';
+
+interface ScheduleStateCellProps {
+ now: Date;
+ state: ScheduleState;
+}
+
+const FLEX_MIN_WIDTH_0 = { minWidth: 0 };
+
+/**
+ * When the task runs next, or, when it will not run on its own, the reason in
+ * its place. The reason is the cell's text; the tooltip only adds what to do.
+ */
+export const ScheduleStateCell = ({ now, state }: ScheduleStateCellProps) => {
+ const { t, i18n } = useTranslation('chat');
+ const locale = i18n.language;
+
+ if (state.health === 'scheduled') {
+ if (!state.nextRunAt) {
+ return (
+ <Text ellipsis type={'secondary'}>
+ {t('taskList.scheduled.state.nextRunUnknown')}
+ </Text>
+ );
+ }
+ return (
+ <Flexbox horizontal align={'baseline'} gap={6} style={FLEX_MIN_WIDTH_0}>
+ <Text style={{ flex: 'none' }} weight={500}>
+ {formatRunMoment(state.nextRunAt, {
+ dateTimeFormat: t('taskSchedule.nextRun.format'),
+ locale,
+ now,
+ })}
+ </Text>
+ <Text ellipsis fontSize={12} style={FLEX_MIN_WIDTH_0} type={'secondary'}>
+ {formatRelativeToNow(state.nextRunAt, now, locale)}
+ </Text>
+ </Flexbox>
+ );
+ }
+
+ if (state.health === 'running') {
+ return (
+ <Text ellipsis>
+ {state.runningSince
+ ? t('taskList.scheduled.state.running', {
+ duration: formatElapsed(state.runningSince, now, locale),
+ })
+ : t('taskList.scheduled.state.runningNoDuration')}
+ </Text>
+ );
+ }
+
+ const reason = {
+ awaitingHuman: {
+ color: cssVar.colorInfo,
+ hint: t('taskList.scheduled.state.awaitingHuman.hint'),
+ text: t('taskList.scheduled.state.awaitingHuman'),
+ },
+ awaitingReview: {
+ color: cssVar.colorInfo,
+ hint: t('taskList.scheduled.state.awaitingReview.hint'),
+ text: t('taskList.scheduled.state.awaitingReview'),
+ },
+ overrun: {
+ color: cssVar.colorWarning,
+ hint: t('taskList.scheduled.state.overrun.hint'),
+ text: state.runningSince
+ ? t('taskList.scheduled.state.overrun', {
+ duration: formatElapsed(state.runningSince, now, locale),
+ })
+ : t('taskList.scheduled.state.runningNoDuration'),
+ },
+ stopped: {
+ color: cssVar.colorError,
+ hint: t('taskList.scheduled.state.stopped.hint'),
+ text: t('taskList.scheduled.state.stopped', { count: state.consecutiveFailures }),
+ },
+ }[state.health];
+
+ return (
+ <Tooltip title={reason.hint}>
+ <Text ellipsis style={{ color: reason.color }} weight={500}>
+ {reason.text}
+ </Text>
+ </Tooltip>
+ );
+};
diff --git a/src/features/AgentTasks/ScheduledTaskTable/ScheduledTaskRow.tsx b/src/features/AgentTasks/ScheduledTaskTable/ScheduledTaskRow.tsx
new file mode 100644
index 00000000000..bd78fb1c19d
--- /dev/null
+++ b/src/features/AgentTasks/ScheduledTaskTable/ScheduledTaskRow.tsx
@@ -0,0 +1,175 @@
+import type { TaskStatus } from '@lobechat/types';
+import { ContextMenuTrigger, Flexbox, Icon, Text, Tooltip } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { LockIcon, TriangleAlert } from 'lucide-react';
+import type { KeyboardEvent } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { type ExecutionStatusVisual, TASK_STATUS_VISUALS } from '@/components/ExecutionStatus';
+import TaskLabelChips from '@/features/TaskLabels/TaskLabelChips';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import type { TaskListItem } from '@/store/task/slices/list/initialState';
+import { useDensityTokens } from '@/styles/density';
+import { sx } from '@/styles/sx';
+
+import {
+ formatIntervalLabel,
+ formatScheduleDescription,
+ formatTimezoneName,
+} from '../AgentTaskDetail/scheduler/helpers';
+import type { TaskItemRouteScope } from '../features/AgentTaskItem';
+import { TaskAssigneeCell } from '../features/TaskAssigneeCell';
+import TaskProjectChip from '../features/TaskProjectChip';
+import { useTaskItemContextMenu } from '../features/useTaskItemContextMenu';
+import { taskDetailPath } from '../shared/taskDetailPath';
+import { useTaskListOriginState } from '../shared/taskListOrigin';
+import { RecentRuns } from './RecentRuns';
+import type { ScheduleHealth, ScheduleState } from './scheduleState';
+import { ScheduleStateCell } from './ScheduleStateCell';
+import { scheduleTableStyles } from './style';
+
+const styles = stylex.create({
+ row: {
+ cursor: 'pointer',
+ outlineColor: { 'default': null, ':focus-visible': cssVar.colorPrimary },
+ outlineOffset: { 'default': null, ':focus-visible': '-2px' },
+ outlineStyle: { 'default': null, ':focus-visible': 'solid' },
+ outlineWidth: { 'default': null, ':focus-visible': '2px' },
+ },
+});
+
+/**
+ * A task's glyph follows what its schedule is doing, not its raw status: a
+ * heartbeat whose fuse blew still has the `scheduled` status.
+ */
+const HEALTH_VISUALS: Record<ScheduleHealth, ExecutionStatusVisual> = {
+ awaitingHuman: TASK_STATUS_VISUALS.paused,
+ awaitingReview: TASK_STATUS_VISUALS.paused,
+ overrun: { color: cssVar.colorWarning, icon: TriangleAlert },
+ running: TASK_STATUS_VISUALS.running,
+ scheduled: TASK_STATUS_VISUALS.scheduled,
+ stopped: TASK_STATUS_VISUALS.failed,
+};
+
+const TASK_STATUS_SET = new Set<string>(Object.keys(TASK_STATUS_VISUALS));
+const toTaskStatus = (status: string): TaskStatus =>
+ TASK_STATUS_SET.has(status) ? (status as TaskStatus) : 'backlog';
+
+const FLEX_MIN_WIDTH_0 = { minWidth: 0 };
+
+interface ScheduledTaskRowProps {
+ /** The surface already belongs to one project, so its rows do not repeat it. */
+ hideProject?: boolean;
+ now: Date;
+ routeScope: TaskItemRouteScope;
+ state: ScheduleState;
+ task: TaskListItem;
+}
+
+/**
+ * One recurring task as a row of the scheduled tasks table: what it is, how
+ * often it runs, when it runs next (or why it will not), how its last runs
+ * went, and who runs it.
+ */
+export const ScheduledTaskRow = ({
+ hideProject,
+ now,
+ routeScope,
+ state,
+ task,
+}: ScheduledTaskRowProps) => {
+ const { t, i18n } = useTranslation('chat');
+ const { fontSize, listRowHeight } = useDensityTokens();
+ const navigate = useWorkspaceAwareNavigate();
+ const taskListOriginState = useTaskListOriginState();
+ const { items: contextMenuItems, onContextMenu } = useTaskItemContextMenu(task, routeScope);
+
+ const open = () =>
+ navigate(
+ taskDetailPath(
+ task.identifier,
+ routeScope === 'agent' ? (task.assigneeAgentId ?? undefined) : undefined,
+ task.name,
+ ),
+ { state: taskListOriginState },
+ );
+
+ const handleKeyDown = (event: KeyboardEvent) => {
+ // Only the row itself: a key pressed inside a cell control belongs to it.
+ if (event.target !== event.currentTarget) return;
+ if (event.key !== 'Enter' && event.key !== ' ') return;
+ event.preventDefault();
+ open();
+ };
+
+ const visual = HEALTH_VISUALS[state.health];
+ const name = task.name?.trim();
+
+ // `automationMode` is the source of truth: a task keeps stale fields of the
+ // mode it was on before.
+ const cadence =
+ task.automationMode === 'schedule' && task.schedulePattern
+ ? formatScheduleDescription(task.schedulePattern, t)
+ : task.automationMode === 'heartbeat' && task.heartbeatInterval
+ ? t('taskSchedule.tag.every', {
+ interval: formatIntervalLabel(task.heartbeatInterval, t),
+ })
+ : undefined;
+ const timezone =
+ task.automationMode === 'schedule' && task.scheduleTimezone
+ ? formatTimezoneName(task.scheduleTimezone, i18n.language)
+ : undefined;
+
+ return (
+ <ContextMenuTrigger items={contextMenuItems} onContextMenu={onContextMenu}>
+ <div
+ {...sx(scheduleTableStyles.grid, styles.row, {
+ fontSize,
+ paddingBlock: (listRowHeight - 24) / 2,
+ })}
+ role={'link'}
+ tabIndex={0}
+ onClick={open}
+ onKeyDown={handleKeyDown}
+ >
+ <div {...stylex.props(scheduleTableStyles.taskCell)}>
+ <Flexbox horizontal align={'center'} gap={8} style={FLEX_MIN_WIDTH_0}>
+ <Icon color={visual.color} icon={visual.icon} size={16} style={{ flex: 'none' }} />
+ {task.visibility === 'private' && (
+ <Tooltip title={t('createTask.visibility.helperPrivate')}>
+ <Icon color={cssVar.colorTextDescription} icon={LockIcon} size={14} />
+ </Tooltip>
+ )}
+ {name && (
+ <Text style={{ flex: 'none' }} type={'secondary'}>
+ {task.identifier}
+ </Text>
+ )}
+ <Text ellipsis style={FLEX_MIN_WIDTH_0} weight={500}>
+ {name || task.identifier}
+ </Text>
+ <TaskLabelChips labels={task.labels} max={2} />
+ {!hideProject && <TaskProjectChip projectId={task.projectId} />}
+ </Flexbox>
+ </div>
+ <div {...stylex.props(scheduleTableStyles.cadenceCell)}>
+ <Tooltip title={timezone && cadence ? `${cadence} · ${timezone}` : undefined}>
+ <Text ellipsis type={'secondary'}>
+ {cadence}
+ </Text>
+ </Tooltip>
+ </div>
+ <div {...stylex.props(scheduleTableStyles.stateCell)}>
+ <ScheduleStateCell now={now} state={state} />
+ </div>
+ <div {...stylex.props(scheduleTableStyles.runsCell)}>
+ <RecentRuns now={now} runs={task.recentRuns} />
+ </div>
+ <div {...stylex.props(scheduleTableStyles.assigneeCell)}>
+ <TaskAssigneeCell status={toTaskStatus(task.status)} task={task} />
+ </div>
+ </div>
+ </ContextMenuTrigger>
+ );
+};
diff --git a/src/features/AgentTasks/ScheduledTaskTable/index.tsx b/src/features/AgentTasks/ScheduledTaskTable/index.tsx
new file mode 100644
index 00000000000..4c3cd2562e4
--- /dev/null
+++ b/src/features/AgentTasks/ScheduledTaskTable/index.tsx
@@ -0,0 +1,264 @@
+import { matchesTaskListFilter, type TaskListFilter } from '@lobechat/types';
+import {
+ AccordionHeader,
+ AccordionItem,
+ AccordionRoot,
+ AccordionTrigger,
+ Center,
+ Divider,
+ Empty,
+ Flexbox,
+ Icon,
+ Skeleton,
+ Text,
+} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { CalendarClockIcon, CircleAlert } from 'lucide-react';
+import { type ReactNode, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncBoundary from '@/components/AsyncBoundary';
+import { type ExecutionStatusVisual, TASK_STATUS_VISUALS } from '@/components/ExecutionStatus';
+import type { TaskListItem } from '@/store/task/slices/list/initialState';
+import { useDensityTokens } from '@/styles/density';
+import { sx } from '@/styles/sx';
+
+import SelectableTaskRow from '../AgentTaskList/selection/SelectableTaskRow';
+import TaskBulkActionBar from '../AgentTaskList/selection/TaskBulkActionBar';
+import { useTaskListSelection } from '../AgentTaskList/selection/useTaskListSelection';
+import type { TaskItemRouteScope } from '../features/AgentTaskItem';
+import { ScheduledTaskRow } from './ScheduledTaskRow';
+import { groupScheduleRows, type ScheduleGroupKey } from './scheduleState';
+import { scheduleTableStyles } from './style';
+
+// The header and the skeleton line up with the row content: the same 2px row
+// inset, then the 20px selection gutter `SelectableTaskRow` reserves.
+const styles = stylex.create({
+ gutter: {
+ paddingInlineStart: '20px',
+ },
+ rowInset: {
+ paddingInline: '2px',
+ },
+});
+
+const GROUP_LABEL_KEYS = {
+ attention: 'taskList.scheduled.group.attention',
+ running: 'taskList.scheduled.group.running',
+ scheduled: 'taskList.scheduled.group.scheduled',
+} as const satisfies Record<ScheduleGroupKey, string>;
+
+const GROUP_VISUALS: Record<ScheduleGroupKey, ExecutionStatusVisual> = {
+ attention: { color: cssVar.colorWarning, icon: CircleAlert },
+ running: TASK_STATUS_VISUALS.running,
+ scheduled: TASK_STATUS_VISUALS.scheduled,
+};
+
+/** How often the table re-reads the clock: next runs, elapsed times and sections follow it. */
+const CLOCK_INTERVAL_MS = 30_000;
+
+const useNow = (intervalMs: number): Date => {
+ const [now, setNow] = useState(() => new Date());
+ useEffect(() => {
+ const id = setInterval(() => setNow(new Date()), intervalMs);
+ return () => clearInterval(id);
+ }, [intervalMs]);
+ return now;
+};
+
+const SKELETON_ROWS = 5;
+
+const ScheduledTaskTableSkeleton = () => {
+ const { listRowHeight } = useDensityTokens();
+ return (
+ <div {...stylex.props(scheduleTableStyles.container)}>
+ {Array.from({ length: SKELETON_ROWS }, (_, index) => (
+ <div {...stylex.props(styles.rowInset)} key={index}>
+ <div {...sx(styles.gutter, { paddingBlock: (listRowHeight - 16) / 2 })}>
+ <div {...stylex.props(scheduleTableStyles.grid)}>
+ <div {...stylex.props(scheduleTableStyles.taskCell)}>
+ <Skeleton height={16} style={{ minWidth: 0 }} width={'60%'} />
+ </div>
+ <div {...stylex.props(scheduleTableStyles.cadenceCell)}>
+ <Skeleton height={14} style={{ minWidth: 0 }} width={96} />
+ </div>
+ <div {...stylex.props(scheduleTableStyles.stateCell)}>
+ <Skeleton height={14} style={{ minWidth: 0 }} width={120} />
+ </div>
+ <div {...stylex.props(scheduleTableStyles.runsCell)}>
+ <Skeleton height={14} style={{ minWidth: 0 }} width={88} />
+ </div>
+ <div {...stylex.props(scheduleTableStyles.assigneeCell)}>
+ <Skeleton.Avatar shape={'circle'} size={'small'} />
+ </div>
+ </div>
+ </div>
+ {index !== SKELETON_ROWS - 1 && <Divider dashed style={{ margin: 0 }} />}
+ </div>
+ ))}
+ </div>
+ );
+};
+
+interface ScheduledTaskTableProps {
+ /**
+ * Settled signal: truthy once the page behind `tasks` has a value in the
+ * store, `undefined` while unsettled.
+ */
+ data?: unknown;
+ /** Call to action under the empty state, e.g. creating the first scheduled task. */
+ emptyAction?: ReactNode;
+ emptyDescription?: string;
+ /** Thrown error from the list fetch: surfaced as a failure state, not a skeleton. */
+ error?: unknown;
+ /**
+ * The page filter the rows were fetched with. Re-applied locally so a row
+ * edited out of it leaves at once.
+ */
+ filter?: TaskListFilter;
+ /** The table already belongs to one project, so its rows do not repeat it. */
+ hideProject?: boolean;
+ /** First load or retry in flight. */
+ isLoading?: boolean;
+ onRetry?: () => void;
+ routeScope: TaskItemRouteScope;
+ /** Identity of the collection behind `tasks`; the selection is dropped whenever it changes. */
+ selectionScope: string;
+ tasks: TaskListItem[];
+}
+
+/**
+ * Recurring tasks as a schedule, not as a to-do list: sectioned by whether
+ * each one needs the user, is running, or is waiting for its next run, with
+ * the waiting ones ordered by when they fire.
+ */
+export const ScheduledTaskTable = ({
+ data,
+ emptyAction,
+ emptyDescription,
+ error,
+ filter,
+ hideProject,
+ isLoading,
+ onRetry,
+ routeScope,
+ selectionScope,
+ tasks: sourceTasks,
+}: ScheduledTaskTableProps) => {
+ const { t } = useTranslation('chat');
+ const now = useNow(CLOCK_INTERVAL_MS);
+ const tasks = useMemo(
+ () =>
+ filter ? sourceTasks.filter((task) => matchesTaskListFilter(task, filter)) : sourceTasks,
+ [filter, sourceTasks],
+ );
+ const groups = useMemo(() => groupScheduleRows(tasks, now), [tasks, now]);
+
+ const [collapsedKeys, setCollapsedKeys] = useState<ReadonlySet<ScheduleGroupKey>>(
+ () => new Set(),
+ );
+ const toggleCollapsed = (key: ScheduleGroupKey) =>
+ setCollapsedKeys((prev) => {
+ const next = new Set(prev);
+ if (next.has(key)) next.delete(key);
+ else next.add(key);
+ return next;
+ });
+
+ // Display order, collapsed sections included: ⌘A selects every task the table lists.
+ const selectableIds = useMemo(
+ () => groups.flatMap((group) => group.rows.map((row) => row.task.id)),
+ [groups],
+ );
+ const listRef = useRef<HTMLDivElement>(null);
+ const { getSelectionOrder } = useTaskListSelection({
+ listRef,
+ scope: selectionScope,
+ selectableIds,
+ });
+
+ return (
+ <AsyncBoundary
+ data={data}
+ error={error}
+ errorVariant={'block'}
+ isEmpty={tasks.length === 0}
+ isLoading={isLoading}
+ loading={<ScheduledTaskTableSkeleton />}
+ empty={
+ <Center height={'80vh'} width={'100%'}>
+ <Empty
+ action={emptyAction}
+ description={emptyDescription ?? t('taskList.scheduled.empty')}
+ icon={CalendarClockIcon}
+ />
+ </Center>
+ }
+ onRetry={onRetry}
+ >
+ <div ref={listRef} {...stylex.props(scheduleTableStyles.container)}>
+ <TaskBulkActionBar tasks={tasks} />
+ <div {...stylex.props(styles.rowInset, styles.gutter)}>
+ <div {...stylex.props(scheduleTableStyles.grid, scheduleTableStyles.head)}>
+ <span>{t('taskList.scheduled.columns.task')}</span>
+ <span>{t('taskList.scheduled.columns.cadence')}</span>
+ <span>{t('taskList.scheduled.columns.nextRun')}</span>
+ <span>{t('taskList.scheduled.columns.recentRuns')}</span>
+ <span style={{ textAlign: 'end' }}>{t('taskList.scheduled.columns.assignee')}</span>
+ </div>
+ </div>
+ <Flexbox gap={16}>
+ {groups.map((group) => {
+ const collapsed = collapsedKeys.has(group.key);
+ const visual = GROUP_VISUALS[group.key];
+ return (
+ <section key={group.key}>
+ <AccordionRoot
+ indicatorPlacement={'start'}
+ value={collapsed ? [] : [group.key]}
+ variant={'filled'}
+ onValueChange={() => toggleCollapsed(group.key)}
+ >
+ <AccordionItem value={group.key}>
+ <AccordionHeader>
+ <AccordionTrigger style={{ paddingBlock: 8, paddingInline: 14 }}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Icon color={visual.color} icon={visual.icon} size={16} />
+ <Text weight={500}>{t(GROUP_LABEL_KEYS[group.key])}</Text>
+ <Text fontSize={12} type={'secondary'}>
+ {group.rows.length}
+ </Text>
+ </Flexbox>
+ </AccordionTrigger>
+ </AccordionHeader>
+ </AccordionItem>
+ </AccordionRoot>
+ {!collapsed &&
+ group.rows.map(({ state, task }, index) => (
+ // Matches the 2px row gap of the ordinary task list.
+ <div key={task.id} style={{ paddingBlock: 1, paddingInline: 2 }}>
+ <SelectableTaskRow
+ id={task.id}
+ label={[task.identifier, task.name?.trim()].filter(Boolean).join(' ')}
+ order={getSelectionOrder}
+ >
+ <ScheduledTaskRow
+ hideProject={hideProject}
+ now={now}
+ routeScope={routeScope}
+ state={state}
+ task={task}
+ />
+ </SelectableTaskRow>
+ {index !== group.rows.length - 1 && <Divider dashed style={{ margin: 0 }} />}
+ </div>
+ ))}
+ </section>
+ );
+ })}
+ </Flexbox>
+ </div>
+ </AsyncBoundary>
+ );
+};
diff --git a/src/features/AgentTasks/ScheduledTaskTable/scheduleState.test.ts b/src/features/AgentTasks/ScheduledTaskTable/scheduleState.test.ts
new file mode 100644
index 00000000000..411152fe6de
--- /dev/null
+++ b/src/features/AgentTasks/ScheduledTaskTable/scheduleState.test.ts
@@ -0,0 +1,229 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ groupScheduleRows,
+ resolveRunOutcome,
+ resolveScheduleState,
+ type ScheduleTaskInput,
+} from './scheduleState';
+
+// Sunday 2026-11-22 12:00 UTC.
+const NOW = new Date('2026-11-22T12:00:00Z');
+
+const daily = (overrides: Partial<ScheduleTaskInput> = {}): ScheduleTaskInput => ({
+ automationMode: 'schedule',
+ id: 'task_daily',
+ schedulePattern: '0 14 * * *',
+ scheduleTimezone: 'UTC',
+ status: 'scheduled',
+ ...overrides,
+});
+
+const heartbeat = (overrides: Partial<ScheduleTaskInput> = {}): ScheduleTaskInput => ({
+ automationMode: 'heartbeat',
+ heartbeatInterval: 3600,
+ id: 'task_heartbeat',
+ status: 'scheduled',
+ ...overrides,
+});
+
+const failures = (consecutiveFailures: number) => ({ scheduler: { consecutiveFailures } });
+
+describe('resolveScheduleState', () => {
+ describe('a schedule waiting for its next run', () => {
+ it("fires at the pattern's next occurrence in its own timezone", () => {
+ expect(resolveScheduleState(daily(), NOW)).toMatchObject({
+ group: 'scheduled',
+ health: 'scheduled',
+ nextRunAt: new Date('2026-11-22T14:00:00Z'),
+ });
+ // 14:00 in Shanghai is 06:00 UTC, already past today.
+ expect(
+ resolveScheduleState(daily({ scheduleTimezone: 'Asia/Shanghai' }), NOW).nextRunAt,
+ ).toEqual(new Date('2026-11-23T06:00:00Z'));
+ });
+
+ it('treats a backlog task with a schedule as armed: the dispatcher still fires it', () => {
+ expect(resolveScheduleState(daily({ status: 'backlog' }), NOW).health).toBe('scheduled');
+ });
+
+ it('keeps a retrying schedule armed and reports its failures', () => {
+ expect(resolveScheduleState(daily({ context: failures(2) }), NOW)).toMatchObject({
+ consecutiveFailures: 2,
+ health: 'scheduled',
+ nextRunAt: new Date('2026-11-22T14:00:00Z'),
+ });
+ });
+
+ it('gives no next run for a pattern that cannot be evaluated', () => {
+ expect(resolveScheduleState(daily({ schedulePattern: 'nonsense' }), NOW)).toMatchObject({
+ health: 'scheduled',
+ nextRunAt: null,
+ });
+ });
+ });
+
+ describe('a heartbeat waiting for its next tick', () => {
+ it('fires one interval after the pending tick was enqueued', () => {
+ const task = heartbeat({
+ context: { scheduler: { scheduledAt: '2026-11-22T11:40:00Z' } },
+ lastHeartbeatAt: '2026-11-22T09:00:00Z',
+ });
+ expect(resolveScheduleState(task, NOW).nextRunAt).toEqual(new Date('2026-11-22T12:40:00Z'));
+ });
+
+ it('steps past now when the last tick is stale', () => {
+ const task = heartbeat({ lastHeartbeatAt: '2026-11-22T08:30:00Z' });
+ expect(resolveScheduleState(task, NOW).nextRunAt).toEqual(new Date('2026-11-22T12:30:00Z'));
+ });
+
+ it('counts from now when it has never ticked', () => {
+ expect(resolveScheduleState(heartbeat(), NOW).nextRunAt).toEqual(
+ new Date('2026-11-22T13:00:00Z'),
+ );
+ });
+ });
+
+ describe('a task that will not fire on its own', () => {
+ it('is stopped once the failure fuse blows, whatever its status says', () => {
+ // A heartbeat keeps `scheduled` after its fuse blows; it is just never re-armed.
+ expect(resolveScheduleState(heartbeat({ context: failures(3) }), NOW)).toMatchObject({
+ group: 'attention',
+ health: 'stopped',
+ nextRunAt: null,
+ });
+ expect(
+ resolveScheduleState(daily({ context: failures(3), status: 'paused' }), NOW).health,
+ ).toBe('stopped');
+ });
+
+ it('is awaiting review while paused', () => {
+ expect(resolveScheduleState(daily({ status: 'paused' }), NOW)).toMatchObject({
+ group: 'attention',
+ health: 'awaitingReview',
+ nextRunAt: null,
+ });
+ });
+
+ it('is awaiting the user while an urgent brief is unanswered', () => {
+ expect(resolveScheduleState(daily({ awaitingHuman: true }), NOW)).toMatchObject({
+ group: 'attention',
+ health: 'awaitingHuman',
+ nextRunAt: null,
+ });
+ // Answering the brief is the way out of the pause too.
+ expect(
+ resolveScheduleState(daily({ awaitingHuman: true, status: 'paused' }), NOW).health,
+ ).toBe('awaitingHuman');
+ });
+ });
+
+ describe('a running task', () => {
+ it('is running from the start of its run in flight', () => {
+ const task = daily({
+ recentRuns: [
+ {
+ completedAt: null,
+ createdAt: new Date('2026-11-22T11:50:00Z'),
+ seq: 2,
+ status: 'running',
+ topicId: 'tpc_2',
+ trigger: 'manual',
+ },
+ ],
+ startedAt: '2026-11-01T00:00:00Z',
+ status: 'running',
+ });
+ expect(resolveScheduleState(task, NOW)).toMatchObject({
+ group: 'running',
+ health: 'running',
+ nextRunAt: null,
+ runningSince: new Date('2026-11-22T11:50:00Z'),
+ });
+ });
+
+ it('is an overrun once an occurrence was lost to it', () => {
+ // Started before yesterday's 14:00 and still going: that slot never fired.
+ const task = daily({ startedAt: '2026-11-21T13:00:00Z', status: 'running' });
+ expect(resolveScheduleState(task, NOW)).toMatchObject({
+ group: 'attention',
+ health: 'overrun',
+ runningSince: new Date('2026-11-21T13:00:00Z'),
+ });
+ });
+
+ it('is still just running inside the grace window of the occurrence it overlaps', () => {
+ const task = daily({
+ schedulePattern: '50 11 * * *',
+ startedAt: '2026-11-22T11:00:00Z',
+ status: 'running',
+ });
+ expect(resolveScheduleState(task, NOW).health).toBe('running');
+ });
+
+ it('calls a heartbeat run an overrun after two intervals, and never before two hours', () => {
+ const run = (startedAt: string, heartbeatInterval: number) =>
+ resolveScheduleState(heartbeat({ heartbeatInterval, startedAt, status: 'running' }), NOW)
+ .health;
+ // A 10-minute heartbeat with a 90-minute run is long, not stuck.
+ expect(run('2026-11-22T10:30:00Z', 600)).toBe('running');
+ expect(run('2026-11-22T09:30:00Z', 600)).toBe('overrun');
+ // A 4-hour heartbeat gets two full intervals.
+ expect(run('2026-11-22T05:00:00Z', 4 * 3600)).toBe('running');
+ expect(run('2026-11-22T03:00:00Z', 4 * 3600)).toBe('overrun');
+ });
+
+ it('is running, not an overrun, when the start of the run is unknown', () => {
+ expect(resolveScheduleState(daily({ status: 'running' }), NOW)).toMatchObject({
+ health: 'running',
+ runningSince: null,
+ });
+ });
+ });
+});
+
+describe('groupScheduleRows', () => {
+ it('lists what needs the user, then running, then waiting by next run', () => {
+ const groups = groupScheduleRows(
+ [
+ daily({ id: 'evening', schedulePattern: '0 20 * * *' }),
+ daily({ id: 'overrun', startedAt: '2026-11-20T00:00:00Z', status: 'running' }),
+ daily({ id: 'afternoon' }),
+ daily({ id: 'review', status: 'paused' }),
+ heartbeat({ id: 'running', startedAt: '2026-11-22T11:55:00Z', status: 'running' }),
+ heartbeat({ context: failures(3), id: 'stopped' }),
+ daily({ awaitingHuman: true, id: 'question' }),
+ daily({ id: 'broken', schedulePattern: 'nonsense' }),
+ daily({ id: 'broken-too', schedulePattern: 'nonsense' }),
+ ],
+ NOW,
+ );
+
+ expect(groups.map((group) => [group.key, group.rows.map((row) => row.task.id)])).toEqual([
+ ['attention', ['stopped', 'question', 'review', 'overrun']],
+ ['running', ['running']],
+ ['scheduled', ['afternoon', 'evening', 'broken', 'broken-too']],
+ ]);
+ });
+
+ it('leaves empty sections out', () => {
+ expect(groupScheduleRows([daily()], NOW).map((group) => group.key)).toEqual(['scheduled']);
+ expect(groupScheduleRows([], NOW)).toEqual([]);
+ });
+});
+
+describe('resolveRunOutcome', () => {
+ it('reads a run status as its outcome', () => {
+ expect(resolveRunOutcome('completed')).toBe('succeeded');
+ expect(resolveRunOutcome('failed')).toBe('failed');
+ expect(resolveRunOutcome('timeout')).toBe('failed');
+ expect(resolveRunOutcome('canceled')).toBe('canceled');
+ expect(resolveRunOutcome('running')).toBe('running');
+ expect(resolveRunOutcome('quota_limited')).toBe('interrupted');
+ expect(resolveRunOutcome('device_offline')).toBe('interrupted');
+ });
+
+ it('does not claim success or failure for a status it does not know', () => {
+ expect(resolveRunOutcome('something_new')).toBe('interrupted');
+ });
+});
diff --git a/src/features/AgentTasks/ScheduledTaskTable/scheduleState.ts b/src/features/AgentTasks/ScheduledTaskTable/scheduleState.ts
new file mode 100644
index 00000000000..937acd6b0eb
--- /dev/null
+++ b/src/features/AgentTasks/ScheduledTaskTable/scheduleState.ts
@@ -0,0 +1,222 @@
+import {
+ DEVICE_OFFLINE_RUN_STATUS,
+ QUOTA_LIMITED_RUN_STATUS,
+ TRANSIENT_FAILED_RUN_STATUS,
+} from '@lobechat/const/goal';
+import type { TaskContext, TaskRecentRun } from '@lobechat/types';
+import { TASK_AUTOMATION_FAILURE_FUSE } from '@lobechat/types';
+import { DEFAULT_SCHEDULE_GRACE_MINUTES, validateCronPattern } from '@lobechat/utils/cronEval';
+
+/**
+ * What a recurring task is doing, in the terms its owner acts on. The task's
+ * `status` alone does not say whether its schedule still fires: a `scheduled`
+ * heartbeat whose fuse blew is no longer re-armed, a `running` task is skipped
+ * by every tick until its run ends, and an unanswered urgent brief holds any
+ * tick back.
+ *
+ * - `stopped`: the failure fuse blew; nothing fires until the task runs clean.
+ * - `awaitingHuman`: an urgent brief is unanswered; ticks are skipped.
+ * - `awaitingReview`: the task is paused for review; a schedule skips it.
+ * - `overrun`: a run is still going past the point the next one was due.
+ * - `running`: a run is in flight.
+ * - `scheduled`: waiting for `nextRunAt`.
+ */
+export type ScheduleHealth =
+ 'awaitingHuman' | 'awaitingReview' | 'overrun' | 'running' | 'scheduled' | 'stopped';
+
+/** The table's sections, in display order. */
+export const SCHEDULE_GROUP_KEYS = ['attention', 'running', 'scheduled'] as const;
+export type ScheduleGroupKey = (typeof SCHEDULE_GROUP_KEYS)[number];
+
+const GROUP_BY_HEALTH: Record<ScheduleHealth, ScheduleGroupKey> = {
+ awaitingHuman: 'attention',
+ awaitingReview: 'attention',
+ overrun: 'attention',
+ running: 'running',
+ scheduled: 'scheduled',
+ stopped: 'attention',
+};
+
+/** The fields of a list row the schedule state is read from. */
+export interface ScheduleTaskInput {
+ automationMode?: 'heartbeat' | 'schedule' | null;
+ awaitingHuman?: boolean;
+ context?: unknown;
+ heartbeatInterval?: number | null;
+ id: string;
+ lastHeartbeatAt?: Date | string | null;
+ recentRuns?: TaskRecentRun[];
+ schedulePattern?: string | null;
+ scheduleTimezone?: string | null;
+ startedAt?: Date | string | null;
+ status: string;
+}
+
+export interface ScheduleState {
+ /** Automation ticks that failed in a row since the last clean one. */
+ consecutiveFailures: number;
+ group: ScheduleGroupKey;
+ health: ScheduleHealth;
+ /** When the task fires next; null whenever it will not fire on its own. */
+ nextRunAt: Date | null;
+ /** Start of the run in flight; null unless the task is running. */
+ runningSince: Date | null;
+}
+
+const MINUTE_MS = 60 * 1000;
+const HOUR_MS = 60 * MINUTE_MS;
+
+/**
+ * A heartbeat has no slot to miss, so a run counts as overrun once it has
+ * lasted two of its own intervals, and never before two hours: a short
+ * interval with a long but healthy run must not be called out.
+ */
+const HEARTBEAT_OVERRUN_FLOOR_MS = 2 * HOUR_MS;
+
+const toDate = (value: Date | string | null | undefined): Date | null => {
+ if (!value) return null;
+ const date = value instanceof Date ? value : new Date(value);
+ return Number.isNaN(date.getTime()) ? null : date;
+};
+
+/** Next occurrence of a cron pattern strictly after `from`; null when it cannot be evaluated. */
+const nextCronOccurrence = (pattern: string, timezone: string | null, from: Date): Date | null => {
+ const result = validateCronPattern(pattern, timezone, { count: 1, from });
+ return result.valid ? result.nextRuns[0] : null;
+};
+
+const nextHeartbeat = (base: Date | null, intervalSeconds: number, now: Date): Date => {
+ const intervalMs = intervalSeconds * 1000;
+ if (!base) return new Date(now.getTime() + intervalMs);
+ const next = base.getTime() + intervalMs;
+ if (next > now.getTime()) return new Date(next);
+ // The pending tick is late (or the base is stale): step to the next slot after now.
+ const steps = Math.floor((now.getTime() - base.getTime()) / intervalMs) + 1;
+ return new Date(base.getTime() + steps * intervalMs);
+};
+
+const resolveNextRunAt = (task: ScheduleTaskInput, now: Date): Date | null => {
+ if (task.automationMode === 'schedule') {
+ if (!task.schedulePattern) return null;
+ return nextCronOccurrence(task.schedulePattern, task.scheduleTimezone ?? null, now);
+ }
+ if (task.automationMode === 'heartbeat') {
+ const interval = task.heartbeatInterval ?? 0;
+ if (interval <= 0) return null;
+ const context = task.context as TaskContext | null | undefined;
+ // The pending tick's enqueue time when known, else the last tick.
+ const base = toDate(context?.scheduler?.scheduledAt) ?? toDate(task.lastHeartbeatAt);
+ return nextHeartbeat(base, interval, now);
+ }
+ return null;
+};
+
+const resolveRunningSince = (task: ScheduleTaskInput): Date | null => {
+ const running = task.recentRuns?.find((run) => run.status === 'running');
+ return toDate(running?.createdAt) ?? toDate(task.startedAt);
+};
+
+const isOverrun = (task: ScheduleTaskInput, since: Date, now: Date): boolean => {
+ if (task.automationMode === 'schedule') {
+ if (!task.schedulePattern) return false;
+ // The dispatcher skips a running task, so the occurrence after the run
+ // began is lost once its grace window has closed.
+ const due = nextCronOccurrence(task.schedulePattern, task.scheduleTimezone ?? null, since);
+ return !!due && due.getTime() + DEFAULT_SCHEDULE_GRACE_MINUTES * MINUTE_MS < now.getTime();
+ }
+ const intervalMs = (task.heartbeatInterval ?? 0) * 1000;
+ if (intervalMs <= 0) return false;
+ return now.getTime() - since.getTime() > Math.max(2 * intervalMs, HEARTBEAT_OVERRUN_FLOOR_MS);
+};
+
+export const resolveScheduleState = (task: ScheduleTaskInput, now: Date): ScheduleState => {
+ const context = task.context as TaskContext | null | undefined;
+ const consecutiveFailures = context?.scheduler?.consecutiveFailures ?? 0;
+ const state = (
+ health: ScheduleHealth,
+ extra: Partial<Pick<ScheduleState, 'nextRunAt' | 'runningSince'>> = {},
+ ): ScheduleState => ({
+ consecutiveFailures,
+ group: GROUP_BY_HEALTH[health],
+ health,
+ nextRunAt: null,
+ runningSince: null,
+ ...extra,
+ });
+
+ if (task.status === 'running') {
+ const runningSince = resolveRunningSince(task);
+ const overrun = !!runningSince && isOverrun(task, runningSince, now);
+ return state(overrun ? 'overrun' : 'running', { runningSince });
+ }
+ if (consecutiveFailures >= TASK_AUTOMATION_FAILURE_FUSE) return state('stopped');
+ // The brief is the more specific ask: answering it is what unblocks the task.
+ if (task.awaitingHuman) return state('awaitingHuman');
+ if (task.status === 'paused') return state('awaitingReview');
+ return state('scheduled', { nextRunAt: resolveNextRunAt(task, now) });
+};
+
+export interface ScheduleRow<T extends ScheduleTaskInput> {
+ state: ScheduleState;
+ task: T;
+}
+
+export interface ScheduleGroup<T extends ScheduleTaskInput> {
+ key: ScheduleGroupKey;
+ rows: ScheduleRow<T>[];
+}
+
+/** Stopped first: it will never recover alone; an overrun may still finish. */
+const ATTENTION_ORDER: ScheduleHealth[] = ['stopped', 'awaitingHuman', 'awaitingReview', 'overrun'];
+
+/** Earlier first; a missing time sorts last, and two missing times tie. */
+const compareTimes = (a: Date | null, b: Date | null): number => {
+ if (!a || !b) return Number(!a) - Number(!b);
+ return a.getTime() - b.getTime();
+};
+
+const compareRows = <T extends ScheduleTaskInput>(a: ScheduleRow<T>, b: ScheduleRow<T>): number => {
+ if (a.state.group === 'attention') {
+ return ATTENTION_ORDER.indexOf(a.state.health) - ATTENTION_ORDER.indexOf(b.state.health);
+ }
+ // Longest-running first: the closest to becoming an overrun.
+ if (a.state.group === 'running') return compareTimes(a.state.runningSince, b.state.runningSince);
+ // Soonest first; a schedule that cannot be evaluated sinks to the end.
+ return compareTimes(a.state.nextRunAt, b.state.nextRunAt);
+};
+
+/**
+ * Sections of the scheduled tasks table: what needs the user, what is running,
+ * then what is waiting, soonest first. Empty sections are left out, and rows
+ * that tie keep the order they came in.
+ */
+export const groupScheduleRows = <T extends ScheduleTaskInput>(
+ tasks: readonly T[],
+ now: Date,
+): ScheduleGroup<T>[] => {
+ const rows = tasks.map((task) => ({ state: resolveScheduleState(task, now), task }));
+ return SCHEDULE_GROUP_KEYS.map((key) => ({
+ key,
+ rows: rows.filter((row) => row.state.group === key).sort(compareRows),
+ })).filter((group) => group.rows.length > 0);
+};
+
+/** How a past run reads at a glance. */
+export type RunOutcome = 'canceled' | 'failed' | 'interrupted' | 'running' | 'succeeded';
+
+const RUN_OUTCOME_BY_STATUS: Record<string, RunOutcome> = {
+ canceled: 'canceled',
+ completed: 'succeeded',
+ // The run could not proceed for a reason outside the task: an offline
+ // device, an exhausted quota, a transient upstream error.
+ [DEVICE_OFFLINE_RUN_STATUS]: 'interrupted',
+ failed: 'failed',
+ [QUOTA_LIMITED_RUN_STATUS]: 'interrupted',
+ running: 'running',
+ timeout: 'failed',
+ [TRANSIENT_FAILED_RUN_STATUS]: 'interrupted',
+};
+
+/** An unknown status reads as interrupted rather than as a success or a failure. */
+export const resolveRunOutcome = (status: string): RunOutcome =>
+ RUN_OUTCOME_BY_STATUS[status] ?? 'interrupted';
diff --git a/src/features/AgentTasks/ScheduledTaskTable/scheduleText.test.ts b/src/features/AgentTasks/ScheduledTaskTable/scheduleText.test.ts
new file mode 100644
index 00000000000..81c54996038
--- /dev/null
+++ b/src/features/AgentTasks/ScheduledTaskTable/scheduleText.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from 'vitest';
+
+import { formatElapsed, formatRelativeToNow, formatRunMoment } from './scheduleText';
+
+// Local time, so "today" does not depend on the machine's timezone.
+const NOW = new Date(2026, 10, 22, 12, 0, 0);
+const options = { dateTimeFormat: 'MMM D HH:mm', locale: 'en-US', now: NOW };
+
+describe('formatRunMoment', () => {
+ it('shows the time alone for a moment today', () => {
+ expect(formatRunMoment(new Date(2026, 10, 22, 14, 0), options)).toBe('14:00');
+ expect(formatRunMoment(new Date(2026, 10, 22, 6, 5), options)).toBe('06:05');
+ });
+
+ it('adds the date for a moment on another day', () => {
+ expect(formatRunMoment(new Date(2026, 10, 23, 6, 0), options)).toBe('Nov 23 06:00');
+ expect(formatRunMoment(new Date(2026, 8, 14, 8, 0), options)).toBe('Sep 14 08:00');
+ });
+
+ it('reads an ISO string the same as a Date', () => {
+ const moment = new Date(2026, 10, 22, 14, 0);
+ expect(formatRunMoment(moment.toISOString(), options)).toBe('14:00');
+ });
+});
+
+describe('formatRelativeToNow', () => {
+ it('reads forward and backward from now', () => {
+ expect(formatRelativeToNow(new Date(2026, 10, 22, 14, 0), NOW, 'en-US')).toBe('in 2 hours');
+ expect(formatRelativeToNow(new Date(2026, 10, 19, 12, 0), NOW, 'en-US')).toBe('3 days ago');
+ });
+});
+
+describe('formatElapsed', () => {
+ it('drops the suffix', () => {
+ expect(formatElapsed(new Date(2026, 10, 22, 11, 48), NOW, 'en-US')).toBe('12 minutes');
+ expect(formatElapsed(new Date(2026, 8, 14, 12, 0), NOW, 'en-US')).toBe('2 months');
+ });
+});
diff --git a/src/features/AgentTasks/ScheduledTaskTable/scheduleText.ts b/src/features/AgentTasks/ScheduledTaskTable/scheduleText.ts
new file mode 100644
index 00000000000..992a08937b4
--- /dev/null
+++ b/src/features/AgentTasks/ScheduledTaskTable/scheduleText.ts
@@ -0,0 +1,38 @@
+import dayjs from 'dayjs';
+import relativeTime from 'dayjs/plugin/relativeTime';
+
+import { normalizeDayjsLocale } from '@/utils/dayjsLocale';
+
+dayjs.extend(relativeTime);
+
+type TimeValue = Date | string;
+
+const localized = (time: TimeValue, locale: string) =>
+ dayjs(time).locale(normalizeDayjsLocale(locale));
+
+interface FormatRunMomentOptions {
+ /** dayjs format for a moment on another day, e.g. `MMM D HH:mm`. */
+ dateTimeFormat: string;
+ locale: string;
+ now: Date;
+}
+
+/**
+ * A run's moment as a clock reading: the time alone when it falls on today
+ * (the viewer's day), date and time otherwise.
+ */
+export const formatRunMoment = (
+ time: TimeValue,
+ { dateTimeFormat, locale, now }: FormatRunMomentOptions,
+): string => {
+ const moment = localized(time, locale);
+ return moment.format(moment.isSame(dayjs(now), 'day') ? 'HH:mm' : dateTimeFormat);
+};
+
+/** "in 2 hours" / "3 days ago", measured from `now`. */
+export const formatRelativeToNow = (time: TimeValue, now: Date, locale: string): string =>
+ localized(time, locale).from(dayjs(now));
+
+/** "12 minutes" / "2 months": how long ago `since` was, without a suffix. */
+export const formatElapsed = (since: TimeValue, now: Date, locale: string): string =>
+ localized(since, locale).from(dayjs(now), true);
diff --git a/src/features/AgentTasks/ScheduledTaskTable/style.ts b/src/features/AgentTasks/ScheduledTaskTable/style.ts
new file mode 100644
index 00000000000..506249ace99
--- /dev/null
+++ b/src/features/AgentTasks/ScheduledTaskTable/style.ts
@@ -0,0 +1,64 @@
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+
+/**
+ * The column grid shared by the table's header and its rows. Below 800px of
+ * container width (a phone, or a desktop page squeezed by side panels) the
+ * columns fold into a three-line card: task and assignee, frequency and recent
+ * runs, then the next run.
+ */
+export const scheduleTableStyles = stylex.create({
+ assigneeCell: {
+ display: 'flex',
+ gridColumn: { 'default': null, '@container (max-width: 800px)': '2' },
+ gridRow: { 'default': null, '@container (max-width: 800px)': '1' },
+ justifyContent: 'flex-end',
+ },
+ cadenceCell: {
+ gridColumn: { 'default': null, '@container (max-width: 800px)': '1' },
+ gridRow: { 'default': null, '@container (max-width: 800px)': '2' },
+ minWidth: 0,
+ // Lines up with the task name, past the status glyph.
+ paddingInlineStart: { 'default': null, '@container (max-width: 800px)': '24px' },
+ },
+ container: {
+ containerType: 'inline-size',
+ width: '100%',
+ },
+ grid: {
+ alignItems: 'center',
+ columnGap: '16px',
+ display: 'grid',
+ gridTemplateColumns: {
+ 'default': 'minmax(0, 1fr) 168px 216px 152px 64px',
+ '@container (max-width: 800px)': 'minmax(0, 1fr) auto',
+ },
+ paddingInline: '12px',
+ rowGap: { 'default': null, '@container (max-width: 800px)': '4px' },
+ },
+ // Column titles only make sense while the columns exist.
+ head: {
+ color: cssVar.colorTextSecondary,
+ display: { 'default': 'grid', '@container (max-width: 800px)': 'none' },
+ fontSize: '12px',
+ paddingBlock: '6px',
+ },
+ runsCell: {
+ display: 'flex',
+ gridColumn: { 'default': null, '@container (max-width: 800px)': '2' },
+ gridRow: { 'default': null, '@container (max-width: 800px)': '2' },
+ justifyContent: { 'default': null, '@container (max-width: 800px)': 'flex-end' },
+ minWidth: 0,
+ },
+ stateCell: {
+ gridColumn: { 'default': null, '@container (max-width: 800px)': '1 / -1' },
+ gridRow: { 'default': null, '@container (max-width: 800px)': '3' },
+ minWidth: 0,
+ paddingInlineStart: { 'default': null, '@container (max-width: 800px)': '24px' },
+ },
+ taskCell: {
+ gridColumn: { 'default': null, '@container (max-width: 800px)': '1' },
+ gridRow: { 'default': null, '@container (max-width: 800px)': '1' },
+ minWidth: 0,
+ },
+});
diff --git a/src/features/AgentTasks/features/AgentTaskItem.tsx b/src/features/AgentTasks/features/AgentTaskItem.tsx
index 8d51938ed66..9baec4bb6ef 100644
--- a/src/features/AgentTasks/features/AgentTaskItem.tsx
+++ b/src/features/AgentTasks/features/AgentTaskItem.tsx
@@ -4,27 +4,21 @@ import { ArchiveIcon, LockIcon } from 'lucide-react';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import TaskLabelChips from '@/features/TaskLabels/TaskLabelChips';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useTaskStore } from '@/store/task';
import type { TaskListItem } from '@/store/task/slices/list/initialState';
import { useDensityTokens } from '@/styles/density';
-import { shouldShowMemberAssignee } from '../shared/memberAssigneeMode';
import { taskDetailPath } from '../shared/taskDetailPath';
import { useTaskListOriginState } from '../shared/taskListOrigin';
-import AssigneeAgentSelector from './AssigneeAgentSelector';
-import AssigneeAvatar from './AssigneeAvatar';
-import AssigneeMemberSelector from './AssigneeMemberSelector';
-import AssigneeUserAvatar from './AssigneeUserAvatar';
import { formatTaskItemDate } from './formatTaskItemDate';
+import { TaskAssigneeCell } from './TaskAssigneeCell';
import TaskPriorityTag from './TaskPriorityTag';
import TaskProjectChip from './TaskProjectChip';
import TaskStatusTag from './TaskStatusTag';
import TaskSubtaskProgressTag from './TaskSubtaskProgressTag';
import TaskTriggerTag from './TaskTriggerTag';
-import { UnassignedAssigneeIcon } from './UnassignedAssigneeIcon';
import { useTaskItemContextMenu } from './useTaskItemContextMenu';
export type TaskItemRouteScope = 'agent' | 'global';
@@ -67,7 +61,6 @@ const AgentTaskItem = memo<TaskItemProps>((props) => {
);
const navigate = useWorkspaceAwareNavigate();
const taskListOriginState = useTaskListOriginState();
- const activeWorkspaceId = useActiveWorkspaceId();
const time = formatTaskItemDate(task.updatedAt || task.createdAt, {
formatOtherYear: t('time.formatOtherYear'),
@@ -165,41 +158,7 @@ const AgentTaskItem = memo<TaskItemProps>((props) => {
</Flexbox>
);
- const assigneeNode = (
- <Flexbox horizontal align={'center'} flex={'none'} gap={4}>
- {shouldShowMemberAssignee(activeWorkspaceId, task.assigneeUserId) && (
- <AssigneeMemberSelector
- currentUserId={task.assigneeUserId}
- taskCreatorId={task.createdByUserId}
- taskIdentifier={task.id}
- taskVisibility={task.visibility}
- >
- {task.assigneeUserId ? (
- <AssigneeUserAvatar profileCard userId={task.assigneeUserId} />
- ) : (
- <Tooltip title={tChat('taskList.assignTo')}>
- <UnassignedAssigneeIcon kind={'human'} />
- </Tooltip>
- )}
- </AssigneeMemberSelector>
- )}
- <AssigneeAgentSelector
- currentAgentId={task.assigneeAgentId}
- disabled={status === 'running'}
- taskCreatorId={task.createdByUserId}
- taskIdentifier={task.id}
- taskVisibility={task.visibility}
- >
- {task.assigneeAgentId ? (
- <AssigneeAvatar agentId={task.assigneeAgentId} profileCard={status !== 'running'} />
- ) : (
- <Tooltip title={status === 'running' ? undefined : tChat('taskList.assignTo')}>
- <AssigneeAvatar agentId={task.assigneeAgentId} />
- </Tooltip>
- )}
- </AssigneeAgentSelector>
- </Flexbox>
- );
+ const assigneeNode = <TaskAssigneeCell status={status} task={task} />;
const projectNode = hideProject ? null : <TaskProjectChip projectId={task.projectId} />;
diff --git a/src/features/AgentTasks/features/TaskAssigneeCell.tsx b/src/features/AgentTasks/features/TaskAssigneeCell.tsx
new file mode 100644
index 00000000000..434763456ed
--- /dev/null
+++ b/src/features/AgentTasks/features/TaskAssigneeCell.tsx
@@ -0,0 +1,68 @@
+import type { TaskStatus } from '@lobechat/types';
+import { Flexbox, Tooltip } from '@lobehub/ui';
+import { useTranslation } from 'react-i18next';
+
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+
+import { shouldShowMemberAssignee } from '../shared/memberAssigneeMode';
+import AssigneeAgentSelector from './AssigneeAgentSelector';
+import AssigneeAvatar from './AssigneeAvatar';
+import AssigneeMemberSelector from './AssigneeMemberSelector';
+import AssigneeUserAvatar from './AssigneeUserAvatar';
+import { UnassignedAssigneeIcon } from './UnassignedAssigneeIcon';
+
+interface TaskAssigneeCellProps {
+ status: TaskStatus;
+ task: {
+ assigneeAgentId?: string | null;
+ assigneeUserId?: string | null;
+ createdByUserId?: string | null;
+ id: string;
+ visibility?: 'private' | 'public';
+ };
+}
+
+/**
+ * Who a task row belongs to: its member owner (workspace only) and the agent
+ * that executes it, each a picker for reassigning in place.
+ */
+export const TaskAssigneeCell = ({ status, task }: TaskAssigneeCellProps) => {
+ const { t } = useTranslation('chat');
+ const activeWorkspaceId = useActiveWorkspaceId();
+
+ return (
+ <Flexbox horizontal align={'center'} flex={'none'} gap={4}>
+ {shouldShowMemberAssignee(activeWorkspaceId, task.assigneeUserId) && (
+ <AssigneeMemberSelector
+ currentUserId={task.assigneeUserId}
+ taskCreatorId={task.createdByUserId}
+ taskIdentifier={task.id}
+ taskVisibility={task.visibility}
+ >
+ {task.assigneeUserId ? (
+ <AssigneeUserAvatar profileCard userId={task.assigneeUserId} />
+ ) : (
+ <Tooltip title={t('taskList.assignTo')}>
+ <UnassignedAssigneeIcon kind={'human'} />
+ </Tooltip>
+ )}
+ </AssigneeMemberSelector>
+ )}
+ <AssigneeAgentSelector
+ currentAgentId={task.assigneeAgentId}
+ disabled={status === 'running'}
+ taskCreatorId={task.createdByUserId}
+ taskIdentifier={task.id}
+ taskVisibility={task.visibility}
+ >
+ {task.assigneeAgentId ? (
+ <AssigneeAvatar agentId={task.assigneeAgentId} profileCard={status !== 'running'} />
+ ) : (
+ <Tooltip title={status === 'running' ? undefined : t('taskList.assignTo')}>
+ <AssigneeAvatar agentId={task.assigneeAgentId} />
+ </Tooltip>
+ )}
+ </AssigneeAgentSelector>
+ </Flexbox>
+ );
+};
diff --git a/src/routes/(main)/tasks/scheduledTaskListLoader.test.ts b/src/routes/(main)/tasks/scheduledTaskListLoader.test.ts
index 8f05d33a022..2d8d110a418 100644
--- a/src/routes/(main)/tasks/scheduledTaskListLoader.test.ts
+++ b/src/routes/(main)/tasks/scheduledTaskListLoader.test.ts
@@ -13,7 +13,10 @@ vi.mock('@/store/task', () => ({
getTaskStoreState: () => ({ preHydrateScheduledTaskList }),
}));
-vi.mock('@/store/task/slices/list/action', () => ({ TASK_COLLECTION_PAGE_SIZE: 50 }));
+vi.mock('@/store/task/slices/list/action', () => ({
+ SCHEDULED_TASK_RECENT_RUNS: 5,
+ TASK_COLLECTION_PAGE_SIZE: 50,
+}));
const request = (path: string) => new Request(`http://localhost${path}`);
@@ -36,6 +39,8 @@ describe('scheduledTaskListLoader', () => {
limit: 50,
offset: 0,
projectId: undefined,
+ // The page asks for the same rows; a different key would miss the seed.
+ recentRuns: 5,
});
});
diff --git a/src/routes/(main)/tasks/scheduledTaskListLoader.ts b/src/routes/(main)/tasks/scheduledTaskListLoader.ts
index c693044a349..b20fdb02a56 100644
--- a/src/routes/(main)/tasks/scheduledTaskListLoader.ts
+++ b/src/routes/(main)/tasks/scheduledTaskListLoader.ts
@@ -3,7 +3,10 @@ import type { LoaderFunctionArgs } from 'react-router';
import { getActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaint';
import { getTaskStoreState } from '@/store/task';
-import { TASK_COLLECTION_PAGE_SIZE } from '@/store/task/slices/list/action';
+import {
+ SCHEDULED_TASK_RECENT_RUNS,
+ TASK_COLLECTION_PAGE_SIZE,
+} from '@/store/task/slices/list/action';
// Route loaders run before React commits the route: the only point where the
// persisted scheduled page (an async read) can land before the Tasks page
@@ -25,6 +28,7 @@ export const scheduledTaskListLoader = async ({
limit: TASK_COLLECTION_PAGE_SIZE,
offset: 0,
projectId: params.projectId,
+ recentRuns: SCHEDULED_TASK_RECENT_RUNS,
}),
PRE_PAINT_HYDRATE_TIMEOUT,
);
diff --git a/src/services/task.ts b/src/services/task.ts
index 16e9dbe642f..1a50e9296f8 100644
--- a/src/services/task.ts
+++ b/src/services/task.ts
@@ -49,6 +49,8 @@ class TaskService {
parentTaskId?: string | null;
priorities?: number[];
projectId?: string;
+ /** Attach each row's latest N runs and its `awaitingHuman` flag. */
+ recentRuns?: number;
/** "My tasks" narrowing: assigned to the caller, or created by them. */
scope?: 'assigned' | 'created';
statuses?: TaskStatus[];
diff --git a/src/store/task/slices/list/action.ts b/src/store/task/slices/list/action.ts
index 8f79cfdf305..d6f627c609b 100644
--- a/src/store/task/slices/list/action.ts
+++ b/src/store/task/slices/list/action.ts
@@ -62,6 +62,9 @@ export const COMPLETE_TASK_LIST_PAGE_SIZE = 500;
/** Page size of the Tasks page's paginated collections (scheduled, "My tasks"). */
export const TASK_COLLECTION_PAGE_SIZE = 50;
+/** How many past runs each row of the scheduled tasks table shows. */
+export const SCHEDULED_TASK_RECENT_RUNS = 5;
+
export interface ScheduledTaskListOptions {
agentId?: string;
/** The Tasks page filter; Home's roll-up sends none. */
@@ -69,6 +72,8 @@ export interface ScheduledTaskListOptions {
limit?: number;
offset?: number;
projectId?: string;
+ /** Rows carry their latest N runs and `awaitingHuman`; Home's roll-up asks for none. */
+ recentRuns?: number;
}
/**
@@ -82,6 +87,7 @@ export const scheduledTaskListQuery = ({
limit,
offset,
projectId,
+ recentRuns,
}: ScheduledTaskListOptions): TaskListQuery => ({
agentId: projectId ? undefined : agentId,
automated: true,
@@ -90,6 +96,8 @@ export const scheduledTaskListQuery = ({
offset,
orderBy: 'updatedAt',
projectId,
+ // Left out of the query (and its key) when unset, so Home's roll-up keeps its entry.
+ ...(recentRuns ? { recentRuns } : {}),
visibility: 'all',
});
export const COMPLETE_TASK_LIST_MAX_ITEMS = 1000;
@@ -214,6 +222,7 @@ export class TaskListSliceActionImpl {
includeArchived: query.includeArchived,
orderBy: query.orderBy,
projectId: query.projectId,
+ ...(query.recentRuns && { recentRuns: query.recentRuns }),
...(query.scope && { scope: query.scope }),
statuses: query.statuses,
visibility: filterToServerVisibility(query.visibility),
diff --git a/src/store/task/slices/list/projection.ts b/src/store/task/slices/list/projection.ts
index 65e7619d29b..2067ec339b4 100644
--- a/src/store/task/slices/list/projection.ts
+++ b/src/store/task/slices/list/projection.ts
@@ -40,6 +40,8 @@ export interface TaskListQuery {
offset?: number;
orderBy?: 'createdAt' | 'updatedAt';
projectId?: string;
+ /** Rows carry their latest N runs and `awaitingHuman` (the scheduled tasks table). */
+ recentRuns?: number;
/** "My tasks": assigned to, or created by, the caller. */
scope?: 'assigned' | 'created';
/** Sorted, so the same status set is one entry. */