Skip to content

๐Ÿคฏ LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

โœจ feat: task card, agent profile nav, CC streaming, view switcher polish (#14277)

Arvin Xu9555e4fda3b7
diff --git a/packages/builtin-tool-claude-code/src/client/Streaming/index.ts b/packages/builtin-tool-claude-code/src/client/Streaming/index.ts
index fd91910b1c5..456d55519cd 100644
--- a/packages/builtin-tool-claude-code/src/client/Streaming/index.ts
+++ b/packages/builtin-tool-claude-code/src/client/Streaming/index.ts
@@ -1,20 +1,42 @@
+import { RunCommandRender } from '@lobechat/shared-tool-ui/renders';
import type { BuiltinStreaming } from '@lobechat/types';
import { ClaudeCodeApiName } from '../../types';
+import EditRender from '../Render/Edit';
+import GlobRender from '../Render/Glob';
+import GrepRender from '../Render/Grep';
+import ReadRender from '../Render/Read';
+import SkillRender from '../Render/Skill';
+import TodoWriteRender from '../Render/TodoWrite';
+import WriteRender from '../Render/Write';
import AgentStreaming from './Agent';
+import { wrapRender } from './wrapRender';
/**
* Claude Code Streaming Components Registry.
*
* Rendered while a CC tool is still executing (args parsed, no tool_result
* yet). Without an entry here, the tool detail falls back to the generic
- * `ๅ‚ๆ•ฐๅˆ—่กจ` argument table. Register only tools whose live state is more
- * useful as bespoke UI than as an arg dump โ€” e.g. `Agent`, where we want to
- * surface the instruction and let the user jump into the subagent thread
- * while the subagent is still running.
+ * `ๅ‚ๆ•ฐๅˆ—่กจ` argument table.
+ *
+ * - `Agent` has its own bespoke streaming view (drops the result block,
+ * surfaces the subagent thread toggle).
+ * - The rest reuse their result Render via `wrapRender`. Those Renders
+ * already gracefully degrade when `content`/`pluginState` are absent
+ * (header-only for Read/Glob/Grep/Skill/Bash; full diff or file body
+ * for Edit/Write since those live in args). Same component for live and
+ * final keeps the UI stable across the result transition.
*/
export const ClaudeCodeStreamings: Record<string, BuiltinStreaming> = {
[ClaudeCodeApiName.Agent]: AgentStreaming as BuiltinStreaming,
+ [ClaudeCodeApiName.Bash]: wrapRender(RunCommandRender),
+ [ClaudeCodeApiName.Edit]: wrapRender(EditRender),
+ [ClaudeCodeApiName.Glob]: wrapRender(GlobRender),
+ [ClaudeCodeApiName.Grep]: wrapRender(GrepRender),
+ [ClaudeCodeApiName.Read]: wrapRender(ReadRender),
+ [ClaudeCodeApiName.Skill]: wrapRender(SkillRender),
+ [ClaudeCodeApiName.TodoWrite]: wrapRender(TodoWriteRender),
+ [ClaudeCodeApiName.Write]: wrapRender(WriteRender),
};
export { default as AgentStreaming } from './Agent';
diff --git a/packages/builtin-tool-claude-code/src/client/Streaming/wrapRender.tsx b/packages/builtin-tool-claude-code/src/client/Streaming/wrapRender.tsx
new file mode 100644
index 00000000000..30dfe601e6d
--- /dev/null
+++ b/packages/builtin-tool-claude-code/src/client/Streaming/wrapRender.tsx
@@ -0,0 +1,21 @@
+'use client';
+
+import type { BuiltinRenderProps, BuiltinStreaming } from '@lobechat/types';
+import { createElement, type ReactNode } from 'react';
+
+type AnyRender = (props: BuiltinRenderProps<any, any, any>) => ReactNode;
+
+/**
+ * Adapt a result `BuiltinRender` so it can stand in as a `BuiltinStreaming`.
+ *
+ * Most CC Renders (`Read`, `Write`, `Edit`, `Glob`, `Grep`, `Skill`,
+ * `Bash`/`RunCommand`, `TodoWrite`) read `args` for the header/diff/list and
+ * gracefully omit the body when `content`/`pluginState` are absent โ€” exactly
+ * the streaming-phase shape. Reusing the Render keeps live and final views
+ * visually identical and avoids duplicating per-tool layouts.
+ */
+export const wrapRender = (Render: AnyRender): BuiltinStreaming => {
+ const Streaming: BuiltinStreaming = ({ args, messageId, apiName, identifier, toolCallId }) =>
+ createElement(Render, { apiName, args, content: null, identifier, messageId, toolCallId });
+ return Streaming;
+};
diff --git a/packages/const/src/plugin.ts b/packages/const/src/plugin.ts
index 441e589016c..4f045b74a23 100644
--- a/packages/const/src/plugin.ts
+++ b/packages/const/src/plugin.ts
@@ -6,6 +6,7 @@ export const ARTIFACT_THINKING_TAG = 'lobeThinking';
export const MENTION_TAG = 'mention';
export const THINKING_TAG = 'think';
export const LOCAL_FILE_TAG = 'localFile';
+export const TASK_TAG = 'task';
// https://regex101.com/r/TwzTkf/2
export const ARTIFACT_TAG_REGEX = /<lobeArtifact\b[^>]*>(?<content>[\S\s]*?)(?:<\/lobeArtifact>|$)/;
diff --git a/packages/database/src/models/__tests__/taskTopic.test.ts b/packages/database/src/models/__tests__/taskTopic.test.ts
index f9f7443fa07..8110d65b23c 100644
--- a/packages/database/src/models/__tests__/taskTopic.test.ts
+++ b/packages/database/src/models/__tests__/taskTopic.test.ts
@@ -1,4 +1,5 @@
// @vitest-environment node
+import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
@@ -17,6 +18,9 @@ const createTopic = async (id: string, uid = userId) => {
return id;
};
+const getTopic = async (id: string) =>
+ (await serverDB.select().from(topics).where(eq(topics.id, id)).limit(1))[0];
+
beforeEach(async () => {
await serverDB.delete(users);
await serverDB.insert(users).values([{ id: userId }, { id: userId2 }]);
@@ -73,6 +77,84 @@ describe('TaskTopicModel', () => {
const topics = await topicModel.findByTaskId(task.id);
expect(topics[0].status).toBe('completed');
});
+
+ it('should mirror completed status to topics row', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const topicModel = new TaskTopicModel(serverDB, userId);
+ const task = await taskModel.create({ instruction: 'Test' });
+ await createTopic('tpc_done');
+
+ await topicModel.add(task.id, 'tpc_done', { seq: 1 });
+ await topicModel.updateStatus(task.id, 'tpc_done', 'completed');
+
+ const topic = await getTopic('tpc_done');
+ expect(topic.status).toBe('completed');
+ expect(topic.completedAt).toBeInstanceOf(Date);
+ });
+
+ it('should stamp completedAt without promoting status for non-completed terminal states', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const topicModel = new TaskTopicModel(serverDB, userId);
+ const task = await taskModel.create({ instruction: 'Test' });
+ await createTopic('tpc_failed');
+
+ await topicModel.add(task.id, 'tpc_failed', { seq: 1 });
+ await topicModel.updateStatus(task.id, 'tpc_failed', 'failed');
+
+ const topic = await getTopic('tpc_failed');
+ expect(topic.completedAt).toBeInstanceOf(Date);
+ // topic.status stays whatever it was (default null), not promoted to 'completed'
+ expect(topic.status).not.toBe('completed');
+ });
+
+ it('should not stamp completedAt for non-terminal status', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const topicModel = new TaskTopicModel(serverDB, userId);
+ const task = await taskModel.create({ instruction: 'Test' });
+ await createTopic('tpc_running');
+
+ await topicModel.add(task.id, 'tpc_running', { seq: 1 });
+ await topicModel.updateStatus(task.id, 'tpc_running', 'running');
+
+ const topic = await getTopic('tpc_running');
+ expect(topic.completedAt).toBeNull();
+ });
+ });
+
+ describe('cancelIfRunning', () => {
+ it('should cancel + stamp completedAt when topic was running', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const topicModel = new TaskTopicModel(serverDB, userId);
+ const task = await taskModel.create({ instruction: 'Test' });
+ await createTopic('tpc_cancel');
+
+ await topicModel.add(task.id, 'tpc_cancel', { seq: 1 });
+ const updated = await topicModel.cancelIfRunning(task.id, 'tpc_cancel');
+
+ expect(updated).toBe(true);
+ const topic = await getTopic('tpc_cancel');
+ expect(topic.completedAt).toBeInstanceOf(Date);
+ expect(topic.status).not.toBe('completed');
+ });
+
+ it('should be a no-op when topic is not running', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const topicModel = new TaskTopicModel(serverDB, userId);
+ const task = await taskModel.create({ instruction: 'Test' });
+ await createTopic('tpc_already_done');
+
+ await topicModel.add(task.id, 'tpc_already_done', { seq: 1 });
+ await topicModel.updateStatus(task.id, 'tpc_already_done', 'completed');
+ const completedAtBefore = (await getTopic('tpc_already_done')).completedAt;
+
+ // sleep one tick so a re-stamp would be detectable
+ await new Promise((r) => setTimeout(r, 5));
+ const updated = await topicModel.cancelIfRunning(task.id, 'tpc_already_done');
+
+ expect(updated).toBe(false);
+ const topic = await getTopic('tpc_already_done');
+ expect(topic.completedAt?.getTime()).toBe(completedAtBefore?.getTime());
+ });
});
describe('timeoutRunning', () => {
@@ -96,6 +178,44 @@ describe('TaskTopicModel', () => {
expect(tpcA!.status).toBe('completed');
expect(tpcB!.status).toBe('timeout');
});
+
+ it('should stamp completedAt on each timed-out topic', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const topicModel = new TaskTopicModel(serverDB, userId);
+ const task = await taskModel.create({ instruction: 'Test' });
+ await createTopic('tpc_t1');
+ await createTopic('tpc_t2');
+
+ await topicModel.add(task.id, 'tpc_t1', { seq: 1 });
+ await topicModel.add(task.id, 'tpc_t2', { seq: 2 });
+
+ await topicModel.timeoutRunning(task.id);
+
+ const t1 = await getTopic('tpc_t1');
+ const t2 = await getTopic('tpc_t2');
+ expect(t1.completedAt).toBeInstanceOf(Date);
+ expect(t2.completedAt).toBeInstanceOf(Date);
+ });
+ });
+
+ describe('findWithHandoff', () => {
+ it('should return completedAt joined from topics', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const topicModel = new TaskTopicModel(serverDB, userId);
+ const task = await taskModel.create({ instruction: 'Test' });
+ await createTopic('tpc_h1');
+ await createTopic('tpc_h2');
+
+ await topicModel.add(task.id, 'tpc_h1', { seq: 1 });
+ await topicModel.add(task.id, 'tpc_h2', { seq: 2 });
+ await topicModel.updateStatus(task.id, 'tpc_h1', 'completed');
+
+ const rows = await topicModel.findWithHandoff(task.id, 10);
+ const h1 = rows.find((r) => r.topicId === 'tpc_h1');
+ const h2 = rows.find((r) => r.topicId === 'tpc_h2');
+ expect(h1?.completedAt).toBeInstanceOf(Date);
+ expect(h2?.completedAt).toBeNull();
+ });
});
describe('updateHandoff', () => {
diff --git a/packages/database/src/models/task.ts b/packages/database/src/models/task.ts
index 80da1960795..27d3631ff6b 100644
--- a/packages/database/src/models/task.ts
+++ b/packages/database/src/models/task.ts
@@ -6,7 +6,7 @@ import type {
WorkspaceDocNode,
WorkspaceTreeNode,
} from '@lobechat/types';
-import { and, desc, eq, inArray, isNotNull, isNull, ne, sql } from 'drizzle-orm';
+import { and, desc, eq, inArray, isNotNull, isNull, ne, notInArray, sql } from 'drizzle-orm';
import { merge } from '@/utils/merge';
@@ -478,6 +478,22 @@ export class TaskModel {
.where(eq(tasks.id, id));
}
+ // Tasks eligible for cron-based dispatch.
+ // Excludes terminal/paused/running โ€” `paused` requires user attention,
+ // `running` is already in flight (and `runTask` would CONFLICT anyway).
+ static async getScheduledTasks(db: LobeChatDatabase): Promise<TaskItem[]> {
+ return db
+ .select()
+ .from(tasks)
+ .where(
+ and(
+ eq(tasks.automationMode, 'schedule'),
+ isNotNull(tasks.schedulePattern),
+ notInArray(tasks.status, ['canceled', 'completed', 'failed', 'paused', 'running']),
+ ),
+ );
+ }
+
// Find stuck tasks (running but heartbeat timed out)
// Only checks tasks that have both lastHeartbeatAt and heartbeatTimeout set
static async findStuckTasks(db: LobeChatDatabase): Promise<TaskItem[]> {
diff --git a/packages/database/src/models/taskTopic.ts b/packages/database/src/models/taskTopic.ts
index 2cedd83c1f2..8b7cb526dd6 100644
--- a/packages/database/src/models/taskTopic.ts
+++ b/packages/database/src/models/taskTopic.ts
@@ -3,8 +3,11 @@ import { and, desc, eq, sql } from 'drizzle-orm';
import type { TaskTopicItem } from '../schemas/task';
import { tasks, taskTopics } from '../schemas/task';
+import { topics } from '../schemas/topic';
import type { LobeChatDatabase } from '../type';
+const TERMINAL_TOPIC_STATUSES = new Set(['canceled', 'completed', 'failed', 'timeout']);
+
export class TaskTopicModel {
private readonly userId: string;
private readonly db: LobeChatDatabase;
@@ -14,6 +17,21 @@ export class TaskTopicModel {
this.userId = userId;
}
+ /**
+ * Mirror a terminal taskTopic transition onto the underlying topic record:
+ * stamp `topics.completedAt` so duration can be computed at read time, and
+ * promote `topics.status` to 'completed' on a clean finish.
+ */
+ private async markTopicEnded(topicId: string, status: string): Promise<void> {
+ const setClause: { completedAt: Date; status?: 'completed' } = { completedAt: new Date() };
+ if (status === 'completed') setClause.status = 'completed';
+
+ await this.db
+ .update(topics)
+ .set(setClause)
+ .where(and(eq(topics.id, topicId), eq(topics.userId, this.userId)));
+ }
+
async add(
taskId: string,
topicId: string,
@@ -42,6 +60,10 @@ export class TaskTopicModel {
eq(taskTopics.userId, this.userId),
),
);
+
+ if (TERMINAL_TOPIC_STATUSES.has(status)) {
+ await this.markTopicEnded(topicId, status);
+ }
}
/**
@@ -61,7 +83,10 @@ export class TaskTopicModel {
),
)
.returning();
- return result.length > 0;
+
+ const updated = result.length > 0;
+ if (updated) await this.markTopicEnded(topicId, 'canceled');
+ return updated;
}
async updateOperationId(taskId: string, topicId: string, operationId?: string): Promise<void> {
@@ -129,7 +154,15 @@ export class TaskTopicModel {
eq(taskTopics.userId, this.userId),
),
)
- .returning();
+ .returning({ topicId: taskTopics.topicId });
+
+ await Promise.all(
+ result
+ .map((r) => r.topicId)
+ .filter((id): id is string => !!id)
+ .map((id) => this.markTopicEnded(id, 'timeout')),
+ );
+
return result.length;
}
@@ -151,7 +184,6 @@ export class TaskTopicModel {
}
async findWithDetails(taskId: string) {
- const { topics } = await import('../schemas/topic');
return this.db
.select({
createdAt: topics.createdAt,
@@ -176,9 +208,9 @@ export class TaskTopicModel {
}
async findWithHandoff(taskId: string, limit: number) {
- const { topics } = await import('../schemas/topic');
return this.db
.select({
+ completedAt: topics.completedAt,
createdAt: taskTopics.createdAt,
handoff: taskTopics.handoff,
metadata: topics.metadata,
diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.ts
index 39f0053c3a9..6f0218d171f 100644
--- a/packages/types/src/task/index.ts
+++ b/packages/types/src/task/index.ts
@@ -213,6 +213,12 @@ export interface TaskDetailActivity {
artifacts?: unknown;
author?: TaskDetailActivityAuthor;
briefType?: string;
+ /**
+ * Topic-only: ISO timestamp when the topic run terminated (any of
+ * completed / failed / canceled / timeout). Pair with `time` (start) to
+ * compute elapsed duration.
+ */
+ completedAt?: string;
content?: string;
createdAt?: string;
cronJobId?: string | null;
diff --git a/packages/utils/src/cronEval.ts b/packages/utils/src/cronEval.ts
new file mode 100644
index 00000000000..551f76e3f85
--- /dev/null
+++ b/packages/utils/src/cronEval.ts
@@ -0,0 +1,163 @@
+import dayjs from 'dayjs';
+import timezone from 'dayjs/plugin/timezone';
+import utc from 'dayjs/plugin/utc';
+
+dayjs.extend(utc);
+dayjs.extend(timezone);
+
+export interface IsExecutionTimeInput {
+ /** Cron pattern in standard 5-field form: `minute hour day month weekday`. */
+ cronPattern: string;
+ /** Defaults to `Date.now()` when omitted โ€” exposed for tests. */
+ currentTime?: Date;
+ /** Last successful execution; used to dedup within the same window. */
+ lastExecutedAt?: Date | null;
+ /** IANA timezone (e.g. `Asia/Shanghai`); defaults to `UTC` when null/empty. */
+ timezone: string | null;
+ /** Tolerance window in minutes โ€” central dispatchers run on a coarse cadence
+ * (e.g. every 30 min), so an exact-minute match is too brittle. */
+ toleranceMinutes?: number;
+}
+
+const DAILY_PATTERN_HOUR_REGEX = /^\d+$/;
+
+/**
+ * Decide whether a cron pattern is "due now" within a tolerance window.
+ *
+ * Designed for a central dispatcher polling on a fixed cadence (e.g. QStash
+ * Schedule firing every 30 minutes). The matcher:
+ *
+ * - Converts the dispatcher's UTC `now` to the pattern's local timezone.
+ * - Dedups against `lastExecutedAt` so the same pattern doesn't fire twice
+ * within its own interval (e.g. a daily 09:00 job won't refire at 09:15
+ * on the same day in `Asia/Shanghai`).
+ * - Catches up missed daily runs: if the dispatcher missed the scheduled hour
+ * (downtime / cold start) and the job hasn't run today yet, a later tick
+ * on the same day still fires it.
+ *
+ * Supported patterns (matches what `packages/utils/src/cron.ts` produces):
+ *
+ * - `*\/N * * * *` โ€” every N minutes
+ * - `M * * * *` โ€” every hour at minute M
+ * - `M *\/N * * *` โ€” every N hours at minute M
+ * - `M H * * *` โ€” daily at H:M
+ * - `M H * * D[,D]` โ€” weekly on weekday list at H:M
+ * - `M *,M * * *` โ€” minute list (e.g. `0,15,30,45`)
+ * - `M H,H * * *` โ€” hour list
+ */
+export const isExecutionTime = (input: IsExecutionTimeInput): boolean => {
+ const {
+ cronPattern,
+ timezone: tz,
+ lastExecutedAt,
+ currentTime = new Date(),
+ toleranceMinutes = 5,
+ } = input;
+
+ const jobTimezone = tz || 'UTC';
+ const localTime = dayjs(currentTime).tz(jobTimezone);
+ const minute = localTime.minute();
+ const hour = localTime.hour();
+
+ const parts = cronPattern.trim().split(/\s+/);
+ if (parts.length !== 5) return false;
+ const [cronMinute, cronHour, , , cronWeekday] = parts;
+
+ // โ”€โ”€ Dedup against last execution โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+ if (lastExecutedAt) {
+ const last = new Date(lastExecutedAt);
+ const minutesSince = (currentTime.getTime() - last.getTime()) / (1000 * 60);
+
+ if (cronMinute.startsWith('*/')) {
+ const minIntervalMin = Number.parseInt(cronMinute.slice(2), 10);
+ if (Number.isFinite(minIntervalMin) && minutesSince < minIntervalMin) return false;
+ } else if (cronHour.startsWith('*/')) {
+ const hourInterval = Number.parseInt(cronHour.slice(2), 10);
+ if (Number.isFinite(hourInterval) && minutesSince < hourInterval * 60) return false;
+ } else if (cronHour === '*') {
+ // Every hour at a specific minute (e.g. `30 * * * *`)
+ if (minutesSince < 60) return false;
+ } else if (DAILY_PATTERN_HOUR_REGEX.test(cronHour)) {
+ // Daily at specific hour โ€” dedup by calendar day in the job's timezone
+ const lastLocal = dayjs(last).tz(jobTimezone);
+ const nowLocal = dayjs(currentTime).tz(jobTimezone);
+ if (
+ lastLocal.year() === nowLocal.year() &&
+ lastLocal.month() === nowLocal.month() &&
+ lastLocal.date() === nowLocal.date()
+ ) {
+ return false;
+ }
+ }
+ }
+
+ const weekday = localTime.day();
+
+ // โ”€โ”€ Daily catch-up: scheduled hour passed today and we haven't run yet โ”€โ”€
+ const isDailyPattern =
+ DAILY_PATTERN_HOUR_REGEX.test(cronHour) && /^(?:\d+|\*\/\d+)$/.test(cronMinute);
+
+ if (isDailyPattern) {
+ const targetHour = Number.parseInt(cronHour, 10);
+ let shouldCatchUp: boolean;
+
+ if (lastExecutedAt) {
+ const lastLocal = dayjs(lastExecutedAt).tz(jobTimezone);
+ const nowLocal = dayjs(currentTime).tz(jobTimezone);
+ const lastIsToday =
+ lastLocal.year() === nowLocal.year() &&
+ lastLocal.month() === nowLocal.month() &&
+ lastLocal.date() === nowLocal.date();
+ shouldCatchUp = !lastIsToday && hour > targetHour;
+ } else {
+ shouldCatchUp = hour > targetHour;
+ }
+
+ if (shouldCatchUp) {
+ if (cronWeekday !== '*') {
+ const allowedWeekdays = cronWeekday.split(',').map((d) => Number.parseInt(d.trim(), 10));
+ if (!allowedWeekdays.includes(weekday)) return false;
+ }
+ return true;
+ }
+ }
+
+ // โ”€โ”€ Minute field โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+ if (cronMinute !== '*') {
+ if (cronMinute.startsWith('*/')) {
+ const interval = Number.parseInt(cronMinute.slice(2), 10);
+ if (!Number.isFinite(interval) || interval <= 0) return false;
+ const lastSlot = Math.floor(minute / interval) * interval;
+ if (minute - lastSlot > toleranceMinutes) return false;
+ } else if (cronMinute.includes(',')) {
+ const allowed = cronMinute.split(',').map((m) => Number.parseInt(m, 10));
+ if (!allowed.some((target) => Math.abs(minute - target) <= toleranceMinutes)) return false;
+ } else {
+ const target = Number.parseInt(cronMinute, 10);
+ if (Math.abs(minute - target) > toleranceMinutes) return false;
+ }
+ }
+
+ // โ”€โ”€ Hour field โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+ if (cronHour !== '*') {
+ if (cronHour.startsWith('*/')) {
+ const interval = Number.parseInt(cronHour.slice(2), 10);
+ if (!Number.isFinite(interval) || interval <= 0) return false;
+ const lastSlot = Math.floor(hour / interval) * interval;
+ if (hour - lastSlot > 0) return false;
+ } else if (cronHour.includes(',')) {
+ const allowed = cronHour.split(',').map((h) => Number.parseInt(h, 10));
+ if (!allowed.includes(hour)) return false;
+ } else {
+ if (hour !== Number.parseInt(cronHour, 10)) return false;
+ }
+ }
+
+ // โ”€โ”€ Weekday field โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+ if (cronWeekday !== '*') {
+ const allowed = cronWeekday.split(',').map((d) => Number.parseInt(d.trim(), 10));
+ if (!allowed.includes(weekday)) return false;
+ }
+
+ return true;
+};
diff --git a/src/features/AgentProfileCard/AgentProfilePopup.tsx b/src/features/AgentProfileCard/AgentProfilePopup.tsx
index 57e97a01ba3..deb5a7a8ca9 100644
--- a/src/features/AgentProfileCard/AgentProfilePopup.tsx
+++ b/src/features/AgentProfileCard/AgentProfilePopup.tsx
@@ -111,6 +111,11 @@ const AgentProfilePopup = memo<AgentProfilePopupProps>(
navigate(`/group/${groupId}/profile?tab=${agentId}`);
};
+ const handleHeaderClick = () => {
+ setOpen(false);
+ navigate(`/agent/${agentId}/profile`);
+ };
+
const hasDisplay = Boolean(merged.title || merged.avatar || merged.description);
const showSkeleton = !hasDisplay && isLoading;
@@ -197,6 +202,7 @@ const AgentProfilePopup = memo<AgentProfilePopupProps>(
</Flexbox>
) : undefined
}
+ onHeaderClick={handleHeaderClick}
>
{modelSection}
</AgentProfileCard>
diff --git a/src/features/AgentProfileCard/index.tsx b/src/features/AgentProfileCard/index.tsx
index e460176098d..496cb20adc8 100644
--- a/src/features/AgentProfileCard/index.tsx
+++ b/src/features/AgentProfileCard/index.tsx
@@ -15,6 +15,16 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
bannerInner: css`
filter: blur(44px);
`,
+ clickableAvatar: css`
+ cursor: pointer;
+ `,
+ clickableTitle: css`
+ cursor: pointer;
+
+ &:hover {
+ color: ${cssVar.colorPrimary};
+ }
+ `,
container: css`
overflow: hidden;
width: 280px;
@@ -63,11 +73,22 @@ export interface AgentProfileCardProps {
headerAction?: ReactNode;
/** Show inline skeletons for fields that are still loading. */
loading?: boolean;
+ /** When set, avatar + title become clickable and trigger this handler. */
+ onHeaderClick?: () => void;
title: string;
}
const AgentProfileCard = memo<AgentProfileCardProps>(
- ({ avatar, backgroundColor, description, headerAction, loading, title, children }) => {
+ ({
+ avatar,
+ backgroundColor,
+ description,
+ headerAction,
+ loading,
+ onHeaderClick,
+ title,
+ children,
+ }) => {
return (
<Flexbox className={styles.container}>
<Center className={styles.banner} style={{ background: cssVar.colorFillTertiary }}>
@@ -86,13 +107,19 @@ const AgentProfileCard = memo<AgentProfileCardProps>(
emojiScaleWithBackground
avatar={avatar || DEFAULT_AVATAR}
background={backgroundColor ?? undefined}
+ className={onHeaderClick ? styles.clickableAvatar : undefined}
shape={'square'}
size={48}
style={{ border: `2px solid ${cssVar.colorBgElevated}` }}
+ onClick={onHeaderClick}
/>
<Flexbox gap={2}>
<Flexbox horizontal align={'center'} justify={'space-between'}>
- <Text ellipsis className={styles.name}>
+ <Text
+ ellipsis
+ className={`${styles.name} ${onHeaderClick ? styles.clickableTitle : ''}`}
+ onClick={onHeaderClick}
+ >
{title}
</Text>
{headerAction}
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskBriefCard.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskBriefCard.tsx
index b3b14ca505f..46c16674730 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskBriefCard.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskBriefCard.tsx
@@ -9,8 +9,8 @@ import {
} from '@lobehub/ui';
import { App } from 'antd';
import { cssVar } from 'antd-style';
-import { MoreHorizontal, Trash } from 'lucide-react';
-import { memo, useCallback, useMemo } from 'react';
+import { Check, ChevronDownIcon, ChevronUpIcon, MoreHorizontal, Trash } from 'lucide-react';
+import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import BriefCardActions from '@/features/DailyBrief/BriefCardActions';
@@ -33,6 +33,9 @@ const TaskBriefCard = memo<TaskBriefCardProps>(
const { t } = useTranslation('home');
const { modal } = App.useApp();
const deleteBrief = useBriefStore((s) => s.deleteBrief);
+ const isResolved = Boolean(brief.resolvedAction);
+ const [expanded, setExpanded] = useState(false);
+ const showFull = !isResolved || expanded;
const handleDelete = useCallback(() => {
modal.confirm({
@@ -76,21 +79,39 @@ const TaskBriefCard = memo<TaskBriefCardProps>(
<Text ellipsis style={{ flex: 1 }} weight={500}>
{brief.title}
</Text>
+ {isResolved && !expanded && (
+ <Flexbox horizontal align={'center'} gap={4}>
+ <Icon color={cssVar.colorTextQuaternary} icon={Check} size={14} />
+ <Text className={briefStyles.resolvedTag}>{t('brief.resolved')}</Text>
+ </Flexbox>
+ )}
<Time date={brief.createdAt} />
+ {isResolved && (
+ <ActionIcon
+ icon={expanded ? ChevronUpIcon : ChevronDownIcon}
+ size={'small'}
+ title={expanded ? t('brief.collapse') : t('brief.expandAll')}
+ onClick={() => setExpanded((v) => !v)}
+ />
+ )}
<DropdownMenu items={menuItems}>
<ActionIcon icon={MoreHorizontal} size={'small'} />
</DropdownMenu>
</Flexbox>
- <BriefCardSummary summary={brief.summary} />
- <BriefCardActions
- actions={brief.actions}
- briefId={brief.id}
- briefType={brief.type}
- resolvedAction={brief.resolvedAction}
- taskId={brief.taskId}
- onAfterAddComment={onAfterAddComment}
- onAfterResolve={onAfterResolve}
- />
+ {showFull && (
+ <>
+ <BriefCardSummary summary={brief.summary} />
+ <BriefCardActions
+ actions={brief.actions}
+ briefId={brief.id}
+ briefType={brief.type}
+ resolvedAction={brief.resolvedAction}
+ taskId={brief.taskId}
+ onAfterAddComment={onAfterAddComment}
+ onAfterResolve={onAfterResolve}
+ />
+ </>
+ )}
</Block>
);
},
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskProperties.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskProperties.tsx
index a605dd62599..d3baa0ec9ff 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskProperties.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskProperties.tsx
@@ -96,10 +96,11 @@ const TaskProperties = memo(() => {
variant={'borderless'}
>
<TaskTriggerTag
- heartbeatInterval={automationMode === 'heartbeat' ? heartbeatInterval : undefined}
+ automationMode={automationMode}
+ heartbeatInterval={heartbeatInterval}
mode="inline"
- schedulePattern={automationMode === 'schedule' ? schedulePattern : undefined}
- scheduleTimezone={automationMode === 'schedule' ? scheduleTimezone : undefined}
+ schedulePattern={schedulePattern}
+ scheduleTimezone={scheduleTimezone}
/>
</Block>
</TaskScheduleConfig>
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx
index b66fc8e46fd..fee0087a6ec 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx
@@ -42,38 +42,11 @@ interface TaskTreeNode {
task: TaskDetailSubtask;
}
-const buildTree = (subtasks: TaskDetailSubtask[]): TaskTreeNode[] => {
- if (subtasks.some((item) => (item.children?.length ?? 0) > 0)) {
- return subtasks.map((task) => ({
- children: buildTree(task.children ?? []),
- task,
- }));
- }
-
- const nodeMap = new Map(
- subtasks.map((task) => [
- task.identifier,
- { children: [] as TaskTreeNode[], task } satisfies TaskTreeNode,
- ]),
- );
- const roots: TaskTreeNode[] = [];
-
- for (const task of subtasks) {
- const node = nodeMap.get(task.identifier);
- if (!node) continue;
-
- const parentIdentifier = task.blockedBy;
- const parent = parentIdentifier ? nodeMap.get(parentIdentifier) : undefined;
- if (parent && parent.task.identifier !== task.identifier) {
- parent.children.push(node);
- continue;
- }
-
- roots.push(node);
- }
-
- return roots;
-};
+const buildTree = (subtasks: TaskDetailSubtask[]): TaskTreeNode[] =>
+ subtasks.map((task) => ({
+ children: buildTree(task.children ?? []),
+ task,
+ }));
const SubtaskTitle = memo<{ task: TaskDetailSubtask }>(({ task }) => {
const status = toTaskStatus(task.status);
@@ -114,6 +87,7 @@ const SubtaskTitle = memo<{ task: TaskDetailSubtask }>(({ task }) => {
onClick={(e) => e.stopPropagation()}
>
<TaskTriggerTag
+ automationMode={task.automationMode}
heartbeatInterval={task.heartbeat?.interval}
schedulePattern={task.schedule?.pattern}
scheduleTimezone={task.schedule?.timezone}
diff --git a/src/features/AgentTasks/AgentTaskDetail/TopicCard.tsx b/src/features/AgentTasks/AgentTaskDetail/TopicCard.tsx
index e1c4a1e28a6..6bea96746ae 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TopicCard.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TopicCard.tsx
@@ -39,8 +39,13 @@ const TopicCard = memo<TopicCardProps>(({ activity }) => {
const openTopicDrawer = useTaskStore((s) => s.openTopicDrawer);
const isRunning = activity.status === 'running';
+ const finalDuration =
+ !isRunning && activity.time && activity.completedAt
+ ? new Date(activity.completedAt).getTime() - new Date(activity.time).getTime()
+ : null;
+
const [elapsed, setElapsed] = useState(() =>
- activity.time ? Date.now() - new Date(activity.time).getTime() : 0,
+ isRunning && activity.time ? Date.now() - new Date(activity.time).getTime() : 0,
);
useEffect(() => {
@@ -60,7 +65,11 @@ const TopicCard = memo<TopicCardProps>(({ activity }) => {
}, [activity.id]);
const startedAt = activity.time ? dayjs(activity.time).fromNow() : '';
- const durationText = isRunning ? formatDuration(elapsed) : '';
+ const durationText = isRunning
+ ? formatDuration(elapsed)
+ : finalDuration != null && finalDuration >= 0
+ ? formatDuration(finalDuration)
+ : '';
const menuItems: DropdownItem[] = [
{
diff --git a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsx b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsx
index 8522e691d1d..1f91a11e0ba 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsx
@@ -7,6 +7,7 @@ import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { ChatList, ConversationProvider, MessageItem } from '@/features/Conversation';
+import { TaskCardScopeProvider } from '@/features/Conversation/Markdown/plugins/Task';
import { useGatewayReconnect } from '@/hooks/useGatewayReconnect';
import { useOperationState } from '@/hooks/useOperationState';
import { useChatStore } from '@/store/chat';
@@ -65,9 +66,11 @@ const TopicChatDrawerBody = memo<TopicChatDrawerBodyProps>(({ agentId, topicId }
replaceMessages(msgs, { context: ctx });
}}
>
- <Flexbox flex={1} height={'100%'} style={{ overflow: 'hidden' }}>
- <ChatList disableActionsBar itemContent={itemContent} />
- </Flexbox>
+ <TaskCardScopeProvider value={true}>
+ <Flexbox flex={1} height={'100%'} style={{ overflow: 'hidden' }}>
+ <ChatList disableActionsBar itemContent={itemContent} />
+ </Flexbox>
+ </TaskCardScopeProvider>
</ConversationProvider>
);
});
diff --git a/src/features/AgentTasks/features/AgentTaskItem.tsx b/src/features/AgentTasks/features/AgentTaskItem.tsx
index 02f18b7edbc..ab38a2f09f8 100644
--- a/src/features/AgentTasks/features/AgentTaskItem.tsx
+++ b/src/features/AgentTasks/features/AgentTaskItem.tsx
@@ -125,6 +125,7 @@ const AgentTaskItem = memo<TaskItemProps>(({ task, variant = 'default' }) => {
taskId={task.identifier}
>
<TaskTriggerTag
+ automationMode={task.automationMode}
heartbeatInterval={taskDetail?.heartbeat?.interval}
schedulePattern={task.schedulePattern}
scheduleTimezone={task.scheduleTimezone}
diff --git a/src/features/AgentTasks/features/TaskTriggerTag.tsx b/src/features/AgentTasks/features/TaskTriggerTag.tsx
index f273ed7430d..6dbe0713b29 100644
--- a/src/features/AgentTasks/features/TaskTriggerTag.tsx
+++ b/src/features/AgentTasks/features/TaskTriggerTag.tsx
@@ -11,6 +11,7 @@ import {
} from '@/features/AgentTasks/AgentTaskDetail/scheduler/helpers';
interface TaskTriggerTagProps {
+ automationMode?: 'heartbeat' | 'schedule' | null;
heartbeatInterval?: number | null;
mode?: 'inline' | 'tag';
schedulePattern?: string | null;
@@ -18,7 +19,7 @@ interface TaskTriggerTagProps {
}
const TaskTriggerTag = memo<TaskTriggerTagProps>(
- ({ heartbeatInterval, mode = 'tag', schedulePattern, scheduleTimezone }) => {
+ ({ automationMode, heartbeatInterval, mode = 'tag', schedulePattern, scheduleTimezone }) => {
const { t, i18n } = useTranslation('chat');
const data = useMemo<
| {
@@ -28,7 +29,9 @@ const TaskTriggerTag = memo<TaskTriggerTagProps>(
}
| undefined
>(() => {
- if (schedulePattern) {
+ // automationMode is the source of truth โ€” DB may carry stale fields from
+ // a previous mode (e.g. a heartbeat task that was once on a schedule).
+ if (automationMode === 'schedule' && schedulePattern) {
const primary = formatScheduleDescription(schedulePattern, t);
const tzName = scheduleTimezone
? formatTimezoneName(scheduleTimezone, i18n.language)
@@ -40,7 +43,7 @@ const TaskTriggerTag = memo<TaskTriggerTagProps>(
};
}
- if (heartbeatInterval && heartbeatInterval > 0) {
+ if (automationMode === 'heartbeat' && heartbeatInterval && heartbeatInterval > 0) {
const every = t('taskSchedule.tag.every', {
interval: formatIntervalLabel(heartbeatInterval, t),
});
@@ -51,7 +54,7 @@ const TaskTriggerTag = memo<TaskTriggerTagProps>(
}
return undefined;
- }, [heartbeatInterval, schedulePattern, scheduleTimezone, t, i18n.language]);
+ }, [automationMode, heartbeatInterval, schedulePattern, scheduleTimezone, t, i18n.language]);
if (mode === 'inline') {
return (
diff --git a/src/features/Conversation/Markdown/plugins/Task/Render.tsx b/src/features/Conversation/Markdown/plugins/Task/Render.tsx
new file mode 100644
index 00000000000..cb2b06c7103
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/Task/Render.tsx
@@ -0,0 +1,257 @@
+import type { TaskStatus } from '@lobechat/types';
+import { Block, Flexbox, Text } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { ClipboardList } from 'lucide-react';
+import { memo, useMemo } from 'react';
+
+import TaskStatusIcon from '@/features/AgentTasks/features/TaskStatusIcon';
+
+import { type MarkdownElementProps } from '../type';
+import { useTaskCardScope } from './context';
+import { type ParsedTaskContent, parseTaskContent } from './parseTaskContent';
+
+const KNOWN_STATUSES: TaskStatus[] = [
+ 'backlog',
+ 'canceled',
+ 'completed',
+ 'failed',
+ 'paused',
+ 'running',
+ 'scheduled',
+];
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ container: css`
+ overflow: hidden;
+ border-radius: 12px;
+ box-shadow: ${cssVar.boxShadowTertiary};
+ `,
+ divider: css`
+ inline-size: 100%;
+ block-size: 1px;
+ background: ${cssVar.colorSplit};
+ `,
+ fallback: css`
+ overflow: auto;
+
+ padding-block: 12px;
+ padding-inline: 14px;
+ border: 1px dashed ${cssVar.colorBorderSecondary};
+ border-radius: 8px;
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ white-space: pre-wrap;
+ `,
+ fieldKey: css`
+ flex: none;
+ min-inline-size: 64px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ fieldRow: css`
+ font-size: 13px;
+ line-height: 1.6;
+ `,
+ fieldValue: css`
+ color: ${cssVar.colorTextSecondary};
+ word-break: break-word;
+ `,
+ headerIcon: css`
+ display: flex;
+ flex: none;
+ align-items: center;
+ justify-content: center;
+
+ inline-size: 32px;
+ block-size: 32px;
+ border-radius: 8px;
+
+ color: ${cssVar.colorPrimary};
+
+ background: ${cssVar.colorPrimaryBg};
+ `,
+ identifier: css`
+ flex: none;
+
+ padding-block: 1px;
+ padding-inline: 6px;
+ border-radius: 4px;
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ instruction: css`
+ font-size: 13px;
+ line-height: 1.7;
+ color: ${cssVar.colorText};
+ white-space: pre-wrap;
+ `,
+ rawList: css`
+ margin: 0;
+ padding: 0;
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 12px;
+ line-height: 1.6;
+ color: ${cssVar.colorTextSecondary};
+ list-style: none;
+
+ li {
+ white-space: pre-wrap;
+ }
+ `,
+ section: css`
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+
+ summary {
+ cursor: pointer;
+ padding-block: 4px;
+ color: ${cssVar.colorTextSecondary};
+
+ &:hover {
+ color: ${cssVar.colorText};
+ }
+ }
+ `,
+}));
+
+const isKnownStatus = (status?: string): status is TaskStatus =>
+ !!status && (KNOWN_STATUSES as string[]).includes(status);
+
+const FieldRow = memo<{ label: string; value?: string }>(({ label, value }) => {
+ if (!value) return null;
+ return (
+ <Flexbox horizontal className={styles.fieldRow} gap={8}>
+ <span className={styles.fieldKey}>{label}</span>
+ <span className={styles.fieldValue}>{value}</span>
+ </Flexbox>
+ );
+});
+
+const RawSection = memo<{ items: string[]; label: string }>(({ items, label }) => {
+ if (!items || items.length === 0) return null;
+ return (
+ <details className={styles.section}>
+ <summary>
+ {label} ({items.length})
+ </summary>
+ <ul className={styles.rawList}>
+ {items.map((line, idx) => (
+ <li key={idx}>{line}</li>
+ ))}
+ </ul>
+ </details>
+ );
+});
+
+interface TaskRenderProps extends MarkdownElementProps {
+ raw?: string;
+}
+
+const Render = memo<TaskRenderProps>(({ children }) => {
+ const enabled = useTaskCardScope();
+ const text = typeof children === 'string' ? children : String(children ?? '');
+ const parsed = useMemo<ParsedTaskContent>(() => parseTaskContent(text), [text]);
+
+ if (!enabled) {
+ return <pre className={styles.fallback}>{text}</pre>;
+ }
+
+ const titleText = parsed.name || parsed.identifier || '';
+
+ return (
+ <Block
+ className={styles.container}
+ gap={12}
+ paddingBlock={14}
+ paddingInline={16}
+ variant={'outlined'}
+ >
+ <Flexbox horizontal align={'center'} gap={12}>
+ <span className={styles.headerIcon}>
+ <ClipboardList size={16} />
+ </span>
+ <Flexbox flex={1} gap={4} style={{ minWidth: 0 }}>
+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
+ {parsed.identifier && <span className={styles.identifier}>{parsed.identifier}</span>}
+ <Text ellipsis weight={500}>
+ {titleText}
+ </Text>
+ </Flexbox>
+ {(parsed.status || parsed.priority) && (
+ <Flexbox horizontal align={'center'} gap={8}>
+ {parsed.status && (
+ <Flexbox horizontal align={'center'} gap={4}>
+ {isKnownStatus(parsed.status) ? (
+ <TaskStatusIcon size={14} status={parsed.status} />
+ ) : (
+ <span style={{ color: cssVar.colorTextTertiary, fontSize: 12 }}>
+ {parsed.statusIcon}
+ </span>
+ )}
+ <Text fontSize={12} type={'secondary'}>
+ {parsed.status}
+ </Text>
+ </Flexbox>
+ )}
+ {parsed.priority && (
+ <Text fontSize={12} type={'secondary'}>
+ ยท Priority: {parsed.priority}
+ </Text>
+ )}
+ </Flexbox>
+ )}
+ </Flexbox>
+ </Flexbox>
+
+ {parsed.instruction && (
+ <>
+ <div className={styles.divider} />
+ <Flexbox gap={4}>
+ <Text fontSize={12} type={'secondary'}>
+ Instruction
+ </Text>
+ <div className={styles.instruction}>{parsed.instruction}</div>
+ </Flexbox>
+ </>
+ )}
+
+ {(parsed.description ||
+ parsed.agent ||
+ parsed.parent ||
+ parsed.topics ||
+ parsed.dependencies ||
+ parsed.review) && (
+ <Flexbox gap={4}>
+ <FieldRow label="Description" value={parsed.description} />
+ <FieldRow label="Agent" value={parsed.agent} />
+ <FieldRow label="Parent" value={parsed.parent} />
+ <FieldRow label="Topics" value={parsed.topics} />
+ <FieldRow label="Dependencies" value={parsed.dependencies} />
+ <FieldRow label="Review" value={parsed.review} />
+ </Flexbox>
+ )}
+
+ {(parsed.subtasks?.length ||
+ parsed.activities?.length ||
+ parsed.workspace?.length ||
+ parsed.reviewRubrics?.length) && (
+ <Flexbox gap={4}>
+ <RawSection items={parsed.subtasks ?? []} label="Subtasks" />
+ <RawSection items={parsed.activities ?? []} label="Activities" />
+ <RawSection items={parsed.workspace ?? []} label="Workspace" />
+ <RawSection items={parsed.reviewRubrics ?? []} label="Review rubrics" />
+ </Flexbox>
+ )}
+ </Block>
+ );
+});
+
+Render.displayName = 'TaskRender';
+
+export default Render;
diff --git a/src/features/Conversation/Markdown/plugins/Task/context.ts b/src/features/Conversation/Markdown/plugins/Task/context.ts
new file mode 100644
index 00000000000..e408555781f
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/Task/context.ts
@@ -0,0 +1,7 @@
+import { createContext, useContext } from 'react';
+
+const TaskCardScopeContext = createContext(false);
+
+export const TaskCardScopeProvider = TaskCardScopeContext.Provider;
+
+export const useTaskCardScope = () => useContext(TaskCardScopeContext);
diff --git a/src/features/Conversation/Markdown/plugins/Task/index.ts b/src/features/Conversation/Markdown/plugins/Task/index.ts
new file mode 100644
index 00000000000..1e3bec540db
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/Task/index.ts
@@ -0,0 +1,16 @@
+import { TASK_TAG } from '@/const/plugin';
+
+import { type MarkdownElement } from '../type';
+import { remarkTaskBlock } from './remarkTaskBlock';
+import Component from './Render';
+
+export { TaskCardScopeProvider } from './context';
+
+const TaskElement: MarkdownElement = {
+ Component,
+ remarkPlugin: remarkTaskBlock,
+ scope: 'user',
+ tag: TASK_TAG,
+};
+
+export default TaskElement;
diff --git a/src/features/Conversation/Markdown/plugins/Task/integration.test.ts b/src/features/Conversation/Markdown/plugins/Task/integration.test.ts
new file mode 100644
index 00000000000..14d99a247ea
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/Task/integration.test.ts
@@ -0,0 +1,64 @@
+import remarkParse from 'remark-parse';
+import { unified } from 'unified';
+import { describe, expect, it } from 'vitest';
+
+import { remarkTaskBlock } from './remarkTaskBlock';
+
+const runRemark = (markdown: string) => {
+ const processor = unified().use(remarkParse).use(remarkTaskBlock);
+ const tree = processor.parse(markdown);
+ return processor.runSync(tree);
+};
+
+describe('task remark integration', () => {
+ it('handles a leading user_feedback block before <task>', () => {
+ const markdown = `<user_feedback>
+<comment id="c1" time="1m ago">looks good</comment>
+</user_feedback>
+
+<task>
+T-1 demo
+Status: โญ• backlog Priority: -
+Instruction: do it.
+
+Review: (not configured)
+</task>`;
+
+ const tree: any = runRemark(markdown);
+ const taskNodes = (tree.children as any[]).filter((c) => c.type === 'taskBlock');
+ expect(taskNodes).toHaveLength(1);
+ const value = taskNodes[0].data.hChildren[0].value as string;
+ expect(value).toContain('T-1 demo');
+ expect(value).toContain('Review: (not configured)');
+ });
+
+ it('does not crash when no <task> tag present', () => {
+ const markdown = `Just a plain message without task xml.`;
+ const tree: any = runRemark(markdown);
+ const taskNodes = (tree.children as any[]).filter((c) => c.type === 'taskBlock');
+ expect(taskNodes).toHaveLength(0);
+ });
+
+ it('captures the entire <task> block content as a single text child', () => {
+ const markdown = `<task>
+<hint>This tag contains the complete task context. Do NOT call viewTask to re-fetch it.</hint>
+T-32 ๅ†™ไธ€ๆœฌใ€ŠAI Agent ๅฎžๆˆ˜ๆŒ‡ๅ—ใ€‹
+Status: โญ• backlog Priority: -
+Instruction: ๅธฎๆˆ‘ๅ†™ไธ€ๆœฌ้ขๅ‘ๅผ€ๅ‘่€…็š„ AI Agent ๆŠ€ๆœฏไนฆ็ฑใ€‚
+
+Review: (not configured)
+</task>`;
+
+ const tree: any = runRemark(markdown);
+
+ const taskNodes = (tree.children as any[]).filter((c) => c.type === 'taskBlock');
+ expect(taskNodes).toHaveLength(1);
+
+ const value = taskNodes[0].data.hChildren[0].value as string;
+ expect(value).toContain('T-32');
+ expect(value).toContain('ๅ†™ไธ€ๆœฌใ€ŠAI Agent ๅฎžๆˆ˜ๆŒ‡ๅ—ใ€‹');
+ expect(value).toContain('Status:');
+ expect(value).toContain('Instruction:');
+ expect(value).toContain('Review: (not configured)');
+ });
+});
diff --git a/src/features/Conversation/Markdown/plugins/Task/parseTaskContent.test.ts b/src/features/Conversation/Markdown/plugins/Task/parseTaskContent.test.ts
new file mode 100644
index 00000000000..151b5f1686f
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/Task/parseTaskContent.test.ts
@@ -0,0 +1,89 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseTaskContent } from './parseTaskContent';
+
+describe('parseTaskContent', () => {
+ it('parses the basic task block from the screenshot', () => {
+ const raw = `<hint>This tag contains the complete task context. Do NOT call viewTask to re-fetch it.</hint>
+T-32 ๅ†™ไธ€ๆœฌใ€ŠAI Agent ๅฎžๆˆ˜ๆŒ‡ๅ—ใ€‹
+Status: โญ• backlog Priority: -
+Instruction: ๅธฎๆˆ‘ๅ†™ไธ€ๆœฌ้ขๅ‘ๅผ€ๅ‘่€…็š„ AI Agent ๆŠ€ๆœฏไนฆ็ฑ๏ผŒๆถต็›–ๅŸบ็ก€ๆฆ‚ๅฟตใ€ไธปๆตๆก†ๆžถใ€ๅฎžๆˆ˜ๆกˆไพ‹ใ€‚็›ฎๆ ‡ 8 ็ซ ๏ผŒๆฏ็ซ  5000-8000 ๅญ—ใ€‚
+่ฏทๅ…ˆๅˆถๅฎšๅคง็บฒ่ฎฉๆˆ‘็กฎ่ฎคๅŽๅ†ๅŠจ็ฌ”ใ€‚
+Agent: agt_9GOn6nUgGw35
+
+Review: (not configured)`;
+
+ const parsed = parseTaskContent(raw);
+
+ expect(parsed.identifier).toBe('T-32');
+ expect(parsed.name).toBe('ๅ†™ไธ€ๆœฌใ€ŠAI Agent ๅฎžๆˆ˜ๆŒ‡ๅ—ใ€‹');
+ expect(parsed.statusIcon).toBe('โญ•');
+ expect(parsed.status).toBe('backlog');
+ expect(parsed.priority).toBe('-');
+ expect(parsed.instruction).toContain('ๅธฎๆˆ‘ๅ†™ไธ€ๆœฌ้ขๅ‘ๅผ€ๅ‘่€…็š„ AI Agent ๆŠ€ๆœฏไนฆ็ฑ');
+ expect(parsed.instruction).toContain('่ฏทๅ…ˆๅˆถๅฎšๅคง็บฒ่ฎฉๆˆ‘็กฎ่ฎคๅŽๅ†ๅŠจ็ฌ”ใ€‚');
+ expect(parsed.agent).toBe('agt_9GOn6nUgGw35');
+ expect(parsed.review).toBe('(not configured)');
+ });
+
+ it('parses subtasks, activities, and workspace sections', () => {
+ const raw = `T-1 Demo task
+Status: โ— running Priority: high
+Instruction: do the thing
+Topics: 2
+
+Subtasks:
+ T-2 โœ“ completed Subtask A
+ T-3 โ—‹ backlog Subtask B โ† blocks: T-2
+
+Workspace (1):
+ ๐Ÿ“ plans (doc-1)
+ โ””โ”€โ”€ ๐Ÿ“„ outline (doc-2) 120 chars
+
+Activities:
+ ๐Ÿ’ฌ 1h ago Topic #1 Outline โœ“ completed
+ ๐Ÿ’ญ 30m ago ๐Ÿ‘ค user Looks good
+
+Review: (not configured)`;
+
+ const parsed = parseTaskContent(raw);
+
+ expect(parsed.identifier).toBe('T-1');
+ expect(parsed.name).toBe('Demo task');
+ expect(parsed.subtasks).toHaveLength(2);
+ expect(parsed.subtasks?.[0]).toContain('T-2');
+ expect(parsed.workspace).toHaveLength(2);
+ expect(parsed.activities).toHaveLength(2);
+ expect(parsed.review).toBe('(not configured)');
+ });
+
+ it('captures rubrics when review is configured', () => {
+ const raw = `T-1 Demo
+Status: โ—‹ backlog Priority: -
+Instruction: x
+
+Review (maxIterations: 3):
+ - clarity [llm] โ‰ฅ 80%
+ - depth [llm]`;
+
+ const parsed = parseTaskContent(raw);
+
+ expect(parsed.review).toBe('Review (maxIterations: 3):');
+ expect(parsed.reviewRubrics).toEqual(['clarity [llm] โ‰ฅ 80%', 'depth [llm]']);
+ });
+
+ it('captures parentTask block', () => {
+ const raw = `T-2 sub
+Status: โ—‹ backlog Priority: -
+Instruction: child task
+
+<parentTask identifier="T-1" name="parent">
+ Instruction: parent goal
+</parentTask>`;
+
+ const parsed = parseTaskContent(raw);
+
+ expect(parsed.parentTaskBlock).toContain('<parentTask identifier="T-1"');
+ expect(parsed.parentTaskBlock).toContain('</parentTask>');
+ });
+});
diff --git a/src/features/Conversation/Markdown/plugins/Task/parseTaskContent.ts b/src/features/Conversation/Markdown/plugins/Task/parseTaskContent.ts
new file mode 100644
index 00000000000..7da39bba9ce
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/Task/parseTaskContent.ts
@@ -0,0 +1,216 @@
+export interface ParsedTaskContent {
+ activities?: string[];
+ agent?: string;
+ dependencies?: string;
+ description?: string;
+ identifier?: string;
+ instruction?: string;
+ name?: string;
+ parent?: string;
+ parentTaskBlock?: string;
+ priority?: string;
+ review?: string;
+ reviewRubrics?: string[];
+ status?: string;
+ statusIcon?: string;
+ subtasks?: string[];
+ topics?: string;
+ workspace?: string[];
+}
+
+const SECTION_KEYS = new Set(['Activities:', 'Subtasks:', 'Workspace', 'Review', 'Review:']);
+
+const splitStatus = (raw: string): { icon?: string; status: string } => {
+ const trimmed = raw.trim();
+ if (!trimmed) return { status: '' };
+ const [first, ...rest] = trimmed.split(/\s+/);
+ if (rest.length === 0) return { status: first };
+ // Heuristic: first token is non-ascii (icon) or short symbol โ†’ treat as icon.
+ if (first.length <= 2 || !/^[A-Z]/i.test(first)) {
+ return { icon: first, status: rest.join(' ') };
+ }
+ return { status: trimmed };
+};
+
+const isSectionHeader = (line: string): boolean => {
+ if (SECTION_KEYS.has(line.trim())) return true;
+ if (/^Workspace\s*\(/.test(line)) return true;
+ if (/^Review\s*\(/.test(line)) return true;
+ return false;
+};
+
+const isFieldLine = (line: string): boolean => {
+ return /^[A-Z][A-Za-z]*:\s/.test(line);
+};
+
+export const parseTaskContent = (raw: string): ParsedTaskContent => {
+ if (!raw) return {};
+
+ // Strip the <hint>...</hint> block if present.
+ const cleaned = raw.replaceAll(/<hint>[\S\s]*?<\/hint>/g, '').trim();
+ const lines = cleaned.split('\n');
+
+ const result: ParsedTaskContent = {};
+ let i = 0;
+
+ const skipBlankLines = () => {
+ while (i < lines.length && lines[i].trim() === '') i++;
+ };
+
+ // Title line: "<identifier> <name...>" or just "<identifier>"
+ skipBlankLines();
+ const titleLine = lines[i]?.trim();
+ if (titleLine) {
+ const spaceIdx = titleLine.indexOf(' ');
+ if (spaceIdx === -1) {
+ result.identifier = titleLine;
+ } else {
+ result.identifier = titleLine.slice(0, spaceIdx);
+ result.name = titleLine.slice(spaceIdx + 1).trim();
+ }
+ i++;
+ }
+
+ // Field block until the first blank line or a section header.
+ while (i < lines.length) {
+ const line = lines[i];
+ if (line.trim() === '') {
+ i++;
+ break;
+ }
+ if (isSectionHeader(line)) break;
+
+ if (line.startsWith('Status:')) {
+ const rest = line.slice('Status:'.length).trim();
+ const priorityMarker = ' Priority:';
+ const priorityIdx = rest.indexOf(priorityMarker);
+ if (priorityIdx === -1) {
+ const { icon, status } = splitStatus(rest);
+ result.statusIcon = icon;
+ result.status = status;
+ } else {
+ const statusPart = rest.slice(0, priorityIdx).trimEnd();
+ const priorityPart = rest.slice(priorityIdx + priorityMarker.length).trim();
+ const { icon, status } = splitStatus(statusPart);
+ result.statusIcon = icon;
+ result.status = status;
+ result.priority = priorityPart;
+ }
+ i++;
+ continue;
+ }
+
+ const colonIdx = line.indexOf(':');
+ if (colonIdx > 0 && /^[A-Z][A-Za-z]*$/.test(line.slice(0, colonIdx))) {
+ const key = line.slice(0, colonIdx).toLowerCase() as keyof ParsedTaskContent;
+ let value = line.slice(colonIdx + 1).trim();
+
+ // For Instruction / Description, accumulate continuation lines until a
+ // blank line, another field, or a section header.
+ if (key === 'instruction' || key === 'description') {
+ i++;
+ while (i < lines.length) {
+ const next = lines[i];
+ if (next.trim() === '') break;
+ if (isFieldLine(next) || isSectionHeader(next)) break;
+ value += '\n' + next;
+ i++;
+ }
+ (result as any)[key] = value.trim();
+ continue;
+ }
+
+ switch (key) {
+ case 'agent':
+ case 'parent':
+ case 'topics':
+ case 'dependencies': {
+ (result as any)[key] = value;
+ break;
+ }
+ // No default
+ }
+ i++;
+ continue;
+ }
+ i++;
+ }
+
+ // Section parsing.
+ while (i < lines.length) {
+ const line = lines[i];
+ if (line.trim() === '') {
+ i++;
+ continue;
+ }
+
+ if (line.startsWith('Subtasks:')) {
+ i++;
+ const block: string[] = [];
+ while (i < lines.length && /^\s+\S/.test(lines[i])) {
+ block.push(lines[i].replace(/^\s{2}/, ''));
+ i++;
+ }
+ result.subtasks = block;
+ continue;
+ }
+
+ if (/^Review(?:\s*\(|:)/.test(line)) {
+ const header = line.trim();
+ i++;
+ const rubrics: string[] = [];
+ while (i < lines.length && /^\s+-/.test(lines[i])) {
+ rubrics.push(lines[i].trim().replace(/^-\s*/, ''));
+ i++;
+ }
+ if (rubrics.length > 0) {
+ result.review = header;
+ result.reviewRubrics = rubrics;
+ } else {
+ result.review = header.replace(/^Review:\s*/, '').replace(/^Review\s*/, '');
+ }
+ continue;
+ }
+
+ if (/^Workspace\s*\(/.test(line)) {
+ i++;
+ const block: string[] = [];
+ while (i < lines.length && /^\s+\S/.test(lines[i])) {
+ block.push(lines[i]);
+ i++;
+ }
+ result.workspace = block;
+ continue;
+ }
+
+ if (line.startsWith('Activities:')) {
+ i++;
+ const block: string[] = [];
+ while (i < lines.length && /^\s+\S/.test(lines[i])) {
+ block.push(lines[i].trim());
+ i++;
+ }
+ result.activities = block;
+ continue;
+ }
+
+ if (line.startsWith('<parentTask')) {
+ const block: string[] = [line];
+ i++;
+ while (i < lines.length) {
+ block.push(lines[i]);
+ if (lines[i].trim() === '</parentTask>') {
+ i++;
+ break;
+ }
+ i++;
+ }
+ result.parentTaskBlock = block.join('\n');
+ continue;
+ }
+
+ i++;
+ }
+
+ return result;
+};
diff --git a/src/features/Conversation/Markdown/plugins/Task/remarkTaskBlock.ts b/src/features/Conversation/Markdown/plugins/Task/remarkTaskBlock.ts
new file mode 100644
index 00000000000..94959edd647
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/Task/remarkTaskBlock.ts
@@ -0,0 +1,132 @@
+import { SKIP, visit } from 'unist-util-visit';
+
+import { TASK_TAG } from '@/const/plugin';
+
+import { treeNodeToString } from '../remarkPlugins/getNodeContent';
+
+const OPEN_TAG = `<${TASK_TAG}>`;
+const CLOSE_TAG = `</${TASK_TAG}>`;
+
+/**
+ * Captures `<task>...</task>` blocks from a markdown AST. Unlike
+ * `createRemarkCustomTagPlugin`, this handles the common case where remark
+ * parses the opening `<task>` together with the surrounding lines into a
+ * single html block, and where the closing `</task>` is buried inside a
+ * later paragraph node.
+ */
+export const remarkTaskBlock = () => (tree: any) => {
+ visit(tree, (node, index, parent) => {
+ if (!parent || index == null) return;
+ if (node.type !== 'html') return;
+ if (typeof node.value !== 'string') return;
+
+ const openIdx = node.value.indexOf(OPEN_TAG);
+ if (openIdx === -1) return;
+
+ // Same node may already contain the closing tag.
+ const sameNodeCloseIdx = node.value.indexOf(CLOSE_TAG, openIdx + OPEN_TAG.length);
+ if (sameNodeCloseIdx !== -1) {
+ const inner = node.value.slice(openIdx + OPEN_TAG.length, sameNodeCloseIdx).trim();
+ const replacement = buildTaskNode(inner, node.position);
+ parent.children.splice(index, 1, replacement);
+ return [SKIP, index + 1];
+ }
+
+ // Otherwise capture content from this node up to the closing tag in a
+ // sibling node.
+ const headInner = node.value.slice(openIdx + OPEN_TAG.length);
+ const collected: string[] = [headInner];
+ let cursor = (index as number) + 1;
+ let closingFound = false;
+ let closingTrailing = '';
+
+ while (cursor < parent.children.length) {
+ const sibling = parent.children[cursor];
+ const closeInSibling = findCloseInSubtree(sibling);
+ if (closeInSibling) {
+ collected.push(closeInSibling.before);
+ closingTrailing = closeInSibling.after.trim();
+ closingFound = true;
+ break;
+ }
+ collected.push(treeNodeToString([sibling]));
+ cursor++;
+ }
+
+ if (!closingFound) return;
+
+ const inner = collected.join('\n').trim();
+ const replacement = buildTaskNode(inner, node.position);
+
+ const removeCount = cursor - (index as number) + 1;
+ const newNodes: any[] = [replacement];
+ if (closingTrailing) {
+ newNodes.push({
+ type: 'paragraph',
+ children: [{ type: 'text', value: closingTrailing }],
+ });
+ }
+ parent.children.splice(index, removeCount, ...newNodes);
+ return [SKIP, index + newNodes.length];
+ });
+};
+
+const buildTaskNode = (inner: string, position?: any) => ({
+ type: `${TASK_TAG}Block`,
+ data: {
+ hName: TASK_TAG,
+ hChildren: [{ type: 'text', value: inner }],
+ },
+ position,
+});
+
+interface CloseMatch {
+ after: string;
+ before: string;
+}
+
+/**
+ * Walks a node subtree looking for the closing tag. Returns the text content
+ * before the tag (preserving everything we want as the inner body) and any
+ * stray text after the tag (so we don't drop content that follows in the same
+ * paragraph). Returns null if the closing tag is not found.
+ */
+const findCloseInSubtree = (root: any): CloseMatch | null => {
+ // Direct html node with the closing tag.
+ if (root.type === 'html' && typeof root.value === 'string') {
+ const idx = root.value.indexOf(CLOSE_TAG);
+ if (idx !== -1) {
+ return {
+ before: root.value.slice(0, idx),
+ after: root.value.slice(idx + CLOSE_TAG.length),
+ };
+ }
+ return null;
+ }
+
+ if (!root.children || !Array.isArray(root.children)) return null;
+
+ const beforeParts: string[] = [];
+ for (let i = 0; i < root.children.length; i++) {
+ const child = root.children[i];
+ if (child.type === 'html' && typeof child.value === 'string') {
+ const idx = child.value.indexOf(CLOSE_TAG);
+ if (idx !== -1) {
+ beforeParts.push(child.value.slice(0, idx));
+ const after = child.value.slice(idx + CLOSE_TAG.length);
+ return {
+ before: beforeParts.join(''),
+ after,
+ };
+ }
+ }
+ const nested = findCloseInSubtree(child);
+ if (nested) {
+ beforeParts.push(nested.before);
+ return { before: beforeParts.join(''), after: nested.after };
+ }
+ beforeParts.push(treeNodeToString([child]));
+ }
+
+ return null;
+};
diff --git a/src/features/Conversation/Markdown/plugins/index.ts b/src/features/Conversation/Markdown/plugins/index.ts
index ecfcdc8421a..736eb031105 100644
--- a/src/features/Conversation/Markdown/plugins/index.ts
+++ b/src/features/Conversation/Markdown/plugins/index.ts
@@ -3,6 +3,7 @@ import LobeArtifact from './LobeArtifact';
import LobeThinking from './LobeThinking';
import LocalFile from './LocalFile';
import Mention from './Mention';
+import Task from './Task';
import Thinking from './Thinking';
import { type MarkdownElement } from './type';
@@ -14,5 +15,6 @@ export const markdownElements: MarkdownElement[] = [
LobeThinking,
LocalFile,
Mention,
+ Task,
ImageSearchRef,
];
diff --git a/src/routes/(main)/agent/features/Conversation/Header/ViewSwitcher/index.tsx b/src/routes/(main)/agent/features/Conversation/Header/ViewSwitcher/index.tsx
index 2acf63f3ccd..b11fd471562 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/ViewSwitcher/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/ViewSwitcher/index.tsx
@@ -8,6 +8,8 @@ import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { SESSION_CHAT_TOPIC_PAGE_URL, SESSION_CHAT_TOPIC_URL } from '@/const/url';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
@@ -56,6 +58,7 @@ const ViewSwitcher = memo(() => {
const params = useParams<{ aid?: string; topicId?: string }>();
const activeTopicId = useChatStore((s) => s.activeTopicId);
const enableAgentTask = useServerConfigStore((s) => featureFlagsSelectors(s).enableAgentTask);
+ const isHeterogeneousAgent = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);
const aid = params.aid;
const topicId = params.topicId ?? activeTopicId ?? undefined;
@@ -120,7 +123,7 @@ const ViewSwitcher = memo(() => {
}
};
- if (!topicId || !enableAgentTask) return null;
+ if (!topicId || !enableAgentTask || isHeterogeneousAgent) return null;
return (
<Segmented
diff --git a/src/routes/(main)/home/features/InputArea/index.tsx b/src/routes/(main)/home/features/InputArea/index.tsx
index f7a5314cc87..b8db5461ba8 100644
--- a/src/routes/(main)/home/features/InputArea/index.tsx
+++ b/src/routes/(main)/home/features/InputArea/index.tsx
@@ -11,7 +11,11 @@ import { useChatStore } from '@/store/chat';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { useHomeStore } from '@/store/home';
-import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
+import {
+ featureFlagsSelectors,
+ serverConfigSelectors,
+ useServerConfigStore,
+} from '@/store/serverConfig';
import CommunityRecommend from '../CommunityRecommend';
import SuggestQuestions from '../SuggestQuestions';
@@ -27,6 +31,7 @@ const InputArea = () => {
const inputActiveMode = useHomeStore((s) => s.inputActiveMode);
const isLobehubSkillEnabled = useServerConfigStore(serverConfigSelectors.enableLobehubSkill);
const isKlavisEnabled = useServerConfigStore(serverConfigSelectors.enableKlavis);
+ const { enableAgentTask } = useServerConfigStore(featureFlagsSelectors);
const isSkillBannerDismissed = useGlobalStore(
systemStatusSelectors.isBannerDismissed(SKILL_INSTALL_BANNER_ID),
);
@@ -68,8 +73,9 @@ const InputArea = () => {
);
const hideStarterList = inputActiveMode && ['agent', 'group', 'write'].includes(inputActiveMode);
- const showSuggestQuestions =
- !inputActiveMode || ['agent', 'group', 'write'].includes(inputActiveMode);
+ const showSuggestQuestions = inputActiveMode
+ ? ['agent', 'group', 'write'].includes(inputActiveMode)
+ : !enableAgentTask;
const extraActionItems = useMemo(
() =>
diff --git a/src/server/services/task/index.test.ts b/src/server/services/task/index.test.ts
index ed821ffdcc0..a3cf819cb9d 100644
--- a/src/server/services/task/index.test.ts
+++ b/src/server/services/task/index.test.ts
@@ -649,6 +649,66 @@ describe('TaskService', () => {
expect(result?.topicCount).toBe(2);
});
+ it('should propagate topic completedAt to the topic activity', async () => {
+ const task = {
+ assigneeAgentId: null,
+ assigneeUserId: null,
+ createdAt: null,
+ description: null,
+ error: null,
+ heartbeatInterval: null,
+ heartbeatTimeout: null,
+ id: 'task_001',
+ identifier: 'TASK-1',
+ instruction: null,
+ lastHeartbeatAt: null,
+ name: 'Task 1',
+ parentTaskId: null,
+ priority: 'normal',
+ status: 'todo',
+ totalTopics: 0,
+ };
+
+ const topics = [
+ {
+ completedAt: new Date('2024-01-03T00:01:30Z'),
+ createdAt: new Date('2024-01-03T00:00:00Z'),
+ handoff: null,
+ seq: 1,
+ status: 'completed',
+ topicId: 'topic-done',
+ },
+ {
+ completedAt: null,
+ createdAt: new Date('2024-01-03T00:05:00Z'),
+ handoff: null,
+ seq: 2,
+ status: 'running',
+ topicId: 'topic-running',
+ },
+ ];
+
+ mockTaskModel.resolve.mockResolvedValue(task);
+ mockTaskModel.findAllDescendants.mockResolvedValue([]);
+ mockTaskModel.getDependencies.mockResolvedValue([]);
+ mockTaskTopicModel.findWithHandoff.mockResolvedValue(topics);
+ mockBriefModel.findByTaskId.mockResolvedValue([]);
+ mockTaskModel.getComments.mockResolvedValue([]);
+ mockTaskModel.getTreePinnedDocuments.mockResolvedValue({ nodeMap: {}, tree: [] });
+ mockTaskModel.findByIds.mockResolvedValue([]);
+ mockTaskModel.getCheckpointConfig.mockReturnValue({});
+ mockTaskModel.getReviewConfig.mockReturnValue(undefined);
+
+ const service = new TaskService(db, userId);
+ const result = await service.getTaskDetail('TASK-1');
+
+ const topicActivities = result?.activities?.filter((a) => a.type === 'topic') ?? [];
+ const done = topicActivities.find((a) => a.id === 'topic-done');
+ const running = topicActivities.find((a) => a.id === 'topic-running');
+ expect(done?.completedAt).toBe('2024-01-03T00:01:30.000Z');
+ expect(running?.completedAt).toBeUndefined();
+ });
+
it('should not include topicCount when no topics exist', async () => {
const task = {
assigneeAgentId: null,
diff --git a/src/server/services/task/index.ts b/src/server/services/task/index.ts
index 586db1ca5dd..53c6118ae80 100644
--- a/src/server/services/task/index.ts
+++ b/src/server/services/task/index.ts
@@ -215,6 +215,7 @@ export class TaskService {
const handoff = t.handoff as TaskTopicHandoff | null;
return {
author: task.assigneeAgentId ? authorMap.get(task.assigneeAgentId) : undefined,
+ completedAt: toISO(t.completedAt),
id: t.topicId ?? undefined,
runningOperation: t.metadata?.runningOperation ?? null,
seq: t.seq,
diff --git a/src/server/services/taskRunner/scheduleTick.ts b/src/server/services/taskRunner/scheduleTick.ts
new file mode 100644
index 00000000000..9f1fd7c6126
--- /dev/null
+++ b/src/server/services/taskRunner/scheduleTick.ts
@@ -0,0 +1,83 @@
+import { TRPCError } from '@trpc/server';
+import debug from 'debug';
+
+import { BriefModel } from '@/database/models/brief';
+import { TaskModel } from '@/database/models/task';
+import { getServerDB } from '@/database/server';
+
+import { TaskRunnerService } from './index';
+
+const log = debug('task-runner:schedule-tick');
+
+const TERMINAL_STATUSES = new Set(['canceled', 'completed', 'failed']);
+const isTerminal = (status: string) => TERMINAL_STATUSES.has(status);
+
+export type ScheduleTickOutcome =
+ | { ran: true; taskIdentifier: string }
+ | { ran: false; reason: ScheduleTickSkipReason };
+
+export type ScheduleTickSkipReason =
+ | 'human-waiting'
+ | 'in-flight'
+ | 'mode-changed'
+ | 'no-pattern'
+ | 'not-found'
+ | 'paused'
+ | 'terminal';
+
+/**
+ * Run a schedule tick โ€” invoked by the QStash `/schedule-execute` HTTP handler
+ * after the central `/schedule-dispatch` decided this task is due.
+ *
+ * DB is the authority: re-checks task state because the dispatch message may
+ * arrive after the user paused, canceled, or changed the automation mode.
+ */
+export async function runScheduleTick(
+ taskId: string,
+ userId: string,
+): Promise<ScheduleTickOutcome> {
+ const db = await getServerDB();
+
+ const taskModel = new TaskModel(db, userId);
+ const task = await taskModel.findById(taskId);
+ if (!task) {
+ log('skip task=%s reason=not-found', taskId);
+ return { ran: false, reason: 'not-found' };
+ }
+ if (task.automationMode !== 'schedule') {
+ log('skip task=%s reason=mode-changed (mode=%s)', taskId, task.automationMode);
+ return { ran: false, reason: 'mode-changed' };
+ }
+ if (!task.schedulePattern) {
+ log('skip task=%s reason=no-pattern', taskId);
+ return { ran: false, reason: 'no-pattern' };
+ }
+ if (isTerminal(task.status)) {
+ log('skip task=%s reason=terminal (status=%s)', taskId, task.status);
+ return { ran: false, reason: 'terminal' };
+ }
+ if (task.status === 'paused') {
+ log('skip task=%s reason=paused', taskId);
+ return { ran: false, reason: 'paused' };
+ }
+
+ const briefModel = new BriefModel(db, userId);
+ if (await briefModel.hasUnresolvedUrgentByTask(taskId)) {
+ log('skip task=%s reason=human-waiting', taskId);
+ return { ran: false, reason: 'human-waiting' };
+ }
+
+ const runner = new TaskRunnerService(db, userId);
+ try {
+ await runner.runTask({ taskId });
+ } catch (e) {
+ // Concurrent tick / manual run already running this task โ€” graceful skip.
+ if (e instanceof TRPCError && e.code === 'CONFLICT') {
+ log('skip task=%s reason=in-flight', taskId);
+ return { ran: false, reason: 'in-flight' };
+ }
+ throw e;
+ }
+ log('ran task=%s identifier=%s', taskId, task.identifier);
+ return { ran: true, taskIdentifier: task.identifier };
+}
diff --git a/src/server/workflows-hono/task/handlers/scheduleDispatch.ts b/src/server/workflows-hono/task/handlers/scheduleDispatch.ts
new file mode 100644
index 00000000000..dd87116a517
--- /dev/null
+++ b/src/server/workflows-hono/task/handlers/scheduleDispatch.ts
@@ -0,0 +1,152 @@
+import { isExecutionTime } from '@lobechat/utils/cronEval';
+import debug from 'debug';
+import type { Context } from 'hono';
+
+import { TaskModel } from '@/database/models/task';
+import { getServerDB } from '@/database/server';
+import { appEnv } from '@/envs/app';
+import { qstashClient } from '@/libs/qstash';
+import { runScheduleTick } from '@/server/services/taskRunner/scheduleTick';
+
+const log = debug('lobe-server:workflows:task:schedule-dispatch');
+
+const SCHEDULE_EXECUTE_PATH = '/api/workflows/task/schedule-execute';
+
+export interface ScheduleDispatchPayload {
+ /** When true, only return what would be dispatched without firing executes. */
+ dryRun?: boolean;
+}
+
+interface DueTask {
+ pattern: string;
+ taskId: string;
+ taskIdentifier: string;
+ timezone: string | null;
+ userId: string;
+}
+
+/**
+ * Cron-style central dispatcher. Registered as a QStash Schedule (e.g.
+ * `*\/30 * * * *`) pointing at this endpoint. On each tick:
+ *
+ * 1. Loads all schedule-mode tasks in dispatchable status (`scheduled`/`backlog`).
+ * 2. Filters by cron pattern + timezone + last-run dedup (`isExecutionTime`).
+ * 3. Fan-outs one QStash message per due task to `/schedule-execute`.
+ *
+ * No per-user authentication: this is a global sweep. Signature verification is
+ * handled by the `qstashAuth` middleware on the route.
+ */
+export async function scheduleDispatch(c: Context) {
+ try {
+ const body = (await c.req.json().catch(() => ({}))) as ScheduleDispatchPayload;
+ const { dryRun = false } = body ?? {};
+
+ const db = await getServerDB();
+ const tasks = await TaskModel.getScheduledTasks(db);
+
+ const now = new Date();
+ const due: DueTask[] = [];
+ for (const task of tasks) {
+ if (!task.schedulePattern) continue;
+ const matches = isExecutionTime({
+ cronPattern: task.schedulePattern,
+ currentTime: now,
+ lastExecutedAt: task.lastHeartbeatAt ?? null,
+ timezone: task.scheduleTimezone,
+ });
+ if (!matches) continue;
+ due.push({
+ pattern: task.schedulePattern,
+ taskId: task.id,
+ taskIdentifier: task.identifier,
+ timezone: task.scheduleTimezone,
+ userId: task.createdByUserId,
+ });
+ }
+
+ log(
+ 'scan: total=%d due=%d skipped=%d dryRun=%s',
+ tasks.length,
+ due.length,
+ tasks.length - due.length,
+ dryRun,
+ );
+
+ if (dryRun || due.length === 0) {
+ return c.json({
+ dispatched: 0,
+ dryRun,
+ due: due.length,
+ skipped: tasks.length - due.length,
+ success: true,
+ total: tasks.length,
+ });
+ }
+
+ const dispatched = await fanout(due);
+
+ return c.json({
+ dispatched,
+ due: due.length,
+ skipped: tasks.length - due.length,
+ success: true,
+ total: tasks.length,
+ });
+ } catch (error) {
+ console.error('[task/schedule-dispatch] Error:', error);
+ return c.json({ error: error instanceof Error ? error.message : 'Internal error' }, 500);
+ }
+}
+
+const fanout = async (due: DueTask[]): Promise<number> => {
+ // In queue mode, hand off via QStash so each task gets its own retry budget
+ // and runs in an isolated handler invocation. Locally, just run inline so
+ // dev / electron can exercise the path without QStash.
+ if (appEnv.enableQueueAgentRuntime) {
+ if (!process.env.APP_URL) {
+ throw new Error('APP_URL is required to fan out scheduled task executions via QStash');
+ }
+ const url = `${process.env.APP_URL.replace(/\/$/, '')}${SCHEDULE_EXECUTE_PATH}`;
+
+ const results = await Promise.allSettled(
+ due.map((d) =>
+ qstashClient.publishJSON({
+ body: { taskId: d.taskId, userId: d.userId },
+ url,
+ }),
+ ),
+ );
+
+ let dispatched = 0;
+ for (const [i, r] of results.entries()) {
+ if (r.status === 'fulfilled') {
+ dispatched += 1;
+ } else {
+ console.error(
+ '[task/schedule-dispatch] failed to publish task=%s identifier=%s: %O',
+ due[i].taskId,
+ due[i].taskIdentifier,
+ r.reason,
+ );
+ }
+ }
+ return dispatched;
+ }
+
+ // Local / dev: invoke runScheduleTick directly. Errors are logged but don't
+ // fail the dispatch โ€” one bad task shouldn't block the rest.
+ const results = await Promise.allSettled(due.map((d) => runScheduleTick(d.taskId, d.userId)));
+ let dispatched = 0;
+ for (const [i, r] of results.entries()) {
+ if (r.status === 'fulfilled') {
+ dispatched += 1;
+ } else {
+ console.error(
+ '[task/schedule-dispatch] inline tick failed task=%s: %O',
+ due[i].taskId,
+ r.reason,
+ );
+ }
+ }
+ return dispatched;
+};
diff --git a/src/server/workflows-hono/task/handlers/scheduleExecute.ts b/src/server/workflows-hono/task/handlers/scheduleExecute.ts
new file mode 100644
index 00000000000..7ea01f17983
--- /dev/null
+++ b/src/server/workflows-hono/task/handlers/scheduleExecute.ts
@@ -0,0 +1,33 @@
+import debug from 'debug';
+import type { Context } from 'hono';
+
+import { runScheduleTick } from '@/server/services/taskRunner/scheduleTick';
+
+const log = debug('lobe-server:workflows:task:schedule-execute');
+
+export interface ScheduleExecutePayload {
+ taskId: string;
+ userId: string;
+}
+
+/**
+ * Per-task executor โ€” handler for QStash messages fanned out by
+ * `/schedule-dispatch`. Mirrors `heartbeatTick.ts`: thin transport adapter,
+ * delegates to `runScheduleTick` which owns DB-state re-validation.
+ */
+export async function scheduleExecute(c: Context) {
+ try {
+ const body = (await c.req.json()) as ScheduleExecutePayload;
+ const { taskId, userId } = body;
+ if (!taskId || !userId) {
+ return c.json({ error: 'Missing required fields: taskId, userId' }, 400);
+ }
+
+ log('Received: taskId=%s userId=%s', taskId, userId);
+ const outcome = await runScheduleTick(taskId, userId);
+ return c.json({ success: true, ...outcome });
+ } catch (error) {
+ console.error('[task/schedule-execute] Error:', error);
+ return c.json({ error: error instanceof Error ? error.message : 'Internal error' }, 500);
+ }
+}
diff --git a/src/server/workflows-hono/task/index.ts b/src/server/workflows-hono/task/index.ts
index b57c35d7ab1..286adb92338 100644
--- a/src/server/workflows-hono/task/index.ts
+++ b/src/server/workflows-hono/task/index.ts
@@ -3,12 +3,16 @@ import { Hono } from 'hono';
import { qstashAuth } from '../middlewares/qstashAuth';
import { heartbeatTick } from './handlers/heartbeatTick';
import { onTopicComplete } from './handlers/onTopicComplete';
+import { scheduleDispatch } from './handlers/scheduleDispatch';
+import { scheduleExecute } from './handlers/scheduleExecute';
import { watchdog } from './handlers/watchdog';
const app = new Hono();
app.post('/on-topic-complete', qstashAuth(), onTopicComplete);
app.post('/heartbeat-tick', qstashAuth(), heartbeatTick);
+app.post('/schedule-dispatch', qstashAuth(), scheduleDispatch);
+app.post('/schedule-execute', qstashAuth(), scheduleExecute);
app.post('/watchdog', qstashAuth(), watchdog);
export default app;