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.

πŸ› fix(task): stop ad-hoc runs & transient errors from stalling scheduled tasks (#16716)

Arvin Xud74f65f05057
diff --git a/apps/server/src/services/taskLifecycle/index.ts b/apps/server/src/services/taskLifecycle/index.ts
index 0f0ef7aaf7e..9a0cce9ad33 100644
--- a/apps/server/src/services/taskLifecycle/index.ts
+++ b/apps/server/src/services/taskLifecycle/index.ts
@@ -18,6 +18,8 @@ import type {
BriefArtifacts,
BriefDecision,
TaskItem,
+ TaskLifecycleAudit,
+ TaskRunTrigger,
TaskSchedulerContext,
TaskTopicHandoff,
} from '@lobechat/types';
@@ -59,16 +61,22 @@ 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 );
-// move to task.config later if it needs to be tunable per-task.
-const HEARTBEAT_FAILURE_FUSE = 3;
+// Consecutive automation-tick 'error' reasons after which we pause the task /
+// stop re-arming and let the urgent brief surface for human attention. A single
+// transient upstream hiccup (429 / network / upstream 500) must NOT permanently
+// stop a recurring task β€” only this many *consecutive* failures do. Hardcoded
+// for now; move to task.config later if it needs to be tunable per-task.
+const AUTOMATION_FAILURE_FUSE = 3;
export interface TopicCompleteParams {
errorMessage?: string;
lastAssistantContent?: string;
operationId: string;
reason: string; // 'done' | 'error' | 'interrupted' | ...
+ // What triggered the run. Manual "run now" failures are ad-hoc and must not
+ // change an automation task's scheduling state (LOBE-11388). Undefined is
+ // treated as 'manual' for backward compatibility with older callers.
+ runTrigger?: TaskRunTrigger;
taskId: string;
taskIdentifier: string;
topicId?: string;
@@ -210,6 +218,12 @@ export class TaskLifecycleService {
log('cap reached for task=%s β€” marking completed post-tick', taskIdentifier);
await this.taskModel.updateStatus(taskId, 'completed', { completedAt: new Date() });
} else if (currentTask.automationMode) {
+ // A successful tick parks the automation task back at its resting
+ // 'scheduled' state and clears the live error column. Before clearing
+ // it, stamp a durable recovery marker + reset the failure fuse so the
+ // recovery is auditable and a later query can still tell the task once
+ // failed β€” the live `error` alone would silently self-heal (LOBE-11390).
+ await this.recordAutomationRecovery(currentTask);
await this.taskModel.updateStatus(taskId, 'scheduled', { error: null });
} else if (!verifyBound && this.taskModel.shouldPauseOnTopicComplete(currentTask)) {
await this.taskModel.updateStatus(taskId, 'paused', { error: null });
@@ -220,19 +234,78 @@ export class TaskLifecycleService {
const topicSeq = currentTask?.totalTopics || '?';
const topicRef = topicId ? ` #${topicSeq} (${topicId})` : '';
+ const errorText = errorMessage || 'Unknown error';
+ // Always surface an urgent error brief β€” a failed run is visible to the
+ // user regardless of what happens to the scheduling state below.
await this.briefModel.create({
actions: DEFAULT_BRIEF_ACTIONS['error'],
agentId: currentTask?.assigneeAgentId || undefined,
priority: 'urgent',
- summary: `Execution failed: ${errorMessage || 'Unknown error'}`,
+ summary: `Execution failed: ${errorText}`,
taskId,
title: `${taskIdentifier} topic${topicRef} error`,
trigger: 'task',
type: 'error',
});
- await this.taskModel.updateStatus(taskId, 'paused');
+ const runTrigger = params.runTrigger ?? 'manual';
+ const isAutomationTick = runTrigger === 'schedule' || runTrigger === 'heartbeat';
+
+ if (!currentTask) {
+ // Task vanished mid-run β€” nothing to transition.
+ } else if (!currentTask.automationMode) {
+ // Ad-hoc / dependency task: pause for user attention (legacy behavior).
+ await this.recordAutomationError(currentTask, errorText, runTrigger);
+ await this.taskModel.updateStatus(taskId, 'paused', { error: errorText });
+ } else if (!isAutomationTick) {
+ // LOBE-11388: a manual "run now" of an automation task failed. This is
+ // an ad-hoc debug/backfill run β€” its failure is NOT a health signal for
+ // the automation. Restore the resting 'scheduled' state (the run had
+ // flipped it to 'running') so the next scheduled tick still fires, and
+ // record the error for visibility β€” but do NOT pause and do NOT touch
+ // the consecutive-failure fuse (only automation ticks count).
+ await this.recordAutomationError(currentTask, errorText, runTrigger);
+ await this.taskModel.updateStatus(taskId, 'scheduled', { error: errorText });
+ } else if (currentTask.automationMode === 'schedule') {
+ // LOBE-11389: a scheduled tick failed. A single transient error must not
+ // permanently pause a recurring task. Count consecutive failures and
+ // only pause once the fuse blows; otherwise keep the task 'scheduled' so
+ // the next tick retries. (Heartbeat tasks are handled by
+ // maybeRearmHeartbeat below, which owns their fuse + re-arm.)
+ const ctx = (currentTask.context as { scheduler?: TaskSchedulerContext } | null) ?? {};
+ const consecutiveFailures = (ctx.scheduler?.consecutiveFailures ?? 0) + 1;
+
+ if (consecutiveFailures >= AUTOMATION_FAILURE_FUSE) {
+ log(
+ 'schedule fuse blown: task=%s consecutiveFailures=%d β€” pausing',
+ taskIdentifier,
+ consecutiveFailures,
+ );
+ await this.recordAutomationError(currentTask, errorText, runTrigger, {
+ consecutiveFailures,
+ pauseReason: `${consecutiveFailures} consecutive scheduled-run failures`,
+ });
+ await this.taskModel.updateStatus(taskId, 'paused', { error: errorText });
+ } else {
+ log(
+ 'schedule error (retryable): task=%s consecutiveFailures=%d/%d',
+ taskIdentifier,
+ consecutiveFailures,
+ AUTOMATION_FAILURE_FUSE,
+ );
+ await this.recordAutomationError(currentTask, errorText, runTrigger, {
+ consecutiveFailures,
+ });
+ await this.taskModel.updateStatus(taskId, 'scheduled', { error: errorText });
+ }
+ } else {
+ // Heartbeat tick failed: record the error and keep the resting
+ // 'scheduled' state. maybeRearmHeartbeat (below) owns the consecutive-
+ // failure fuse and the re-arm decision for heartbeat tasks.
+ await this.recordAutomationError(currentTask, errorText, runTrigger);
+ await this.taskModel.updateStatus(taskId, 'scheduled', { error: errorText });
+ }
}
// Bridge the finished task's handoff back to the creator conversation
@@ -307,10 +380,69 @@ export class TaskLifecycleService {
const runCount = await this.taskTopicModel.countByTask(task.id, {
since: new Date(startedAtIso),
+ // Only scheduled ticks consume the quota β€” manual "run now" invocations
+ // are ad-hoc and must not push the task toward its cap (LOBE-11391).
+ triggers: ['schedule'],
});
return runCount >= maxExecutions;
}
+ /**
+ * Append a failure to the durable lifecycle audit trail
+ * (`context.lifecycle`). Unlike the live `tasks.error` column β€” cleared by
+ * the next successful run β€” this history survives a later success so a missed
+ * fire / prior pause stays diagnosable after the fact (LOBE-11390).
+ *
+ * When `extra.pauseReason` is set, also stamps `lastPausedAt`/`lastPauseReason`
+ * (the failure fuse just auto-paused the task). When `extra.consecutiveFailures`
+ * is set, mirrors it into `context.scheduler` so the schedule fuse persists.
+ */
+ private async recordAutomationError(
+ task: TaskItem,
+ errorText: string,
+ trigger: TaskRunTrigger,
+ extra?: { consecutiveFailures?: number; pauseReason?: string },
+ ): Promise<void> {
+ const ctx = (task.context as { lifecycle?: TaskLifecycleAudit } | null) ?? {};
+ const now = new Date().toISOString();
+
+ const lifecycle: TaskLifecycleAudit = {
+ errorCount: (ctx.lifecycle?.errorCount ?? 0) + 1,
+ lastError: { at: now, message: errorText, trigger },
+ };
+ if (extra?.pauseReason) {
+ lifecycle.lastPausedAt = now;
+ lifecycle.lastPauseReason = extra.pauseReason;
+ }
+
+ const patch: Record<string, unknown> = { lifecycle };
+ if (extra?.consecutiveFailures !== undefined) {
+ patch.scheduler = { consecutiveFailures: extra.consecutiveFailures };
+ }
+
+ await this.taskModel.updateContext(task.id, patch);
+ }
+
+ /**
+ * Stamp a durable recovery marker when a successful automation tick clears a
+ * prior error, and reset the consecutive-failure fuse. Only writes when the
+ * task was actually in an error state β€” a clean run after a clean run is a
+ * no-op so the audit stays low-noise.
+ */
+ private async recordAutomationRecovery(task: TaskItem): Promise<void> {
+ const ctx = (task.context as { scheduler?: TaskSchedulerContext } | null) ?? {};
+ const consecutiveFailures = ctx.scheduler?.consecutiveFailures ?? 0;
+ const wasErrored = !!task.error || consecutiveFailures > 0;
+ if (!wasErrored) return;
+
+ const patch: Record<string, unknown> = {
+ lifecycle: { lastRecoveredAt: new Date().toISOString() },
+ };
+ if (consecutiveFailures > 0) patch.scheduler = { consecutiveFailures: 0 };
+
+ await this.taskModel.updateContext(task.id, patch);
+ }
+
/**
* Re-arm the next heartbeat tick after `onTopicComplete`.
*
@@ -332,7 +464,7 @@ export class TaskLifecycleService {
if (reason === 'error') {
consecutiveFailures += 1;
- if (consecutiveFailures >= HEARTBEAT_FAILURE_FUSE) {
+ if (consecutiveFailures >= AUTOMATION_FAILURE_FUSE) {
log(
'fuse blown: task=%s consecutiveFailures=%d β€” not re-arming',
task.identifier,
diff --git a/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts b/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts
index b3b8282b095..0fc76cd7a26 100644
--- a/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts
+++ b/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts
@@ -39,6 +39,7 @@ const baseTask = (overrides: Partial<TaskItem> = {}): TaskItem =>
describe('TaskLifecycleService.onTopicComplete', () => {
let service: TaskLifecycleService;
let updateStatus: ReturnType<typeof vi.fn>;
+ let updateContext: ReturnType<typeof vi.fn>;
let findById: ReturnType<typeof vi.fn>;
let updateHeartbeat: ReturnType<typeof vi.fn>;
let updateTopicStatus: ReturnType<typeof vi.fn>;
@@ -51,6 +52,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
service = new TaskLifecycleService({} as any, 'user-1');
updateStatus = vi.fn().mockResolvedValue(null);
+ updateContext = vi.fn().mockResolvedValue(null);
findById = vi.fn();
updateHeartbeat = vi.fn().mockResolvedValue(undefined);
updateTopicStatus = vi.fn().mockResolvedValue(undefined);
@@ -60,6 +62,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
const taskModel = (service as any).taskModel;
taskModel.updateStatus = updateStatus;
+ taskModel.updateContext = updateContext;
taskModel.findById = findById;
taskModel.updateHeartbeat = updateHeartbeat;
taskModel.getReviewConfig = getReviewConfig;
@@ -331,8 +334,8 @@ describe('TaskLifecycleService.onTopicComplete', () => {
});
describe('reason=error', () => {
- it('automation task β†’ status="paused" (error always pauses)', async () => {
- const task = baseTask({ automationMode: 'heartbeat' });
+ it('non-automation task β†’ status="paused" (unchanged behavior)', async () => {
+ const task = baseTask({ automationMode: null });
findById.mockResolvedValue(task);
await service.onTopicComplete({
@@ -344,24 +347,201 @@ describe('TaskLifecycleService.onTopicComplete', () => {
topicId: 'topic-1',
});
- expect(updateStatus).toHaveBeenCalledWith('task-1', 'paused');
- expect(updateStatus).not.toHaveBeenCalledWith('task-1', 'scheduled', expect.anything());
+ expect(updateStatus).toHaveBeenCalledWith('task-1', 'paused', { error: 'boom' });
});
- it('non-automation task β†’ status="paused" (unchanged behavior)', async () => {
- const task = baseTask({ automationMode: null });
+ it('LOBE-11388: manual run of a schedule task fails β†’ restored to scheduled, NOT paused', async () => {
+ const task = baseTask({ automationMode: 'schedule', status: 'running' });
+ findById.mockResolvedValue(task);
+
+ await service.onTopicComplete({
+ errorMessage: 'boom',
+ operationId: 'op-1',
+ reason: 'error',
+ runTrigger: 'manual',
+ taskId: 'task-1',
+ taskIdentifier: 'TASK-1',
+ topicId: 'topic-1',
+ });
+
+ // Restored to the resting scheduled state so the next cron tick still
+ // fires β€” never paused off the schedule.
+ expect(updateStatus).toHaveBeenCalledWith('task-1', 'scheduled', { error: 'boom' });
+ expect(updateStatus).not.toHaveBeenCalledWith('task-1', 'paused', expect.anything());
+ // Manual failure must NOT touch the consecutive-failure fuse.
+ expect(updateContext).not.toHaveBeenCalledWith(
+ 'task-1',
+ expect.objectContaining({ scheduler: expect.anything() }),
+ );
+ });
+
+ it('LOBE-11388: undefined runTrigger defaults to manual (backward compat)', async () => {
+ const task = baseTask({ automationMode: 'schedule' });
+ findById.mockResolvedValue(task);
+
+ await service.onTopicComplete({
+ errorMessage: 'boom',
+ operationId: 'op-1',
+ reason: 'error',
+ taskId: 'task-1',
+ taskIdentifier: 'TASK-1',
+ topicId: 'topic-1',
+ });
+
+ expect(updateStatus).not.toHaveBeenCalledWith('task-1', 'paused', expect.anything());
+ expect(updateStatus).toHaveBeenCalledWith('task-1', 'scheduled', { error: 'boom' });
+ });
+
+ it('LOBE-11389: scheduled run fails below fuse β†’ stays scheduled + increments failures', async () => {
+ const task = baseTask({
+ automationMode: 'schedule',
+ context: { scheduler: { consecutiveFailures: 1 } } as any,
+ });
+ findById.mockResolvedValue(task);
+
+ await service.onTopicComplete({
+ errorMessage: 'boom',
+ operationId: 'op-1',
+ reason: 'error',
+ runTrigger: 'schedule',
+ taskId: 'task-1',
+ taskIdentifier: 'TASK-1',
+ topicId: 'topic-1',
+ });
+
+ // 1 prior + this one = 2, below the fuse of 3 β†’ retryable, stays scheduled.
+ expect(updateStatus).toHaveBeenCalledWith('task-1', 'scheduled', { error: 'boom' });
+ expect(updateStatus).not.toHaveBeenCalledWith('task-1', 'paused', expect.anything());
+ expect(updateContext).toHaveBeenCalledWith(
+ 'task-1',
+ expect.objectContaining({ scheduler: { consecutiveFailures: 2 } }),
+ );
+ });
+
+ it('LOBE-11389: scheduled run fails AT fuse β†’ pauses for human attention', async () => {
+ const task = baseTask({
+ automationMode: 'schedule',
+ context: { scheduler: { consecutiveFailures: 2 } } as any,
+ });
findById.mockResolvedValue(task);
await service.onTopicComplete({
errorMessage: 'boom',
operationId: 'op-1',
reason: 'error',
+ runTrigger: 'schedule',
taskId: 'task-1',
taskIdentifier: 'TASK-1',
topicId: 'topic-1',
});
- expect(updateStatus).toHaveBeenCalledWith('task-1', 'paused');
+ // 2 prior + this one = 3 = fuse β†’ pause.
+ expect(updateStatus).toHaveBeenCalledWith('task-1', 'paused', { error: 'boom' });
+ // Audit trail records the pause reason durably (LOBE-11390).
+ expect(updateContext).toHaveBeenCalledWith(
+ 'task-1',
+ expect.objectContaining({
+ lifecycle: expect.objectContaining({ lastPausedAt: expect.any(String) }),
+ scheduler: { consecutiveFailures: 3 },
+ }),
+ );
+ });
+
+ it('LOBE-11390: every error appends to the durable lifecycle audit trail', async () => {
+ const task = baseTask({
+ automationMode: 'schedule',
+ context: { lifecycle: { errorCount: 4 } } as any,
+ });
+ findById.mockResolvedValue(task);
+
+ await service.onTopicComplete({
+ errorMessage: 'boom',
+ operationId: 'op-1',
+ reason: 'error',
+ runTrigger: 'schedule',
+ taskId: 'task-1',
+ taskIdentifier: 'TASK-1',
+ topicId: 'topic-1',
+ });
+
+ expect(updateContext).toHaveBeenCalledWith(
+ 'task-1',
+ expect.objectContaining({
+ lifecycle: expect.objectContaining({
+ errorCount: 5,
+ lastError: expect.objectContaining({ message: 'boom', trigger: 'schedule' }),
+ }),
+ }),
+ );
+ });
+
+ it('every error branch still emits an urgent error brief', async () => {
+ const task = baseTask({ automationMode: 'schedule' });
+ findById.mockResolvedValue(task);
+
+ await service.onTopicComplete({
+ errorMessage: 'boom',
+ operationId: 'op-1',
+ reason: 'error',
+ runTrigger: 'manual',
+ taskId: 'task-1',
+ taskIdentifier: 'TASK-1',
+ topicId: 'topic-1',
+ });
+
+ expect(createBrief).toHaveBeenCalledWith(
+ expect.objectContaining({ priority: 'urgent', type: 'error' }),
+ );
+ });
+ });
+
+ describe('reason=done recovery audit (LOBE-11390)', () => {
+ it('successful automation tick after an error stamps lastRecoveredAt + resets fuse', async () => {
+ const task = baseTask({
+ automationMode: 'schedule',
+ context: { scheduler: { consecutiveFailures: 2 } } as any,
+ error: 'previous boom',
+ status: 'running',
+ });
+ findById.mockResolvedValue(task);
+
+ await service.onTopicComplete({
+ operationId: 'op-1',
+ reason: 'done',
+ runTrigger: 'schedule',
+ taskId: 'task-1',
+ taskIdentifier: 'TASK-1',
+ topicId: 'topic-1',
+ });
+
+ expect(updateContext).toHaveBeenCalledWith(
+ 'task-1',
+ expect.objectContaining({
+ lifecycle: expect.objectContaining({ lastRecoveredAt: expect.any(String) }),
+ scheduler: { consecutiveFailures: 0 },
+ }),
+ );
+ // Live error still cleared so the UI shows a clean current state.
+ expect(updateStatus).toHaveBeenCalledWith('task-1', 'scheduled', { error: null });
+ });
+
+ it('successful automation tick with no prior error does NOT write a recovery marker', async () => {
+ const task = baseTask({ automationMode: 'schedule', context: {} as any, error: null });
+ findById.mockResolvedValue(task);
+
+ await service.onTopicComplete({
+ operationId: 'op-1',
+ reason: 'done',
+ runTrigger: 'schedule',
+ taskId: 'task-1',
+ taskIdentifier: 'TASK-1',
+ topicId: 'topic-1',
+ });
+
+ expect(updateContext).not.toHaveBeenCalledWith(
+ 'task-1',
+ expect.objectContaining({ lifecycle: expect.anything() }),
+ );
});
});
});
diff --git a/apps/server/src/services/taskRunner/heartbeatTick.test.ts b/apps/server/src/services/taskRunner/heartbeatTick.test.ts
new file mode 100644
index 00000000000..e61b6a1004a
--- /dev/null
+++ b/apps/server/src/services/taskRunner/heartbeatTick.test.ts
@@ -0,0 +1,101 @@
+// @vitest-environment node
+import { TRPCError } from '@trpc/server';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { BriefModel } from '@/database/models/brief';
+
+import { runHeartbeatTick } from './heartbeatTick';
+import { TaskRunnerService } from './index';
+
+const { mockSelectTask, mockSetTaskSchedulerExecutionCallback } = vi.hoisted(() => ({
+ mockSelectTask: vi.fn(),
+ mockSetTaskSchedulerExecutionCallback: vi.fn(),
+}));
+
+vi.mock('@/database/server', () => ({
+ getServerDB: vi.fn().mockResolvedValue({
+ select: () => ({
+ from: () => ({
+ where: () => ({
+ limit: () => mockSelectTask(),
+ }),
+ }),
+ }),
+ }),
+}));
+
+vi.mock('@/database/models/brief', () => ({
+ BriefModel: vi.fn(),
+}));
+
+vi.mock('@/server/services/taskScheduler', () => ({
+ setTaskSchedulerExecutionCallback: mockSetTaskSchedulerExecutionCallback,
+}));
+
+vi.mock('./index', () => ({
+ TaskRunnerService: vi.fn(),
+}));
+
+describe('runHeartbeatTick', () => {
+ const taskId = 'task-1';
+ const userId = 'user-1';
+
+ const mockBriefModel = {
+ hasUnresolvedUrgentByTask: vi.fn().mockResolvedValue(false),
+ };
+ const mockRunner = {
+ runTask: vi.fn(),
+ };
+
+ const baseTask = (overrides: Partial<Record<string, unknown>> = {}) => ({
+ automationMode: 'heartbeat',
+ heartbeatInterval: 30,
+ id: taskId,
+ identifier: 'T-1',
+ status: 'scheduled',
+ ...overrides,
+ });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockSelectTask.mockResolvedValue([]);
+ mockBriefModel.hasUnresolvedUrgentByTask.mockResolvedValue(false);
+ (BriefModel as any).mockImplementation(() => mockBriefModel);
+ (TaskRunnerService as any).mockImplementation(() => mockRunner);
+ });
+
+ it('runs the task and excludes transient error briefs from tick gating', async () => {
+ mockSelectTask.mockResolvedValue([baseTask()]);
+ mockRunner.runTask.mockResolvedValue(undefined);
+
+ const outcome = await runHeartbeatTick(taskId, userId);
+
+ expect(outcome).toEqual({ ran: true, taskIdentifier: 'T-1' });
+ expect(mockBriefModel.hasUnresolvedUrgentByTask).toHaveBeenCalledWith(taskId, {
+ excludeTypes: ['error'],
+ });
+ expect(mockRunner.runTask).toHaveBeenCalledWith({ taskId, trigger: 'heartbeat' });
+ });
+
+ it('still skips when a non-error urgent brief requires human input', async () => {
+ mockSelectTask.mockResolvedValue([baseTask()]);
+ mockBriefModel.hasUnresolvedUrgentByTask.mockResolvedValue(true);
+
+ const outcome = await runHeartbeatTick(taskId, userId);
+
+ expect(outcome).toEqual({ ran: false, reason: 'human-waiting' });
+ expect(mockBriefModel.hasUnresolvedUrgentByTask).toHaveBeenCalledWith(taskId, {
+ excludeTypes: ['error'],
+ });
+ expect(mockRunner.runTask).not.toHaveBeenCalled();
+ });
+
+ it('returns in-flight when runTask raises a CONFLICT', async () => {
+ mockSelectTask.mockResolvedValue([baseTask()]);
+ mockRunner.runTask.mockRejectedValue(new TRPCError({ code: 'CONFLICT', message: 'busy' }));
+
+ const outcome = await runHeartbeatTick(taskId, userId);
+
+ expect(outcome).toEqual({ ran: false, reason: 'in-flight' });
+ });
+});
diff --git a/apps/server/src/services/taskRunner/heartbeatTick.ts b/apps/server/src/services/taskRunner/heartbeatTick.ts
index 81b9bbab31b..a4a20a25104 100644
--- a/apps/server/src/services/taskRunner/heartbeatTick.ts
+++ b/apps/server/src/services/taskRunner/heartbeatTick.ts
@@ -15,16 +15,10 @@ 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 };
+ { ran: true; taskIdentifier: string } | { ran: false; reason: HeartbeatTickSkipReason };
export type HeartbeatTickSkipReason =
- | 'human-waiting'
- | 'in-flight'
- | 'mode-changed'
- | 'no-interval'
- | 'not-found'
- | 'terminal';
+ 'human-waiting' | 'in-flight' | 'mode-changed' | 'no-interval' | 'not-found' | 'terminal';
/**
* Run a heartbeat tick β€” invoked by both the LocalScheduler `setTimeout`
@@ -66,14 +60,14 @@ export async function runHeartbeatTick(
const wsId = task.workspaceId ?? undefined;
const briefModel = new BriefModel(db, userId, wsId);
- if (await briefModel.hasUnresolvedUrgentByTask(taskId)) {
+ if (await briefModel.hasUnresolvedUrgentByTask(taskId, { excludeTypes: ['error'] })) {
log('skip task=%s reason=human-waiting', taskId);
return { ran: false, reason: 'human-waiting' };
}
const runner = new TaskRunnerService(db, userId, wsId);
try {
- await runner.runTask({ taskId });
+ await runner.runTask({ taskId, trigger: 'heartbeat' });
} 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,
diff --git a/apps/server/src/services/taskRunner/index.ts b/apps/server/src/services/taskRunner/index.ts
index 01b5f33cff8..372b209be4b 100644
--- a/apps/server/src/services/taskRunner/index.ts
+++ b/apps/server/src/services/taskRunner/index.ts
@@ -1,7 +1,7 @@
import { TaskIdentifier as TaskSkillIdentifier } from '@lobechat/builtin-skills';
import { BriefIdentifier } from '@lobechat/builtin-tool-brief';
import { INBOX_SESSION_ID } from '@lobechat/const';
-import type { ExecAgentResult, TaskItem } from '@lobechat/types';
+import type { ExecAgentResult, TaskItem, TaskRunTrigger } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import debug from 'debug';
@@ -22,6 +22,13 @@ export interface RunTaskParams {
continueTopicId?: string;
extraPrompt?: string;
taskId: string;
+ /**
+ * What triggered this run. Defaults to `'manual'` β€” the ad-hoc "run now"
+ * path (TRPC `task.run`, agent `runTask` tool). The scheduler ticks pass
+ * `'schedule'` / `'heartbeat'` so the lifecycle can tell an ad-hoc run apart
+ * from an automation tick (LOBE-11388/11391).
+ */
+ trigger?: TaskRunTrigger;
}
export interface RunTaskResult extends ExecAgentResult {
@@ -59,7 +66,7 @@ export class TaskRunnerService {
}
async runTask(params: RunTaskParams): Promise<RunTaskResult> {
- const { taskId: idOrIdentifier, continueTopicId, extraPrompt } = params;
+ const { taskId: idOrIdentifier, continueTopicId, extraPrompt, trigger = 'manual' } = params;
const task = await this.taskModel.resolve(idOrIdentifier);
if (!task) {
@@ -194,6 +201,7 @@ export class TaskRunnerService {
lastAssistantContent: event.lastAssistantContent,
operationId: event.operationId,
reason: event.reason || 'done',
+ runTrigger: trigger,
taskId,
taskIdentifier,
topicId: event.topicId,
@@ -202,7 +210,10 @@ export class TaskRunnerService {
id: 'task-on-complete',
type: 'onComplete' as const,
webhook: {
- body: { taskId, taskIdentifier, userId },
+ // `runTrigger` rides in the static body so the production webhook
+ // callback (which reconstructs onTopicComplete params server-side)
+ // knows whether this was a manual run or an automation tick.
+ body: { runTrigger: trigger, taskId, taskIdentifier, userId },
delivery: 'qstash' as const,
url: '/api/workflows/task/on-topic-complete',
},
@@ -228,6 +239,7 @@ export class TaskRunnerService {
await this.taskTopicModel.add(task.id, result.topicId, {
operationId: result.operationId,
seq: (task.totalTopics || 0) + 1,
+ trigger,
});
}
}
@@ -244,9 +256,18 @@ export class TaskRunnerService {
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',
- });
+ const errorText = error instanceof Error ? error.message : 'Unknown error';
+ // A failed kickoff must not kill an automation task's schedule: the
+ // scheduling state is not a per-run health signal. Restore the
+ // resting 'scheduled' state so the next tick still fires (this is
+ // the sync mirror of the async onTopicComplete error handling β€”
+ // LOBE-11388/11389). Non-automation (ad-hoc / dependency) tasks keep
+ // the legacy pause-for-attention behavior.
+ if (failedTask.automationMode) {
+ await this.taskModel.updateStatus(failedTask.id, 'scheduled', { error: errorText });
+ } else {
+ await this.taskModel.updateStatus(failedTask.id, 'paused', { error: errorText });
+ }
}
} catch {
// Rollback itself failed, ignore
diff --git a/apps/server/src/services/taskRunner/scheduleTick.test.ts b/apps/server/src/services/taskRunner/scheduleTick.test.ts
index 28e0c72ca1a..2cca560f0b9 100644
--- a/apps/server/src/services/taskRunner/scheduleTick.test.ts
+++ b/apps/server/src/services/taskRunner/scheduleTick.test.ts
@@ -111,8 +111,11 @@ describe('runScheduleTick', () => {
const outcome = await runScheduleTick(taskId, userId);
expect(outcome).toEqual({ ran: true, taskIdentifier: 'T-1' });
+ expect(mockBriefModel.hasUnresolvedUrgentByTask).toHaveBeenCalledWith(taskId, {
+ excludeTypes: ['error'],
+ });
expect(mockTaskTopicModel.countByTask).not.toHaveBeenCalled();
- expect(mockRunner.runTask).toHaveBeenCalledWith({ taskId });
+ expect(mockRunner.runTask).toHaveBeenCalledWith({ taskId, trigger: 'schedule' });
});
it('runs the task when the run count is still under maxExecutions', async () => {
@@ -123,10 +126,12 @@ describe('runScheduleTick', () => {
const outcome = await runScheduleTick(taskId, userId);
expect(outcome).toEqual({ ran: true, taskIdentifier: 'T-1' });
+ // Quota counts only scheduled ticks, not ad-hoc manual runs (LOBE-11391).
expect(mockTaskTopicModel.countByTask).toHaveBeenCalledWith(taskId, {
since: new Date('2026-05-01T00:00:00Z'),
+ triggers: ['schedule'],
});
- expect(mockRunner.runTask).toHaveBeenCalledWith({ taskId });
+ expect(mockRunner.runTask).toHaveBeenCalledWith({ taskId, trigger: 'schedule' });
expect(mockTaskModel.updateStatus).not.toHaveBeenCalled();
});
@@ -175,6 +180,9 @@ describe('runScheduleTick', () => {
const outcome = await runScheduleTick(taskId, userId);
expect(outcome).toEqual({ ran: false, reason: 'human-waiting' });
+ expect(mockBriefModel.hasUnresolvedUrgentByTask).toHaveBeenCalledWith(taskId, {
+ excludeTypes: ['error'],
+ });
expect(mockRunner.runTask).not.toHaveBeenCalled();
});
});
diff --git a/apps/server/src/services/taskRunner/scheduleTick.ts b/apps/server/src/services/taskRunner/scheduleTick.ts
index 1796fffdacd..288536e4cd5 100644
--- a/apps/server/src/services/taskRunner/scheduleTick.ts
+++ b/apps/server/src/services/taskRunner/scheduleTick.ts
@@ -16,8 +16,7 @@ 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 };
+ { ran: true; taskIdentifier: string } | { ran: false; reason: ScheduleTickSkipReason };
export type ScheduleTickSkipReason =
| 'human-waiting'
@@ -74,7 +73,7 @@ export async function runScheduleTick(
}
const briefModel = new BriefModel(db, userId, wsId);
- if (await briefModel.hasUnresolvedUrgentByTask(taskId)) {
+ if (await briefModel.hasUnresolvedUrgentByTask(taskId, { excludeTypes: ['error'] })) {
log('skip task=%s reason=human-waiting', taskId);
return { ran: false, reason: 'human-waiting' };
}
@@ -101,7 +100,12 @@ export async function runScheduleTick(
if (startedAtIso) {
const startedAt = new Date(startedAtIso);
const topicModel = new TaskTopicModel(db, userId, wsId);
- const runCount = await topicModel.countByTask(taskId, { since: startedAt });
+ // Only automation ticks count against the quota β€” ad-hoc manual runs must
+ // not consume scheduled executions (LOBE-11391).
+ const runCount = await topicModel.countByTask(taskId, {
+ since: startedAt,
+ triggers: ['schedule'],
+ });
if (runCount >= maxExecutions) {
log(
'skip task=%s reason=max-executions-reached (%d/%d) β€” marking completed',
@@ -118,7 +122,7 @@ export async function runScheduleTick(
const runner = new TaskRunnerService(db, userId, wsId);
try {
- await runner.runTask({ taskId });
+ await runner.runTask({ taskId, trigger: 'schedule' });
} catch (e) {
// Concurrent tick / manual run already running this task β€” graceful skip.
if (e instanceof TRPCError && e.code === 'CONFLICT') {
diff --git a/packages/database/src/models/__tests__/taskTopic.test.ts b/packages/database/src/models/__tests__/taskTopic.test.ts
index 49ecfb96885..163bfe0c62e 100644
--- a/packages/database/src/models/__tests__/taskTopic.test.ts
+++ b/packages/database/src/models/__tests__/taskTopic.test.ts
@@ -273,6 +273,29 @@ describe('TaskTopicModel', () => {
expect(await topicModel.countByTask(task2.id)).toBe(1);
});
+ it('only counts the requested triggers, excluding manual + legacy-null rows', async () => {
+ // LOBE-11391: the maxExecutions quota must count scheduled ticks only β€”
+ // manual "run now" invocations and legacy rows (null trigger) don't count.
+ const taskModel = new TaskModel(serverDB, userId);
+ const topicModel = new TaskTopicModel(serverDB, userId);
+ const task = await taskModel.create({ instruction: 'Test' });
+ await createTopic('tpc_sched');
+ await createTopic('tpc_manual');
+ await createTopic('tpc_legacy');
+
+ await topicModel.add(task.id, 'tpc_sched', { seq: 1, trigger: 'schedule' });
+ await topicModel.add(task.id, 'tpc_manual', { seq: 2, trigger: 'manual' });
+ await topicModel.add(task.id, 'tpc_legacy', { seq: 3 }); // no trigger β†’ null
+
+ // Unfiltered still counts everything.
+ expect(await topicModel.countByTask(task.id)).toBe(3);
+ // Scheduled-only counts just the one scheduled tick.
+ expect(await topicModel.countByTask(task.id, { triggers: ['schedule'] })).toBe(1);
+ expect(await topicModel.countByTask(task.id, { triggers: ['schedule', 'heartbeat'] })).toBe(
+ 1,
+ );
+ });
+
it('does not count topics owned by a different user', async () => {
const taskModel = new TaskModel(serverDB, userId);
const topicModel = new TaskTopicModel(serverDB, userId);
diff --git a/packages/database/src/models/taskTopic.ts b/packages/database/src/models/taskTopic.ts
index d4c8da39cf2..7585a24608e 100644
--- a/packages/database/src/models/taskTopic.ts
+++ b/packages/database/src/models/taskTopic.ts
@@ -63,7 +63,11 @@ export class TaskTopicModel {
async add(
taskId: string,
topicId: string,
- params: { operationId?: string; seq: number },
+ params: {
+ operationId?: string;
+ seq: number;
+ trigger?: 'manual' | 'schedule' | 'heartbeat';
+ },
): Promise<void> {
const visibility = await this.getTaskVisibility(taskId);
await this.db
@@ -73,6 +77,7 @@ export class TaskTopicModel {
seq: params.seq,
taskId,
topicId,
+ trigger: params.trigger,
userId: this.userId,
visibility,
workspaceId: this.workspaceId ?? null,
@@ -211,9 +216,22 @@ export class TaskTopicModel {
return result[0] || null;
}
- async countByTask(taskId: string, options?: { since?: Date }): Promise<number> {
+ /**
+ * Count a task's runs, optionally scoped by creation time and/or trigger
+ * source.
+ *
+ * `triggers` filters on the `trigger` column so the maxExecutions quota can
+ * count only automation ticks and ignore ad-hoc manual runs (LOBE-11391).
+ * Legacy rows have a NULL trigger; they are excluded whenever `triggers` is
+ * passed (they predate the column and can't be attributed to a schedule).
+ */
+ async countByTask(
+ taskId: string,
+ options?: { since?: Date; triggers?: Array<'manual' | 'schedule' | 'heartbeat'> },
+ ): Promise<number> {
const conditions = [eq(taskTopics.taskId, taskId), this.ownership()];
if (options?.since) conditions.push(gte(taskTopics.createdAt, options.since));
+ if (options?.triggers?.length) conditions.push(inArray(taskTopics.trigger, options.triggers));
const rows = await this.db
.select({ value: count() })
diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.ts
index 5ac0d387689..2fe99e91ad5 100644
--- a/packages/types/src/task/index.ts
+++ b/packages/types/src/task/index.ts
@@ -13,6 +13,19 @@ export type TaskActivityType = 'brief' | 'comment' | 'created' | 'topic';
// null = no automation
export type TaskAutomationMode = 'heartbeat' | 'schedule';
+/**
+ * What triggered a given task run. Threaded from the run entry point
+ * (`TaskRunnerService.runTask`) through to `onTopicComplete` so lifecycle
+ * decisions can tell an ad-hoc manual "run now" apart from an automation tick.
+ *
+ * - `manual` β€” user (or an agent tool call) invoked the run ad-hoc. Its
+ * failure is a one-off signal and must NOT change the task's
+ * scheduling state, nor count against the maxExecutions quota.
+ * - `schedule` β€” a cron `schedule` tick fired the run.
+ * - `heartbeat` β€” a heartbeat interval tick fired the run.
+ */
+export type TaskRunTrigger = 'manual' | 'schedule' | 'heartbeat';
+
// ── Config types ──
export interface CheckpointConfig {
@@ -126,9 +139,10 @@ export interface TaskTopicHandoff {
// ── 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.
+ // Count of consecutive automation-tick 'error' reasons since the last 'done'.
+ // When it hits the fuse threshold (currently 3) we pause the task / stop
+ // re-arming until the user resolves the urgent brief. Manual "run now"
+ // failures do NOT touch this counter.
consecutiveFailures?: number;
// ISO timestamp when the latest tick was scheduled. Informational only.
scheduledAt?: string;
@@ -137,6 +151,31 @@ export interface TaskSchedulerContext {
tickMessageId?: string;
}
+/**
+ * Durable lifecycle audit trail for a task, stored under
+ * `tasks.context.lifecycle`. Unlike the live `tasks.error` column β€” which is
+ * cleared on the next successful run so the UI only shows the *current* error β€”
+ * this pocket is append-style history that a later success does NOT wipe. It
+ * exists so "the morning check silently didn't fire" is diagnosable after the
+ * fact instead of being masked by a later manual success (LOBE-11390).
+ */
+export interface TaskLifecycleAudit {
+ // Monotonic lifetime count of failed runs (never reset on success).
+ errorCount?: number;
+ // The most recent failure, retained even after a later success clears the
+ // live `error` column.
+ lastError?: {
+ at: string;
+ message: string;
+ trigger?: TaskRunTrigger;
+ };
+ lastPausedAt?: string;
+ // When the task was last auto-paused by the failure fuse, and why.
+ lastPauseReason?: string;
+ // When a successful run last cleared a prior error state (recovery marker).
+ lastRecoveredAt?: string;
+}
+
// Pointer back to the agent conversation that spawned this task via the
// `createTask` tool. Captured at creation so the task lifecycle can deliver the
// handoff result back to that session once the task completes.
@@ -157,6 +196,7 @@ export interface TaskOriginContext {
}
export interface TaskContext {
+ lifecycle?: TaskLifecycleAudit;
origin?: TaskOriginContext;
scheduler?: TaskSchedulerContext;
}
diff --git a/src/components/InvalidAPIKey/__tests__/ComfyUIForm.test.tsx b/src/components/InvalidAPIKey/__tests__/ComfyUIForm.test.tsx
deleted file mode 100644
index 4266a7bd862..00000000000
--- a/src/components/InvalidAPIKey/__tests__/ComfyUIForm.test.tsx
+++ /dev/null
@@ -1,138 +0,0 @@
-import type * as AntdStyleModule from 'antd-style';
-import { ModelProvider } from 'model-bank';
-import { describe, expect, it, vi } from 'vitest';
-
-import APIKeyForm from '../index';
-
-// Mock the dependencies
-vi.mock('@/store/aiInfra', () => ({
- useAiInfraStore: vi.fn(() => ({
- updateAiProviderConfig: vi.fn(),
- useFetchAiProviderRuntimeState: vi.fn(() => ({})),
- aiProviderRuntimeConfig: {},
- })),
-}));
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
-vi.mock('antd-style', async (importOriginal) => {
- const actual = await importOriginal<typeof AntdStyleModule>();
-
- return {
- ...actual,
- createStaticStyles: vi.fn((fn: any) =>
- fn({
- css: () => '',
- cssVar: {},
- cx: (...args: any[]) => args.filter(Boolean).join(' '),
- }),
- ),
- useTheme: () => ({
- colorTextSecondary: '#999',
- }),
- };
-});
-
-vi.mock('@/components/FormInput', () => ({
- FormInput: vi.fn(({ value, onChange, ...props }) => (
- <input
- data-testid="form-input"
- value={value}
- onChange={(e) => onChange?.(e.target.value)}
- {...props}
- />
- )),
- FormPassword: vi.fn(({ value, onChange, ...props }) => (
- <input
- data-testid="form-password"
- type="password"
- value={value}
- onChange={(e) => onChange?.(e.target.value)}
- {...props}
- />
- )),
-}));
-
-vi.mock('@/components/KeyValueEditor', () => ({
- default: vi.fn(() => <div data-testid="key-value-editor">Key-Value Editor</div>),
-}));
-
-vi.mock('@lobehub/icons', () => ({
- ComfyUI: {
- Combine: vi.fn(() => <div data-testid="comfyui-icon">ComfyUI Icon</div>),
- },
- ProviderIcon: vi.fn(() => <div data-testid="provider-icon">Provider Icon</div>),
-}));
-
-vi.mock('@lobehub/ui', () => ({
- ShikiLobeTheme: { name: 'lobe-test', type: 'dark' as const, colors: {} },
- Icon: vi.fn(({ icon, ...props }) => (
- <div data-testid="icon" {...props}>
- {icon?.name}
- </div>
- )),
- Select: vi.fn(({ value, options, onChange, ...props }) => (
- <select
- data-testid="select"
- value={value}
- onChange={(e) => onChange?.(e.target.value)}
- {...props}
- >
- {options?.map((option: any) => (
- <option key={option.value} value={option.value}>
- {option.label}
- </option>
- ))}
- </select>
- )),
- Button: vi.fn(({ children, onClick, ...props }) => (
- <button data-testid="button" onClick={onClick} {...props}>
- {children}
- </button>
- )),
- ProviderIcon: vi.fn(() => <div data-testid="provider-icon">Provider Icon</div>),
- Center: vi.fn(({ children, ...props }) => (
- <div data-testid="center" {...props}>
- {children}
- </div>
- )),
- Flexbox: vi.fn(({ children, ...props }) => (
- <div data-testid="flexbox" {...props}>
- {children}
- </div>
- )),
-}));
-
-vi.mock('@/features/ChatList/Error/style', () => ({
- FormAction: vi.fn(({ children, title, description, avatar, ...props }) => (
- <div data-testid="form-action" {...props}>
- <div data-testid="avatar">{avatar}</div>
- <div data-testid="title">{title}</div>
- <div data-testid="description">{description}</div>
- {children}
- </div>
- )),
- ErrorActionContainer: vi.fn(({ children, ...props }) => (
- <div data-testid="error-action-container" {...props}>
- {children}
- </div>
- )),
-}));
-
-describe('ComfyUIForm Integration', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it('should use ComfyUI provider correctly', () => {
- expect(ModelProvider.ComfyUI).toBe('comfyui');
- });
-
- it('should import APIKeyForm without errors', () => {
- expect(APIKeyForm).toBeDefined();
- });
-});
diff --git a/src/server/workflows-hono/task/handlers/onTopicComplete.ts b/src/server/workflows-hono/task/handlers/onTopicComplete.ts
index 9e2304cb8e9..5ad18f168cf 100644
--- a/src/server/workflows-hono/task/handlers/onTopicComplete.ts
+++ b/src/server/workflows-hono/task/handlers/onTopicComplete.ts
@@ -1,3 +1,4 @@
+import type { TaskRunTrigger } from '@lobechat/types';
import debug from 'debug';
import { and, eq } from 'drizzle-orm';
import type { Context } from 'hono';
@@ -15,6 +16,8 @@ export interface OnTopicCompletePayload {
lastAssistantContent?: string;
operationId: string;
reason?: string;
+ // Static body field set by TaskRunnerService β€” what triggered the run.
+ runTrigger?: TaskRunTrigger;
taskId: string;
taskIdentifier: string;
topicId?: string;
@@ -29,6 +32,7 @@ export async function onTopicComplete(c: Context) {
lastAssistantContent,
operationId,
reason,
+ runTrigger,
taskId,
taskIdentifier,
topicId,
@@ -63,6 +67,7 @@ export async function onTopicComplete(c: Context) {
lastAssistantContent,
operationId,
reason: reason || 'done',
+ runTrigger,
taskId,
taskIdentifier,
topicId,