π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(task): settle a leftover running run instead of refusing runTask (#23431)
AmAzing-5cd61e1b9d64
diff --git a/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.tsindex 20f53a231ba..69b6c16acd0 100644--- a/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts+++ b/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts@@ -812,37 +812,6 @@ describe('Task Router Integration', () => {});});- describe('run idempotency', () => {- it('resolves a task identifier to its row when starting a run', async () => {- const task = await caller.create(taskInput(testAgentId));-- await caller.run({ id: task.data.identifier });-- const updated = await caller.detail({ id: task.data.id });- expect(updated.data?.status).toBe('running');- });-- it('should reject run when a topic is already running', async () => {- const task = await caller.create(taskInput(testAgentId));-- // First run succeeds- await caller.run({ id: task.data.id });-- // Second run should fail with CONFLICT- await expect(caller.run({ id: task.data.id })).rejects.toThrow(/already has a running topic/);- });-- it('should reject continue on already running topic', async () => {- const task = await caller.create(taskInput(testAgentId));-- await caller.run({ id: task.data.id });-- await expect(caller.run({ continueTopicId: 'tpc_test', id: task.data.id })).rejects.toThrow(- /already running/,- );- });- });-describe('usage', () => {it('aggregates the task topic usage', async () => {const task = await caller.create({ instruction: 'Measure this task' });diff --git a/apps/server/src/routers/lambda/__tests__/integration/task.run.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/task.run.integration.test.tsnew file mode 100644index 00000000000..ef7c66eb199--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/integration/task.run.integration.test.ts@@ -0,0 +1,197 @@+// @vitest-environment node+import { type LobeChatDatabase } from '@lobechat/database';+import { getTestDB } from '@lobechat/database/test-utils';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { TaskTopicModel } from '@/database/models/taskTopic';++import { taskRouter } from '../../task';+import {+ cleanupTestUser,+ createTestAgent,+ createTestContext,+ createTestTopic,+ createTestUser,+} from './setup';++const taskInput = (+ agentId: string,+): Parameters<ReturnType<typeof taskRouter.createCaller>['create']>[0] => ({+ assigneeAgentId: agentId,+ instruction: 'Test',+});++let testDB: LobeChatDatabase;+vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return testDB;+ }),+}));++const mockExecAgent = vi.fn();+vi.mock('@/server/services/aiAgent', () => ({+ AiAgentService: vi.fn().mockImplementation(function () {+ return {+ execAgent: mockExecAgent,+ interruptTask: vi.fn().mockResolvedValue({ success: true }),+ };+ }),+}));++vi.mock('@/server/services/taskLifecycle', () => ({+ TaskLifecycleService: vi.fn().mockImplementation(function () {+ return { onTopicComplete: vi.fn() };+ }),+}));++vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeFromDB: vi.fn(),+}));++describe('Task Router run', () => {+ let serverDB: LobeChatDatabase;+ let userId: string;+ let testAgentId: string;+ let testTopicId: string;+ let caller: ReturnType<typeof taskRouter.createCaller>;++ beforeEach(async () => {+ vi.clearAllMocks();+ serverDB = await getTestDB();+ testDB = serverDB;+ userId = await createTestUser(serverDB);+ testAgentId = await createTestAgent(serverDB, userId, 'agt_test');+ testTopicId = await createTestTopic(serverDB, userId, 'tpc_test');+ mockExecAgent.mockResolvedValue({+ operationId: 'op_test',+ success: true,+ topicId: testTopicId,+ });+ caller = taskRouter.createCaller(createTestContext(userId));+ });++ afterEach(async () => {+ await cleanupTestUser(serverDB, userId);+ });++ describe('run idempotency', () => {+ it('resolves a task identifier to its row when starting a run', async () => {+ const task = await caller.create(taskInput(testAgentId));++ await caller.run({ id: task.data.identifier });++ const updated = await caller.detail({ id: task.data.id });+ expect(updated.data?.status).toBe('running');+ });++ it('should reject run when a topic is already running', async () => {+ const task = await caller.create(taskInput(testAgentId));++ // First run succeeds+ await caller.run({ id: task.data.id });++ // Second run should fail with CONFLICT+ await expect(caller.run({ id: task.data.id })).rejects.toThrow(/already has a running topic/);+ });++ it('should reject continue on already running topic', async () => {+ const task = await caller.create(taskInput(testAgentId));++ await caller.run({ id: task.data.id });++ await expect(caller.run({ continueTopicId: 'tpc_test', id: task.data.id })).rejects.toThrow(+ /already running/,+ );+ });++ describe('a running topic left behind by an ended operation', () => {+ const SIX_HOURS_AGO = () => new Date(Date.now() - 6 * 60 * 60 * 1000);++ /** A scheduled task at rest whose earlier run row still reads `running`. */+ const seedBlockedScheduledTask = async (operation: {+ completedAt?: Date | null;+ status: 'done' | 'running';+ updatedAt: Date;+ }) => {+ const { agentOperations, tasks } = await import('@/database/schemas');+ const { eq } = await import('drizzle-orm');+ const task = await caller.create(taskInput(testAgentId));+ const topicId = await createTestTopic(serverDB, userId);+ const operationId = `op_${topicId}`;+ await serverDB.insert(agentOperations).values({+ completedAt: operation.completedAt ?? null,+ id: operationId,+ status: operation.status,+ topicId,+ updatedAt: operation.updatedAt,+ userId,+ });+ await new TaskTopicModel(serverDB, userId).add(task.data.id, topicId, {+ operationId,+ seq: 1,+ trigger: 'schedule',+ });+ // Back at rest between ticks: no reconciliation sweep looks at this row.+ await serverDB.update(tasks).set({ status: 'scheduled' }).where(eq(tasks.id, task.data.id));+ return { operationId, taskId: task.data.id, topicId };+ };++ afterEach(async () => {+ const { agentOperations } = await import('@/database/schemas');+ const { eq } = await import('drizzle-orm');+ await serverDB.delete(agentOperations).where(eq(agentOperations.userId, userId));+ });++ it('settles the leftover run and starts the new one', async () => {+ const ended = SIX_HOURS_AGO();+ const { taskId, topicId } = await seedBlockedScheduledTask({+ completedAt: ended,+ status: 'done',+ updatedAt: ended,+ });++ await caller.run({ id: taskId });++ const runs = await new TaskTopicModel(serverDB, userId).findByTaskId(taskId);+ expect(runs.map((run) => [run.topicId, run.status]).sort()).toEqual(+ [+ [testTopicId, 'running'],+ [topicId, 'completed'],+ ].sort(),+ );+ expect(mockExecAgent).toHaveBeenCalledTimes(1);+ });++ it('lets the leftover topic itself be continued', async () => {+ const ended = SIX_HOURS_AGO();+ const { taskId, topicId } = await seedBlockedScheduledTask({+ completedAt: ended,+ status: 'done',+ updatedAt: ended,+ });++ await caller.run({ continueTopicId: topicId, id: taskId });++ expect(mockExecAgent).toHaveBeenCalledWith(+ expect.objectContaining({ appContext: expect.objectContaining({ topicId }) }),+ );+ });++ it('still refuses a run that is live, naming its operation and state', async () => {+ const { operationId, taskId, topicId } = await seedBlockedScheduledTask({+ status: 'running',+ updatedAt: new Date(),+ });++ await expect(caller.run({ id: taskId })).rejects.toThrow(+ new RegExp(+ `running topic \\(${topicId}\\): operation ${operationId} is running .*lh task topic cancel ${topicId}`,+ ),+ );+ expect(mockExecAgent).not.toHaveBeenCalled();+ const [run] = await new TaskTopicModel(serverDB, userId).findByTaskId(taskId);+ expect(run.status).toBe('running');+ });+ });+ });+});diff --git a/apps/server/src/services/taskLifecycle/reconcile.test.ts b/apps/server/src/services/taskLifecycle/reconcile.test.tsindex 639b3e97245..eb950510450 100644--- a/apps/server/src/services/taskLifecycle/reconcile.test.ts+++ b/apps/server/src/services/taskLifecycle/reconcile.test.ts@@ -12,6 +12,7 @@ import { isRunAlreadySettled, ORPHANED_RUN_GRACE_MS, reconcileOrphanedTaskRuns }const {findOrphanedRunningTopics,findRunByTopicId,+ findRunningByTaskIds,findTaskById,claimRun,onTopicComplete,@@ -19,6 +20,7 @@ const {} = vi.hoisted(() => ({findOrphanedRunningTopics: vi.fn(),findRunByTopicId: vi.fn(),+ findRunningByTaskIds: vi.fn(),findTaskById: vi.fn(),claimRun: vi.fn(),onTopicComplete: vi.fn(),@@ -38,7 +40,7 @@ vi.mock('@/database/models/task', () => ({vi.mock('@/database/models/taskTopic', () => ({TaskTopicModel: vi.fn(function () {- return { findByTopicId: findRunByTopicId };+ return { findByTopicId: findRunByTopicId, findRunningByTaskIds };}),}));@@ -242,6 +244,7 @@ describe('isRunAlreadySettled', () => {claimRun.mockReset().mockResolvedValue(true);onTopicComplete.mockReset().mockResolvedValue(undefined);findRunByTopicId.mockReset();+ findRunningByTaskIds.mockReset().mockResolvedValue([]);findTaskById.mockReset();});@@ -309,6 +312,40 @@ describe('isRunAlreadySettled', () => {expect(await isRunAlreadySettled(db, 'user-1', undefined, { ...callback, reason: 'interrupted' }),).toBe(false);- expect(findRunByTopicId).not.toHaveBeenCalled();+ });++ it.each(['done', 'error', 'interrupted'])(+ 'fences a late %s delivery once the Task has started its next run',+ async (reason) => {+ // The runner settled this leftover run and started a new one; the old+ // run's delayed delivery must not move the Task under the live run.+ findRunByTopicId.mockResolvedValue({+ operationId: 'op-1',+ status: 'completed',+ taskId: 'task-1',+ topicId: 'tpc-1',+ });+ findRunningByTaskIds.mockResolvedValue([+ { operationId: 'op-2', status: 'running', taskId: 'task-1', topicId: 'tpc-2' },+ ]);+ findTaskById.mockResolvedValue({ id: 'task-1', status: 'running' });++ expect(await isRunAlreadySettled(db, 'user-1', undefined, { ...callback, reason })).toBe(+ true,+ );+ },+ );++ it('lets a delivery through while its own run is the one still running', async () => {+ const run = { operationId: 'op-1', status: 'running', taskId: 'task-1', topicId: 'tpc-1' };+ findRunByTopicId.mockResolvedValue(run);+ findRunningByTaskIds.mockResolvedValue([+ run,+ { operationId: 'op-2', status: 'running', taskId: 'task-1', topicId: 'tpc-2' },+ ]);++ expect(+ await isRunAlreadySettled(db, 'user-1', undefined, { ...callback, reason: 'done' }),+ ).toBe(false);});});diff --git a/apps/server/src/services/taskLifecycle/reconcile.ts b/apps/server/src/services/taskLifecycle/reconcile.tsindex 5782bbc888c..f91b3155484 100644--- a/apps/server/src/services/taskLifecycle/reconcile.ts+++ b/apps/server/src/services/taskLifecycle/reconcile.ts@@ -193,8 +193,13 @@ const handBackClaimedRun = async (* `LEASE_EXPIRED_ERROR` is the existing vocabulary for exactly that. Settling it* as an unrecoverable failure instead would open a decision gate for work that* only needs another attempt.+ *+ * The runner reuses it for a leftover run that blocks a new one (see+ * `taskRunner/runConflict`), so both paths classify a dead run the same way.*/-const resolveOrphanedRunError = (row: OrphanedRunningTopic): string => {+export const resolveOrphanedRunError = (+ row: Pick<OrphanedRunningTopic, 'completionReason' | 'operationError' | 'operationStatus'>,+): string => {// `agent_operations.error` holds the raw `state.error`, so the message can sit// nested β a provider failure is `{ errorType, error: { message } }`. Read it// the way the completion hook does, or a real quota / provider failure would@@ -241,8 +246,11 @@ export interface SettledRunQuery {* Task still `running` is a settle that broke midway, and is let through so the* retry can finish it.*- * Only failures are fenced β the sweep never settles a successful or interrupted- * run, so those deliveries keep their existing behaviour.+ * Any outcome is fenced once the Task has started its next run: the runner+ * settles a leftover run of any outcome before starting a new one (see+ * `taskRunner/runConflict`), and a delivery for it that lands afterwards would+ * pause, reschedule or complete the Task under that live run. Otherwise only+ * failures are fenced β the sweep never settles a successful or interrupted run.*/export const isRunAlreadySettled = async (db: LobeChatDatabase,@@ -250,12 +258,18 @@ export const isRunAlreadySettled = async (workspaceId: string | undefined,{ operationId, reason, taskId, topicId }: SettledRunQuery,): Promise<boolean> => {- if (reason !== 'error' || !topicId) return false;+ if (!topicId) return false;- const run = await new TaskTopicModel(db, userId, workspaceId).findByTopicId(topicId);+ const taskTopicModel = new TaskTopicModel(db, userId, workspaceId);+ const run = await taskTopicModel.findByTopicId(topicId);if (!run || run.taskId !== taskId || run.operationId !== operationId) return false;if (run.status === 'running') return false;+ const running = await taskTopicModel.findRunningByTaskIds([taskId]);+ if (running.some((row) => row.topicId !== topicId)) return true;++ if (reason !== 'error') return false;+const task = await new TaskModel(db, userId, workspaceId).findById(taskId);return !!task && task.status !== 'running';};diff --git a/apps/server/src/services/taskRunner/index.ts b/apps/server/src/services/taskRunner/index.tsindex 5516cb26842..7730fe38c2f 100644--- a/apps/server/src/services/taskRunner/index.ts+++ b/apps/server/src/services/taskRunner/index.ts@@ -30,6 +30,7 @@ import {resolveTaskRunExecution,resolveTopicExecutionPatch,} from './resolveRunExecution';+import { clearBlockingRun } from './runConflict';const log = debug('task-runner');@@ -222,22 +223,17 @@ export class TaskRunnerService {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.`,- });- }+ // A `running` row may be a leftover whose operation ended long ago; those+ // are settled here, and a real concurrent run is refused with its state.+ const blockingRuns = existingTopics.filter(+ (t) => t.status === 'running' && (!continueTopicId || t.topicId === continueTopicId),+ );+ for (const row of blockingRuns) {+ await clearBlockingRun(+ { db: this.db, userId: this.userId, workspaceId: this.workspaceId },+ row,+ { continuing: !!continueTopicId },+ );}// Auto-detect and clean up timed-out topicsdiff --git a/apps/server/src/services/taskRunner/runConflict.test.ts b/apps/server/src/services/taskRunner/runConflict.test.tsnew file mode 100644index 00000000000..5d60b0ad38f--- /dev/null+++ b/apps/server/src/services/taskRunner/runConflict.test.ts@@ -0,0 +1,221 @@+import { TRANSIENT_FAILED_RUN_STATUS } from '@lobechat/const/goal';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { ORPHANED_RUN_GRACE_MS } from '@/server/services/taskLifecycle/reconcile';++import { clearBlockingRun } from './runConflict';++const mocks = vi.hoisted(() => ({+ claim: vi.fn(),+ findById: vi.fn(),+ findByTopicId: vi.fn(),+ findLiveByTopic: vi.fn(),+}));++vi.mock('@/database/models/agentOperation', () => ({+ AgentOperationModel: vi.fn().mockImplementation(function () {+ return { findById: mocks.findById, findLiveByTopic: mocks.findLiveByTopic };+ }),+}));+vi.mock('@/database/models/taskTopic', () => ({+ TaskTopicModel: vi.fn().mockImplementation(function () {+ return { findByTopicId: mocks.findByTopicId };+ }),+}));+vi.mock('@/database/repositories/taskRunClaim', () => ({+ TaskRunClaimRepo: vi.fn().mockImplementation(function () {+ return { claim: mocks.claim };+ }),+}));+vi.mock('@/server/services/taskLifecycle', () => ({ TaskLifecycleService: vi.fn() }));++const NOW = Date.parse('2026-11-18T02:00:00.000Z');+const LONG_AGO = new Date(NOW - 6 * 60 * 60 * 1000);+const JUST_NOW = new Date(NOW - 60 * 1000);++const ctx = { db: {} as any, userId: 'user-1', workspaceId: 'ws-1' };++const row = (overrides: Record<string, unknown> = {}) =>+ ({+ operationId: 'op_old',+ status: 'running',+ taskId: 'task-1',+ topicId: 'tpc_stale',+ ...overrides,+ }) as any;++const operation = (overrides: Record<string, unknown> = {}) => ({+ completedAt: LONG_AGO,+ completionReason: 'done',+ error: null,+ id: 'op_old',+ status: 'done',+ updatedAt: LONG_AGO,+ ...overrides,+});++describe('clearBlockingRun', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.findLiveByTopic.mockResolvedValue([]);+ mocks.claim.mockResolvedValue(true);+ });++ describe('leftover runs', () => {+ it('settles a run whose operation finished hours ago, so the new run can start', async () => {+ mocks.findById.mockResolvedValue(operation());++ await expect(+ clearBlockingRun(ctx, row(), { continuing: false, now: NOW }),+ ).resolves.toBeUndefined();++ expect(mocks.claim).toHaveBeenCalledWith('tpc_stale', 'op_old', 'completed');+ });++ it('settles an interrupted run the way a Stop would', async () => {+ mocks.findById.mockResolvedValue(+ operation({ completionReason: 'interrupted', status: 'interrupted' }),+ );++ await clearBlockingRun(ctx, row(), { continuing: true, now: NOW });++ expect(mocks.claim).toHaveBeenCalledWith('tpc_stale', 'op_old', 'canceled');+ });++ it('settles an abandoned run with no recorded error as failed, like the sweep', async () => {+ mocks.findById.mockResolvedValue(+ operation({ completionReason: 'lease_expired', status: 'abandoned' }),+ );++ await clearBlockingRun(ctx, row(), { continuing: false, now: NOW });++ expect(mocks.claim).toHaveBeenCalledWith('tpc_stale', 'op_old', 'failed');+ });++ it('keeps a transient provider failure retryable', async () => {+ mocks.findById.mockResolvedValue(+ operation({+ completionReason: 'error',+ error: { message: 'fetch failed' },+ status: 'error',+ }),+ );++ await clearBlockingRun(ctx, row(), { continuing: false, now: NOW });++ expect(mocks.claim).toHaveBeenCalledWith('tpc_stale', 'op_old', TRANSIENT_FAILED_RUN_STATUS);+ });++ it('settles a run that recorded a plain failure as failed', async () => {+ mocks.findById.mockResolvedValue(+ operation({+ completionReason: 'error',+ error: { message: 'Tool call failed: invalid arguments' },+ status: 'error',+ }),+ );++ await clearBlockingRun(ctx, row(), { continuing: false, now: NOW });++ expect(mocks.claim).toHaveBeenCalledWith('tpc_stale', 'op_old', 'failed');+ });++ it('goes ahead when another writer settled the row first', async () => {+ mocks.findById.mockResolvedValue(operation());+ mocks.claim.mockResolvedValue(false);+ mocks.findByTopicId.mockResolvedValue(row({ status: 'completed' }));++ await expect(+ clearBlockingRun(ctx, row(), { continuing: false, now: NOW }),+ ).resolves.toBeUndefined();+ });++ it('refuses when a newer run took the row over in the meantime', async () => {+ mocks.findById+ .mockResolvedValueOnce(operation())+ .mockResolvedValueOnce(+ operation({ completedAt: null, id: 'op_new', status: 'running', updatedAt: JUST_NOW }),+ );+ mocks.claim.mockResolvedValue(false);+ mocks.findByTopicId.mockResolvedValue(row({ operationId: 'op_new' }));++ await expect(+ clearBlockingRun(ctx, row(), { continuing: false, now: NOW }),+ ).rejects.toMatchObject({+ code: 'CONFLICT',+ message: expect.stringContaining('operation op_new is running'),+ });+ });+ });++ describe('real conflicts', () => {+ it('names the live operation, its status and how to stop it', async () => {+ mocks.findById.mockResolvedValue(+ operation({ completedAt: null, status: 'waiting_for_client', updatedAt: JUST_NOW }),+ );++ const error = await clearBlockingRun(ctx, row(), { continuing: false, now: NOW }).catch(+ (e) => e,+ );++ expect(error).toMatchObject({ code: 'CONFLICT' });+ expect(error.message).toBe(+ `Task already has a running topic (tpc_stale): operation op_old is waiting_for_client (last update ${JUST_NOW.toISOString()}). Wait for it to finish, or stop it first with \`lh task topic cancel tpc_stale\` (this pauses the task; resume it afterwards).`,+ );+ expect(mocks.claim).not.toHaveBeenCalled();+ });++ it('treats a topic with another operation in flight as live', async () => {+ mocks.findById.mockResolvedValue(operation());+ mocks.findLiveByTopic.mockResolvedValue([+ operation({ completedAt: null, id: 'op_followup', status: 'running', updatedAt: JUST_NOW }),+ ]);++ await expect(+ clearBlockingRun(ctx, row(), { continuing: true, now: NOW }),+ ).rejects.toMatchObject({+ code: 'CONFLICT',+ message: expect.stringMatching(+ /^Topic tpc_stale is already running: operation op_followup is running/,+ ),+ });+ expect(mocks.claim).not.toHaveBeenCalled();+ });++ it('leaves a run that just ended to its own completion hook', async () => {+ mocks.findById.mockResolvedValue(operation({ completedAt: JUST_NOW, status: 'error' }));++ const error = await clearBlockingRun(ctx, row(), { continuing: false, now: NOW }).catch(+ (e) => e,+ );++ expect(error).toMatchObject({ code: 'CONFLICT' });+ expect(error.message).toContain(+ `ended (error) at ${JUST_NOW.toISOString()} and its result is still being recorded`,+ );+ expect(error.message).toContain(+ `Retry after ${new Date(JUST_NOW.getTime() + ORPHANED_RUN_GRACE_MS).toISOString()}`,+ );+ expect(mocks.claim).not.toHaveBeenCalled();+ });++ it('does not guess when the operation cannot be found', async () => {+ mocks.findById.mockResolvedValue(undefined);++ await expect(+ clearBlockingRun(ctx, row(), { continuing: false, now: NOW }),+ ).rejects.toMatchObject({+ code: 'CONFLICT',+ message: expect.stringContaining('no operation can be found for it'),+ });+ expect(mocks.claim).not.toHaveBeenCalled();+ });++ it('does not guess when the row names no operation', async () => {+ await expect(+ clearBlockingRun(ctx, row({ operationId: null }), { continuing: false, now: NOW }),+ ).rejects.toMatchObject({ code: 'CONFLICT' });+ expect(mocks.findById).not.toHaveBeenCalled();+ });+ });+});diff --git a/apps/server/src/services/taskRunner/runConflict.ts b/apps/server/src/services/taskRunner/runConflict.tsnew file mode 100644index 00000000000..1c4be0afc6a--- /dev/null+++ b/apps/server/src/services/taskRunner/runConflict.ts@@ -0,0 +1,200 @@+import type { AgentOperationStatus } from '@lobechat/types';+import { isAgentOperationInFlight, isAgentOperationSettled } from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import debug from 'debug';++import { AgentOperationModel } from '@/database/models/agentOperation';+import { TaskTopicModel } from '@/database/models/taskTopic';+import { TaskRunClaimRepo } from '@/database/repositories/taskRunClaim';+import type { LobeChatDatabase } from '@/database/type';+import { resolveFailedRunStatus } from '@/server/services/goal/recoveryPolicy';+import {+ ORPHANED_RUN_GRACE_MS,+ resolveOrphanedRunError,+} from '@/server/services/taskLifecycle/reconcile';++const log = debug('task-runner:run-conflict');++/** The run-row fields this check reads. */+interface BlockingRunRow {+ operationId: string | null;+ topicId: string | null;+}++type OperationRecord = NonNullable<Awaited<ReturnType<AgentOperationModel['findById']>>>;++/**+ * What a `running` run row that stands in the way of a new run really is.+ *+ * The row's status is only what the Task side last wrote. Its operation's+ * terminal state reaches the row through a fire-and-forget completion hook, and+ * the reconciliation sweeps only repair rows under a Task that is still+ * `running`, and only for some operation outcomes. A scheduled Task that went+ * back to `scheduled` keeps a dead row forever: every tick skips it as+ * in-flight and every manual run is refused.+ */+type BlockingRun =+ /** An operation on the topic has not settled: a real concurrent run. */+ | { kind: 'live'; operationId: string; since: Date; status: AgentOperationStatus }+ /** The run ended a moment ago and its completion hook may still land. */+ | { kind: 'settling'; endedAt: Date; operationId: string; status: AgentOperationStatus }+ /** The run ended long ago and nothing on the topic is in flight. */+ | { kind: 'stale'; operation: OperationRecord }+ /** No operation to judge the row against; leave the call to a person. */+ | { kind: 'unknown' };++interface RunConflictContext {+ db: LobeChatDatabase;+ userId: string;+ workspaceId?: string;+}++const endedAt = (operation: OperationRecord): Date =>+ new Date(operation.completedAt ?? operation.updatedAt);++const inspectBlockingRun = async (+ ctx: RunConflictContext,+ row: BlockingRunRow,+ now: number,+): Promise<BlockingRun> => {+ if (!row.operationId || !row.topicId) return { kind: 'unknown' };++ const operationModel = new AgentOperationModel(ctx.db, ctx.userId, ctx.workspaceId);+ const operation = await operationModel.findById(row.operationId);+ if (!operation) return { kind: 'unknown' };++ if (isAgentOperationInFlight(operation.status)) {+ return {+ kind: 'live',+ operationId: operation.id,+ since: new Date(operation.updatedAt),+ status: operation.status,+ };+ }++ // A follow-up started in the run's conversation may not own the row yet; a+ // topic with anything still in flight is a run that is still going.+ const [liveOnTopic] = await operationModel.findLiveByTopic(row.topicId);+ if (liveOnTopic) {+ return {+ kind: 'live',+ operationId: liveOnTopic.id,+ since: new Date(liveOnTopic.updatedAt),+ status: liveOnTopic.status,+ };+ }++ if (!isAgentOperationSettled(operation.status)) return { kind: 'unknown' };++ // Same grace window as the reconciliation sweep: the operation is settled+ // before its hook is dispatched, so a recent end may still be reported.+ if (now - endedAt(operation).getTime() < ORPHANED_RUN_GRACE_MS) {+ return {+ endedAt: endedAt(operation),+ kind: 'settling',+ operationId: operation.id,+ status: operation.status,+ };+ }++ return { kind: 'stale', operation };+};++/** The run status the lost completion hook would have written. */+const settledRunStatus = (operation: OperationRecord): string => {+ if (operation.status === 'done') return 'completed';+ // Same status a user's Stop and the interrupted-run sweep write.+ if (operation.status === 'interrupted') return 'canceled';+ return resolveFailedRunStatus(+ resolveOrphanedRunError({+ completionReason: operation.completionReason,+ operationError: operation.error ?? null,+ operationStatus: operation.status,+ }),+ );+};++const STOP_HINT = (topicId: string) =>+ `stop it first with \`lh task topic cancel ${topicId}\` (this pauses the task; resume it afterwards)`;++const conflictMessage = (topicId: string, continuing: boolean, run: BlockingRun): string => {+ const head = continuing+ ? `Topic ${topicId} is already running`+ : `Task already has a running topic (${topicId})`;++ switch (run.kind) {+ case 'live': {+ return `${head}: operation ${run.operationId} is ${run.status} (last update ${run.since.toISOString()}). Wait for it to finish, or ${STOP_HINT(topicId)}.`;+ }+ case 'settling': {+ const retryAt = new Date(run.endedAt.getTime() + ORPHANED_RUN_GRACE_MS);+ return `${head}: operation ${run.operationId} ended (${run.status}) at ${run.endedAt.toISOString()} and its result is still being recorded. Retry after ${retryAt.toISOString()}.`;+ }+ default: {+ return `${head}, but no operation can be found for it. If nothing is running there, ${STOP_HINT(topicId)}.`;+ }+ }+};++/**+ * Clear a `running` run row that blocks a new run, or refuse the run with what+ * is actually going on.+ *+ * A row whose operation ended past the grace window, with nothing else in+ * flight on its topic, is a leftover: it is settled with the status its lost+ * hook would have written and the new run goes ahead. Anything else is a real+ * conflict, and the error names the operation, its status and what to do next.+ *+ * Only the run row and the topic's end stamp are written, not the Task+ * lifecycle: the caller is starting the next run of this Task right now, so a+ * failure brief or a Task transition for the dead one would only be noise.+ */+export const clearBlockingRun = async (+ ctx: RunConflictContext,+ row: BlockingRunRow,+ options: { continuing: boolean; now?: number },+): Promise<void> => {+ const topicId = row.topicId ?? 'unknown';+ const now = options.now ?? Date.now();+ const run = await inspectBlockingRun(ctx, row, now);++ if (run.kind === 'stale') {+ const status = settledRunStatus(run.operation);+ const claimed = await new TaskRunClaimRepo(ctx.db, ctx.userId, ctx.workspaceId).claim(+ topicId,+ run.operation.id,+ status,+ );+ if (claimed) {+ log(+ 'settled stale run %s (operation %s ended %s) as %s',+ topicId,+ run.operation.id,+ run.operation.status,+ status,+ );+ return;+ }++ // Someone else settled it (fine) or a newer run took the row over (not).+ const current = await new TaskTopicModel(ctx.db, ctx.userId, ctx.workspaceId).findByTopicId(+ topicId,+ );+ if (current?.status !== 'running') return;++ const latest = await inspectBlockingRun(ctx, current, now);+ throw new TRPCError({+ code: 'CONFLICT',+ message: conflictMessage(+ topicId,+ options.continuing,+ latest.kind === 'stale' ? { kind: 'unknown' } : latest,+ ),+ });+ }++ throw new TRPCError({+ code: 'CONFLICT',+ message: conflictMessage(topicId, options.continuing, run),+ });+};diff --git a/packages/builtin-tool-task/src/manifest.ts b/packages/builtin-tool-task/src/manifest.tsindex 987e2e2a957..db998db0b96 100644--- a/packages/builtin-tool-task/src/manifest.ts+++ b/packages/builtin-tool-task/src/manifest.ts@@ -370,7 +370,7 @@ export const TaskManifest: BuiltinToolManifest = {},{description:- 'Trigger an actual run of a task β this kicks off the assigned agent in a new (or continued) topic. Use this to START tasks; do NOT use updateTaskStatus(running) to start a task, that only flips the status flag without actually executing anything. The task must already have an assigneeAgentId; if not, edit the task to assign one first. Will fail with a CONFLICT-style error if the task already has a running topic (cancel it first or pass continueTopicId).',+ 'Trigger an actual run of a task β this kicks off the assigned agent in a new (or continued) topic. Use this to START tasks; do NOT use updateTaskStatus(running) to start a task, that only flips the status flag without actually executing anything. The task must already have an assigneeAgentId; if not, edit the task to assign one first. If the task already has a live run, this fails with a CONFLICT error naming the operation behind that run, its status and the next step; a run whose operation ended long ago is cleaned up and no longer blocks. Running a scheduled task by hand works as a test tick: it does not count toward maxExecutions, and the task returns to scheduled afterwards.',name: TaskApiName.runTask,parameters: {properties: {