π€― 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 runs whose operation ended without reaching the Task (#20284)
Arvin Xu7fb922cb1205
diff --git a/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.test.ts b/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.test.tsnew file mode 100644index 00000000000..d4faf9c5090--- /dev/null+++ b/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.test.ts@@ -0,0 +1,75 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { onTopicComplete } from './onTopicComplete';++const { getServerDB, isRunAlreadySettled, lifecycleOnTopicComplete } = vi.hoisted(() => ({+ getServerDB: vi.fn(),+ isRunAlreadySettled: vi.fn(),+ lifecycleOnTopicComplete: vi.fn(),+}));++vi.mock('@/database/server', () => ({ getServerDB }));+vi.mock('@/server/services/taskLifecycle', () => ({+ TaskLifecycleService: vi.fn(function () {+ return { onTopicComplete: lifecycleOnTopicComplete };+ }),+}));+vi.mock('@/server/services/taskLifecycle/reconcile', () => ({ isRunAlreadySettled }));++const makeContext = (body: Record<string, unknown>) => {+ const json = vi.fn(function (payload, status = 200) {+ return { payload, status };+ });+ return {+ context: { json, req: { json: vi.fn().mockResolvedValue(body) } } as any,+ json,+ };+};++const failedRunPayload = {+ errorMessage: 'You exceeded your current quota',+ operationId: 'op-1',+ reason: 'error',+ taskId: 'task-1',+ taskIdentifier: 'T-1',+ topicId: 'tpc-1',+ userId: 'user-1',+};++describe('onTopicComplete webhook', () => {+ beforeEach(() => {+ const chain = {+ from: () => chain,+ limit: async () => [{ workspaceId: 'ws-1' }],+ where: () => chain,+ };+ getServerDB.mockReset().mockResolvedValue({ select: () => chain });+ isRunAlreadySettled.mockReset().mockResolvedValue(false);+ lifecycleOnTopicComplete.mockReset().mockResolvedValue(undefined);+ });++ it('drives the lifecycle for a run nobody has settled yet', async () => {+ const { context, json } = makeContext(failedRunPayload);++ await onTopicComplete(context);++ expect(isRunAlreadySettled).toHaveBeenCalledWith(expect.anything(), 'user-1', 'ws-1', {+ operationId: 'op-1',+ reason: 'error',+ taskId: 'task-1',+ topicId: 'tpc-1',+ });+ expect(lifecycleOnTopicComplete).toHaveBeenCalledTimes(1);+ expect(json).toHaveBeenCalledWith({ success: true });+ });++ it('acks a delayed delivery for a run the sweep already settled without re-applying it', async () => {+ isRunAlreadySettled.mockResolvedValue(true);+ const { context, json } = makeContext(failedRunPayload);++ await onTopicComplete(context);++ expect(lifecycleOnTopicComplete).not.toHaveBeenCalled();+ expect(json).toHaveBeenCalledWith({ skipped: 'already-settled', success: true });+ });+});diff --git a/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.ts b/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.tsindex 38c7cdb4086..90a9e877763 100644--- a/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.ts+++ b/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.ts@@ -6,6 +6,7 @@ import type { Context } from 'hono';import { tasks } from '@/database/schemas';import { getServerDB } from '@/database/server';import { TaskLifecycleService } from '@/server/services/taskLifecycle';+import { isRunAlreadySettled } from '@/server/services/taskLifecycle/reconcile';const log = debug('lobe-server:workflows:task:on-topic-complete');@@ -65,6 +66,23 @@ export async function onTopicComplete(c: Context) {.where(and(eq(tasks.id, taskId), eq(tasks.createdByUserId, userId))).limit(1);const wsId = taskRow?.workspaceId ?? undefined;++ // A delivery delayed past the orphaned-run grace window can land after the+ // reconciliation sweep already settled this run. Driving the lifecycle again+ // would double-apply it (a second urgent error brief, double fuse counting),+ // so ack and stop β QStash must not retry a delivery that has nothing to do.+ if (+ await isRunAlreadySettled(db, userId, wsId, {+ operationId,+ reason: reason || 'done',+ taskId,+ topicId,+ })+ ) {+ log('Skipped: run %s of task %s was already settled', operationId, taskId);+ return c.json({ skipped: 'already-settled', success: true });+ }+const taskLifecycle = new TaskLifecycleService(db, userId, wsId);await taskLifecycle.onTopicComplete({diff --git a/apps/server/src/router-hono/workflows/task/handlers/watchdog.ts b/apps/server/src/router-hono/workflows/task/handlers/watchdog.tsindex 84ec6e8ef6e..a95ea3f11a3 100644--- a/apps/server/src/router-hono/workflows/task/handlers/watchdog.ts+++ b/apps/server/src/router-hono/workflows/task/handlers/watchdog.ts@@ -4,15 +4,22 @@ import type { Context } from 'hono';import { BriefModel } from '@/database/models/brief';import { TaskModel } from '@/database/models/task';import { getServerDB } from '@/database/server';+import { reconcileOrphanedTaskRuns } from '@/server/services/taskLifecycle/reconcile';import { TaskResultBridgeService } from '@/server/services/taskResultBridge';import { TaskResultCallbackRedisStore } from '@/server/services/taskResultBridge/redisStore';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.+ * Cron-style watchdog. Two nets over Tasks that are `running` with nothing+ * behind them:+ *+ * 1. `lastHeartbeatAt + heartbeatTimeout < now()` β the automation-heartbeat+ * net, which marks the Task `failed` with an urgent brief.+ * 2. A `running` run row whose operation already ended (see+ * {@link reconcileOrphanedTaskRuns}) β the net for a Task the first one+ * cannot see, either because it sets no `heartbeatTimeout` or because its+ * run ends without ever delivering its terminal state.** No per-user authentication: this is a global sweep registered as a QStash* Schedule (cron). Signature verification is handled by the `qstashAuth`@@ -46,6 +53,13 @@ export async function watchdog(c: Context) {failed.push(task.identifier);}+ // The heartbeat net above cannot see every stuck Task: it requires a+ // configured `heartbeatTimeout`, which schedule and goal tasks do not set. A+ // run whose terminal delivery was lost leaves no trace here at all, so its+ // Task would read as `running` forever (LOBE-12391). Settle those from the+ // operation's own end instead.+ const reconciled = await reconcileOrphanedTaskRuns(db);+const recoverableCallbacks = await TaskResultCallbackRedisStore.findRecoverableScopes();const recoveredCallbacks: string[] = [];for (const scope of recoverableCallbacks) {@@ -72,14 +86,16 @@ export async function watchdog(c: Context) {}log(- 'Watchdog scan: checked=%d failed=%d callbacks=%d',+ 'Watchdog scan: checked=%d failed=%d orphaned=%d callbacks=%d',stuckTasks.length,failed.length,+ reconciled.converged.length,recoveredCallbacks.length,);return c.json({checked: stuckTasks.length,failed,+ orphaned: reconciled,recoveredCallbacks,success: true,});diff --git a/apps/server/src/services/agentRuntime/AbandonOperationService.ts b/apps/server/src/services/agentRuntime/AbandonOperationService.tsindex 93676d03bfd..acc99f507cd 100644--- a/apps/server/src/services/agentRuntime/AbandonOperationService.ts+++ b/apps/server/src/services/agentRuntime/AbandonOperationService.ts@@ -24,6 +24,20 @@ import { createDefaultSnapshotStore } from './snapshotStore';const log = debug('lobe-server:abandon-operation');+/**+ * Report a failure that leaves terminal state unsettled.+ *+ * Everything on this path is best-effort, but some of it is not optional:+ * when the durable row, the run row or the terminal hook fails here, the run+ * ends with a row still claiming to be `running` and nothing left to report it+ * β a Task that never settles, a Goal that waits on it, and a user looking at a+ * spinner (LOBE-12391). Those failures get a real log line; the ones that only+ * cost a retry stay on `debug`.+ */+const reportSettleFailure = (message: string, context: unknown): void => {+ console.error(`[abandon-operation] ${message}: %O`, context);+};+interface AbandonOperationOptions {coordinator?: AgentRuntimeCoordinator;snapshotStore?: ISnapshotStore | null;@@ -231,7 +245,10 @@ export class AbandonOperationService {result.assistantMessageUpdated = true;}} catch (e) {- log('[%s] assistant failure row write failed (non-fatal): %O', operationId, e);+ reportSettleFailure(+ `abandoned op failed to mark its assistant message (op=${operationId})`,+ e,+ );}}@@ -242,7 +259,7 @@ export class AbandonOperationService {});await topicModel.settleRunningOperation(origin.topicId, operationId);} catch (e) {- log('[%s] abandoned op runningOperation cleanup failed (non-fatal): %O', operationId, e);+ reportSettleFailure(`abandoned op failed to settle its topic (op=${operationId})`, e);}}@@ -255,7 +272,10 @@ export class AbandonOperationService {skipErrorMessageWrite: result.assistantMessageUpdated,});} catch (e) {- log('[%s] abandoned op lifecycle dispatch failed (non-fatal): %O', operationId, e);+ reportSettleFailure(+ `abandoned op failed to dispatch its terminal hooks (op=${operationId})`,+ e,+ );}}@@ -283,7 +303,10 @@ export class AbandonOperationService {log('[%s] durable row settled by abandon safety net', operationId);}} catch (e) {- log('[%s] abandon safety-net settle failed (non-fatal): %O', operationId, e);+ reportSettleFailure(+ `abandon safety net could not retire the durable row (op=${operationId})`,+ e,+ );}}@@ -417,7 +440,10 @@ export class AbandonOperationService {totalTokens: 0,});} catch (e) {- log('[%s] no-state abandon: recordCompletion failed (non-fatal): %O', operationId, e);+ reportSettleFailure(+ `no-state abandon could not retire the durable row (op=${operationId})`,+ e,+ );}}@@ -485,7 +511,10 @@ export class AbandonOperationService {: { skipErrorMessageWrite: true },);} catch (e) {- log('[%s] no-state abandon: lifecycle dispatch failed (non-fatal): %O', operationId, e);+ reportSettleFailure(+ `no-state abandon failed to dispatch its terminal hooks (op=${operationId})`,+ e,+ );}}@@ -604,7 +633,13 @@ export class AbandonOperationService {}return { ...topicHooks, ...(await this.findPlaceholderMessage(op, operationId)) };} catch (e) {- log('[%s] no-state abandon: topic lookup failed (non-fatal): %O', operationId, e);+ // The topic could not be settled, so this run's hooks are suppressed β+ // which means the Task behind it never hears that it ended. Visible+ // even though the path continues.+ reportSettleFailure(+ `no-state abandon could not settle its topic, so the terminal hooks are suppressed (op=${operationId})`,+ e,+ );// A failed settle cannot rule out a newer operation on the topic, and// firing this run's task hook would then pause the replacement's Task.return { ...(await this.findPlaceholderMessage(op, operationId)), ownershipUnproven: true };diff --git a/apps/server/src/services/taskLifecycle/reconcile.test.ts b/apps/server/src/services/taskLifecycle/reconcile.test.tsnew file mode 100644index 00000000000..639b3e97245--- /dev/null+++ b/apps/server/src/services/taskLifecycle/reconcile.test.ts@@ -0,0 +1,314 @@+import {+ ABANDONED_OPERATION_ERROR_PREFIX,+ DEVICE_OFFLINE_RUN_STATUS,+ LEASE_EXPIRED_ERROR,+} from '@lobechat/const/goal';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { OrphanedRunningTopic } from '@/database/models/task';++import { isRunAlreadySettled, ORPHANED_RUN_GRACE_MS, reconcileOrphanedTaskRuns } from './reconcile';++const {+ findOrphanedRunningTopics,+ findRunByTopicId,+ findTaskById,+ claimRun,+ onTopicComplete,+ releaseRun,+} = vi.hoisted(() => ({+ findOrphanedRunningTopics: vi.fn(),+ findRunByTopicId: vi.fn(),+ findTaskById: vi.fn(),+ claimRun: vi.fn(),+ onTopicComplete: vi.fn(),+ releaseRun: vi.fn(),+}));++vi.mock('@/database/models/task', () => ({+ TaskModel: Object.assign(+ vi.fn(function () {+ return { findById: findTaskById };+ }),+ {+ findOrphanedRunningTopics: (...args: unknown[]) => findOrphanedRunningTopics(...args),+ },+ ),+}));++vi.mock('@/database/models/taskTopic', () => ({+ TaskTopicModel: vi.fn(function () {+ return { findByTopicId: findRunByTopicId };+ }),+}));++vi.mock('@/database/repositories/taskRunClaim', () => ({+ TaskRunClaimRepo: vi.fn(function () {+ return { claim: claimRun, release: releaseRun };+ }),+}));++vi.mock('./index', () => ({+ TaskLifecycleService: vi.fn(function () {+ return { onTopicComplete };+ }),+}));++const orphanedRun = (overrides: Partial<OrphanedRunningTopic> = {}): OrphanedRunningTopic => ({+ completionReason: 'lease_expired',+ operationError: null,+ operationId: 'op-1',+ operationStatus: 'abandoned',+ taskId: 'task-1',+ taskIdentifier: 'T-1',+ topicId: 'tpc-1',+ trigger: 'goal',+ userId: 'user-1',+ workspaceId: null,+ ...overrides,+});++const db = {} as never;++describe('reconcileOrphanedTaskRuns', () => {+ beforeEach(() => {+ findOrphanedRunningTopics.mockReset().mockResolvedValue([]);+ claimRun.mockReset().mockResolvedValue(true);+ onTopicComplete.mockReset().mockResolvedValue(undefined);+ releaseRun.mockReset().mockResolvedValue(true);+ findTaskById.mockReset().mockResolvedValue({ id: 'task-1', status: 'running' });+ findRunByTopicId.mockReset().mockResolvedValue(null);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('settles a run whose operation ended without reaching its Task', async () => {+ findOrphanedRunningTopics.mockResolvedValue([orphanedRun()]);++ const result = await reconcileOrphanedTaskRuns(db);++ // The claim is what makes the settle single-owner, and it must name the+ // operation so a newer run on the same Task can never be the one settled.+ expect(claimRun).toHaveBeenCalledWith('tpc-1', 'op-1', 'failed');+ // The Task is settled by driving the ordinary lifecycle β not by a second+ // implementation of it β so every Task kind keeps the behaviour the lost+ // hook would have produced.+ expect(onTopicComplete).toHaveBeenCalledWith({+ errorCode: undefined,+ errorMessage: `${ABANDONED_OPERATION_ERROR_PREFIX} lease_expired`,+ operationId: 'op-1',+ reason: 'error',+ runTrigger: 'goal',+ taskId: 'task-1',+ taskIdentifier: 'T-1',+ topicId: 'tpc-1',+ });+ expect(result).toMatchObject({ checked: 1, converged: ['tpc-1'], failed: [], skipped: [] });+ });++ it('prefers the failure the operation recorded, so its classification survives', async () => {+ findOrphanedRunningTopics.mockResolvedValue([+ orphanedRun({+ completionReason: 'error',+ operationError: { message: 'DEVICE_OFFLINE' },+ operationStatus: 'error',+ }),+ ]);++ await reconcileOrphanedTaskRuns(db);++ // `resolveFailedRunStatus` reads the message, so a device-offline run stays+ // an offline run β worth-not-charging-to-the-attempt-budget behaviour that+ // the goal recovery keys on, rather than being flattened into a plain+ // failure.+ expect(claimRun).toHaveBeenCalledWith('tpc-1', 'op-1', DEVICE_OFFLINE_RUN_STATUS);+ expect(onTopicComplete).toHaveBeenCalledWith(+ expect.objectContaining({ errorMessage: 'DEVICE_OFFLINE' }),+ );+ });++ it('reads a provider failure nested in the raw runtime error payload', async () => {+ // Regression: `agent_operations.error` stores the raw `state.error`, whose+ // message sits under `error`. Reading only the top-level `message` turned a+ // real quota failure into a lost run β retried by the Goal coordinator as if+ // nothing had judged it, and briefed without its "Upgrade plan" remedy.+ findOrphanedRunningTopics.mockResolvedValue([+ orphanedRun({+ completionReason: 'error',+ operationError: {+ error: { message: 'You exceeded your current quota' },+ errorType: 'InsufficientBudgetForModel',+ provider: 'openai',+ },+ operationStatus: 'error',+ }),+ ]);++ await reconcileOrphanedTaskRuns(db);++ expect(onTopicComplete).toHaveBeenCalledWith(+ expect.objectContaining({+ errorCode: 'InsufficientBudgetForModel',+ errorMessage: 'You exceeded your current quota',+ }),+ );+ });++ it('settles a silent end as a lost run, not as a judged failure', async () => {+ findOrphanedRunningTopics.mockResolvedValue([+ orphanedRun({ completionReason: null, operationStatus: 'error' }),+ ]);++ await reconcileOrphanedTaskRuns(db);++ // Nothing judged the work, so the recovery is another attempt β the goal+ // coordinator reads `lease expired` as exactly that. A made-up failure text+ // here would open a decision gate on a human instead.+ expect(onTopicComplete).toHaveBeenCalledWith(+ expect.objectContaining({ errorMessage: LEASE_EXPIRED_ERROR }),+ );+ expect(claimRun).toHaveBeenCalledWith('tpc-1', 'op-1', 'failed');+ });++ it('leaves a row another writer already claimed alone', async () => {+ findOrphanedRunningTopics.mockResolvedValue([orphanedRun()]);+ claimRun.mockResolvedValue(false);++ const result = await reconcileOrphanedTaskRuns(db);++ expect(onTopicComplete).not.toHaveBeenCalled();+ expect(result).toMatchObject({ checked: 1, converged: [], skipped: ['tpc-1'] });+ });++ it('hands the row back when the settle fails, so the next pass retries it', async () => {+ findOrphanedRunningTopics.mockResolvedValue([orphanedRun()]);+ onTopicComplete.mockRejectedValue(new Error('lifecycle exploded'));++ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ const result = await reconcileOrphanedTaskRuns(db);++ // A claimed-but-unsettled row is the very shape this reconciliation exists+ // to remove, so it must not be left terminal with its Task still `running`.+ expect(releaseRun).toHaveBeenCalledWith('tpc-1', 'op-1', 'failed');+ expect(result).toMatchObject({ checked: 1, converged: [], failed: ['tpc-1'] });+ expect(consoleError).toHaveBeenCalled();+ });++ it('keeps the run settled when the settle failed after the Task moved on', async () => {+ // Regression: the lifecycle can throw after it already parked the Task+ // (`paused` / `scheduled`). Re-opening the run then would strand it β the+ // finder only picks runs whose Task is still `running`, so a `running` run+ // under a paused Task would never be retried.+ findOrphanedRunningTopics.mockResolvedValue([orphanedRun()]);+ onTopicComplete.mockRejectedValue(new Error('final findById failed'));+ findTaskById.mockResolvedValue({ id: 'task-1', status: 'paused' });++ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ const result = await reconcileOrphanedTaskRuns(db);++ expect(releaseRun).not.toHaveBeenCalled();+ expect(result).toMatchObject({ checked: 1, converged: [], failed: ['tpc-1'] });+ expect(consoleError).toHaveBeenCalled();+ });++ it('scopes the scan to runs that have been over for the grace window', async () => {+ await reconcileOrphanedTaskRuns(db);++ const [, options] = findOrphanedRunningTopics.mock.calls[0];+ expect(options.staleBefore.getTime()).toBeCloseTo(Date.now() - ORPHANED_RUN_GRACE_MS, -4);+ });++ it('passes an explicit window and limit through, for a bounded catch-up pass', async () => {+ const staleBefore = new Date('2026-07-01T00:00:00Z');++ await reconcileOrphanedTaskRuns(db, { limit: 5, staleBefore });++ expect(findOrphanedRunningTopics).toHaveBeenCalledWith(db, { limit: 5, staleBefore });+ });+});++describe('isRunAlreadySettled', () => {+ const callback = {+ operationId: 'op-1',+ reason: 'error',+ taskId: 'task-1',+ topicId: 'tpc-1',+ };++ beforeEach(() => {+ findOrphanedRunningTopics.mockReset().mockResolvedValue([]);+ claimRun.mockReset().mockResolvedValue(true);+ onTopicComplete.mockReset().mockResolvedValue(undefined);+ findRunByTopicId.mockReset();+ findTaskById.mockReset();+ });++ it('fences a delayed failure callback that lands after the sweep settled the run', async () => {+ // Regression: the sweep's claim only excluded competing sweeps. A QStash+ // delivery delayed past the grace window then drove the same lifecycle a+ // second time β a duplicate urgent error brief, the fuse counted twice.+ const run = { operationId: 'op-1', status: 'running', taskId: 'task-1', topicId: 'tpc-1' };+ const task = { id: 'task-1', status: 'running' };+ findRunByTopicId.mockImplementation(async () => run);+ findTaskById.mockImplementation(async () => task);+ findOrphanedRunningTopics.mockResolvedValue([orphanedRun()]);+ claimRun.mockImplementation(async (_topicId, _opId, status) => {+ run.status = status;+ return true;+ });+ onTopicComplete.mockImplementation(async () => {+ task.status = 'paused';+ });++ // Before the sweep, the callback is the one settling the run.+ expect(await isRunAlreadySettled(db, 'user-1', undefined, callback)).toBe(false);++ await reconcileOrphanedTaskRuns(db);++ expect(await isRunAlreadySettled(db, 'user-1', undefined, callback)).toBe(true);+ });++ it('lets a retry through when an earlier settle broke before moving the Task on', async () => {+ findRunByTopicId.mockResolvedValue({+ operationId: 'op-1',+ status: 'failed',+ taskId: 'task-1',+ topicId: 'tpc-1',+ });+ findTaskById.mockResolvedValue({ id: 'task-1', status: 'running' });++ expect(await isRunAlreadySettled(db, 'user-1', undefined, callback)).toBe(false);+ });++ it('never fences a run row a newer operation now owns', async () => {+ findRunByTopicId.mockResolvedValue({+ operationId: 'op-2',+ status: 'failed',+ taskId: 'task-1',+ topicId: 'tpc-1',+ });+ findTaskById.mockResolvedValue({ id: 'task-1', status: 'paused' });++ expect(await isRunAlreadySettled(db, 'user-1', undefined, callback)).toBe(false);+ });++ it('leaves successful and interrupted deliveries alone', async () => {+ findRunByTopicId.mockResolvedValue({+ operationId: 'op-1',+ status: 'canceled',+ taskId: 'task-1',+ topicId: 'tpc-1',+ });+ findTaskById.mockResolvedValue({ id: 'task-1', status: 'paused' });++ expect(+ await isRunAlreadySettled(db, 'user-1', undefined, { ...callback, reason: 'done' }),+ ).toBe(false);+ expect(+ await isRunAlreadySettled(db, 'user-1', undefined, { ...callback, reason: 'interrupted' }),+ ).toBe(false);+ expect(findRunByTopicId).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/taskLifecycle/reconcile.ts b/apps/server/src/services/taskLifecycle/reconcile.tsnew file mode 100644index 00000000000..80830bc5ea7--- /dev/null+++ b/apps/server/src/services/taskLifecycle/reconcile.ts@@ -0,0 +1,261 @@+import { ABANDONED_OPERATION_ERROR_PREFIX, LEASE_EXPIRED_ERROR } from '@lobechat/const/goal';+import { extractErrorMessage } from '@lobechat/model-runtime/errors';+import debug from 'debug';++import type { OrphanedRunningTopic } from '@/database/models/task';+import { TaskModel } from '@/database/models/task';+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 { TaskLifecycleService } from './index';++const log = debug('task-lifecycle:reconcile');++/**+ * How long a run may hold a `running` row after its operation already ended+ * before the sweep calls it orphaned.+ *+ * The operation is settled *before* its `onComplete` hook is dispatched, so this+ * window is what keeps the sweep from racing the normal path β including a hook+ * whose first delivery fails and is retried. It is deliberately the same order+ * of magnitude as the goal sweep's own stale window: both are looking for the+ * same class of lost delivery, just from opposite ends of the graph.+ */+export const ORPHANED_RUN_GRACE_MS = 15 * 60 * 1000;++export interface ReconcileOrphanedRunsOptions {+ /**+ * Cap on the rows settled in one pass. A backlog of historical zombies drains+ * over successive ticks instead of settling hundreds of Tasks β and emitting+ * a failure card for each β in a single burst.+ */+ limit?: number;+ /** Override the grace window. Tests use it to age a fixture. */+ staleBefore?: Date;+}++export interface ReconcileOrphanedRunsResult {+ /** Rows the finder returned. */+ checked: number;+ /** Topic ids this pass actually settled. */+ converged: string[];+ /** Rows whose settle failed; they stay `running` for the next pass to retry. */+ failed: string[];+ /** Rows another writer claimed first, or whose run moved on under us. */+ skipped: string[];+}++/**+ * Settle Task runs whose operation ended without reaching the Task.+ *+ * The run's terminal state normally reaches `task_topics` / `tasks` through its+ * `onComplete` webhook. That delivery is fire-and-forget, so when it is lost β+ * the watchdog abandoning a run is the common case β nothing settles the rows+ * and the Task keeps a `running` run forever (LOBE-12391). Downstream, that+ * stale row reads as a live run: the Goal view shows the dead attempt's frozen+ * heartbeat, and the coordinator parks on it instead of recovering.+ *+ * This is the second entry point into the same `TaskLifecycleService`, not a+ * parallel implementation of it: the converge drives `onTopicComplete` with the+ * outcome the run actually had, so every Task kind keeps the behaviour it would+ * have got from the hook β automation fuse arithmetic, the goal retry for a lost+ * run, the error brief, the verify boundary.+ */+export const reconcileOrphanedTaskRuns = async (+ db: LobeChatDatabase,+ options: ReconcileOrphanedRunsOptions = {},+): Promise<ReconcileOrphanedRunsResult> => {+ const staleBefore = options.staleBefore ?? new Date(Date.now() - ORPHANED_RUN_GRACE_MS);+ const rows = await TaskModel.findOrphanedRunningTopics(db, {+ limit: options.limit,+ staleBefore,+ });++ const converged: string[] = [];+ const skipped: string[] = [];+ const failed: string[] = [];++ for (const row of rows) {+ try {+ const settled = await settleOrphanedRun(db, row);+ if (settled) converged.push(row.topicId);+ else skipped.push(row.topicId);+ } catch (error) {+ // One row must not take the sweep down with it; the rest are independent.+ failed.push(row.topicId);+ console.error('[task-reconcile] orphaned run settle failed: %O', { error, row });+ }+ }++ log(+ 'orphaned runs: checked=%d converged=%d skipped=%d failed=%d',+ rows.length,+ converged.length,+ skipped.length,+ failed.length,+ );++ return { checked: rows.length, converged, failed, skipped };+};++/**+ * Settle one orphaned run, or report that somebody else got there first.+ *+ * The claim comes first: a `task_topics` row only moves out of `running` while+ * it still names *this* operation, so two overlapping sweeps β or a hook that+ * finally lands late β can never report the same dead run twice. It is handed+ * back if the settle then fails, because a row left terminal with its Task still+ * `running` is precisely the shape this reconciliation exists to remove.+ */+const settleOrphanedRun = async (+ db: LobeChatDatabase,+ row: OrphanedRunningTopic,+): Promise<boolean> => {+ const errorMessage = resolveOrphanedRunError(row);+ const runStatus = resolveFailedRunStatus(errorMessage);+ const claimRepo = new TaskRunClaimRepo(db, row.userId, row.workspaceId ?? undefined);++ if (!(await claimRepo.claim(row.topicId, row.operationId, runStatus))) {+ return false;+ }++ try {+ await new TaskLifecycleService(db, row.userId, row.workspaceId ?? undefined).onTopicComplete({+ // The structured type picks the error brief's remedy (a budget failure+ // leads with "Upgrade plan"), exactly as the lost hook would have.+ errorCode: resolveOrphanedRunErrorType(row),+ errorMessage,+ operationId: row.operationId,+ reason: 'error',+ // The trigger decides whether a failure touches an automation task's+ // schedule state, so it must be the one the run actually started with.+ runTrigger: row.trigger ?? undefined,+ taskId: row.taskId,+ taskIdentifier: row.taskIdentifier,+ topicId: row.topicId,+ });+ } catch (error) {+ await handBackClaimedRun(db, row, runStatus, claimRepo).catch((rollbackError) =>+ console.error('[task-reconcile] failed to re-open a claimed run: %O', {+ error: rollbackError,+ operationId: row.operationId,+ }),+ );+ throw error;+ }++ return true;+};++/**+ * Undo the claim of a run whose settle failed β but only while that can still+ * be retried.+ *+ * The finder only picks runs whose Task is still `running`. When the lifecycle+ * threw *after* moving the Task on (to `paused` / `scheduled`, say), re-opening+ * the run would strand it: a `running` run under a Task the sweep never looks at+ * again. The Task transition is the settle's decisive write, so a run that got+ * that far stays settled; only a Task still `running` gets its run handed back.+ */+const handBackClaimedRun = async (+ db: LobeChatDatabase,+ row: OrphanedRunningTopic,+ runStatus: string,+ claimRepo: TaskRunClaimRepo,+): Promise<void> => {+ const task = await new TaskModel(db, row.userId, row.workspaceId ?? undefined).findById(+ row.taskId,+ );+ if (task && task.status !== 'running') {+ log(+ 'settle of %s failed after its Task moved to %s; keeping the run settled',+ row.topicId,+ task.status,+ );+ return;+ }++ await claimRepo.release(row.topicId, row.operationId, runStatus);+};++/**+ * The failure text an orphaned run is settled with.+ *+ * The operation's own recorded failure is preferred, so a device-offline run or+ * a watchdog abandonment keeps its specific classification β `resolveFailedRunStatus`+ * reads this text for the run row, and the Goal coordinator's `isLostRunError`+ * decides retry-versus-human-gate from it.+ *+ * With nothing recorded, the run is settled as a lost run rather than as a+ * judged failure: no delivery ever happened, nobody judged the work, and+ * `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.+ */+const resolveOrphanedRunError = (row: OrphanedRunningTopic): 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+ // fall through to the lost-run text and be retried as if nothing judged it.+ const recorded = extractErrorMessage(row.operationError);+ if (recorded?.trim()) return recorded.trim();++ if (row.operationStatus === 'abandoned') {+ return `${ABANDONED_OPERATION_ERROR_PREFIX} ${row.completionReason ?? 'lease_expired'}`;+ }++ return LEASE_EXPIRED_ERROR;+};++/**+ * The structured error type the operation recorded, if any β the raw payload+ * carries it as `errorType`, a normalized one as `type`.+ */+const resolveOrphanedRunErrorType = (row: OrphanedRunningTopic): string | undefined => {+ const error = row.operationError;+ if (!error) return undefined;+ const type = error.errorType ?? error.type;+ return typeof type === 'string' && type ? type : undefined;+};++export interface SettledRunQuery {+ operationId: string;+ reason: string;+ taskId: string;+ topicId?: string;+}++/**+ * Whether a failed run's `onComplete` delivery arrives for a run that was+ * already settled β by this reconciliation, most often, when the hook was+ * delayed past the grace window rather than lost.+ *+ * The lifecycle is not idempotent: driving it twice emits a second urgent error+ * brief, counts the failure into an automation's fuse twice, and re-parks a Task+ * that may have moved on. The sweep's claim fences competing sweeps; this is the+ * same fence read from the callback side. A run is settled once its own row has+ * left `running` *and* its Task has moved on: the sweep makes both writes, as+ * does a callback that already ran to completion. A row that is terminal under a+ * 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.+ */+export const isRunAlreadySettled = async (+ db: LobeChatDatabase,+ userId: string,+ workspaceId: string | undefined,+ { operationId, reason, taskId, topicId }: SettledRunQuery,+): Promise<boolean> => {+ if (reason !== 'error' || !topicId) return false;++ const run = await new TaskTopicModel(db, userId, workspaceId).findByTopicId(topicId);+ if (!run || run.taskId !== taskId || run.operationId !== operationId) return false;+ if (run.status === 'running') return false;++ const task = await new TaskModel(db, userId, workspaceId).findById(taskId);+ return !!task && task.status !== 'running';+};diff --git a/packages/database/src/models/__tests__/task.orphanedRuns.test.ts b/packages/database/src/models/__tests__/task.orphanedRuns.test.tsnew file mode 100644index 00000000000..92570df8eaf--- /dev/null+++ b/packages/database/src/models/__tests__/task.orphanedRuns.test.ts@@ -0,0 +1,258 @@+// @vitest-environment node+import { eq, sql } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { TaskRunClaimRepo } from '../../repositories/taskRunClaim';+import { agentOperations, tasks, taskTopics, topics, users } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { TaskModel } from '../task';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'orphaned-runs-test-user-id';++/** Every fixture ends before this, so the grace window never hides one. */+const staleBefore = new Date('2026-10-02T15:00:00Z');+const longAgo = new Date('2026-10-02T14:00:00Z');++let seq = 0;++interface SeedOptions {+ /** When the operation ended. Defaults to well before the window. */+ endedAt?: Date;+ operationStatus?:+ 'abandoned' | 'done' | 'error' | 'interrupted' | 'running' | 'waiting_for_human';+ /** Set to make the operation a sub-agent child. */+ parentOperationId?: string;+ /** The run row's status; `running` is the one this net looks for. */+ runStatus?: string;+ taskStatus?: string;+ /** Omit to seed a run row with no operation behind it. */+ withOperation?: boolean;+}++/** One Task with one run of it, plus the operation behind that run. */+const seed = async (options: SeedOptions = {}) => {+ seq += 1;+ const taskId = `task-${seq}`;+ const topicId = `tpc-${seq}`;+ const operationId = `op-${seq}`;++ await serverDB.insert(tasks).values({+ createdByUserId: userId,+ id: taskId,+ identifier: `T-${seq}`,+ instruction: 'do the thing',+ seq,+ status: options.taskStatus ?? 'running',+ });+ await serverDB.insert(topics).values({ id: topicId, userId });+ await serverDB.insert(taskTopics).values({+ operationId: options.withOperation === false ? undefined : operationId,+ seq: 1,+ status: options.runStatus ?? 'running',+ taskId,+ topicId,+ userId,+ });++ if (options.withOperation !== false) {+ await serverDB.insert(agentOperations).values({+ completedAt: options.endedAt ?? longAgo,+ id: operationId,+ parentOperationId: options.parentOperationId,+ status: options.operationStatus ?? 'error',+ taskId,+ topicId,+ userId,+ updatedAt: options.endedAt ?? longAgo,+ });+ }++ return { operationId, taskId, topicId };+};++const find = () => TaskModel.findOrphanedRunningTopics(serverDB, { staleBefore });++const readRun = async (topicId: string) =>+ (await serverDB.select().from(taskTopics).where(eq(taskTopics.topicId, topicId)).limit(1))[0];++const readTopic = async (topicId: string) =>+ (await serverDB.select().from(topics).where(eq(topics.id, topicId)).limit(1))[0];++beforeEach(async () => {+ // `agent_operations.userId` is deliberately not a foreign key, so deleting the+ // user does not cascade it away.+ await serverDB.delete(agentOperations);+ await serverDB.delete(taskTopics);+ await serverDB.delete(topics);+ await serverDB.delete(tasks);+ await serverDB.delete(users);+ seq = 0;+ await serverDB.insert(users).values([{ id: userId }]);+});++afterEach(async () => {+ await serverDB.delete(agentOperations);+ await serverDB.delete(users);+});++describe('TaskModel.findOrphanedRunningTopics', () => {+ it('returns a running Task run whose operation already ended', async () => {+ const { operationId, taskId, topicId } = await seed({ operationStatus: 'abandoned' });++ const rows = await find();++ expect(rows).toHaveLength(1);+ expect(rows[0]).toMatchObject({+ operationId,+ operationStatus: 'abandoned',+ taskId,+ taskIdentifier: 'T-1',+ topicId,+ userId,+ });+ });++ it('ignores an operation that has not settled', async () => {+ await seed({ operationStatus: 'running' });+ await seed({ operationStatus: 'waiting_for_human' });++ expect(await find()).toHaveLength(0);+ });++ it('ignores a run that succeeded and one the user interrupted', async () => {+ // `done` needs the success path's own inputs to settle and `interrupted`+ // belongs to the interrupt path: settling either from here would mislabel+ // the outcome, so this net must not see them at all.+ await seed({ operationStatus: 'done' });+ await seed({ operationStatus: 'interrupted' });++ expect(await find()).toHaveLength(0);+ });++ it('ignores an operation that ended inside the grace window', async () => {+ await seed({ endedAt: new Date('2026-10-02T16:00:00Z') });++ expect(await find()).toHaveLength(0);+ });++ it('ignores a run whose Task already left `running`', async () => {+ await seed({ taskStatus: 'paused' });++ expect(await find()).toHaveLength(0);+ });++ it('ignores a run row that was already settled', async () => {+ await seed({ runStatus: 'failed' });++ expect(await find()).toHaveLength(0);+ });++ it('ignores a run row with no operation behind it', async () => {+ await seed({ withOperation: false });++ expect(await find()).toHaveLength(0);+ });++ it('ignores a sub-agent child operation', async () => {+ await seed({ parentOperationId: 'op-parent' });++ expect(await find()).toHaveLength(0);+ });++ it('lists every orphaned run, oldest first, capped by the limit', async () => {+ // Seeded out of order so the returned order can only come from the query.+ const newest = await seed({ endedAt: new Date('2026-10-02T14:30:00Z') });+ const oldest = await seed({ endedAt: new Date('2026-10-02T14:00:00Z') });+ const middle = await seed({ endedAt: new Date('2026-10-02T14:15:00Z') });++ const all = await TaskModel.findOrphanedRunningTopics(serverDB, { staleBefore });+ expect(all.map((row) => row.operationId)).toEqual([+ oldest.operationId,+ middle.operationId,+ newest.operationId,+ ]);++ const capped = await TaskModel.findOrphanedRunningTopics(serverDB, { limit: 2, staleBefore });+ expect(capped).toHaveLength(2);+ });+});++describe('TaskRunClaimRepo', () => {+ it('flips a run that still names its own operation out of `running`', async () => {+ const { operationId, topicId } = await seed();+ const model = new TaskRunClaimRepo(serverDB, userId);++ expect(await model.claim(topicId, operationId, 'failed')).toBe(true);++ expect((await readRun(topicId)).status).toBe('failed');+ // The run is over, so the topic gets its end stamp too.+ expect((await readTopic(topicId)).completedAt).toBeInstanceOf(Date);+ });++ it('leaves the run `running` when the topic end stamp fails', async () => {+ // Regression: the claim committed before the topic stamp, so a failed stamp+ // threw past the caller's rollback and left the run terminal while its Task+ // stayed `running` β invisible to the next sweep, which only looks at+ // `running` rows.+ const { operationId, topicId } = await seed();+ const model = new TaskRunClaimRepo(serverDB, userId);+ await serverDB.execute(sql`+ CREATE OR REPLACE FUNCTION orphaned_runs_test_fail_topic_stamp() RETURNS trigger AS $$+ BEGIN RAISE EXCEPTION 'topic stamp failed'; END;+ $$ LANGUAGE plpgsql+ `);+ await serverDB.execute(sql`+ CREATE TRIGGER orphaned_runs_test_fail_topic_stamp BEFORE UPDATE ON topics+ FOR EACH ROW EXECUTE FUNCTION orphaned_runs_test_fail_topic_stamp()+ `);++ try {+ await expect(model.claim(topicId, operationId, 'failed')).rejects.toThrow();+ } finally {+ await serverDB.execute(+ sql`DROP TRIGGER IF EXISTS orphaned_runs_test_fail_topic_stamp ON topics`,+ );+ await serverDB.execute(sql`DROP FUNCTION IF EXISTS orphaned_runs_test_fail_topic_stamp()`);+ }++ expect((await readRun(topicId)).status).toBe('running');+ expect((await readTopic(topicId)).completedAt).toBeNull();+ });++ it('refuses a run that has already settled', async () => {+ const { operationId, topicId } = await seed({ runStatus: 'failed' });+ const model = new TaskRunClaimRepo(serverDB, userId);++ expect(await model.claim(topicId, operationId, 'failed')).toBe(false);+ });++ it('refuses a run a newer operation has taken over', async () => {+ const { topicId } = await seed();+ const model = new TaskRunClaimRepo(serverDB, userId);++ expect(await model.claim(topicId, 'op-someone-else', 'failed')).toBe(false);+ expect((await readRun(topicId)).status).toBe('running');+ });++ it('hands its own run back when the settle it was claimed for failed', async () => {+ const { operationId, topicId } = await seed();+ const model = new TaskRunClaimRepo(serverDB, userId);+ await model.claim(topicId, operationId, 'failed');++ expect(await model.release(topicId, operationId, 'failed')).toBe(true);+ expect((await readRun(topicId)).status).toBe('running');+ expect((await readTopic(topicId)).completedAt).toBeNull();+ });++ it('never re-opens a run that is no longer the claimed one', async () => {+ const { operationId, topicId } = await seed();+ const model = new TaskRunClaimRepo(serverDB, userId);+ await model.claim(topicId, operationId, 'failed');++ expect(await model.release(topicId, 'op-someone-else', 'failed')).toBe(false);+ expect((await readRun(topicId)).status).toBe('failed');+ });+});diff --git a/packages/database/src/models/task.ts b/packages/database/src/models/task.tsindex 9b25c5013f3..5fed994ee60 100644--- a/packages/database/src/models/task.ts+++ b/packages/database/src/models/task.ts@@ -1,4 +1,5 @@import type {+ AgentOperationStatus,CheckpointConfig,NewTask,TaskActivityLogPayload,@@ -6,6 +7,7 @@ import type {TaskAutomationMode,TaskAutomationSnapshot,TaskItem,+ TaskRunTrigger,TaskSubtaskProgress,TaskVerifyConfig,WorkspaceData,@@ -39,6 +41,8 @@ import type { AnyPgColumn } from 'drizzle-orm/pg-core';import { merge } from '@/utils/merge';+import type { AgentOperationError } from '../schemas/agentOperations';+import { agentOperations } from '../schemas/agentOperations';import { documents } from '../schemas/file';import type {NewTaskActivity,@@ -75,6 +79,35 @@ const TRACKED_TASK_COLUMNS = ['status',] as const;+/**+ * Operation outcomes the orphaned-run reconciliation settles.+ *+ * An allow-list on purpose. `done` needs the success path's own inputs (the+ * run's last assistant content, the creator bridge) and `interrupted` belongs+ * to the interrupt path, so converging either from a sweep would mislabel the+ * outcome; and an operation status added later is skipped rather than guessed+ * at.+ */+const ORPHANED_RUN_OPERATION_STATUSES: AgentOperationStatus[] = ['abandoned', 'error'];++/** One `running` Task run whose operation has already ended β see the finder. */+export interface OrphanedRunningTopic {+ completionReason: string | null;+ /**+ * The failure the operation recorded, when it recorded one β the raw+ * `state.error`, so its message may be nested (`{ errorType, error: { message } }`).+ */+ operationError: AgentOperationError | null;+ operationId: string;+ operationStatus: AgentOperationStatus;+ taskId: string;+ taskIdentifier: string;+ topicId: string;+ trigger: TaskRunTrigger | null;+ userId: string;+ workspaceId: string | null;+}+/** The automation columns folded into one value β see `TaskAutomationSnapshot`. *//*** The actor columns plus the payload tombstone for one activity row. An@@ -1696,6 +1729,71 @@ export class TaskModel {);}+ /**+ * Running Task runs whose operation has already ended.+ *+ * The terminal state of a run reaches `task_topics` / `tasks` through the+ * run's `onComplete` webhook, and that delivery is fire-and-forget: when it is+ * lost, the Task keeps a `running` run forever. Everything downstream then+ * believes a dead run is live β the Goal view reads its frozen heartbeat as+ * activity, and the coordinator parks on `waiting_external` instead of+ * recovering it (LOBE-12391). This finder is what lets a sweep settle those+ * rows without depending on the lost delivery.+ *+ * The grace window is what keeps the sweep from racing the normal path: the+ * operation is settled before its hook is dispatched, so only a run that has+ * been over for longer than any delivery lag is treated as orphaned.+ */+ static async findOrphanedRunningTopics(+ db: LobeChatDatabase,+ options: { limit?: number; staleBefore: Date },+ ): Promise<OrphanedRunningTopic[]> {+ const { limit = 200, staleBefore } = options;++ return (+ db+ .select({+ completionReason: agentOperations.completionReason,+ operationError: agentOperations.error,+ operationId: agentOperations.id,+ operationStatus: agentOperations.status,+ taskId: tasks.id,+ taskIdentifier: tasks.identifier,+ // Non-null by the guard below; the column is only nullable because a+ // legacy row could have been written without one.+ topicId: sql<string>`${taskTopics.topicId}`,+ trigger: taskTopics.trigger,+ userId: tasks.createdByUserId,+ workspaceId: tasks.workspaceId,+ })+ .from(taskTopics)+ // The run row names the operation it belongs to; a row without one cannot+ // be judged against an operation at all and is left alone.+ .innerJoin(agentOperations, eq(taskTopics.operationId, agentOperations.id))+ .innerJoin(tasks, eq(taskTopics.taskId, tasks.id))+ .where(+ and(+ eq(taskTopics.status, 'running'),+ // Only a Task that still believes it is running is repaired here.+ // One that left `running` was settled deliberately β by the user, or+ // by a cascade that already cancelled its run β and must not be+ // dragged back into a failure.+ eq(tasks.status, 'running'),+ isNotNull(taskTopics.operationId),+ // A run row with no topic cannot be driven through the lifecycle.+ isNotNull(taskTopics.topicId),+ // Sub-agent children extend their parent's turn and never own the+ // Task's run row, so only a top-level operation may settle it.+ isNull(agentOperations.parentOperationId),+ inArray(agentOperations.status, ORPHANED_RUN_OPERATION_STATUSES),+ sql`coalesce(${agentOperations.completedAt}, ${agentOperations.updatedAt}) < ${staleBefore}`,+ ),+ )+ .orderBy(sql`coalesce(${agentOperations.completedAt}, ${agentOperations.updatedAt})`)+ .limit(limit)+ );+ }+// ========== Dependencies ==========private depsOwnership = () =>diff --git a/packages/database/src/models/taskTopic.ts b/packages/database/src/models/taskTopic.tsindex 02272f2db61..c7e7f0af686 100644--- a/packages/database/src/models/taskTopic.ts+++ b/packages/database/src/models/taskTopic.ts@@ -8,7 +8,7 @@ import { topics } from '../schemas/topic';import type { LobeChatDatabase } from '../type';import { buildWorkspaceWhere } from '../utils/workspace';-const TERMINAL_TOPIC_STATUSES = new Set([+export const TERMINAL_TOPIC_STATUSES = new Set(['canceled','completed',DEVICE_OFFLINE_RUN_STATUS,@@ -52,7 +52,7 @@ export class TaskTopicModel {* stamp `topics.completedAt` so duration can be computed at read time, and* promote `topics.status` to 'completed' on a clean finish.*/- private async markTopicEnded(topicId: string, status: string): Promise<void> {+ async markTopicEnded(topicId: string, status: string): Promise<void> {const setClause: { completedAt: Date; status?: 'completed' } = { completedAt: new Date() };if (status === 'completed') setClause.status = 'completed';@@ -242,6 +242,69 @@ export class TaskTopicModel {return result.length;}+ /**+ * Flip one run out of `running` β but only while it is still that exact run.+ *+ * Unlike {@link updateStatus}, a miss is a real answer rather than a silent+ * no-op: a row a newer operation has already replaced, or one another writer+ * settled a moment ago, returns `false`. Only the run row is written; the+ * topic's end stamp is the caller's to commit alongside it β see+ * `TaskRunClaimRepo`.+ */+ async claimRunIfRunning(topicId: string, operationId: string, status: string): Promise<boolean> {+ const result = await this.db+ .update(taskTopics)+ .set({ status })+ .where(+ and(+ eq(taskTopics.topicId, topicId),+ eq(taskTopics.operationId, operationId),+ eq(taskTopics.status, 'running'),+ this.ownership(),+ ),+ )+ .returning({ topicId: taskTopics.topicId });++ return result.length > 0;+ }++ /**+ * Put a run claimed by {@link claimRunIfRunning} back to `running`.+ *+ * Keyed on the same operation as the claim, so a newer run that took the row+ * over in between is never reopened. Only the run row is written; clearing the+ * topic's end stamp is the caller's β see `TaskRunClaimRepo`.+ */+ async reopenRun(topicId: string, operationId: string, fromStatus: string): Promise<boolean> {+ const result = await this.db+ .update(taskTopics)+ .set({ status: 'running' })+ .where(+ and(+ eq(taskTopics.topicId, topicId),+ eq(taskTopics.operationId, operationId),+ eq(taskTopics.status, fromStatus),+ this.ownership(),+ ),+ )+ .returning({ topicId: taskTopics.topicId });++ return result.length > 0;+ }++ /** Undo {@link markTopicEnded}'s end stamp for a run that is live again. */+ async clearTopicEnded(topicId: string): Promise<void> {+ await this.db+ .update(topics)+ .set({ completedAt: null })+ .where(+ and(+ eq(topics.id, topicId),+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics),+ ),+ );+ }+async findByTopicId(topicId: string): Promise<TaskTopicItem | null> {const result = await this.db.select()diff --git a/packages/database/src/repositories/taskRunClaim/index.ts b/packages/database/src/repositories/taskRunClaim/index.tsnew file mode 100644index 00000000000..7e033ea8904--- /dev/null+++ b/packages/database/src/repositories/taskRunClaim/index.ts@@ -0,0 +1,48 @@+import { TaskTopicModel, TERMINAL_TOPIC_STATUSES } from '../../models/taskTopic';+import type { LobeChatDatabase } from '../../type';++/**+ * The orphaned-run reconciliation's claim on a Task run, as one unit of work.+ *+ * A claim moves the `task_topics` run row out of `running` and stamps the end+ * of the underlying topic. Those are two aggregates, so the pair commits here in+ * one transaction rather than inside {@link TaskTopicModel}: committed+ * separately, a failed stamp would leave the run terminal with the claimer never+ * learning it won, so nothing would hand it back β and the sweep only looks at+ * `running` rows, so that run could never be retried.+ */+export class TaskRunClaimRepo {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ ) {}++ private model = (db: LobeChatDatabase) => new TaskTopicModel(db, this.userId, this.workspaceId);++ /**+ * Claim one run while it is still `running` under `operationId`. Returns+ * `false` when a newer operation has replaced it or another writer already+ * settled it.+ */+ claim = async (topicId: string, operationId: string, status: string): Promise<boolean> =>+ this.db.transaction(async (tx) => {+ const model = this.model(tx as LobeChatDatabase);+ if (!(await model.claimRunIfRunning(topicId, operationId, status))) return false;+ if (TERMINAL_TOPIC_STATUSES.has(status)) await model.markTopicEnded(topicId, status);+ return true;+ });++ /**+ * Hand back a run claimed by {@link claim} whose settle failed, so the next+ * sweep retries it. Keyed on the same operation as the claim, so a newer run+ * that took the row over in between is never reopened.+ */+ release = async (topicId: string, operationId: string, fromStatus: string): Promise<boolean> =>+ this.db.transaction(async (tx) => {+ const model = this.model(tx as LobeChatDatabase);+ if (!(await model.reopenRun(topicId, operationId, fromStatus))) return false;+ await model.clearTopicEnded(topicId);+ return true;+ });+}