π€― 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(agent-runtime): settle operations whose first step fails to dispatch (#22872)
Mocha580c3e82097e
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.deferredInit.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.deferredInit.test.tsindex 7829ff15f34..dfc20fe078e 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.deferredInit.test.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.deferredInit.test.ts@@ -6,6 +6,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { hookDispatcher } from '../../hooks';import { type AgentExecutionParams } from '../../types';import { AgentRuntimeService } from '..';+import { DurableStatusUnavailableError } from '../executionErrors';+import { stubRunningDurableOperation } from './testUtils';vi.mock('@lobechat/model-runtime', (...args) =>import('./testUtils').then((m) =>@@ -146,6 +148,7 @@ describe('AgentRuntimeService executeStep', () => {beforeEach(() => {vi.clearAllMocks();+ stubRunningDurableOperation();process.env.AGENT_RUNTIME_BASE_URL = 'http://localhost:3010';});@@ -417,6 +420,29 @@ describe('AgentRuntimeService executeStep', () => {});});+ it('leaves the run for a queue retry when the durable row cannot be read after init', async () => {+ const runDeferredInit = vi.fn().mockResolvedValue({+ context: { phase: 'user_input', payload: {} },+ state: { operationToolSet: { enabledToolIds: ['lobe-web-browsing'] } },+ });+ const svc = buildService(runDeferredInit);+ const { coordinator, step } = wireStep(svc);+ coordinator.isInterrupted.mockResolvedValue(false);+ vi.spyOn((svc as any).agentOperationModel, 'findById')+ .mockResolvedValueOnce({ id: 'test-operation-1', status: 'running' })+ .mockRejectedValue(new Error('connection reset'));+ const dispatch = vi.spyOn((svc as any).completionLifecycle, 'dispatchHooks');++ await expect(svc.executeStep({ ...mockParams, stepIndex: 0 })).rejects.toBeInstanceOf(+ DurableStatusUnavailableError,+ );++ expect(runDeferredInit).toHaveBeenCalledTimes(1);+ expect(step).not.toHaveBeenCalled();+ expect(coordinator.saveAgentState).not.toHaveBeenCalled();+ expect(dispatch).not.toHaveBeenCalled();+ });+it('does not initialize a shared run whose share was revoked after enqueue', async () => {const runDeferredInit = vi.fn();const verifyShareRunStillAuthorized = vi.fn().mockResolvedValue(false);diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/testUtils.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/testUtils.tsindex 6779d008a12..5313db55817 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/testUtils.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/testUtils.ts@@ -7,8 +7,20 @@ import type { UIChatMessage } from '@lobechat/types';import type * as ModelBankModule from 'model-bank';import { vi } from 'vitest';+import { AgentOperationModel } from '@/database/models/agentOperation';+import type { AgentRuntimeService } from '..';+/**+ * `executeStep` refuses to run when the durable terminal-status read fails.+ * Scenario tests use an empty database stand-in, so answer the query with the+ * live row they intend to exercise instead of letting `db.select` run.+ */+export const stubRunningDurableOperation = () =>+ vi.spyOn(AgentOperationModel.prototype, 'findById').mockResolvedValue({+ status: 'running',+ } as any);+/** The `importOriginal` a `vi.mock` factory receives. */type ImportOriginal = <T = unknown>() => Promise<T>;@@ -241,6 +253,7 @@ export const setUpService = (mockUserId: string,): ServiceTestContext => {vi.clearAllMocks();+ stubRunningDurableOperation();process.env.AGENT_RUNTIME_BASE_URL = 'http://localhost:3010';// Mock databasediff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.dispatch.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.dispatch.test.tsnew file mode 100644index 00000000000..5901dd3053e--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.dispatch.test.ts@@ -0,0 +1,126 @@+// @vitest-environment node+import { describe, expect, it, vi } from 'vitest';++import { type OperationCreationParams } from '../types';+import { createOperation, type CreateOperationDeps } from './createOperation';+import { executeStep, type ExecuteStepDeps } from './executeStep';++const params = {+ agentConfig: {},+ appContext: {},+ initialContext: { phase: 'user_input' },+ modelRuntimeConfig: { model: 'test' },+ operationId: 'dispatch-failure',+ toolSet: { manifestMap: {} },+ userId: 'test-user',+} as OperationCreationParams;++const setup = () => {+ const failure = new Error('queue publish timed out');+ const recordDispatchFailure = vi.fn().mockResolvedValue(true);+ const deps = {+ agentOperationModel: { recordDispatchFailure },+ baseURL: 'http://localhost/api/agent',+ completionLifecycle: { recordStart: vi.fn().mockResolvedValue(true) },+ coordinator: { createAgentOperation: vi.fn(), saveAgentState: vi.fn() },+ queueService: { scheduleMessage: vi.fn().mockRejectedValue(failure) },+ resolveLlmExecutor: vi.fn(),+ } as unknown as CreateOperationDeps;+ return { deps, failure, recordDispatchFailure };+};++describe('operation dispatch failure', () => {+ it('durably settles a rejected first delivery before exposing its error', async () => {+ const { deps, failure, recordDispatchFailure } = setup();+ await expect(createOperation(deps, params)).rejects.toBe(failure);+ expect(recordDispatchFailure).toHaveBeenCalledWith(params.operationId, failure.message);+ });++ it('awaits the durable failure write before rejecting', async () => {+ const { deps, recordDispatchFailure } = setup();+ let finish!: () => void;+ recordDispatchFailure.mockImplementation(+ () =>+ new Promise<void>((resolve) => {+ finish = resolve;+ }),+ );+ let rejected = false;+ const result = createOperation(deps, params).catch(() => {+ rejected = true;+ });+ await vi.waitFor(() => expect(recordDispatchFailure).toHaveBeenCalled());+ expect(rejected).toBe(false);+ finish();+ await result;+ expect(rejected).toBe(true);+ });++ it('leaves a prepared intervention continuation running for its own recovery', async () => {+ const { deps, failure, recordDispatchFailure } = setup();+ const interventionResolution = {+ resolutionRequestId: 'resolution-1',+ sourceOperationId: 'source-operation',+ sourceToolMessageIds: ['tool-message-1'],+ };+ Object.assign(deps.agentOperationModel, {+ findById: vi.fn().mockResolvedValue({+ metadata: { agentInterventionContinuation: interventionResolution },+ status: 'running',+ }),+ recordAgentInterventionPreparation: vi.fn().mockResolvedValue(true),+ });+ Object.assign(deps.coordinator, {+ loadAgentState: vi.fn().mockResolvedValue({ metadata: {} }),+ });++ await expect(createOperation(deps, { ...params, interventionResolution })).rejects.toBe(+ failure,+ );+ expect(recordDispatchFailure).not.toHaveBeenCalled();+ });++ it('keeps a successful first delivery running', async () => {+ const { deps, recordDispatchFailure } = setup();+ vi.mocked(deps.queueService!.scheduleMessage).mockResolvedValue('queued');+ await expect(createOperation(deps, params)).resolves.toMatchObject({ autoStarted: true });+ expect(recordDispatchFailure).not.toHaveBeenCalled();+ });+});++describe('uncertain delivery of a terminal operation', () => {+ it.each(['error', 'interrupted', 'done', 'abandoned'] as const)(+ 'ACKs %s without entering model or tool execution',+ async (status) => {+ const createAgentRuntime = vi.fn();+ const tryClaimStep = vi.fn();+ const deps = {+ agentOperationModel: { findById: vi.fn().mockResolvedValue({ status }) },+ coordinator: { tryClaimStep },+ createAgentRuntime,+ } as unknown as ExecuteStepDeps;+ await expect(+ executeStep(deps, { operationId: params.operationId, stepIndex: 0 }),+ ).resolves.toMatchObject({+ success: true,+ nextStepScheduled: false,+ stepResult: null,+ });+ expect(createAgentRuntime).not.toHaveBeenCalled();+ expect(tryClaimStep).not.toHaveBeenCalled();+ },+ );++ it('refuses execution when the durable terminal status cannot be read', async () => {+ const error = new Error('operation database unavailable');+ const tryClaimStep = vi.fn();+ const deps = {+ agentOperationModel: { findById: vi.fn().mockRejectedValue(error) },+ coordinator: { tryClaimStep },+ } as unknown as ExecuteStepDeps;+ await expect(+ executeStep(deps, { operationId: params.operationId, stepIndex: 0 }),+ ).rejects.toMatchObject({ cause: error, name: 'DurableStatusUnavailableError' });+ expect(tryClaimStep).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.tsindex f5f3234d39f..a5378ca9423 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts@@ -317,7 +317,22 @@ export async function createOperation(retries: queueRetries,stepIndex: initialStepCount,}),- );+ ).catch(async (error: unknown) => {+ // An intervention continuation keeps its own recovery: the prepared+ // continuation republishes this same deterministic operation, so it+ // must stay running for that retry to execute.+ if (!interventionResolution) {+ // A publish timeout may still have delivered the message. The durable+ // terminal guard makes a late delivery ACK without executing, and the+ // reaper's running-only CAS excludes this user-visible failed request.+ // Await persistence before returning the startup error to the caller.+ await deps.agentOperationModel.recordDispatchFailure(+ operationId,+ error instanceof Error ? error.message : String(error),+ );+ }+ throw error;+ });if (interventionResolution && deduplicationId) {await deps.persistInterventionDispatchAck({deduplicationId,diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/failure.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/failure.tsindex 33b07f1f1d6..244603dcaf4 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/failure.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/failure.ts@@ -8,7 +8,7 @@ import { formatErrorForState } from '@/server/modules/AgentRuntime/formatErrorFoimport { CriticalAgentInterventionPersistenceError } from '../../CompletionLifecycle';import { logToolCallPc } from '../../formalObservation';-import { StepOwnershipLostError } from '../executionErrors';+import { DurableStatusUnavailableError, StepOwnershipLostError } from '../executionErrors';import type { AgentRuntimeServiceContext } from '../types';const log = debug('lobe-server:agent-runtime-service');@@ -22,7 +22,8 @@ export type StepFailureDeps = Pick<* A step threw. Record it on the span, persist the error state, settle the* completion lifecycle and finalize the trace, then rethrow β except a failed* intervention Review publication, which keeps the run parked for the retry,- * and a lost step lock, which leaves the run to whoever owns it now.+ * a lost step lock, which leaves the run to whoever owns it now, and an+ * unreadable durable status, which leaves the run for the queue retry.*/export async function failStep(deps: StepFailureDeps,@@ -49,6 +50,14 @@ export async function failStep(log('[%s][%d] Step lock lost before commit; leaving the run as it is', operationId, stepIndex);throw error;}+ if (error instanceof DurableStatusUnavailableError) {+ log(+ '[%s][%d] Durable status unavailable; leaving the run for a queue retry',+ operationId,+ stepIndex,+ );+ throw error;+ }const isInterventionPersistenceFailure =error instanceof CriticalAgentInterventionPersistenceError;diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executionErrors.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executionErrors.tsindex 8b1a1686c4c..4649a2095d9 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executionErrors.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executionErrors.ts@@ -4,6 +4,25 @@* must not commit: `failStep` rethrows it untouched, so the queue redelivers* the step and its claim decides who runs it.*/+/**+ * The durable operation row could not be read, so this delivery cannot tell+ * whether the run still belongs to it. The step refuses to run and must not+ * settle the run either: the queue redelivers it and the next attempt re-checks.+ */+export class DurableStatusUnavailableError extends Error {+ constructor(+ public readonly operationId: string,+ public readonly stepIndex: number,+ options?: { cause?: unknown },+ ) {+ super(+ `Durable status of operation ${operationId} is unavailable at step ${stepIndex}`,+ options,+ );+ this.name = 'DurableStatusUnavailableError';+ }+}+export class StepOwnershipLostError extends Error {constructor(public readonly operationId: string,diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.localRetry.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.localRetry.test.tsnew file mode 100644index 00000000000..df31003b8cb--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.localRetry.test.ts@@ -0,0 +1,76 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { LocalQueueServiceImpl } from '@/server/services/queue/impls';++import { DurableStatusUnavailableError } from './executionErrors';+import {+ LOCAL_DURABLE_STATUS_RETRY_DELAYS_MS,+ type RuntimeFactoryDeps,+ setupLocalExecutionCallback,+} from './runtimeFactory';++const captureCallback = (executeStep: ReturnType<typeof vi.fn>) => {+ const impl = new LocalQueueServiceImpl();+ const setCallback = vi.spyOn(impl, 'setExecutionCallback');+ setupLocalExecutionCallback({+ executeStep,+ queueService: { getImpl: () => impl },+ } as unknown as RuntimeFactoryDeps);+ return setCallback.mock.calls[0][0];+};++const unavailable = () => new DurableStatusUnavailableError('op-1', 0);++describe('local delivery of a step that refused an unreadable durable status', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ it('retries the step once the status can be read again', async () => {+ const executeStep = vi+ .fn()+ .mockRejectedValueOnce(unavailable())+ .mockResolvedValueOnce({ success: true });+ const callback = captureCallback(executeStep);++ const delivery = callback('op-1', 0, { phase: 'user_input' }, { approvedToolCall: 'call-1' });+ await vi.advanceTimersByTimeAsync(LOCAL_DURABLE_STATUS_RETRY_DELAYS_MS[0]);+ await delivery;++ expect(executeStep).toHaveBeenCalledTimes(2);+ expect(executeStep).toHaveBeenLastCalledWith({+ approvedToolCall: 'call-1',+ context: { phase: 'user_input' },+ operationId: 'op-1',+ stepIndex: 0,+ });+ });++ it('gives up after the retry budget, like an exhausted queue redelivery', async () => {+ const executeStep = vi.fn().mockRejectedValue(unavailable());+ const callback = captureCallback(executeStep);++ const delivery = expect(callback('op-1', 0, {}, undefined)).rejects.toBeInstanceOf(+ DurableStatusUnavailableError,+ );+ for (const delay of LOCAL_DURABLE_STATUS_RETRY_DELAYS_MS) {+ await vi.advanceTimersByTimeAsync(delay);+ }+ await delivery;++ expect(executeStep).toHaveBeenCalledTimes(LOCAL_DURABLE_STATUS_RETRY_DELAYS_MS.length + 1);+ });++ it('does not retry other step failures', async () => {+ const failure = new Error('model failed');+ const executeStep = vi.fn().mockRejectedValue(failure);+ const callback = captureCallback(executeStep);++ await expect(callback('op-1', 0, {}, undefined)).rejects.toBe(failure);+ expect(executeStep).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.tsindex c9074d8715e..96a1cdc3ef6 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts@@ -23,6 +23,7 @@ import { stateHasEntityFileEdits } from '@/server/services/workRegistration';import { hookDispatcher } from '../hooks';import { createEvalConnectorHook } from './evalConnectorHook';import { createEvalToolGateHook } from './evalToolGateHook';+import { DurableStatusUnavailableError } from './executionErrors';import type { AgentRuntimeServiceContext } from './types';const log = debug('lobe-server:agent-runtime-service');@@ -44,6 +45,13 @@ export type RuntimeFactoryDeps = Pick<| 'workspaceId'>;+/**+ * Local deliveries are not redelivered when they throw, so a step that refused+ * to run on an unreadable durable status retries here, the way QStash would+ * redeliver it (same budget as its default `retries`).+ */+export const LOCAL_DURABLE_STATUS_RETRY_DELAYS_MS = [1000, 2000, 4000] as const;+/*** Setup execution callback for LocalQueueServiceImpl* This breaks the circular dependency by using callback injection@@ -59,7 +67,22 @@ export function setupLocalExecutionCallback(deps: RuntimeFactoryDeps): void {// toolMessageId, resumeAsyncTool, β¦) ride the request body into// executeStep. Without this spread, local/in-memory resumes silently// lose their intervention/resume signal.- await deps.executeStep({ context, operationId, stepIndex, ...payload });+ for (let attempt = 0; ; attempt++) {+ try {+ await deps.executeStep({ context, operationId, stepIndex, ...payload });+ return;+ } catch (error) {+ const delay = LOCAL_DURABLE_STATUS_RETRY_DELAYS_MS[attempt];+ if (!(error instanceof DurableStatusUnavailableError) || delay === undefined) throw error;+ log(+ '[%s][%d] Durable status unavailable; retrying in %dms',+ operationId,+ stepIndex,+ delay,+ );+ await new Promise((resolve) => setTimeout(resolve, delay));+ }+ }});}}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/terminalStatus.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/terminalStatus.tsindex 49643833a1f..ddf8562b791 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/terminalStatus.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/terminalStatus.ts@@ -3,6 +3,8 @@ import debug from 'debug';import type { AgentOperationModel } from '@/database/models/agentOperation';+import { DurableStatusUnavailableError } from './executionErrors';+const log = debug('lobe-server:agent-runtime-service');export const isTerminalAgentStatus = (status: AgentState['status'] | undefined) =>@@ -11,9 +13,9 @@ export const isTerminalAgentStatus = (status: AgentState['status'] | undefined)/*** The durable operation row's status when it is terminal, else `undefined`.* Redis keeps the resumable step state, but the row is the authority for- * cancellation, abandonment and recovery. A read failure preserves runtime- * availability: it reads as not terminal, and the step lock and the normal- * persistence path still apply.+ * cancellation, abandonment and recovery. A read failure refuses execution+ * with `DurableStatusUnavailableError`: the step neither runs nor settles the+ * run, and a queue retry re-checks the row before spending on models or tools.*/export const loadTerminalDurableStatus = async (agentOperationModel: AgentOperationModel,@@ -32,6 +34,7 @@ export const loadTerminalDurableStatus = async (}} catch (error) {log('[%s][%d] Durable operation status check failed: %O', operationId, stepIndex, error);+ throw new DurableStatusUnavailableError(operationId, stepIndex, { cause: error });}return undefined;};diff --git a/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts b/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.tsindex 6ba54ce05d5..d9ff01a5c07 100644--- a/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts@@ -21,6 +21,18 @@ const stubUiMessagesSnapshot = (service: unknown) => {};};+/**+ * `executeStep` refuses to run when the durable terminal check fails. These+ * tests exercise the step loop with an empty database stand-in, so give the+ * operation row the non-terminal status a live run would have.+ */+const stubRunningDurableOperation = (service: unknown) => {+ vi.spyOn(+ (service as { agentOperationModel: { findById: (...args: any[]) => any } }).agentOperationModel,+ 'findById',+ ).mockResolvedValue({ status: 'running' } as any);+};+vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'http://localhost:3010' } }));vi.mock('@/database/models/message', () => ({MessageModel: vi.fn().mockImplementation(function () {@@ -106,7 +118,7 @@ describe('AgentRuntimeService Agent Signal hook integration', () => {it('emits source events for beforeStep and afterStep boundaries',- { timeout: 20_000 },+ { timeout: 60_000 },async () => {(globalThis as AgentSignalRedisTestGlobal).__agentSignalRedisClient = mockRedis;mockRedis.set.mockResolvedValue('OK');@@ -118,6 +130,7 @@ describe('AgentRuntimeService Agent Signal hook integration', () => {const { AgentRuntimeService } = await import('../AgentRuntimeService');const service = new AgentRuntimeService({} as any, 'user-1', { queueService: null });stubUiMessagesSnapshot(service);+ stubRunningDurableOperation(service);const coordinator = (service as any).coordinator;vi.spyOn(coordinator, 'loadAgentState').mockResolvedValue({@@ -221,6 +234,7 @@ describe('AgentRuntimeService Agent Signal hook integration', () => {snapshotStore: snapshotStore as any,});stubUiMessagesSnapshot(service);+ stubRunningDurableOperation(service);const coordinator = (service as any).coordinator;vi.spyOn(coordinator, 'loadAgentState').mockResolvedValue({@@ -320,6 +334,7 @@ describe('AgentRuntimeService Agent Signal hook integration', () => {snapshotStore: snapshotStore as any,});stubUiMessagesSnapshot(service);+ stubRunningDurableOperation(service);const coordinator = (service as any).coordinator;vi.spyOn(coordinator, 'loadAgentState').mockResolvedValue({diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.ownership.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.ownership.test.tsindex 85e0e5d1050..4482158cb33 100644--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.ownership.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.ownership.test.ts@@ -1,9 +1,10 @@// @vitest-environment node-import { describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';import { LocalQueueServiceImpl } from '@/server/services/queue/impls';import { AgentRuntimeService } from '../AgentRuntimeService';+import { stubRunningDurableOperation } from '../AgentRuntimeService/__tests__/testUtils';import { StepOwnershipLostError } from '../AgentRuntimeService/executionErrors';// Mock all heavy dependencies to isolate executeStep logic@@ -72,6 +73,10 @@ vi.mock('@lobechat/builtin-tools/dynamicInterventionAudits', () => ({dynamicInterventionAudits: [],}));+beforeEach(() => {+ stubRunningDurableOperation();+});+describe('AgentRuntimeService.executeStep - step ownership', () => {// A step whose LLM call outlives the lock TTL can be claimed by a redelivery// while it still runs. Whichever attempt no longer owns the lock must notdiff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.tsindex 3ab64fb2d48..6094754ccaf 100644--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts@@ -1,7 +1,7 @@// @vitest-environment nodeimport { GeneralChatAgent, GraphAgent } from '@lobechat/agent-runtime';import type { AgentGraph } from '@lobechat/types';-import { describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';import {type AgentInterventionContinuationProvenance,@@ -10,6 +10,7 @@ import {import { createRuntimeExecutors } from '@/server/modules/AgentRuntime/RuntimeExecutors';import { AgentRuntimeService } from '../AgentRuntimeService';+import { stubRunningDurableOperation } from '../AgentRuntimeService/__tests__/testUtils';import { CriticalAgentInterventionPersistenceError } from '../CompletionLifecycle';import { hookDispatcher } from '../hooks';@@ -98,6 +99,10 @@ vi.mock('@lobechat/builtin-tools/dynamicInterventionAudits', () => ({dynamicInterventionAudits: [],}));+beforeEach(() => {+ stubRunningDurableOperation();+});+describe('AgentRuntimeService intervention continuation dispatch recovery', () => {const operationId = 'op-intervention-recovery';const provenance: AgentInterventionContinuationProvenance = {diff --git a/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.ts b/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.tsindex bb500485829..ea736f5c1ba 100644--- a/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.ts@@ -9,9 +9,10 @@* This catches payload format regressions that unit tests miss because* they mock the dispatch layer.*/-import { describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';import { AgentRuntimeService } from '../AgentRuntimeService';+import { stubRunningDurableOperation } from '../AgentRuntimeService/__tests__/testUtils';import { hookDispatcher } from '../hooks';import type { AgentHookEvent } from '../hooks/types';@@ -80,6 +81,10 @@ vi.mock('@lobechat/builtin-tools/dynamicInterventionAudits', () => ({dynamicInterventionAudits: [],}));+beforeEach(() => {+ stubRunningDurableOperation();+});+describe('Hooks integration β afterStep event carries step presentation data', () => {const createService = () => new AgentRuntimeService({} as any, 'user-1', { queueService: null });diff --git a/packages/database/src/models/__tests__/agentOperation.dispatch.test.ts b/packages/database/src/models/__tests__/agentOperation.dispatch.test.tsnew file mode 100644index 00000000000..73181c205ad--- /dev/null+++ b/packages/database/src/models/__tests__/agentOperation.dispatch.test.ts@@ -0,0 +1,81 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { agentOperations, users } from '../../schemas';+import { AgentOperationModel } from '../agentOperation';++const db = await getTestDB();+const userId = 'dispatch-contract-user';+const model = () => new AgentOperationModel(db, userId);+const staleBefore = new Date(Date.now() - 60_000);++beforeEach(async () => {+ await db.insert(users).values({ id: userId });+});+afterEach(async () => {+ await db.delete(agentOperations).where(eq(agentOperations.userId, userId));+ await db.delete(users).where(eq(users.id, userId));+});++const stale = async (id: string) => {+ await model().recordStart({ operationId: id });+ await db+ .update(agentOperations)+ .set({ updatedAt: new Date(0) })+ .where(eq(agentOperations.id, id));+};++describe('failed dispatch recovery boundary', () => {+ it('persists the reason and prevents either recovery entry point from claiming the failed run', async () => {+ await stale('dispatch-error');+ expect(await model().recordDispatchFailure('dispatch-error', 'queue unavailable')).toBe(true);+ expect(await model().findById('dispatch-error')).toMatchObject({+ status: 'error',+ completionReason: 'error',+ error: { message: 'queue unavailable', type: 'QueueDispatchError' },+ completedAt: expect.any(Date),+ });+ await db+ .update(agentOperations)+ .set({ updatedAt: new Date(0) })+ .where(eq(agentOperations.id, 'dispatch-error'));+ expect(+ await Promise.all([+ model().claimStaleRedrive('dispatch-error', staleBefore, 3),+ model().claimStaleRedrive('dispatch-error', staleBefore, 3),+ ]),+ ).toEqual([null, null]);+ expect(await model().settleStaleRunning('dispatch-error', staleBefore)).toBe(false);+ });++ it.each(['done', 'error', 'interrupted'] as const)(+ 'preserves an existing %s outcome',+ async (status) => {+ await model().recordStart({ operationId: 'already-terminal' });+ await model().recordCompletion('already-terminal', { status, completionReason: status });+ expect(await model().recordDispatchFailure('already-terminal', 'late timeout')).toBe(false);+ expect(await model().findById('already-terminal')).toMatchObject({ status, error: null });+ },+ );++ it('allows exactly one simultaneous stale claim from separate reaper instances', async () => {+ await stale('concurrent-claim');+ const claims = await Promise.all([+ model().claimStaleRedrive('concurrent-claim', staleBefore, 3),+ model().claimStaleRedrive('concurrent-claim', staleBefore, 3),+ ]);+ expect(claims.filter((attempt) => attempt !== null)).toEqual([1]);+ expect(claims.filter((attempt) => attempt === null)).toHaveLength(1);+ });++ it('lets exactly one of the redrive and abandon entry points claim a stale run', async () => {+ await stale('entry-race');+ const [attempt, settled] = await Promise.all([+ model().claimStaleRedrive('entry-race', staleBefore, 3),+ model().settleStaleRunning('entry-race', staleBefore),+ ]);+ expect([attempt !== null, settled].filter(Boolean)).toHaveLength(1);+ });+});diff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.tsindex 4e8f8a04aca..74a22afe6a6 100644--- a/packages/database/src/models/agentOperation.ts+++ b/packages/database/src/models/agentOperation.ts@@ -406,6 +406,28 @@ export class AgentOperationModel {: null;}+ /** A rejected publish must never be resurrected by stale recovery. */+ async recordDispatchFailure(operationId: string, message: string): Promise<boolean> {+ const [row] = await this.db+ .update(agentOperations)+ .set({+ completedAt: new Date(),+ completionReason: 'error',+ error: { message, type: 'QueueDispatchError' },+ status: 'error',+ })+ .where(+ and(+ eq(agentOperations.id, operationId),+ eq(agentOperations.status, 'running'),+ this.ownership(),+ ),+ )+ .returning({ id: agentOperations.id });++ return Boolean(row);+ }+/** Idempotently settle a running operation without rewriting an existing terminal outcome. */async settleRunning(operationId: string,