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): wire QStash-driven heartbeat self-rescheduling (#14199)

Arvin Xu35c3d5e08d1b
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 9833bfc70e4..cdfb3a6abe1 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -137,6 +137,7 @@
"extendParams.urlContext.desc": "When enabled, web links will be automatically parsed to retrieve the actual webpage context content",
"extendParams.urlContext.title": "Extract Webpage Link Content",
"followUpPlaceholder": "Follow up. @ to assign tasks to other agents.",
+ "followUpPlaceholderHeterogeneous": "Follow up.",
"group.desc": "Move a task forward with multiple Agents in one shared space.",
"group.memberTooltip": "There are {{count}} members in the group",
"group.orchestratorThinking": "Orchestrator is thinking...",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index d129dc8bf00..739a364b11c 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -137,6 +137,7 @@
"extendParams.urlContext.desc": "开启后会自动解析网页链接,提取网页内容作为上下文",
"extendParams.urlContext.title": "提取网页链接内容",
"followUpPlaceholder": "继续跟进。使用 @ 分配任务给其他智能体。",
+ "followUpPlaceholderHeterogeneous": "继续跟进。",
"group.desc": "在同一对话空间,让多个助理一起推进任务",
"group.memberTooltip": "群组内有 {{count}} 名成员",
"group.orchestratorThinking": "主持人思考中…",
diff --git a/packages/database/src/models/brief.ts b/packages/database/src/models/brief.ts
index 45764602b97..2f7749b4242 100644
--- a/packages/database/src/models/brief.ts
+++ b/packages/database/src/models/brief.ts
@@ -1,4 +1,4 @@
-import { and, desc, eq, isNull, sql } from 'drizzle-orm';
+import { and, desc, eq, isNull, notInArray, sql } from 'drizzle-orm';
import type { BriefItem, NewBrief } from '../schemas/task';
import { briefs } from '../schemas/task';
@@ -84,6 +84,34 @@ export class BriefModel {
.orderBy(desc(briefs.createdAt));
}
+ // Used by heartbeat re-arm to skip rescheduling when a task is already
+ // waiting on user action (review max-iter etc). Optionally exclude brief
+ // types — heartbeat callers exclude `error` because transient errors are
+ // governed by the fuse counter, not by the existence of the error brief
+ // itself (otherwise the very first error would block all retries).
+ async hasUnresolvedUrgentByTask(
+ taskId: string,
+ options?: { excludeTypes?: string[] },
+ ): Promise<boolean> {
+ const excludeTypes = options?.excludeTypes ?? [];
+ const conditions = [
+ eq(briefs.userId, this.userId),
+ eq(briefs.taskId, taskId),
+ eq(briefs.priority, 'urgent'),
+ isNull(briefs.resolvedAt),
+ ];
+ if (excludeTypes.length > 0) {
+ conditions.push(notInArray(briefs.type, excludeTypes));
+ }
+
+ const rows = await this.db
+ .select({ id: briefs.id })
+ .from(briefs)
+ .where(and(...conditions))
+ .limit(1);
+ return rows.length > 0;
+ }
+
async findByCronJobId(cronJobId: string): Promise<BriefItem[]> {
return this.db
.select()
diff --git a/packages/database/src/models/task.ts b/packages/database/src/models/task.ts
index 267cae061b0..4dfb8d7eae2 100644
--- a/packages/database/src/models/task.ts
+++ b/packages/database/src/models/task.ts
@@ -412,6 +412,22 @@ export class TaskModel {
return this.update(id, { config });
}
+ // ========== Context (runtime state) ==========
+
+ /**
+ * Deep-merge into the task's context JSONB. Used by the heartbeat scheduler
+ * to update `context.scheduler.{tickMessageId, consecutiveFailures, ...}`
+ * without disturbing other namespaces under context.
+ */
+ async updateContext(id: string, partial: Record<string, unknown>): Promise<TaskItem | null> {
+ const task = await this.findById(id);
+ if (!task) return null;
+
+ const current = (task.context as Record<string, unknown>) || {};
+ const context = merge(current, partial);
+ return this.update(id, { context });
+ }
+
// ========== Checkpoint ==========
getCheckpointConfig(task: TaskItem): CheckpointConfig {
diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.ts
index f2d7f9dea7b..478c97432d5 100644
--- a/packages/types/src/task/index.ts
+++ b/packages/types/src/task/index.ts
@@ -51,6 +51,24 @@ export interface TaskTopicHandoff {
title?: string;
}
+// ── Task context (runtime state pockets stored in tasks.context JSONB) ──
+
+export interface TaskSchedulerContext {
+ // Count of consecutive 'error' reasons since the last 'done'. When it hits
+ // the fuse threshold (currently 3) we stop re-arming until the user resolves
+ // the urgent brief.
+ consecutiveFailures?: number;
+ // ISO timestamp when the latest tick was scheduled. Informational only.
+ scheduledAt?: string;
+ // QStash messageId (or LocalScheduler scheduleId) for the next tick. Used to
+ // cancel when the user wants an interval change to take effect immediately.
+ tickMessageId?: string;
+}
+
+export interface TaskContext {
+ scheduler?: TaskSchedulerContext;
+}
+
// ── Task list item (shared between router response and client) ──
export interface TaskParticipant {
diff --git a/src/features/ChatInput/InputEditor/Placeholder.tsx b/src/features/ChatInput/InputEditor/Placeholder.tsx
index d783eb04aeb..596a84d4ca3 100644
--- a/src/features/ChatInput/InputEditor/Placeholder.tsx
+++ b/src/features/ChatInput/InputEditor/Placeholder.tsx
@@ -22,11 +22,16 @@ const Placeholder = memo<PlaceholderProps>(
: combineKeys([KeyEnum.Mod, KeyEnum.Enter]);
const { t } = useTranslation('chat');
+ const isHeterogeneous = !!heterogeneousName;
+
if (variant === 'followUp') {
- return <span>{t('followUpPlaceholder')}</span>;
+ return (
+ <span>
+ {t(isHeterogeneous ? 'followUpPlaceholderHeterogeneous' : 'followUpPlaceholder')}
+ </span>
+ );
}
- const isHeterogeneous = !!heterogeneousName;
const i18nKey = isHeterogeneous
? 'sendPlaceholderHeterogeneous'
: showAgentAssignmentHint
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index e841e26d455..68b43d5343c 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -385,6 +385,7 @@ export default {
'searchAgents': 'Search agents...',
'selectedAgents': 'Selected agents',
'followUpPlaceholder': 'Follow up. @ to assign tasks to other agents.',
+ 'followUpPlaceholderHeterogeneous': 'Follow up.',
'sendPlaceholder': 'Ask, create, or start a task, <hotkey><hotkey/>',
'sendPlaceholderHeterogeneous': 'Ask {{name}} to do a task...',
'sendPlaceholderWithAgentAssignment':
diff --git a/src/routes/(main)/home/features/SuggestQuestions/index.tsx b/src/routes/(main)/home/features/SuggestQuestions/index.tsx
index 905d3fa6c6b..103d2d59b18 100644
--- a/src/routes/(main)/home/features/SuggestQuestions/index.tsx
+++ b/src/routes/(main)/home/features/SuggestQuestions/index.tsx
@@ -7,6 +7,7 @@ import { memo, Suspense } from 'react';
import { useTranslation } from 'react-i18next';
import { type StarterMode } from '@/store/home';
+import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
import GroupBlock from '../components/GroupBlock';
import List from './List';
@@ -19,8 +20,11 @@ interface SuggestQuestionsProps {
const SuggestQuestions = memo<SuggestQuestionsProps>(({ mode }) => {
const { t } = useTranslation('common');
+ const { enableAgentTask } = useServerConfigStore(featureFlagsSelectors);
const { questions, refresh } = useRandomQuestions(mode);
+ if (enableAgentTask) return null;
+
if (mode && !['agent', 'group', 'write'].includes(mode)) {
return null;
}
diff --git a/src/server/routers/lambda/task.ts b/src/server/routers/lambda/task.ts
index 2018b181d9c..4a422e859a3 100644
--- a/src/server/routers/lambda/task.ts
+++ b/src/server/routers/lambda/task.ts
@@ -1,13 +1,5 @@
-import { TaskIdentifier as TaskSkillIdentifier } from '@lobechat/builtin-skills';
-import { BriefIdentifier } from '@lobechat/builtin-tool-brief';
import { TASK_STATUSES } from '@lobechat/builtin-tool-task';
-import { buildTaskRunPrompt } from '@lobechat/prompts';
-import type {
- TaskListItem,
- TaskParticipant,
- TaskTopicHandoff,
- WorkspaceData,
-} from '@lobechat/types';
+import type { TaskListItem, TaskParticipant } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
@@ -22,6 +14,7 @@ import { AiAgentService } from '@/server/services/aiAgent';
import { TaskService } from '@/server/services/task';
import { TaskLifecycleService } from '@/server/services/taskLifecycle';
import { TaskReviewService } from '@/server/services/taskReview';
+import { TaskRunnerService } from '@/server/services/taskRunner';
const taskProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
@@ -95,183 +88,6 @@ const groupListSchema = z.object({
parentTaskId: z.string().nullable().optional(),
});
-// Helper: build task prompt with handoff context from previous topics
-async function buildTaskPrompt(
- task: Awaited<ReturnType<TaskModel['findById']>> & {},
- ctx: {
- briefModel: BriefModel;
- taskModel: TaskModel;
- taskTopicModel: TaskTopicModel;
- },
- extraPrompt?: string,
-): Promise<string> {
- const { briefModel, taskModel, taskTopicModel } = ctx;
-
- const [topics, briefs, comments, subtasks, dependencies, documents] = await Promise.all([
- task.totalTopics && task.totalTopics > 0
- ? taskTopicModel.findWithHandoff(task.id).catch(() => [])
- : Promise.resolve([]),
- briefModel.findByTaskId(task.id).catch(() => []),
- taskModel.getComments(task.id).catch(() => []),
- taskModel.findSubtasks(task.id).catch(() => []),
- taskModel.getDependencies(task.id).catch(() => []),
- taskModel
- .getTreePinnedDocuments(task.id)
- .catch((): WorkspaceData => ({ nodeMap: {}, tree: [] })),
- ]);
-
- // Batch-fetch dependencies for all subtasks to show blockedBy info
- const subtaskIds = subtasks.map((s: any) => s.id);
- const subtaskDeps =
- subtaskIds.length > 0
- ? await taskModel.getDependenciesByTaskIds(subtaskIds).catch(() => [])
- : [];
- // Build a map: subtaskId -> dependsOn identifier
- const subtaskIdToIdentifier = new Map(subtasks.map((s: any) => [s.id, s.identifier]));
- const subtaskDepMap = new Map<string, string>();
- for (const dep of subtaskDeps as any[]) {
- const depIdentifier = subtaskIdToIdentifier.get(dep.dependsOnId);
- if (depIdentifier) subtaskDepMap.set(dep.taskId, depIdentifier);
- }
-
- // Resolve dependency task identifiers
- const depTaskIds = [...new Set(dependencies.map((d: any) => d.dependsOnId))];
- const depTasks = await taskModel.findByIds(depTaskIds);
- const depIdToIdentifier = new Map(depTasks.map((t: any) => [t.id, t.identifier]));
-
- // Resolve parent task context (identifier + sibling subtasks)
- let parentIdentifier: string | null = null;
- let parentTaskContext:
- | {
- identifier: string;
- instruction: string;
- name?: string | null;
- subtasks?: Array<{
- blockedBy?: string;
- identifier: string;
- name?: string | null;
- priority?: number | null;
- status: string;
- }>;
- }
- | undefined;
-
- if (task.parentTaskId) {
- const parent = await taskModel.findById(task.parentTaskId);
- parentIdentifier = parent?.identifier || null;
- if (parent) {
- const siblings = await taskModel.findSubtasks(task.parentTaskId).catch(() => []);
- const siblingIds = siblings.map((s: any) => s.id);
- const siblingDeps =
- siblingIds.length > 0
- ? await taskModel.getDependenciesByTaskIds(siblingIds).catch(() => [])
- : [];
- const siblingIdToIdentifier = new Map(siblings.map((s: any) => [s.id, s.identifier]));
- const siblingDepMap = new Map<string, string>();
- for (const dep of siblingDeps as any[]) {
- const depId = siblingIdToIdentifier.get(dep.dependsOnId);
- if (depId) siblingDepMap.set(dep.taskId, depId);
- }
-
- parentTaskContext = {
- identifier: parent.identifier,
- instruction: parent.instruction,
- name: parent.name,
- subtasks: siblings.map((s: any) => ({
- blockedBy: siblingDepMap.get(s.id),
- identifier: s.identifier,
- name: s.name,
- priority: s.priority,
- status: s.status,
- })),
- };
- }
- }
-
- return buildTaskRunPrompt({
- activities: {
- briefs: briefs.map((b: any) => ({
- createdAt: b.createdAt,
- id: b.id,
- priority: b.priority,
- resolvedAction: b.resolvedAction,
- resolvedAt: b.resolvedAt,
- resolvedComment: b.resolvedComment,
- summary: b.summary,
- title: b.title,
- type: b.type,
- })),
- comments: comments.map((c: any) => ({
- agentId: c.authorAgentId,
- content: c.content,
- createdAt: c.createdAt,
- id: c.id,
- })),
- subtasks: subtasks.map((s: any) => ({
- createdAt: s.createdAt,
- id: s.id,
- identifier: s.identifier,
- name: s.name,
- status: s.status,
- })),
- topics: (topics as any[]).map((t) => {
- const handoff = t.handoff as TaskTopicHandoff | null;
- return {
- createdAt: t.createdAt,
- handoff,
- id: t.topicId || t.id,
- seq: t.seq,
- status: t.status,
- title: handoff?.title || t.title,
- };
- }),
- },
- extraPrompt,
- parentTask: parentTaskContext,
- task: {
- assigneeAgentId: task.assigneeAgentId,
- dependencies: dependencies.map((d: any) => ({
- dependsOn: depIdToIdentifier.get(d.dependsOnId) ?? d.dependsOnId,
- type: d.type,
- })),
- description: task.description,
- id: task.id,
- identifier: task.identifier,
- instruction: task.instruction,
- name: task.name,
- parentIdentifier,
- priority: task.priority,
- review: taskModel.getReviewConfig(task) as any,
- status: task.status,
- subtasks: subtasks.map((s: any) => ({
- blockedBy: subtaskDepMap.get(s.id),
- identifier: s.identifier,
- name: s.name,
- priority: s.priority,
- status: s.status,
- })),
- },
- workspace: documents.tree.map((rootNode) => {
- const rootDoc = documents.nodeMap[rootNode.id];
- return {
- children: rootNode.children.map((child) => {
- const childDoc = documents.nodeMap[child.id];
- return {
- createdAt: childDoc?.createdAt,
- documentId: child.id,
- size: childDoc?.charCount ?? undefined,
- sourceTaskIdentifier: childDoc?.sourceTaskIdentifier ?? undefined,
- title: childDoc?.title,
- };
- }),
- createdAt: rootDoc?.createdAt,
- documentId: rootNode.id,
- title: rootDoc?.title,
- };
- }),
- });
-}
-
// Helper: resolve id/identifier and throw if not found
async function resolveOrThrow(model: TaskModel, id: string) {
const task = await model.resolve(id);
@@ -820,166 +636,14 @@ export const taskRouter = router({
),
)
.mutation(async ({ input, ctx }) => {
- const { id, prompt: extraPrompt, continueTopicId } = input;
try {
- const model = ctx.taskModel;
- const task = await resolveOrThrow(model, id);
-
- // Ensure task has an assigned agent
- if (!task.assigneeAgentId) {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: 'Task has no assigned agent. Use --agent when creating or edit the task.',
- });
- }
-
- // Idempotency checks
- const existingTopics = await ctx.taskTopicModel.findByTaskId(task.id);
-
- if (continueTopicId) {
- // If continuing a topic that's already running, reject
- const target = existingTopics.find((t) => t.topicId === continueTopicId);
- if (target?.status === 'running') {
- throw new TRPCError({
- code: 'CONFLICT',
- message: `Topic ${continueTopicId} is already running.`,
- });
- }
- } else {
- // If there's already a running topic, reject creating a new one
- const runningTopic = existingTopics.find((t) => t.status === 'running');
- if (runningTopic) {
- throw new TRPCError({
- code: 'CONFLICT',
- message: `Task already has a running topic (${runningTopic.topicId}). Cancel it first or use --continue.`,
- });
- }
- }
-
- // Auto-detect and clean up timed-out topics
- if (task.lastHeartbeatAt && task.heartbeatTimeout) {
- const elapsed = (Date.now() - new Date(task.lastHeartbeatAt).getTime()) / 1000;
- if (elapsed > task.heartbeatTimeout) {
- await ctx.taskTopicModel.timeoutRunning(task.id);
- }
- }
-
- // Build prompt with handoff context from previous topics
- const prompt = await buildTaskPrompt(task, ctx, extraPrompt);
-
- // Update task status to running if not already, clear previous error
- if (task.status !== 'running') {
- await model.updateStatus(task.id, 'running', { error: null, startedAt: new Date() });
- } else if (task.error) {
- await model.update(task.id, { error: null });
- }
-
- // Call AiAgentService.execAgent
- // assigneeAgentId can be either a raw agentId (agt_xxx) or a slug (inbox)
- const agentRef = task.assigneeAgentId!;
- const isSlug = !agentRef.startsWith('agt_');
-
- const aiAgentService = new AiAgentService(ctx.serverDB, ctx.userId);
- const taskId = task.id;
- const taskIdentifier = task.identifier;
- const { taskLifecycle } = ctx;
- const db = ctx.serverDB;
- const userId = ctx.userId;
-
- // Task execution auto-injects the Task skill. The legacy Notebook tool
- // has been deprecated and is no longer injected — document output now
- // flows through the agent-documents tool, which is enabled via the
- // agent config (see INBOX runtime / createEnableChecker).
- // Conditionally inject Brief tool based on checkpoint/review config.
- const checkpoint = model.getCheckpointConfig(task);
- const reviewConfig = model.getReviewConfig(task);
- const pluginIds = [TaskSkillIdentifier];
- if (!reviewConfig?.enabled && checkpoint.onAgentRequest !== false) {
- pluginIds.push(BriefIdentifier);
- }
-
- // Read per-task model/provider overrides from task.config
- const taskConfig = (task.config ?? {}) as Record<string, unknown>;
-
- const result = await aiAgentService.execAgent({
- ...(isSlug ? { slug: agentRef } : { agentId: agentRef }),
- additionalPluginIds: pluginIds,
- ...(typeof taskConfig.model === 'string' && { model: taskConfig.model }),
- ...(typeof taskConfig.provider === 'string' && { provider: taskConfig.provider }),
- hooks: [
- {
- handler: async (event) => {
- await taskLifecycle.onTopicComplete({
- errorMessage: event.errorMessage,
- lastAssistantContent: event.lastAssistantContent,
- operationId: event.operationId,
- reason: event.reason || 'done',
- taskId,
- taskIdentifier,
- topicId: event.topicId,
- });
- },
- id: 'task-on-complete',
- type: 'onComplete' as const,
- webhook: {
- body: { taskId, taskIdentifier, userId },
- url: '/api/workflows/task/on-topic-complete',
- },
- },
- ],
- prompt,
- taskId: task.id,
- title: extraPrompt ? extraPrompt.slice(0, 100) : task.name || task.identifier,
- trigger: 'task',
- userInterventionConfig: { approvalMode: 'headless' },
- // Continue on existing topic if specified
- ...(continueTopicId && { appContext: { topicId: continueTopicId } }),
+ const runner = new TaskRunnerService(ctx.serverDB, ctx.userId);
+ return await runner.runTask({
+ continueTopicId: input.continueTopicId,
+ extraPrompt: input.prompt,
+ taskId: input.id,
});
-
- // Update task topic count, current topic, and association
- if (result.topicId) {
- if (continueTopicId) {
- // Continuing existing topic — update status and operationId
- await ctx.taskTopicModel.updateStatus(task.id, continueTopicId, 'running');
- await ctx.taskTopicModel.updateOperationId(
- task.id,
- continueTopicId,
- result.operationId,
- );
- await model.updateCurrentTopic(task.id, continueTopicId);
- } else {
- // New topic
- await model.incrementTopicCount(task.id);
- await model.updateCurrentTopic(task.id, result.topicId);
- await ctx.taskTopicModel.add(task.id, result.topicId, {
- operationId: result.operationId,
- seq: (task.totalTopics || 0) + 1,
- });
- }
- }
-
- // Update heartbeat
- await model.updateHeartbeat(task.id);
-
- return {
- ...result,
- taskId: task.id,
- taskIdentifier: task.identifier,
- };
} catch (error) {
- // Rollback task status to paused on failure
- try {
- const model = ctx.taskModel;
- const failedTask = await model.resolve(id);
- if (failedTask && failedTask.status === 'running') {
- await model.updateStatus(failedTask.id, 'paused', {
- error: error instanceof Error ? error.message : 'Unknown error',
- });
- }
- } catch {
- // Rollback itself failed, ignore
- }
-
if (error instanceof TRPCError) throw error;
console.error('[task:run]', error);
throw new TRPCError({
diff --git a/src/server/services/taskLifecycle/heartbeatRearm.test.ts b/src/server/services/taskLifecycle/heartbeatRearm.test.ts
new file mode 100644
index 00000000000..edc899a87d4
--- /dev/null
+++ b/src/server/services/taskLifecycle/heartbeatRearm.test.ts
@@ -0,0 +1,161 @@
+// @vitest-environment node
+import type { TaskItem, TaskSchedulerContext } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { TaskLifecycleService } from './index';
+
+const fakeScheduler = {
+ cancelScheduled: vi.fn().mockResolvedValue(undefined),
+ scheduleNextTopic: vi.fn().mockResolvedValue('msg-new'),
+};
+
+vi.mock('@/server/services/taskScheduler', () => ({
+ createTaskSchedulerModule: () => fakeScheduler,
+}));
+
+const baseTask = (overrides: Partial<TaskItem> = {}): TaskItem =>
+ ({
+ automationMode: 'heartbeat',
+ config: {},
+ context: {},
+ error: null,
+ heartbeatInterval: 30,
+ heartbeatTimeout: 600,
+ id: 'task-1',
+ identifier: 'TASK-1',
+ name: 'demo',
+ status: 'paused',
+ ...overrides,
+ }) as unknown as TaskItem;
+
+describe('TaskLifecycleService.maybeRearmHeartbeat', () => {
+ let service: TaskLifecycleService;
+ let updateContext: ReturnType<typeof vi.fn>;
+ let hasUnresolvedUrgent: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ fakeScheduler.scheduleNextTopic.mockClear().mockResolvedValue('msg-new');
+ fakeScheduler.cancelScheduled.mockClear().mockResolvedValue(undefined);
+
+ service = new TaskLifecycleService({} as any, 'user-1');
+
+ updateContext = vi.fn().mockResolvedValue(null);
+ hasUnresolvedUrgent = vi.fn().mockResolvedValue(false);
+
+ (service as any).taskModel.updateContext = updateContext;
+ (service as any).briefModel.hasUnresolvedUrgentByTask = hasUnresolvedUrgent;
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ const rearm = (task: TaskItem, reason: string) =>
+ (service as any).maybeRearmHeartbeat(task, reason);
+
+ it('schedules next tick and writes scheduler context on done', async () => {
+ await rearm(baseTask(), 'done');
+
+ expect(fakeScheduler.scheduleNextTopic).toHaveBeenCalledWith({
+ delay: 30,
+ taskId: 'task-1',
+ userId: 'user-1',
+ });
+ expect(updateContext).toHaveBeenCalledWith('task-1', {
+ scheduler: expect.objectContaining({
+ consecutiveFailures: 0,
+ tickMessageId: 'msg-new',
+ }),
+ });
+ });
+
+ it('skips when automationMode is not heartbeat', async () => {
+ await rearm(baseTask({ automationMode: null }), 'done');
+
+ expect(fakeScheduler.scheduleNextTopic).not.toHaveBeenCalled();
+ expect(updateContext).not.toHaveBeenCalled();
+ });
+
+ it('skips when heartbeatInterval is missing or zero', async () => {
+ await rearm(baseTask({ heartbeatInterval: 0 }), 'done');
+ await rearm(baseTask({ heartbeatInterval: null }), 'done');
+
+ expect(fakeScheduler.scheduleNextTopic).not.toHaveBeenCalled();
+ });
+
+ it.each(['completed', 'failed', 'canceled'])('skips on terminal status %s', async (status) => {
+ await rearm(baseTask({ status }), 'done');
+
+ expect(fakeScheduler.scheduleNextTopic).not.toHaveBeenCalled();
+ });
+
+ it('skips when a non-error unresolved urgent brief exists, but persists failure count', async () => {
+ hasUnresolvedUrgent.mockResolvedValue(true);
+
+ await rearm(baseTask(), 'error');
+
+ expect(hasUnresolvedUrgent).toHaveBeenCalledWith('task-1', { excludeTypes: ['error'] });
+ expect(fakeScheduler.scheduleNextTopic).not.toHaveBeenCalled();
+ expect(updateContext).toHaveBeenCalledWith('task-1', {
+ scheduler: { consecutiveFailures: 1 },
+ });
+ });
+
+ it('does NOT block re-arm on an error brief — fuse alone governs error retries', async () => {
+ // Caller passes excludeTypes: ['error'], so brief query returns false even
+ // when there's a fresh error brief. The first error must still schedule
+ // the next tick so the fuse can count up to 3.
+ hasUnresolvedUrgent.mockResolvedValue(false);
+
+ await rearm(baseTask(), 'error');
+
+ expect(hasUnresolvedUrgent).toHaveBeenCalledWith('task-1', { excludeTypes: ['error'] });
+ expect(fakeScheduler.scheduleNextTopic).toHaveBeenCalled();
+ expect(updateContext).toHaveBeenCalledWith('task-1', {
+ scheduler: expect.objectContaining({ consecutiveFailures: 1 }),
+ });
+ });
+
+ it('increments consecutiveFailures on error', async () => {
+ const ctx: { scheduler: TaskSchedulerContext } = {
+ scheduler: { consecutiveFailures: 1 },
+ };
+
+ await rearm(baseTask({ context: ctx }), 'error');
+
+ expect(fakeScheduler.scheduleNextTopic).toHaveBeenCalled();
+ expect(updateContext).toHaveBeenCalledWith('task-1', {
+ scheduler: expect.objectContaining({ consecutiveFailures: 2 }),
+ });
+ });
+
+ it('blows the fuse at 3 consecutive errors and stops re-arming', async () => {
+ const ctx: { scheduler: TaskSchedulerContext } = {
+ scheduler: { consecutiveFailures: 2 },
+ };
+
+ await rearm(baseTask({ context: ctx }), 'error');
+
+ expect(fakeScheduler.scheduleNextTopic).not.toHaveBeenCalled();
+ expect(updateContext).toHaveBeenCalledWith('task-1', {
+ scheduler: { consecutiveFailures: 3 },
+ });
+ });
+
+ it('resets consecutiveFailures on done', async () => {
+ const ctx: { scheduler: TaskSchedulerContext } = {
+ scheduler: { consecutiveFailures: 2, tickMessageId: 'old-msg' },
+ };
+
+ await rearm(baseTask({ context: ctx }), 'done');
+
+ expect(fakeScheduler.cancelScheduled).toHaveBeenCalledWith('old-msg');
+ expect(fakeScheduler.scheduleNextTopic).toHaveBeenCalled();
+ expect(updateContext).toHaveBeenCalledWith('task-1', {
+ scheduler: expect.objectContaining({
+ consecutiveFailures: 0,
+ tickMessageId: 'msg-new',
+ }),
+ });
+ });
+});
diff --git a/src/server/services/taskLifecycle/index.ts b/src/server/services/taskLifecycle/index.ts
index 22a9a9f3049..fc01d688e97 100644
--- a/src/server/services/taskLifecycle/index.ts
+++ b/src/server/services/taskLifecycle/index.ts
@@ -1,4 +1,5 @@
import { chainTaskTopicHandoff, TASK_TOPIC_HANDOFF_SCHEMA } from '@lobechat/prompts';
+import type { TaskItem, TaskSchedulerContext } from '@lobechat/types';
import { DEFAULT_BRIEF_ACTIONS } from '@lobechat/types';
import debug from 'debug';
@@ -10,9 +11,18 @@ import type { LobeChatDatabase } from '@/database/type';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
import { SystemAgentService } from '@/server/services/systemAgent';
import { TaskReviewService } from '@/server/services/taskReview';
+import { createTaskSchedulerModule } from '@/server/services/taskScheduler';
const log = debug('task-lifecycle');
+const TERMINAL_STATUSES = new Set(['canceled', 'completed', 'failed']);
+const isTerminal = (status: string) => TERMINAL_STATUSES.has(status);
+
+// Consecutive 'error' reasons after which we stop re-arming and let the
+// urgent brief surface for human attention. Hardcoded for now (per LOBE-8233);
+// move to task.config later if it needs to be tunable per-task.
+const HEARTBEAT_FAILURE_FUSE = 3;
+
export interface TopicCompleteParams {
errorMessage?: string;
lastAssistantContent?: string;
@@ -115,6 +125,95 @@ export class TaskLifecycleService {
await this.taskModel.updateStatus(taskId, 'paused');
}
+
+ // Heartbeat re-arm: re-read task state (status / context may have just
+ // been mutated by the branches above) and decide whether to publish the
+ // next tick.
+ const finalTask = await this.taskModel.findById(taskId);
+ if (finalTask) await this.maybeRearmHeartbeat(finalTask, reason);
+ }
+
+ /**
+ * Re-arm the next heartbeat tick after `onTopicComplete`.
+ *
+ * Skips when:
+ * - task is not in heartbeat mode or has no positive interval
+ * - task hit a terminal status (completed / canceled / failed)
+ * - an unresolved urgent brief exists for this task (human is waiting)
+ * - consecutive failures hit the fuse threshold (gives up until the user
+ * resolves the urgent error brief)
+ */
+ private async maybeRearmHeartbeat(task: TaskItem, reason: string): Promise<void> {
+ if (task.automationMode !== 'heartbeat') return;
+ if (!task.heartbeatInterval || task.heartbeatInterval <= 0) return;
+ if (isTerminal(task.status)) return;
+
+ const ctx = (task.context as { scheduler?: TaskSchedulerContext } | null) ?? {};
+ const sched = ctx.scheduler ?? {};
+ let consecutiveFailures = sched.consecutiveFailures ?? 0;
+
+ if (reason === 'error') {
+ consecutiveFailures += 1;
+ if (consecutiveFailures >= HEARTBEAT_FAILURE_FUSE) {
+ log(
+ 'fuse blown: task=%s consecutiveFailures=%d — not re-arming',
+ task.identifier,
+ consecutiveFailures,
+ );
+ await this.taskModel.updateContext(task.id, {
+ scheduler: { consecutiveFailures },
+ });
+ return;
+ }
+ } else if (reason === 'done') {
+ consecutiveFailures = 0;
+ }
+
+ // Exclude `error` briefs from the human-waiting check: error briefs are
+ // created on every error and are governed by the fuse counter above.
+ // Without this exclusion, the urgent error brief from the *just-completed*
+ // failure would block re-arm and the fuse threshold would be unreachable.
+ if (await this.briefModel.hasUnresolvedUrgentByTask(task.id, { excludeTypes: ['error'] })) {
+ log('skip re-arm: task=%s has unresolved urgent brief', task.identifier);
+ await this.taskModel.updateContext(task.id, {
+ scheduler: { consecutiveFailures },
+ });
+ return;
+ }
+
+ try {
+ const scheduler = createTaskSchedulerModule();
+
+ // Cancel any prior tick (defensive — we usually wouldn't have one
+ // pending here, since the prior tick has already fired to bring us
+ // into onTopicComplete).
+ if (sched.tickMessageId) {
+ await scheduler.cancelScheduled(sched.tickMessageId).catch(() => undefined);
+ }
+
+ const tickMessageId = await scheduler.scheduleNextTopic({
+ delay: task.heartbeatInterval,
+ taskId: task.id,
+ userId: this.userId,
+ });
+
+ await this.taskModel.updateContext(task.id, {
+ scheduler: {
+ consecutiveFailures,
+ scheduledAt: new Date().toISOString(),
+ tickMessageId,
+ },
+ });
+
+ log(
+ 're-armed task=%s delay=%ds messageId=%s',
+ task.identifier,
+ task.heartbeatInterval,
+ tickMessageId,
+ );
+ } catch (e) {
+ console.warn('[TaskLifecycle] re-arm failed:', e);
+ }
}
/**
diff --git a/src/server/services/taskRunner/buildTaskPrompt.ts b/src/server/services/taskRunner/buildTaskPrompt.ts
new file mode 100644
index 00000000000..8471cc7f57c
--- /dev/null
+++ b/src/server/services/taskRunner/buildTaskPrompt.ts
@@ -0,0 +1,187 @@
+import { buildTaskRunPrompt } from '@lobechat/prompts';
+import type { TaskItem, TaskTopicHandoff, WorkspaceData } from '@lobechat/types';
+
+import type { BriefModel } from '@/database/models/brief';
+import type { TaskModel } from '@/database/models/task';
+import type { TaskTopicModel } from '@/database/models/taskTopic';
+
+export interface BuildTaskPromptDeps {
+ briefModel: BriefModel;
+ taskModel: TaskModel;
+ taskTopicModel: TaskTopicModel;
+}
+
+/**
+ * Server-side orchestrator: fetches task context from the DB and renders the
+ * prompt that `task.run` injects into the agent runtime.
+ *
+ * Pure prompt rendering lives in `@lobechat/prompts` (`buildTaskRunPrompt`).
+ * This wrapper is the DB-aware layer that assembles the input from models.
+ */
+export async function buildTaskPrompt(
+ task: TaskItem,
+ deps: BuildTaskPromptDeps,
+ extraPrompt?: string,
+): Promise<string> {
+ const { briefModel, taskModel, taskTopicModel } = deps;
+
+ const [topics, briefs, comments, subtasks, dependencies, documents] = await Promise.all([
+ task.totalTopics && task.totalTopics > 0
+ ? taskTopicModel.findWithHandoff(task.id).catch(() => [])
+ : Promise.resolve([]),
+ briefModel.findByTaskId(task.id).catch(() => []),
+ taskModel.getComments(task.id).catch(() => []),
+ taskModel.findSubtasks(task.id).catch(() => []),
+ taskModel.getDependencies(task.id).catch(() => []),
+ taskModel
+ .getTreePinnedDocuments(task.id)
+ .catch((): WorkspaceData => ({ nodeMap: {}, tree: [] })),
+ ]);
+
+ const subtaskIds = subtasks.map((s: any) => s.id);
+ const subtaskDeps =
+ subtaskIds.length > 0
+ ? await taskModel.getDependenciesByTaskIds(subtaskIds).catch(() => [])
+ : [];
+ const subtaskIdToIdentifier = new Map(subtasks.map((s: any) => [s.id, s.identifier]));
+ const subtaskDepMap = new Map<string, string>();
+ for (const dep of subtaskDeps as any[]) {
+ const depIdentifier = subtaskIdToIdentifier.get(dep.dependsOnId);
+ if (depIdentifier) subtaskDepMap.set(dep.taskId, depIdentifier);
+ }
+
+ const depTaskIds = [...new Set(dependencies.map((d: any) => d.dependsOnId))];
+ const depTasks = await taskModel.findByIds(depTaskIds);
+ const depIdToIdentifier = new Map(depTasks.map((t: any) => [t.id, t.identifier]));
+
+ let parentIdentifier: string | null = null;
+ let parentTaskContext:
+ | {
+ identifier: string;
+ instruction: string;
+ name?: string | null;
+ subtasks?: Array<{
+ blockedBy?: string;
+ identifier: string;
+ name?: string | null;
+ priority?: number | null;
+ status: string;
+ }>;
+ }
+ | undefined;
+
+ if (task.parentTaskId) {
+ const parent = await taskModel.findById(task.parentTaskId);
+ parentIdentifier = parent?.identifier || null;
+ if (parent) {
+ const siblings = await taskModel.findSubtasks(task.parentTaskId).catch(() => []);
+ const siblingIds = siblings.map((s: any) => s.id);
+ const siblingDeps =
+ siblingIds.length > 0
+ ? await taskModel.getDependenciesByTaskIds(siblingIds).catch(() => [])
+ : [];
+ const siblingIdToIdentifier = new Map(siblings.map((s: any) => [s.id, s.identifier]));
+ const siblingDepMap = new Map<string, string>();
+ for (const dep of siblingDeps as any[]) {
+ const depId = siblingIdToIdentifier.get(dep.dependsOnId);
+ if (depId) siblingDepMap.set(dep.taskId, depId);
+ }
+
+ parentTaskContext = {
+ identifier: parent.identifier,
+ instruction: parent.instruction,
+ name: parent.name,
+ subtasks: siblings.map((s: any) => ({
+ blockedBy: siblingDepMap.get(s.id),
+ identifier: s.identifier,
+ name: s.name,
+ priority: s.priority,
+ status: s.status,
+ })),
+ };
+ }
+ }
+
+ return buildTaskRunPrompt({
+ activities: {
+ briefs: briefs.map((b: any) => ({
+ createdAt: b.createdAt,
+ id: b.id,
+ priority: b.priority,
+ resolvedAction: b.resolvedAction,
+ resolvedAt: b.resolvedAt,
+ resolvedComment: b.resolvedComment,
+ summary: b.summary,
+ title: b.title,
+ type: b.type,
+ })),
+ comments: comments.map((c: any) => ({
+ agentId: c.authorAgentId,
+ content: c.content,
+ createdAt: c.createdAt,
+ id: c.id,
+ })),
+ subtasks: subtasks.map((s: any) => ({
+ createdAt: s.createdAt,
+ id: s.id,
+ identifier: s.identifier,
+ name: s.name,
+ status: s.status,
+ })),
+ topics: (topics as any[]).map((t) => {
+ const handoff = t.handoff as TaskTopicHandoff | null;
+ return {
+ createdAt: t.createdAt,
+ handoff,
+ id: t.topicId || t.id,
+ seq: t.seq,
+ status: t.status,
+ title: handoff?.title || t.title,
+ };
+ }),
+ },
+ extraPrompt,
+ parentTask: parentTaskContext,
+ task: {
+ assigneeAgentId: task.assigneeAgentId,
+ dependencies: dependencies.map((d: any) => ({
+ dependsOn: depIdToIdentifier.get(d.dependsOnId) ?? d.dependsOnId,
+ type: d.type,
+ })),
+ description: task.description,
+ id: task.id,
+ identifier: task.identifier,
+ instruction: task.instruction,
+ name: task.name,
+ parentIdentifier,
+ priority: task.priority,
+ review: taskModel.getReviewConfig(task) as any,
+ status: task.status,
+ subtasks: subtasks.map((s: any) => ({
+ blockedBy: subtaskDepMap.get(s.id),
+ identifier: s.identifier,
+ name: s.name,
+ priority: s.priority,
+ status: s.status,
+ })),
+ },
+ workspace: documents.tree.map((rootNode) => {
+ const rootDoc = documents.nodeMap[rootNode.id];
+ return {
+ children: rootNode.children.map((child) => {
+ const childDoc = documents.nodeMap[child.id];
+ return {
+ createdAt: childDoc?.createdAt,
+ documentId: child.id,
+ size: childDoc?.charCount ?? undefined,
+ sourceTaskIdentifier: childDoc?.sourceTaskIdentifier ?? undefined,
+ title: childDoc?.title,
+ };
+ }),
+ createdAt: rootDoc?.createdAt,
+ documentId: rootNode.id,
+ title: rootDoc?.title,
+ };
+ }),
+ });
+}
diff --git a/src/server/services/taskRunner/heartbeatTick.ts b/src/server/services/taskRunner/heartbeatTick.ts
new file mode 100644
index 00000000000..f3d95fb9674
--- /dev/null
+++ b/src/server/services/taskRunner/heartbeatTick.ts
@@ -0,0 +1,90 @@
+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 { setTaskSchedulerExecutionCallback } from '@/server/services/taskScheduler';
+
+import { TaskRunnerService } from './index';
+
+const log = debug('task-runner:heartbeat-tick');
+
+const TERMINAL_STATUSES = new Set(['canceled', 'completed', 'failed']);
+const isTerminal = (status: string) => TERMINAL_STATUSES.has(status);
+
+export type HeartbeatTickOutcome =
+ | { ran: true; taskIdentifier: string }
+ | { ran: false; reason: HeartbeatTickSkipReason };
+
+export type HeartbeatTickSkipReason =
+ | 'human-waiting'
+ | 'in-flight'
+ | 'mode-changed'
+ | 'no-interval'
+ | 'not-found'
+ | 'terminal';
+
+/**
+ * Run a heartbeat tick — invoked by both the LocalScheduler `setTimeout`
+ * callback and the QStash `/heartbeat-tick` HTTP handler.
+ *
+ * DB is the authority: every check below re-reads task state because the
+ * scheduled message may arrive after the user paused, canceled, or changed
+ * the task's automation mode.
+ */
+export async function runHeartbeatTick(
+ taskId: string,
+ userId: string,
+): Promise<HeartbeatTickOutcome> {
+ 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 !== 'heartbeat') {
+ log('skip task=%s reason=mode-changed (mode=%s)', taskId, task.automationMode);
+ return { ran: false, reason: 'mode-changed' };
+ }
+ if (isTerminal(task.status)) {
+ log('skip task=%s reason=terminal (status=%s)', taskId, task.status);
+ return { ran: false, reason: 'terminal' };
+ }
+ if (!task.heartbeatInterval || task.heartbeatInterval <= 0) {
+ log('skip task=%s reason=no-interval', taskId);
+ return { ran: false, reason: 'no-interval' };
+ }
+
+ 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 — treat as a
+ // graceful skip. runTask's own rollback only fires when *it* set running,
+ // so the in-flight run keeps its 'running' status untouched.
+ 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 };
+}
+
+// Side effect: wire `runHeartbeatTick` into the LocalScheduler's setTimeout
+// callback. Importing this module from anywhere in the server bundle (the
+// heartbeat-tick handler is the natural place) ensures local-mode heartbeat
+// loops actually fire.
+setTaskSchedulerExecutionCallback(async (taskId, userId) => {
+ await runHeartbeatTick(taskId, userId);
+});
diff --git a/src/server/services/taskRunner/index.ts b/src/server/services/taskRunner/index.ts
new file mode 100644
index 00000000000..bf158654d73
--- /dev/null
+++ b/src/server/services/taskRunner/index.ts
@@ -0,0 +1,216 @@
+import { TaskIdentifier as TaskSkillIdentifier } from '@lobechat/builtin-skills';
+import { BriefIdentifier } from '@lobechat/builtin-tool-brief';
+import type { ExecAgentResult } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import debug from 'debug';
+
+import { BriefModel } from '@/database/models/brief';
+import { TaskModel } from '@/database/models/task';
+import { TaskTopicModel } from '@/database/models/taskTopic';
+import type { LobeChatDatabase } from '@/database/type';
+import { AiAgentService } from '@/server/services/aiAgent';
+import { TaskLifecycleService } from '@/server/services/taskLifecycle';
+
+import { buildTaskPrompt } from './buildTaskPrompt';
+
+const log = debug('task-runner');
+
+export interface RunTaskParams {
+ continueTopicId?: string;
+ extraPrompt?: string;
+ taskId: string;
+}
+
+export interface RunTaskResult extends ExecAgentResult {
+ taskId: string;
+ taskIdentifier: string;
+}
+
+/**
+ * TaskRunnerService — orchestrates a single Task run.
+ *
+ * Used by:
+ * - `task.run` TRPC mutation (user-triggered)
+ * - `heartbeat-tick` workflow handler (QStash self-rescheduling)
+ */
+export class TaskRunnerService {
+ private briefModel: BriefModel;
+ private db: LobeChatDatabase;
+ private taskLifecycle: TaskLifecycleService;
+ private taskModel: TaskModel;
+ private taskTopicModel: TaskTopicModel;
+ private userId: string;
+
+ constructor(db: LobeChatDatabase, userId: string) {
+ this.db = db;
+ this.userId = userId;
+ this.taskModel = new TaskModel(db, userId);
+ this.taskTopicModel = new TaskTopicModel(db, userId);
+ this.briefModel = new BriefModel(db, userId);
+ this.taskLifecycle = new TaskLifecycleService(db, userId);
+ }
+
+ async runTask(params: RunTaskParams): Promise<RunTaskResult> {
+ const { taskId: idOrIdentifier, continueTopicId, extraPrompt } = params;
+
+ const task = await this.taskModel.resolve(idOrIdentifier);
+ if (!task) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });
+ }
+
+ // Track whether *this* invocation transitioned the task to 'running'. The
+ // catch-block rollback must only fire when we own the running state —
+ // otherwise an early failure (e.g. CONFLICT thrown because a concurrent
+ // run is in flight) would clobber the in-flight run's status to 'paused'.
+ let weSetRunning = false;
+
+ try {
+ if (!task.assigneeAgentId) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Task has no assigned agent. Use --agent when creating or edit the task.',
+ });
+ }
+
+ const existingTopics = await this.taskTopicModel.findByTaskId(task.id);
+
+ if (continueTopicId) {
+ const target = existingTopics.find((t) => t.topicId === continueTopicId);
+ if (target?.status === 'running') {
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: `Topic ${continueTopicId} is already running.`,
+ });
+ }
+ } else {
+ const runningTopic = existingTopics.find((t) => t.status === 'running');
+ if (runningTopic) {
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: `Task already has a running topic (${runningTopic.topicId}). Cancel it first or use --continue.`,
+ });
+ }
+ }
+
+ // Auto-detect and clean up timed-out topics
+ if (task.lastHeartbeatAt && task.heartbeatTimeout) {
+ const elapsed = (Date.now() - new Date(task.lastHeartbeatAt).getTime()) / 1000;
+ if (elapsed > task.heartbeatTimeout) {
+ await this.taskTopicModel.timeoutRunning(task.id);
+ }
+ }
+
+ const prompt = await buildTaskPrompt(
+ task,
+ {
+ briefModel: this.briefModel,
+ taskModel: this.taskModel,
+ taskTopicModel: this.taskTopicModel,
+ },
+ extraPrompt,
+ );
+
+ if (task.status !== 'running') {
+ await this.taskModel.updateStatus(task.id, 'running', {
+ error: null,
+ startedAt: new Date(),
+ });
+ weSetRunning = true;
+ } else if (task.error) {
+ await this.taskModel.update(task.id, { error: null });
+ }
+
+ const agentRef = task.assigneeAgentId!;
+ const isSlug = !agentRef.startsWith('agt_');
+
+ const aiAgentService = new AiAgentService(this.db, this.userId);
+ const taskId = task.id;
+ const taskIdentifier = task.identifier;
+ const taskLifecycle = this.taskLifecycle;
+ const userId = this.userId;
+
+ const checkpoint = this.taskModel.getCheckpointConfig(task);
+ const reviewConfig = this.taskModel.getReviewConfig(task);
+ const pluginIds = [TaskSkillIdentifier];
+ if (!reviewConfig?.enabled && checkpoint.onAgentRequest !== false) {
+ pluginIds.push(BriefIdentifier);
+ }
+
+ const taskConfig = (task.config ?? {}) as Record<string, unknown>;
+
+ log('runTask: %s (continue=%s)', taskIdentifier, continueTopicId);
+
+ const result = await aiAgentService.execAgent({
+ ...(isSlug ? { slug: agentRef } : { agentId: agentRef }),
+ additionalPluginIds: pluginIds,
+ ...(typeof taskConfig.model === 'string' && { model: taskConfig.model }),
+ ...(typeof taskConfig.provider === 'string' && { provider: taskConfig.provider }),
+ hooks: [
+ {
+ handler: async (event) => {
+ await taskLifecycle.onTopicComplete({
+ errorMessage: event.errorMessage,
+ lastAssistantContent: event.lastAssistantContent,
+ operationId: event.operationId,
+ reason: event.reason || 'done',
+ taskId,
+ taskIdentifier,
+ topicId: event.topicId,
+ });
+ },
+ id: 'task-on-complete',
+ type: 'onComplete' as const,
+ webhook: {
+ body: { taskId, taskIdentifier, userId },
+ url: '/api/workflows/task/on-topic-complete',
+ },
+ },
+ ],
+ prompt,
+ taskId: task.id,
+ title: extraPrompt ? extraPrompt.slice(0, 100) : task.name || task.identifier,
+ trigger: 'task',
+ userInterventionConfig: { approvalMode: 'headless' },
+ ...(continueTopicId && { appContext: { topicId: continueTopicId } }),
+ });
+
+ if (result.topicId) {
+ if (continueTopicId) {
+ await this.taskTopicModel.updateStatus(task.id, continueTopicId, 'running');
+ await this.taskTopicModel.updateOperationId(task.id, continueTopicId, result.operationId);
+ await this.taskModel.updateCurrentTopic(task.id, continueTopicId);
+ } else {
+ await this.taskModel.incrementTopicCount(task.id);
+ await this.taskModel.updateCurrentTopic(task.id, result.topicId);
+ await this.taskTopicModel.add(task.id, result.topicId, {
+ operationId: result.operationId,
+ seq: (task.totalTopics || 0) + 1,
+ });
+ }
+ }
+
+ await this.taskModel.updateHeartbeat(task.id);
+
+ return {
+ ...result,
+ taskId: task.id,
+ taskIdentifier: task.identifier,
+ };
+ } catch (error) {
+ if (weSetRunning) {
+ try {
+ const failedTask = await this.taskModel.resolve(idOrIdentifier);
+ if (failedTask && failedTask.status === 'running') {
+ await this.taskModel.updateStatus(failedTask.id, 'paused', {
+ error: error instanceof Error ? error.message : 'Unknown error',
+ });
+ }
+ } catch {
+ // Rollback itself failed, ignore
+ }
+ }
+
+ throw error;
+ }
+ }
+}
diff --git a/src/server/services/taskScheduler/impls/index.ts b/src/server/services/taskScheduler/impls/index.ts
index 3f951b55f26..d637d0ce250 100644
--- a/src/server/services/taskScheduler/impls/index.ts
+++ b/src/server/services/taskScheduler/impls/index.ts
@@ -1,25 +1,65 @@
import { appEnv } from '@/envs/app';
+import { qstashClient } from '@/libs/qstash';
-import { LocalTaskScheduler } from './local';
+import { LocalTaskScheduler, type TaskExecutionCallback } from './local';
+import { QStashTaskScheduler } from './qstash';
import type { TaskSchedulerImpl } from './type';
-// QStash implementation will be added later
-// import { QStashTaskScheduler } from './qstash';
+let cachedScheduler: TaskSchedulerImpl | null = null;
+let cachedExecutionCallback: TaskExecutionCallback | null = null;
/**
- * Create task scheduler module
+ * Get (or lazily create) the singleton task scheduler.
*
- * When AGENT_RUNTIME_MODE=queue: QStash (production)
- * When default: Local (setTimeout-based)
+ * - `AGENT_RUNTIME_MODE=queue`: QStash (production)
+ * - default: Local (setTimeout-based, dev / electron)
+ *
+ * Singleton because `LocalTaskScheduler` holds in-memory `setTimeout` state and
+ * a per-request instance would orphan pending timers on the next request.
*/
export const createTaskSchedulerModule = (): TaskSchedulerImpl => {
+ if (cachedScheduler) return cachedScheduler;
+
if (appEnv.enableQueueAgentRuntime) {
- // TODO: QStash implementation
- // return new QStashTaskScheduler({ qstashToken });
+ const baseUrl = process.env.APP_URL;
+ if (!baseUrl) {
+ throw new Error('APP_URL is required to schedule heartbeat ticks via QStash');
+ }
+ cachedScheduler = new QStashTaskScheduler({ baseUrl, qstashClient });
+ return cachedScheduler;
+ }
+
+ const local = new LocalTaskScheduler();
+ if (cachedExecutionCallback) local.setExecutionCallback(cachedExecutionCallback);
+ cachedScheduler = local;
+
+ // Lazy-load the heartbeat tick runner so it registers its own callback via
+ // `setTaskSchedulerExecutionCallback`. Dynamic import avoids the import
+ // cycle (heartbeatTick → TaskRunnerService → TaskLifecycleService →
+ // createTaskSchedulerModule). Heartbeat ticks always fire after `delay`
+ // seconds, so the dynamic import resolves long before the first tick.
+ if (!cachedExecutionCallback) {
+ void import('@/server/services/taskRunner/heartbeatTick').catch((e) => {
+ console.warn('[taskScheduler] failed to load heartbeat tick runner:', e);
+ });
}
- return new LocalTaskScheduler();
+ return cachedScheduler;
+};
+
+/**
+ * Register the in-process callback the LocalTaskScheduler invokes on tick.
+ * Cloud (QStash) mode ignores this — its callback is the HTTP `/heartbeat-tick`
+ * handler. Calling this after a Local scheduler is already created retroactively
+ * wires the callback in.
+ */
+export const setTaskSchedulerExecutionCallback = (callback: TaskExecutionCallback): void => {
+ cachedExecutionCallback = callback;
+ if (cachedScheduler instanceof LocalTaskScheduler) {
+ cachedScheduler.setExecutionCallback(callback);
+ }
};
export { LocalTaskScheduler } from './local';
+export { QStashTaskScheduler } from './qstash';
export type { TaskSchedulerImpl } from './type';
diff --git a/src/server/services/taskScheduler/impls/qstash.test.ts b/src/server/services/taskScheduler/impls/qstash.test.ts
new file mode 100644
index 00000000000..f45a696146e
--- /dev/null
+++ b/src/server/services/taskScheduler/impls/qstash.test.ts
@@ -0,0 +1,105 @@
+// @vitest-environment node
+import type { Client } from '@upstash/qstash';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { QStashTaskScheduler } from './qstash';
+
+const makeClient = () => {
+ const publishJSON = vi.fn();
+ const messagesDelete = vi.fn();
+ const client = {
+ messages: { delete: messagesDelete },
+ publishJSON,
+ } as unknown as Client;
+ return { client, messagesDelete, publishJSON };
+};
+
+describe('QStashTaskScheduler', () => {
+ let publishJSON: ReturnType<typeof vi.fn>;
+ let messagesDelete: ReturnType<typeof vi.fn>;
+ let scheduler: QStashTaskScheduler;
+
+ beforeEach(() => {
+ const { client, publishJSON: pj, messagesDelete: md } = makeClient();
+ publishJSON = pj;
+ messagesDelete = md;
+ scheduler = new QStashTaskScheduler({
+ baseUrl: 'https://app.example.com',
+ qstashClient: client,
+ });
+ });
+
+ describe('scheduleNextTopic', () => {
+ it('publishes a delayed message to /heartbeat-tick and returns messageId', async () => {
+ publishJSON.mockResolvedValue({ messageId: 'msg-abc' });
+
+ const id = await scheduler.scheduleNextTopic({
+ delay: 60,
+ taskId: 'task-1',
+ userId: 'user-1',
+ });
+
+ expect(id).toBe('msg-abc');
+ expect(publishJSON).toHaveBeenCalledWith({
+ body: { taskId: 'task-1', userId: 'user-1' },
+ delay: 60,
+ url: 'https://app.example.com/api/workflows/task/heartbeat-tick',
+ });
+ });
+
+ it('defaults delay to 0 when not provided', async () => {
+ publishJSON.mockResolvedValue({ messageId: 'msg-2' });
+
+ await scheduler.scheduleNextTopic({ taskId: 't', userId: 'u' });
+
+ expect(publishJSON).toHaveBeenCalledWith(expect.objectContaining({ delay: 0 }));
+ });
+
+ it('strips trailing slash from baseUrl', async () => {
+ const { client, publishJSON: pj } = makeClient();
+ pj.mockResolvedValue({ messageId: 'm' });
+ const sched = new QStashTaskScheduler({
+ baseUrl: 'https://app.example.com/',
+ qstashClient: client,
+ });
+
+ await sched.scheduleNextTopic({ taskId: 't', userId: 'u' });
+
+ expect(pj).toHaveBeenCalledWith(
+ expect.objectContaining({
+ url: 'https://app.example.com/api/workflows/task/heartbeat-tick',
+ }),
+ );
+ });
+
+ it('returns empty string when response lacks messageId (defensive)', async () => {
+ publishJSON.mockResolvedValue({} as any);
+
+ const id = await scheduler.scheduleNextTopic({ taskId: 't', userId: 'u' });
+
+ expect(id).toBe('');
+ });
+ });
+
+ describe('cancelScheduled', () => {
+ it('calls messages.delete with the messageId', async () => {
+ messagesDelete.mockResolvedValue(undefined);
+
+ await scheduler.cancelScheduled('msg-xyz');
+
+ expect(messagesDelete).toHaveBeenCalledWith('msg-xyz');
+ });
+
+ it('is a no-op for empty messageId', async () => {
+ await scheduler.cancelScheduled('');
+
+ expect(messagesDelete).not.toHaveBeenCalled();
+ });
+
+ it('swallows errors (already delivered / not found)', async () => {
+ messagesDelete.mockRejectedValue(new Error('not found'));
+
+ await expect(scheduler.cancelScheduled('msg-gone')).resolves.toBeUndefined();
+ });
+ });
+});
diff --git a/src/server/services/taskScheduler/impls/qstash.ts b/src/server/services/taskScheduler/impls/qstash.ts
new file mode 100644
index 00000000000..2d88afcadaa
--- /dev/null
+++ b/src/server/services/taskScheduler/impls/qstash.ts
@@ -0,0 +1,61 @@
+import type { Client } from '@upstash/qstash';
+import debug from 'debug';
+
+import type { ScheduleNextTopicParams, TaskSchedulerImpl } from './type';
+
+const log = debug('task-scheduler:qstash');
+
+const HEARTBEAT_TICK_PATH = '/api/workflows/task/heartbeat-tick';
+
+export interface QStashTaskSchedulerConfig {
+ /** Absolute base URL (e.g. `process.env.APP_URL`). Used to build the tick callback URL. */
+ baseUrl: string;
+ qstashClient: Client;
+}
+
+/**
+ * QStash-backed task scheduler.
+ *
+ * Each `scheduleNextTopic` call publishes a one-shot delayed message; QStash will
+ * POST `{ taskId, userId }` to `/api/workflows/task/heartbeat-tick` after `delay`
+ * seconds. The handler is responsible for re-checking task state (DB is the
+ * authority — a tick may arrive after the user paused or canceled the task).
+ */
+export class QStashTaskScheduler implements TaskSchedulerImpl {
+ private baseUrl: string;
+ private qstashClient: Client;
+
+ constructor(config: QStashTaskSchedulerConfig) {
+ this.qstashClient = config.qstashClient;
+ this.baseUrl = config.baseUrl.replace(/\/$/, '');
+ }
+
+ async scheduleNextTopic(params: ScheduleNextTopicParams): Promise<string> {
+ const { taskId, userId, delay = 0 } = params;
+ const url = `${this.baseUrl}${HEARTBEAT_TICK_PATH}`;
+
+ log('Publishing tick: task=%s delay=%ds url=%s', taskId, delay, url);
+
+ const response = await this.qstashClient.publishJSON({
+ body: { taskId, userId },
+ delay,
+ url,
+ });
+
+ const messageId = 'messageId' in response ? response.messageId : '';
+ log('Published tick messageId=%s', messageId);
+ return messageId;
+ }
+
+ async cancelScheduled(messageId: string): Promise<void> {
+ if (!messageId) return;
+ try {
+ await this.qstashClient.messages.delete(messageId);
+ log('Canceled tick messageId=%s', messageId);
+ } catch (error) {
+ // Already delivered / not found — silent. The handler does idempotency
+ // checks against DB state, so a stale tick will be ignored anyway.
+ log('cancelScheduled noop (likely already delivered): %s, %O', messageId, error);
+ }
+ }
+}
diff --git a/src/server/services/taskScheduler/index.ts b/src/server/services/taskScheduler/index.ts
index b604725ea7f..6abbdaff513 100644
--- a/src/server/services/taskScheduler/index.ts
+++ b/src/server/services/taskScheduler/index.ts
@@ -1,2 +1,7 @@
-export { createTaskSchedulerModule, LocalTaskScheduler } from './impls';
+export {
+ createTaskSchedulerModule,
+ LocalTaskScheduler,
+ QStashTaskScheduler,
+ setTaskSchedulerExecutionCallback,
+} from './impls';
export type { ScheduleNextTopicParams, TaskSchedulerImpl } from './impls/type';
diff --git a/src/server/workflows-hono/middlewares/qstashAuth.ts b/src/server/workflows-hono/middlewares/qstashAuth.ts
new file mode 100644
index 00000000000..23f67c90dac
--- /dev/null
+++ b/src/server/workflows-hono/middlewares/qstashAuth.ts
@@ -0,0 +1,34 @@
+import debug from 'debug';
+import type { MiddlewareHandler } from 'hono';
+
+import { verifyQStashSignature } from '@/libs/qstash';
+
+const log = debug('lobe-server:workflows:qstash-auth');
+
+/**
+ * Hono middleware that verifies the `Upstash-Signature` header on incoming
+ * QStash webhook calls.
+ *
+ * - When `QSTASH_CURRENT_SIGNING_KEY` is unset (dev / electron), verification
+ * is skipped — matching the existing `verifyQStashSignature` behavior.
+ * - On signature mismatch, returns `401 Invalid signature` and aborts the
+ * handler chain.
+ * - The body is consumed via `c.req.text()` to compute the HMAC; downstream
+ * handlers can still call `c.req.json()` because Hono caches across body
+ * formats (`bodyCache` cross-converts text ↔ json).
+ *
+ * Use for one-shot QStash webhook receivers. For Upstash *Workflow* endpoints
+ * (multi-step `serve()` integrations) use `@upstash/workflow/hono`'s built-in
+ * verification instead.
+ */
+export const qstashAuth = (): MiddlewareHandler => async (c, next) => {
+ if (process.env.QSTASH_CURRENT_SIGNING_KEY) {
+ const rawBody = await c.req.text();
+ const ok = await verifyQStashSignature(c.req.raw, rawBody);
+ if (!ok) {
+ log('Rejected: invalid QStash signature on %s', c.req.path);
+ return c.json({ error: 'Invalid signature' }, 401);
+ }
+ }
+ await next();
+};
diff --git a/src/server/workflows-hono/task/handlers/heartbeatTick.ts b/src/server/workflows-hono/task/handlers/heartbeatTick.ts
new file mode 100644
index 00000000000..cb7ac728173
--- /dev/null
+++ b/src/server/workflows-hono/task/handlers/heartbeatTick.ts
@@ -0,0 +1,28 @@
+import debug from 'debug';
+import type { Context } from 'hono';
+
+import { runHeartbeatTick } from '@/server/services/taskRunner/heartbeatTick';
+
+const log = debug('lobe-server:workflows:task:heartbeat-tick');
+
+export interface HeartbeatTickPayload {
+ taskId: string;
+ userId: string;
+}
+
+export async function heartbeatTick(c: Context) {
+ try {
+ const body = (await c.req.json()) as HeartbeatTickPayload;
+ const { taskId, userId } = body;
+ if (!taskId || !userId) {
+ return c.json({ error: 'Missing required fields: taskId, userId' }, 400);
+ }
+
+ log('Received tick: taskId=%s userId=%s', taskId, userId);
+ const outcome = await runHeartbeatTick(taskId, userId);
+ return c.json({ success: true, ...outcome });
+ } catch (error) {
+ console.error('[task/heartbeat-tick] Error:', error);
+ return c.json({ error: error instanceof Error ? error.message : 'Internal error' }, 500);
+ }
+}
diff --git a/src/server/workflows-hono/task/handlers/watchdog.ts b/src/server/workflows-hono/task/handlers/watchdog.ts
new file mode 100644
index 00000000000..e2c161af892
--- /dev/null
+++ b/src/server/workflows-hono/task/handlers/watchdog.ts
@@ -0,0 +1,55 @@
+import debug from 'debug';
+import type { Context } from 'hono';
+
+import { BriefModel } from '@/database/models/brief';
+import { TaskModel } from '@/database/models/task';
+import { getServerDB } from '@/database/server';
+
+const log = debug('lobe-server:workflows:task:watchdog');
+
+/**
+ * Cron-style watchdog. Scans all `running` tasks where
+ * `lastHeartbeatAt + heartbeatTimeout < now()` and marks them `failed`,
+ * leaving an urgent brief for the user.
+ *
+ * No per-user authentication: this is a global sweep registered as a QStash
+ * Schedule (cron). Signature verification is handled by the `qstashAuth`
+ * middleware mounted on the route.
+ */
+export async function watchdog(c: Context) {
+ try {
+ const db = await getServerDB();
+ const stuckTasks = await TaskModel.findStuckTasks(db);
+ const failed: string[] = [];
+
+ for (const task of stuckTasks) {
+ const taskModel = new TaskModel(db, task.createdByUserId);
+ await taskModel.updateStatus(task.id, 'failed', {
+ completedAt: new Date(),
+ error: 'Heartbeat timeout',
+ });
+
+ const briefModel = new BriefModel(db, task.createdByUserId);
+ await briefModel.create({
+ agentId: task.assigneeAgentId || undefined,
+ priority: 'urgent',
+ summary: `Task has been running without heartbeat update for more than ${task.heartbeatTimeout} seconds.`,
+ taskId: task.id,
+ title: `${task.identifier} heartbeat timeout`,
+ type: 'error',
+ });
+
+ failed.push(task.identifier);
+ }
+
+ log('Watchdog scan: checked=%d failed=%d', stuckTasks.length, failed.length);
+ return c.json({
+ checked: stuckTasks.length,
+ failed,
+ success: true,
+ });
+ } catch (error) {
+ console.error('[task/watchdog] 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 96bb4817190..b57c35d7ab1 100644
--- a/src/server/workflows-hono/task/index.ts
+++ b/src/server/workflows-hono/task/index.ts
@@ -1,9 +1,14 @@
import { Hono } from 'hono';
+import { qstashAuth } from '../middlewares/qstashAuth';
+import { heartbeatTick } from './handlers/heartbeatTick';
import { onTopicComplete } from './handlers/onTopicComplete';
+import { watchdog } from './handlers/watchdog';
const app = new Hono();
-app.post('/on-topic-complete', onTopicComplete);
+app.post('/on-topic-complete', qstashAuth(), onTopicComplete);
+app.post('/heartbeat-tick', qstashAuth(), heartbeatTick);
+app.post('/watchdog', qstashAuth(), watchdog);
export default app;