π€― 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: recover abandoned goal work safely (#18656)
Arvin Xuba7f1ee7ec69
diff --git a/apps/cli/src/commands/goal.ts b/apps/cli/src/commands/goal.tsindex 0d0012bf437..58c3b9e3ccb 100644--- a/apps/cli/src/commands/goal.ts+++ b/apps/cli/src/commands/goal.ts@@ -75,13 +75,17 @@ export function registerGoalCommand(program: Command) {.option('--max-cost <usd>', 'Maximum total cost in USD').option('--max-attempts-per-work <n>', 'Attempts per Work before opening a decision gate').option('--max-steps-per-run <n>', 'Optional agent step cap per Work run (for example 500)')+ .option(+ '--operation-lease-timeout-ms <n>',+ 'Reclaim a Work operation after this idle time (minimum: 60000)',+ ).option('--json [fields]', 'Output JSON').action(async (title: string, options) => {const client = await getTrpcClient();const result = await client.goal.create.mutate({agentId: options.agent,config:- options.maxAttemptsPerWork || options.maxStepsPerRun+ options.maxAttemptsPerWork || options.maxStepsPerRun || options.operationLeaseTimeoutMs? {recovery: {maxAttemptsPerWork: options.maxAttemptsPerWork@@ -90,6 +94,9 @@ export function registerGoalCommand(program: Command) {maxStepsPerRun: options.maxStepsPerRun? Number.parseInt(options.maxStepsPerRun, 10): undefined,+ operationLeaseTimeoutMs: options.operationLeaseTimeoutMs+ ? Number.parseInt(options.operationLeaseTimeoutMs, 10)+ : undefined,},}: undefined,diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.tsindex e01c84465b8..be520bc3443 100644--- a/apps/server/src/routers/lambda/goal.ts+++ b/apps/server/src/routers/lambda/goal.ts@@ -101,6 +101,7 @@ export const goalRouter = router({.object({maxAttemptsPerWork: z.number().int().positive().optional(),maxStepsPerRun: z.number().int().positive().nullable().optional(),+ operationLeaseTimeoutMs: z.number().int().min(60_000).optional(),}).optional(),})diff --git a/apps/server/src/services/agentDocuments/headlessEditor.test.ts b/apps/server/src/services/agentDocuments/headlessEditor.test.tsindex 86097d13336..4a39a8ce6ac 100644--- a/apps/server/src/services/agentDocuments/headlessEditor.test.ts+++ b/apps/server/src/services/agentDocuments/headlessEditor.test.ts@@ -38,6 +38,31 @@ describe('agent document headless editor', () => {expect(isValidEditorData(snapshot.editorData)).toBe(true);});+ it('should safely serialize concurrent headless document lifecycles', async () => {+ const sources = await Promise.all(+ Array.from({ length: 6 }, (_, index) =>+ createMarkdownEditorSnapshot(+ `# Report ${index}\n\n| Supplier | Price |\n| --- | --- |\n${`| Vendor ${index} | $${index} |\n`.repeat(40)}`,+ ),+ ),+ );++ const snapshots = await Promise.all(+ sources.map((source) =>+ exportEditorDataSnapshot({+ editorData: source.editorData,+ fallbackContent: source.content,+ litexml: true,+ }),+ ),+ );++ snapshots.forEach((snapshot, index) => {+ expect(snapshot.content).toContain(`Report ${index}`);+ expect(snapshot.litexml).toContain(`Vendor ${index}`);+ });+ });+it('should apply LiteXML operations and persist diff nodes for later human review', async () => {const initial = await exportEditorDataSnapshot({fallbackContent: 'Original',diff --git a/apps/server/src/services/agentDocuments/headlessEditor.ts b/apps/server/src/services/agentDocuments/headlessEditor.tsindex 607743e743f..f81c9025956 100644--- a/apps/server/src/services/agentDocuments/headlessEditor.ts+++ b/apps/server/src/services/agentDocuments/headlessEditor.ts@@ -1,5 +1,5 @@-/* eslint-disable @typescript-eslint/consistent-type-imports */import type { HeadlessLiteXMLOperation } from '@lobehub/editor/headless';+import { createHeadlessEditor } from '@lobehub/editor/headless';import type { SerializedEditorState, SerializedLexicalNode } from 'lexical';import { EMPTY_EDITOR_STATE } from '@/libs/editor/constants';@@ -103,8 +103,29 @@ interface LoadEditorStateParams {fallbackContent?: string;}+// @lobehub/editor's headless Lexical runtime keeps process-global node state while+// hydrating snapshots with stable ids. Concurrent document reads can therefore+// corrupt one another (or observe a partially initialized HeadlessEditor). Keep+// the complete create/hydrate/export/destroy lifecycle serialized.+let headlessEditorTail: Promise<void> = Promise.resolve();++const withHeadlessEditorLock = async <T>(run: () => Promise<T> | T): Promise<T> => {+ const previous = headlessEditorTail;+ let release: () => void = () => {};+ headlessEditorTail = new Promise<void>((resolve) => {+ release = resolve;+ });++ await previous;+ try {+ return await run();+ } finally {+ release();+ }+};+const exportSnapshot = (- editor: ReturnType<(typeof import('@lobehub/editor/headless'))['createHeadlessEditor']>,+ editor: ReturnType<typeof createHeadlessEditor>,litexml = false,): AgentDocumentEditorSnapshot => {const snapshot = editor.export({ litexml });@@ -117,7 +138,7 @@ const exportSnapshot = (};const hydrateMarkdownOrEmptyState = (- editor: ReturnType<(typeof import('@lobehub/editor/headless'))['createHeadlessEditor']>,+ editor: ReturnType<typeof createHeadlessEditor>,content: string,options?: { keepId?: boolean },) => {@@ -133,10 +154,10 @@ const hydrateMarkdownOrEmptyState = (};const createEditorWithState = (- createHeadlessEditor: (typeof import('@lobehub/editor/headless'))['createHeadlessEditor'],+ createEditor: typeof createHeadlessEditor,{ editorData, fallbackContent = '' }: LoadEditorStateParams,) => {- let editor = createHeadlessEditor();+ let editor = createEditor();if (isValidEditorData(editorData)) {try {@@ -159,7 +180,7 @@ const createEditorWithState = (// editor at an empty root. Recreate the editor before hydrating Markdown so// no partially parsed Lexical state can leak into the fallback snapshot.editor.destroy();- editor = createHeadlessEditor();+ editor = createEditor();}hydrateMarkdownOrEmptyState(editor, fallbackContent, { keepId: true });@@ -168,32 +189,32 @@ const createEditorWithState = (export const createMarkdownEditorSnapshot = async (content: string,-): Promise<AgentDocumentEditorSnapshot> => {- const { createHeadlessEditor } = await import('@lobehub/editor/headless');- const editor = createHeadlessEditor();+): Promise<AgentDocumentEditorSnapshot> =>+ withHeadlessEditorLock(() => {+ const editor = createHeadlessEditor();- try {- hydrateMarkdownOrEmptyState(editor, content);- return exportSnapshot(editor);- } finally {- editor.destroy();- }-};+ try {+ hydrateMarkdownOrEmptyState(editor, content);+ return exportSnapshot(editor);+ } finally {+ editor.destroy();+ }+ });export const exportEditorDataSnapshot = async (params: LoadEditorStateParams & { litexml?: boolean },-): Promise<AgentDocumentEditorSnapshot> => {- const { createHeadlessEditor } = await import('@lobehub/editor/headless');- const { editor, recoveredFromMarkdown } = createEditorWithState(createHeadlessEditor, params);+): Promise<AgentDocumentEditorSnapshot> =>+ withHeadlessEditorLock(() => {+ const { editor, recoveredFromMarkdown } = createEditorWithState(createHeadlessEditor, params);- try {- const snapshot = exportSnapshot(editor, params.litexml);+ try {+ const snapshot = exportSnapshot(editor, params.litexml);- return recoveredFromMarkdown ? { ...snapshot, recoveredFromMarkdown: true } : snapshot;- } finally {- editor.destroy();- }-};+ return recoveredFromMarkdown ? { ...snapshot, recoveredFromMarkdown: true } : snapshot;+ } finally {+ editor.destroy();+ }+ });export const applyLiteXMLOperations = async ({editorData,@@ -201,29 +222,29 @@ export const applyLiteXMLOperations = async ({operations,}: LoadEditorStateParams & {operations: AgentDocumentLiteXMLOperation[];-}): Promise<AgentDocumentEditSnapshot> => {- const { createHeadlessEditor } = await import('@lobehub/editor/headless');- const { editor } = createEditorWithState(createHeadlessEditor, { editorData, fallbackContent });+}): Promise<AgentDocumentEditSnapshot> =>+ withHeadlessEditorLock(async () => {+ const { editor } = createEditorWithState(createHeadlessEditor, { editorData, fallbackContent });- try {- const beforeSnapshot = exportSnapshot(editor, true);- await editor.applyLiteXML(orderLiteXMLOperations(operations).map(toHeadlessLiteXMLOperation));- const snapshot = exportSnapshot(editor, true);+ try {+ const beforeSnapshot = exportSnapshot(editor, true);+ await editor.applyLiteXML(orderLiteXMLOperations(operations).map(toHeadlessLiteXMLOperation));+ const snapshot = exportSnapshot(editor, true);- if (fallbackContent?.trim().length && snapshot.content.trim().length === 0) {- throw new Error('Agent document node edit unexpectedly produced empty content');- }+ if (fallbackContent?.trim().length && snapshot.content.trim().length === 0) {+ throw new Error('Agent document node edit unexpectedly produced empty content');+ }- if (- operations.length > 0 &&- JSON.stringify(snapshot.editorData) === JSON.stringify(beforeSnapshot.editorData) &&- snapshot.litexml === beforeSnapshot.litexml- ) {- throw new Error('Agent document node edit did not change the document');- }+ if (+ operations.length > 0 &&+ JSON.stringify(snapshot.editorData) === JSON.stringify(beforeSnapshot.editorData) &&+ snapshot.litexml === beforeSnapshot.litexml+ ) {+ throw new Error('Agent document node edit did not change the document');+ }- return { ...snapshot, previousEditorData: beforeSnapshot.editorData };- } finally {- editor.destroy();- }-};+ return { ...snapshot, previousEditorData: beforeSnapshot.editorData };+ } finally {+ editor.destroy();+ }+ });diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.tsindex a049be3f4d8..b2a38d9115d 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts@@ -690,6 +690,23 @@ describe('AgentRuntimeService', () => {mockCoordinator.getOperationMetadata.mockResolvedValue(mockMetadata);});+ it('acks a delayed delivery after the durable operation was abandoned', async () => {+ vi.spyOn((service as any).agentOperationModel, 'findById').mockResolvedValue({+ id: mockParams.operationId,+ status: 'abandoned',+ });++ const result = await service.executeStep(mockParams);++ expect(result).toEqual({+ nextStepScheduled: false,+ state: { status: 'interrupted' },+ stepResult: null,+ success: true,+ });+ expect(mockCoordinator.tryClaimStep).not.toHaveBeenCalled();+ });+it('should pass resolved contextWindowTokens into compressionConfig', async () => {vi.mocked(getModelPropertyWithFallback).mockResolvedValueOnce(200_000);diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex 4b16b55c42e..63dee1bbcc9 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -142,6 +142,7 @@ const STEP_ABORT_POLL_INTERVAL_MS = 2_000;/** Cap on the exponential backoff multiplier after consecutive poll failures. */const STEP_ABORT_POLL_MAX_BACKOFF = 8;const STEP_LOCK_HEARTBEAT_MS = 30_000;+const DURABLE_LEASE_HEARTBEAT_EVERY_TICKS = 3;const EVAL_TOOL_FORWARDING_HOOK_ID = 'eval-tool-forwarding';const toToolForwardingFailure = (error?: unknown): ToolRunResult => ({@@ -383,6 +384,7 @@ export interface AgentRuntimeServiceOptions {* ```*/export class AgentRuntimeService {+ private agentOperationModel: AgentOperationModel;private agentFactory?: (config: GeneralAgentConfig) => Agent;private completionLifecycle: CompletionLifecycle;private coordinator: AgentRuntimeCoordinator;@@ -442,6 +444,7 @@ export class AgentRuntimeService {this.userId = userId;this.workspaceId = options?.workspaceId;const workspaceId = this.workspaceId;+ this.agentOperationModel = new AgentOperationModel(db, this.userId, workspaceId);this.messageModel = new MessageModel(db, this.userId, workspaceId);this.completionLifecycle = new CompletionLifecycle(db, userId, workspaceId);this.humanIntervention = new HumanInterventionHandler(db, this.messageModel);@@ -463,10 +466,18 @@ export class AgentRuntimeService {stepIndex: number,ownerId: string,): () => void {+ let heartbeatTick = 0;const timer = setInterval(() => {- this.coordinator- .refreshStepLock(operationId, stepIndex, STEP_LOCK_TTL_SECONDS, ownerId)- .then((refreshed) => {+ heartbeatTick += 1;+ const refreshDurableLease = heartbeatTick % DURABLE_LEASE_HEARTBEAT_EVERY_TICKS === 0;++ Promise.all([+ this.coordinator.refreshStepLock(operationId, stepIndex, STEP_LOCK_TTL_SECONDS, ownerId),+ refreshDurableLease+ ? this.agentOperationModel.touchRunning(operationId)+ : Promise.resolve(true),+ ])+ .then(([refreshed, leaseRefreshed]) => {if (!refreshed) {log('[%s][%d] Step lock heartbeat did not refresh; ownership may have changed',@@ -474,6 +485,13 @@ export class AgentRuntimeService {stepIndex,);}+ if (!leaseRefreshed) {+ log(+ '[%s][%d] Durable operation lease was lost; terminal persistence will be rejected',+ operationId,+ stepIndex,+ );+ }}).catch((error) => {log('[%s][%d] Step lock heartbeat failed: %O', operationId, stepIndex, error);@@ -863,6 +881,40 @@ export class AgentRuntimeService {return this.handleGroupMemberTimeout(groupMemberTimeout);}+ // Redis keeps the resumable step state, but the durable operation row is+ // the authority for cancellation/recovery. A queued QStash delivery can+ // outlive a crashed process and arrive after Goal recovery has atomically+ // marked that operation interrupted. ACK it without touching the old+ // topic; otherwise the abandoned attempt can finish concurrently with its+ // replacement and submit a second Acceptance run.+ try {+ const durableOperation = await this.agentOperationModel.findById(operationId);+ if (+ durableOperation &&+ ['done', 'error', 'interrupted', 'abandoned'].includes(durableOperation.status)+ ) {+ log(+ '[%s][%d] Skipping delivery for terminal durable operation (%s)',+ operationId,+ stepIndex,+ durableOperation.status,+ );+ return {+ nextStepScheduled: false,+ state: {+ status:+ durableOperation.status === 'abandoned' ? 'interrupted' : durableOperation.status,+ },+ stepResult: null,+ success: true,+ };+ }+ } catch (error) {+ // Preserve runtime availability when the durable store has a transient+ // read failure. The step lock and normal persistence path still apply.+ log('[%s][%d] Durable operation status check failed: %O', operationId, stepIndex, error);+ }+// Watchdog re-check for a parked async-tool wait: re-run the barrier + CAS// without claiming the step lock or executing anything. Idempotent β the// CAS guarantees at most one real resume regardless of how many checks run.@@ -1014,6 +1066,9 @@ export class AgentRuntimeService {};}+ await this.agentOperationModel.touchRunning(operationId).catch((error) => {+ log('[%s][%d] Operation lease refresh failed: %O', operationId, stepIndex, error);+ });const stopStepLockHeartbeat = this.startStepLockHeartbeat(operationId,stepIndex,diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.tsindex 7211104ccbf..d4bda3f8e93 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts@@ -209,7 +209,11 @@ export class CompletionLifecycle {* outage must never block hook dispatch or the executor's terminal* cleanup path.*/- private async persistCompletion(operationId: string, state: any, reason: string): Promise<void> {+ private async persistCompletion(+ operationId: string,+ state: any,+ reason: string,+ ): Promise<boolean> {const completionReason: any =reason === 'max_steps' ||reason === 'cost_limit' ||@@ -255,7 +259,7 @@ export class CompletionLifecycle {};try {- await this.agentOperationModel.recordCompletion(operationId, {+ const accepted = await this.agentOperationModel.recordCompletion(operationId, {completedAt,completionReason,cost: state?.cost ?? null,@@ -286,6 +290,12 @@ export class CompletionLifecycle {// the scalar columns β the reporting surface β carry the whole tree.usage: state?.usage ?? null,});+ if (!accepted) {+ const operation = await this.agentOperationModel.findById(operationId);+ // Preserve the historical best-effort behavior when no durable start+ // row exists, but never let a conflicting terminal owner be replaced.+ if (operation) return false;+ }} catch (error) {log('[%s] Failed to persist operation completion (non-fatal): %O', operationId, error);}@@ -305,6 +315,8 @@ export class CompletionLifecycle {log('[%s] Failed to recompute topic usage rollup (non-fatal): %O', operationId, error);}}++ return true;}/** Best-effort child-usage rollup β a DB hiccup must not fail the completion write. */@@ -642,7 +654,11 @@ export class CompletionLifecycle {// Finalize the agent_operations row before user hooks fire so// downstream consumers see the row in its terminal shape.- await this.persistCompletion(operationId, state, reason);+ const completionAccepted = await this.persistCompletion(operationId, state, reason);+ if (completionAccepted === false) {+ log('[%s] Skipping hooks for an operation with a conflicting terminal owner', operationId);+ return;+ }if (isAsyncToolPark) return;diff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.tsindex 0e09d4c2977..4c1210e3c38 100644--- a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts@@ -548,6 +548,21 @@ describe('CompletionLifecycle.dispatchHooks β error persistence', () => {expect(persistCompletion).toHaveBeenCalledBefore(dispatch);});++ it('does not dispatch hooks when another owner already interrupted the operation', async () => {+ const lifecycle = buildLifecycle();+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(false);+ const dispatch = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(() => {});++ await lifecycle.dispatchHooks(+ 'op-reclaimed',+ { metadata: { _hooks: [] }, status: 'done' },+ 'done',+ );++ expect(dispatch).not.toHaveBeenCalled();+ });});describe('CompletionLifecycle.dispatchHooks β verify plan race', () => {diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.tsindex f2171a5519c..4e06f509a66 100644--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts@@ -656,17 +656,26 @@ describe('AgentRuntimeService.executeStep - step idempotency (distributed lock)'vi.useFakeTimers();const service = createService();const coordinator = (service as any).coordinator;+ const touchRunning = vi+ .spyOn((service as any).agentOperationModel, 'touchRunning')+ .mockResolvedValue(true);try {const stopHeartbeat = (service as any).startStepLockHeartbeat('op-heartbeat', 7, 'owner-1');await vi.advanceTimersByTimeAsync(30_000);expect(coordinator.refreshStepLock).toHaveBeenCalledWith('op-heartbeat', 7, 120, 'owner-1');+ expect(touchRunning).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(60_000);++ expect(coordinator.refreshStepLock).toHaveBeenCalledTimes(3);+ expect(touchRunning).toHaveBeenCalledTimes(1);stopHeartbeat();await vi.advanceTimersByTimeAsync(30_000);- expect(coordinator.refreshStepLock).toHaveBeenCalledTimes(1);+ expect(coordinator.refreshStepLock).toHaveBeenCalledTimes(3);} finally {vi.useRealTimers();}diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.tsindex 0367c0400ef..5151bdab33b 100644--- a/apps/server/src/services/goal/index.test.ts+++ b/apps/server/src/services/goal/index.test.ts@@ -1,11 +1,15 @@// @vitest-environment node+import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { getTestDB } from '@/database/core/getTestDB';import { AcceptanceModel } from '@/database/models/acceptance';+import { AgentOperationModel } from '@/database/models/agentOperation';import { TaskModel } from '@/database/models/task';+import { TaskTopicModel } from '@/database/models/taskTopic';import {acceptances,+ agentOperations,agents,goalEdges,goalEvents,@@ -28,6 +32,7 @@ beforeEach(async () => {});afterEach(async () => {+ vi.restoreAllMocks();// PGlite does not consistently order the nested user -> goal -> graph// cascades, so clear graph leaves explicitly before their owned roots.await serverDB.delete(goalNodeDecisions);@@ -36,6 +41,7 @@ afterEach(async () => {await serverDB.delete(goalNodes);await serverDB.delete(goals);await serverDB.delete(acceptances);+ await serverDB.delete(agentOperations);await serverDB.delete(tasks);await serverDB.delete(agents);await serverDB.delete(users);@@ -286,6 +292,155 @@ describe('GoalService', () => {expect((await service.graph(graph.goal.id)).decisions).toHaveLength(0);});+ it('reclaims a stale running Work operation and starts the next attempt', async () => {+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({+ agentId: 'agent-recovery',+ assistantMessageId: 'message-assistant',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'started',+ operationId: 'op-recovery',+ status: 'running',+ success: true,+ taskId: 'placeholder',+ taskIdentifier: 'T-recovery',+ timestamp: new Date().toISOString(),+ topicId: 'topic-recovery',+ userMessageId: 'message-user',+ });+ vi.spyOn(TaskTopicModel.prototype, 'findRunningByTaskIds').mockResolvedValue([+ { operationId: 'op-stale', topicId: 'topic-stale' } as never,+ ]);+ const timeoutSpy = vi+ .spyOn(TaskTopicModel.prototype, 'updateStatus')+ .mockResolvedValue(undefined);+ const settleSpy = vi+ .spyOn(AgentOperationModel.prototype, 'settleStaleRunning')+ .mockResolvedValue(true);++ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: {+ recovery: { maxAttemptsPerWork: 3, operationLeaseTimeoutMs: 60_000 },+ },+ title: 'Recover interrupted work',+ work: ['Run a durable experiment'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.update(created.taskId!, { totalTopics: 1 });+ await taskModel.updateStatus(created.taskId!, 'running');++ const recovered = await service.tick(graph.goal.id);++ expect(settleSpy).toHaveBeenCalledWith('op-stale', expect.any(Date));+ expect(timeoutSpy).toHaveBeenCalledWith(created.taskId, 'topic-stale', 'timeout');+ expect(runSpy).toHaveBeenCalledWith({+ maxSteps: undefined,+ taskId: created.taskId,+ trigger: 'goal',+ });+ expect(recovered).toMatchObject({+ message: expect.stringContaining('Recovered abandoned task'),+ outcome: 'waiting_external',+ taskId: created.taskId,+ });+ });++ it('does not reclaim a running Work operation without a persisted topic id', async () => {+ vi.spyOn(TaskTopicModel.prototype, 'findRunningByTaskIds').mockResolvedValue([+ { operationId: 'op-without-topic', topicId: null } as never,+ ]);+ const settleSpy = vi.spyOn(AgentOperationModel.prototype, 'settleStaleRunning');++ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { operationLeaseTimeoutMs: 60_000 } },+ title: 'Wait for topic persistence',+ work: ['Run a durable experiment'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'running');++ const waiting = await service.tick(graph.goal.id);++ expect(settleSpy).not.toHaveBeenCalled();+ expect(waiting).toMatchObject({+ message: expect.stringContaining('is running'),+ outcome: 'waiting_external',+ taskId: created.taskId,+ });+ });++ it('rolls back the operation reclaim when recovery bookkeeping fails', async () => {+ vi.spyOn(TaskTopicModel.prototype, 'findRunningByTaskIds').mockResolvedValue([+ { operationId: 'op-atomic-recovery', topicId: 'topic-stale' } as never,+ ]);+ vi.spyOn(TaskTopicModel.prototype, 'updateStatus').mockRejectedValueOnce(+ new Error('topic update failed'),+ );++ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const operationModel = new AgentOperationModel(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { operationLeaseTimeoutMs: 60_000 } },+ title: 'Atomic abandoned recovery',+ work: ['Run a durable experiment'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'running');+ await operationModel.recordStart({ operationId: 'op-atomic-recovery' });+ await serverDB+ .update(agentOperations)+ .set({ updatedAt: new Date('2026-01-01T00:00:00.000Z') })+ .where(eq(agentOperations.id, 'op-atomic-recovery'));++ await expect(service.tick(graph.goal.id)).rejects.toThrow('topic update failed');++ expect((await operationModel.findById('op-atomic-recovery'))?.status).toBe('running');+ expect((await taskModel.findById(created.taskId!))?.status).toBe('running');+ });++ it('resumes automatic recovery after the atomic bookkeeping transaction committed', async () => {+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({+ agentId: 'agent-recovery',+ assistantMessageId: 'message-assistant',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'started',+ operationId: 'op-recovery-next',+ status: 'running',+ success: true,+ taskId: 'placeholder',+ taskIdentifier: 'T-recovery',+ timestamp: new Date().toISOString(),+ topicId: 'topic-recovery-next',+ userMessageId: 'message-user',+ });+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { maxAttemptsPerWork: 3 } },+ title: 'Resume abandoned recovery',+ work: ['Run a durable experiment'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.update(created.taskId!, { totalTopics: 1 });+ await taskModel.updateStatus(created.taskId!, 'paused', {+ error: 'Goal Work operation lease expired.',+ });++ const recovered = await service.tick(graph.goal.id);++ expect(runSpy).toHaveBeenCalledOnce();+ expect(recovered).toMatchObject({+ message: expect.stringContaining('Recovered abandoned task'),+ outcome: 'waiting_external',+ });+ });+it('opens the decision gate only after the Work attempt budget is exhausted', async () => {const service = new GoalService(serverDB, userId);const taskModel = new TaskModel(serverDB, userId);diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.tsindex 26a87daeef5..c2a33e75859 100644--- a/apps/server/src/services/goal/index.ts+++ b/apps/server/src/services/goal/index.ts@@ -10,6 +10,7 @@ import type {} from '@lobechat/types';import { TRPCError } from '@trpc/server';+import { AgentOperationModel } from '@/database/models/agentOperation';import { GoalModel } from '@/database/models/goal';import { GoalGraphModel } from '@/database/models/goalGraph';import { ProjectModel } from '@/database/models/project';@@ -22,7 +23,7 @@ import { assertAgentUsableBy } from '@/database/utils/agent-access';import { TaskService } from '../task';import { TaskRunnerService } from '../taskRunner';import { AcceptanceService } from '../verify/acceptanceService';-import { resolveWorkMaxSteps } from './recoveryPolicy';+import { resolveOperationLeaseTimeout, resolveWorkMaxSteps } from './recoveryPolicy';import { WorkRecoveryCoordinator } from './workRecoveryCoordinator';const WORK_NODE_CLAIM_TTL_MS = 5 * 60 * 1000;@@ -414,6 +415,9 @@ export class GoalService {task.status === 'canceled' ||(task.status === 'paused' && task.error)) {+ if (task.status === 'paused' && task.error === 'Goal Work operation lease expired.') {+ return this.resumeAbandonedWorkRecovery(graph, frontier.id, task);+ }if (task.status === 'paused' && task.error === 'Delivery did not pass verification.') {const taskIds = graph.nodes.flatMap((node) => (node.taskId ? [node.taskId] : []));const runs = await this.taskTopicModel.findWithHandoffByTaskIds(taskIds, 10_000);@@ -464,6 +468,10 @@ export class GoalService {};}if (task.status === 'running' || task.status === 'scheduled') {+ if (task.status === 'running') {+ const recovered = await this.recoverAbandonedWork(graph, frontier.id, task);+ if (recovered) return recovered;+ }return {goalId,message: `Task ${task.identifier} is ${task.status}`,@@ -526,6 +534,76 @@ export class GoalService {}};+ private recoverAbandonedWork = async (+ graph: GoalGraphSnapshot,+ nodeId: string,+ task: TaskItem,+ ): Promise<GoalTickResult | undefined> => {+ const [runningTopic] = await this.taskTopicModel.findRunningByTaskIds([task.id]);+ const operationId = runningTopic?.operationId;+ const topicId = runningTopic?.topicId;+ if (!operationId || !topicId) return undefined;++ const staleBefore = new Date(Date.now() - resolveOperationLeaseTimeout(graph.goal));+ const reclaimed = await this.db.transaction(async (tx) => {+ const settled = await new AgentOperationModel(+ tx,+ this.userId,+ this.workspaceId,+ ).settleStaleRunning(operationId, staleBefore);+ if (!settled) return false;++ await new TaskTopicModel(tx, this.userId, this.workspaceId).updateStatus(+ task.id,+ topicId,+ 'timeout',+ );+ await new TaskModel(tx, this.userId, this.workspaceId).updateStatus(task.id, 'paused', {+ error: 'Goal Work operation lease expired.',+ });+ return true;+ });+ if (!reclaimed) return undefined;++ return this.resumeAbandonedWorkRecovery(graph, nodeId, task);+ };++ private resumeAbandonedWorkRecovery = async (+ graph: GoalGraphSnapshot,+ nodeId: string,+ task: TaskItem,+ ): Promise<GoalTickResult> => {+ const recovery = await new WorkRecoveryCoordinator(+ this.db,+ this.userId,+ this.workspaceId,+ ).recover({ goal: graph.goal, task, taskCarried: false });+ if (recovery === 'continued') {+ await this.graphModel.updateNodeStatus(+ graph.goal.id,+ nodeId,+ 'active',+ 'Recovered an abandoned Work operation and started the next attempt',+ );+ await this.goalModel.updateStatus(graph.goal.id, 'running');+ return {+ goalId: graph.goal.id,+ message: `Recovered abandoned task ${task.identifier}`,+ nodeId,+ outcome: 'waiting_external',+ taskId: task.id,+ };+ }++ const reason =+ recovery === 'exhausted-cost'+ ? 'Goal cost budget was exhausted after an operation was abandoned'+ : recovery === 'exhausted-rounds'+ ? 'Work attempt budget was exhausted after an operation was abandoned'+ : 'Automatic recovery could not restart an abandoned operation';+ return this.openFailureDecision(graph, nodeId, task.id, reason);+ };+private buildWorkInstruction = (graph: GoalGraphSnapshot,title: string,diff --git a/apps/server/src/services/goal/recoveryPolicy.test.ts b/apps/server/src/services/goal/recoveryPolicy.test.tsnew file mode 100644index 00000000000..559be6c5f85--- /dev/null+++ b/apps/server/src/services/goal/recoveryPolicy.test.ts@@ -0,0 +1,14 @@+import type { GoalItem } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { MIN_OPERATION_LEASE_TIMEOUT_MS, resolveOperationLeaseTimeout } from './recoveryPolicy';++describe('resolveOperationLeaseTimeout', () => {+ it('does not allow a lease shorter than two durable heartbeat intervals', () => {+ const goal = {+ config: { recovery: { operationLeaseTimeoutMs: 10_000 } },+ } as GoalItem;++ expect(resolveOperationLeaseTimeout(goal)).toBe(MIN_OPERATION_LEASE_TIMEOUT_MS);+ });+});diff --git a/apps/server/src/services/goal/recoveryPolicy.ts b/apps/server/src/services/goal/recoveryPolicy.tsindex 2c73d41ba32..42254b10a7b 100644--- a/apps/server/src/services/goal/recoveryPolicy.ts+++ b/apps/server/src/services/goal/recoveryPolicy.ts@@ -3,6 +3,11 @@ import type { GoalItem } from '@lobechat/types';import { resolveGoalRoundBudget } from '@/server/services/verify/goalBudget';const DEFAULT_MAX_ATTEMPTS_PER_WORK = 3;+const DEFAULT_OPERATION_LEASE_TIMEOUT_MS = 5 * 60 * 1000;+// Agent runtime refreshes the durable operation lease every third 30-second+// step-lock heartbeat. Keep the timeout above two durable heartbeat intervals+// so a transient missed write cannot reclaim a healthy operation.+export const MIN_OPERATION_LEASE_TIMEOUT_MS = 3 * 60 * 1000;export const resolveWorkAttemptBudget = (goal: GoalItem, taskCarried: boolean): number => {const configured = goal.config?.recovery?.maxAttemptsPerWork;@@ -14,3 +19,10 @@ export const resolveWorkMaxSteps = (goal: GoalItem): number | undefined => {const configured = goal.config?.recovery?.maxStepsPerRun;return typeof configured === 'number' && configured > 0 ? configured : undefined;};++export const resolveOperationLeaseTimeout = (goal: GoalItem): number => {+ const configured = goal.config?.recovery?.operationLeaseTimeoutMs;+ return typeof configured === 'number' && configured > 0+ ? Math.max(configured, MIN_OPERATION_LEASE_TIMEOUT_MS)+ : DEFAULT_OPERATION_LEASE_TIMEOUT_MS;+};diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.tsindex 40cc496b344..5a422119ee0 100644--- a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts+++ b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts@@ -64,6 +64,8 @@ const createFakePersistenceHandler = () => {return handler as unknown as HeterogeneousPersistenceHandler & typeof handler;};+const createFakeAgentOperationModel = () => ({ touchRunning: vi.fn(async () => true) });+const buildEvent = (type: AgentStreamEvent['type'],stepIndex: number,@@ -81,6 +83,7 @@ const createService = () => {const { manager, published } = createFakeStreamManager();const persistenceHandler = createFakePersistenceHandler();+ const agentOperationModel = createFakeAgentOperationModel();const topicModel = {settleRunningOperation: vi.fn(async (_topicId: string, operationId: string): Promise<any> => ({assistantMessageId: 'asst-1',@@ -89,11 +92,12 @@ const createService = (})),};const service = new HeterogeneousAgentService({} as any, 'user-test', {+ agentOperationModel: agentOperationModel as any,persistenceHandler,streamEventManager: overrides.streamEventManager ?? manager,topicModel: topicModel as any,});- return { manager, persistenceHandler, published, service, topicModel };+ return { agentOperationModel, manager, persistenceHandler, published, service, topicModel };};describe('HeterogeneousAgentService', () => {@@ -140,6 +144,35 @@ describe('HeterogeneousAgentService', () => {});describe('heteroIngest', () => {+ it('refreshes the durable operation lease before accepting a batch', async () => {+ const { agentOperationModel, persistenceHandler, service } = createService();++ await service.heteroIngest({+ agentType: 'codex',+ events: [buildEvent('stream_chunk', 0)],+ operationId: 'op-1',+ topicId: 'topic-1',+ });++ expect(agentOperationModel.touchRunning).toHaveBeenCalledWith('op-1');+ expect(persistenceHandler.ingest).toHaveBeenCalledOnce();+ });++ it('ignores delayed batches after the operation lost its lease', async () => {+ const { agentOperationModel, manager, persistenceHandler, service } = createService();+ agentOperationModel.touchRunning.mockResolvedValue(false);++ await service.heteroIngest({+ agentType: 'claude-code',+ events: [buildEvent('stream_chunk', 0)],+ operationId: 'op-reclaimed',+ topicId: 'topic-1',+ });++ expect(persistenceHandler.ingest).not.toHaveBeenCalled();+ expect(manager.publishStreamEvent).not.toHaveBeenCalled();+ });+it('republishes every event through the stream manager preserving ordering', async () => {const { manager, published, service } = createService();@@ -199,6 +232,7 @@ describe('HeterogeneousAgentService', () => {};const persistenceHandler = createFakePersistenceHandler();const service = new HeterogeneousAgentService({} as any, 'user-test', {+ agentOperationModel: createFakeAgentOperationModel() as any,persistenceHandler,streamEventManager: manager as IStreamEventManager,});@@ -269,6 +303,7 @@ describe('HeterogeneousAgentService', () => {};const persistenceHandler = createFakePersistenceHandler();const service = new HeterogeneousAgentService({} as any, 'user-test', {+ agentOperationModel: createFakeAgentOperationModel() as any,persistenceHandler,streamEventManager: manager as IStreamEventManager,});@@ -325,6 +360,7 @@ describe('HeterogeneousAgentService', () => {markEventPublished: vi.fn(),} as unknown as HeterogeneousPersistenceHandler;const service = new HeterogeneousAgentService({} as any, 'user-test', {+ agentOperationModel: createFakeAgentOperationModel() as any,persistenceHandler,streamEventManager: manager as IStreamEventManager,});@@ -350,6 +386,7 @@ describe('HeterogeneousAgentService', () => {}),} as unknown as HeterogeneousPersistenceHandler;const service = new HeterogeneousAgentService({} as any, 'user-test', {+ agentOperationModel: createFakeAgentOperationModel() as any,persistenceHandler,streamEventManager: manager as IStreamEventManager,});@@ -376,6 +413,7 @@ describe('HeterogeneousAgentService', () => {}),} as unknown as HeterogeneousPersistenceHandler;const service = new HeterogeneousAgentService({} as any, 'user-test', {+ agentOperationModel: createFakeAgentOperationModel() as any,persistenceHandler,streamEventManager: manager as IStreamEventManager,});diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.tsindex 6afed1caa1b..1a05bda60d4 100644--- a/apps/server/src/services/heterogeneousAgent/index.ts+++ b/apps/server/src/services/heterogeneousAgent/index.ts@@ -100,6 +100,8 @@ export const normalizeHeterogeneousFinishError = (};export interface HeterogeneousAgentServiceOptions {+ /** Inject a pre-built operation model (used by tests). */+ agentOperationModel?: AgentOperationModel;/** Inject a pre-built persistence handler (used by tests). */persistenceHandler?: HeterogeneousPersistenceHandler;/** Inject a snapshot store (used by tests); defaults to the env-resolved store. */@@ -128,6 +130,7 @@ export interface HeterogeneousAgentServiceOptions {* `topic.metadata.heterogeneousSessions`.*/export class HeterogeneousAgentService {+ private readonly agentOperationModel: AgentOperationModel;private readonly db: LobeChatDatabase;private readonly messageModel: MessageModel;private readonly persistenceHandler: HeterogeneousPersistenceHandler;@@ -146,6 +149,8 @@ export class HeterogeneousAgentService {this.userId = userId;const workspaceId = options.workspaceId;this.workspaceId = workspaceId;+ this.agentOperationModel =+ options.agentOperationModel ?? new AgentOperationModel(db, userId, workspaceId);this.messageModel = new MessageModel(db, userId, workspaceId);this.streamEventManager = options.streamEventManager ?? createStreamEventManager();this.topicModel = options.topicModel ?? new TopicModel(db, userId, workspaceId);@@ -173,6 +178,12 @@ export class HeterogeneousAgentService {events.length,);+ const leaseRefreshed = await this.agentOperationModel.touchRunning(operationId);+ if (!leaseRefreshed) {+ log('heteroIngest: ignore terminal or missing operation op=%s', operationId);+ return;+ }+// Persist FIRST, then publish β the renderer's gateway handler triggers// `fetchAndReplaceMessages` on stream_start / tool_end / step_complete,// so DB must already reflect the latest writes when the WS event lands.diff --git a/apps/server/src/services/workRegistration/registerWorksForOperation.ts b/apps/server/src/services/workRegistration/registerWorksForOperation.tsindex 0e4363dd76c..00386c99429 100644--- a/apps/server/src/services/workRegistration/registerWorksForOperation.ts+++ b/apps/server/src/services/workRegistration/registerWorksForOperation.ts@@ -1,6 +1,5 @@import { createHash } from 'node:crypto';-import { isParkedStatus } from '@lobechat/agent-runtime';import { SkillsIdentifier } from '@lobechat/builtin-tool-skills';import {classifyEditedFile,@@ -314,7 +313,7 @@ export const registerWorksForOperation = async (// scan, so the parent will never scan again and the repair's edits would be// lost. Distinguish by the parent's status:// - parent still active (idle / running / parked β waiting_for_human or- // waiting_for_async_tool, per isParkedStatus) β it will scan the whole+ // waiting_for_async_tool) β it will scan the whole// subtree on its own completion, so no-op here to avoid the duplicate.// - parent already terminal (done / error / interrupted) β register this// op's OWN edits (a legitimately new version for the repair), scanning@@ -327,7 +326,8 @@ export const registerWorksForOperation = async (!parentStatus ||parentStatus === 'idle' ||parentStatus === 'running' ||- isParkedStatus(parentStatus);+ parentStatus === 'waiting_for_human' ||+ parentStatus === 'waiting_for_async_tool';if (parentActive) {log('[%s] Skipping file Work registration: parent operation is still active (%s)',diff --git a/packages/database/src/models/__tests__/agentOperation.test.ts b/packages/database/src/models/__tests__/agentOperation.test.tsindex cfdf1456167..d6291020303 100644--- a/packages/database/src/models/__tests__/agentOperation.test.ts+++ b/packages/database/src/models/__tests__/agentOperation.test.ts@@ -210,6 +210,61 @@ describe('AgentOperationModel', () => {});});+ describe('operation lease', () => {+ it('refreshes a running operation and only settles an expired lease', async () => {+ const model = new AgentOperationModel(serverDB, userId);+ const operationId = 'op-lease';+ await model.recordStart({ operationId });+ await serverDB+ .update(agentOperations)+ .set({ updatedAt: new Date('2026-01-01T00:00:00.000Z') })+ .where(eq(agentOperations.id, operationId));++ await model.touchRunning(operationId);+ const refreshed = await model.findById(operationId);+ expect(refreshed!.updatedAt.getTime()).toBeGreaterThan(+ new Date('2026-01-01T00:00:00.000Z').getTime(),+ );++ expect(await model.settleStaleRunning(operationId, new Date(Date.now() - 60_000))).toBe(+ false,+ );+ expect((await model.findById(operationId))?.status).toBe('running');++ await serverDB+ .update(agentOperations)+ .set({ updatedAt: new Date('2026-01-01T00:00:00.000Z') })+ .where(eq(agentOperations.id, operationId));+ expect(await model.settleStaleRunning(operationId, new Date(Date.now() - 60_000))).toBe(true);+ expect(await model.findById(operationId)).toMatchObject({+ completionReason: 'lease_expired',+ status: 'abandoned',+ });+ });++ it('does not let a late completion overwrite a reclaimed operation', async () => {+ const model = new AgentOperationModel(serverDB, userId);+ const operationId = 'op-reclaimed-completion-race';+ await model.recordStart({ operationId });+ await serverDB+ .update(agentOperations)+ .set({ updatedAt: new Date('2026-01-01T00:00:00.000Z') })+ .where(eq(agentOperations.id, operationId));++ expect(await model.settleStaleRunning(operationId, new Date(Date.now() - 60_000))).toBe(true);+ expect(+ await model.recordCompletion(operationId, {+ completionReason: 'done',+ status: 'done',+ }),+ ).toBe(false);+ expect(await model.findById(operationId)).toMatchObject({+ completionReason: 'lease_expired',+ status: 'abandoned',+ });+ });+ });+describe('sumChildUsage', () => {const seedChild = async (model: AgentOperationModel,diff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.tsindex 303310e51cd..1f1658699c4 100644--- a/packages/database/src/models/agentOperation.ts+++ b/packages/database/src/models/agentOperation.ts@@ -1,4 +1,8 @@-import type { VerifyRunStatus } from '@lobechat/types';+import type {+ AgentOperationCompletionReason,+ AgentOperationStatus,+ VerifyRunStatus,+} from '@lobechat/types';import { and, eq, gte, inArray, isNotNull, or, sql } from 'drizzle-orm';import { today } from '@/utils/time';@@ -55,14 +59,7 @@ export interface ChildUsageRollup {export interface RecordOperationCompletionParams {completedAt?: Date;- completionReason?:- | 'done'- | 'error'- | 'interrupted'- | 'max_steps'- | 'cost_limit'- | 'waiting_for_human'- | 'waiting_for_async_tool';+ completionReason?: AgentOperationCompletionReason;cost?: Record<string, unknown> | null;error?: AgentOperationError | null;interruption?: AgentOperationInterruption | null;@@ -74,8 +71,7 @@ export interface RecordOperationCompletionParams {processingTimeMs?: number | null;/** Backfill the executed provider β see {@link RecordOperationCompletionParams.model}. */provider?: string | null;- status:- 'running' | 'waiting_for_human' | 'waiting_for_async_tool' | 'done' | 'error' | 'interrupted';+ status: Exclude<AgentOperationStatus, 'idle'>;stepCount?: number | null;toolCalls?: number | null;totalCost?: number | null;@@ -163,7 +159,7 @@ export class AgentOperationModel {async recordCompletion(operationId: string,params: RecordOperationCompletionParams,- ): Promise<void> {+ ): Promise<boolean> {const updates: Partial<NewAgentOperation> = {completionReason: params.completionReason,status: params.status,@@ -190,10 +186,26 @@ export class AgentOperationModel {if (params.interruption !== undefined) updates.interruption = params.interruption;if (params.traceS3Key !== undefined) updates.traceS3Key = params.traceS3Key;- await this.db+ const [row] = await this.db.update(agentOperations).set(updates)- .where(and(eq(agentOperations.id, operationId), this.ownership()));+ .where(+ and(+ eq(agentOperations.id, operationId),+ or(+ inArray(agentOperations.status, [+ 'running',+ 'waiting_for_human',+ 'waiting_for_async_tool',+ ]),+ eq(agentOperations.status, params.status),+ ),+ this.ownership(),+ ),+ )+ .returning({ id: agentOperations.id });++ return Boolean(row);}/** Idempotently settle a running operation without rewriting an existing terminal outcome. */@@ -219,6 +231,48 @@ export class AgentOperationModel {return Boolean(row);}+ /** Refresh the durable liveness lease while an operation owns an execution step. */+ async touchRunning(operationId: string): Promise<boolean> {+ const [row] = await this.db+ .update(agentOperations)+ .set({ updatedAt: new Date() })+ .where(+ and(+ eq(agentOperations.id, operationId),+ eq(agentOperations.status, 'running'),+ this.ownership(),+ ),+ )+ .returning({ id: agentOperations.id });++ return Boolean(row);+ }++ /**+ * Atomically retire an operation whose liveness lease has expired. A concurrent+ * heartbeat wins by moving updatedAt past staleBefore, preventing false recovery.+ */+ async settleStaleRunning(operationId: string, staleBefore: Date): Promise<boolean> {+ const [row] = await this.db+ .update(agentOperations)+ .set({+ completedAt: new Date(),+ completionReason: 'lease_expired',+ status: 'abandoned',+ })+ .where(+ and(+ eq(agentOperations.id, operationId),+ eq(agentOperations.status, 'running'),+ sql`${agentOperations.updatedAt} < ${staleBefore}`,+ this.ownership(),+ ),+ )+ .returning({ id: agentOperations.id });++ return Boolean(row);+ }+/*** Sum the terminal usage of every child operation forked from `parentOperationId`* (`callSubAgent` children, isolated group members).diff --git a/packages/database/src/schemas/agentOperations.ts b/packages/database/src/schemas/agentOperations.tsindex 0e780c872f3..fa2f6555a46 100644--- a/packages/database/src/schemas/agentOperations.ts+++ b/packages/database/src/schemas/agentOperations.ts@@ -1,5 +1,9 @@import { verifyRunStatuses } from '@lobechat/const/verify';-import type { VerifyCheckItem } from '@lobechat/types';+import type {+ AgentOperationCompletionReason,+ AgentOperationStatus,+ VerifyCheckItem,+} from '@lobechat/types';import { boolean, index, integer, jsonb, pgTable, text } from 'drizzle-orm/pg-core';import { amountNumeric, timestamps, timestamptz } from './_helpers';@@ -9,26 +13,6 @@ import { tasks } from './task';import { threads, topics } from './topic';import { workspaces } from './workspace';-const operationStatuses = [- 'idle',- 'running',- 'waiting_for_human',- 'waiting_for_async_tool',- 'done',- 'error',- 'interrupted',-] as const;--const completionReasons = [- 'done',- 'error',- 'interrupted',- 'max_steps',- 'cost_limit',- 'waiting_for_human',- 'waiting_for_async_tool',-] as const;-export interface AgentOperationInterruption {canResume: boolean;interruptedAt: string;@@ -74,8 +58,8 @@ export const agentOperations = pgTable(parentOperationId: text('parent_operation_id'),// ---- Lifecycle ----- status: text('status', { enum: operationStatuses }).notNull(),- completionReason: text('completion_reason', { enum: completionReasons }),+ status: text('status').$type<AgentOperationStatus>().notNull(),+ completionReason: text('completion_reason').$type<AgentOperationCompletionReason>(),// ---- Verify (delivery checker) β DEPRECATED, moved to verify_runs ----// The plan snapshot + rollup status now live on `verify_runs` (the sessiondiff --git a/packages/types/src/agentOperation.ts b/packages/types/src/agentOperation.tsnew file mode 100644index 00000000000..2ac693f326e--- /dev/null+++ b/packages/types/src/agentOperation.ts@@ -0,0 +1,19 @@+export type AgentOperationStatus =+ | 'abandoned'+ | 'done'+ | 'error'+ | 'idle'+ | 'interrupted'+ | 'running'+ | 'waiting_for_async_tool'+ | 'waiting_for_human';++export type AgentOperationCompletionReason =+ | 'cost_limit'+ | 'done'+ | 'error'+ | 'interrupted'+ | 'lease_expired'+ | 'max_steps'+ | 'waiting_for_async_tool'+ | 'waiting_for_human';diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.tsindex 1fa74d820f1..2f14766a294 100644--- a/packages/types/src/goal.ts+++ b/packages/types/src/goal.ts@@ -27,6 +27,8 @@ export interface GoalRecoveryPolicy {maxAttemptsPerWork?: number;/** Per-operation agent step limit. Null/undefined leaves the runtime uncapped. */maxStepsPerRun?: number | null;+ /** Time without a durable runtime lease refresh before a running Work is reclaimed. */+ operationLeaseTimeoutMs?: number;}export interface GoalConfig {diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex e62fe2fa6f6..567ed76f78f 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -2,6 +2,7 @@ export * from './agent';export * from './agentExecution';export * from './agentGroup';export * from './agentHook';+export * from './agentOperation';export * from './aiChat';export * from './aiProvider';export * from './apiKey';