Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix: finalize abandoned operation lifecycle (#16894)

Arvin Xu31db72866c37
diff --git a/apps/server/src/services/agentRuntime/AbandonOperationService.ts b/apps/server/src/services/agentRuntime/AbandonOperationService.ts
index 5cc3402ddf8..857c7ff595a 100644
--- a/apps/server/src/services/agentRuntime/AbandonOperationService.ts
+++ b/apps/server/src/services/agentRuntime/AbandonOperationService.ts
@@ -15,6 +15,7 @@ import type { LobeChatDatabase } from '@/database/type';
// its workspace-package transitive deps in the unit-test environment.
import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime/AgentRuntimeCoordinator';
+import { CompletionLifecycle } from './CompletionLifecycle';
import { OperationTraceRecorder } from './OperationTraceRecorder';
import { createDefaultSnapshotStore } from './snapshotStore';
@@ -108,9 +109,14 @@ export class AbandonOperationService {
isSubAgent?: boolean;
orchestrationRole?: 'supervisor' | 'member';
threadId?: string | null;
+ topicId?: string | null;
userId?: string;
workspaceId?: string;
};
+ const shouldDispatchAbandonedLifecycle =
+ state.status === 'running' ||
+ state.status === 'waiting_for_human' ||
+ state.status === 'waiting_for_async_tool';
const message = `Operation abandoned: ${reason}`;
const error: ChatMessageError = {
body: { message },
@@ -154,6 +160,36 @@ export class AbandonOperationService {
}
}
+ if (!metadata.isSubAgent && metadata.userId) {
+ if (metadata.topicId) {
+ try {
+ const topicModel = new TopicModel(this.db, metadata.userId, metadata.workspaceId);
+ const topic = await topicModel.findById(metadata.topicId);
+ const running = topic?.metadata?.runningOperation as
+ { assistantMessageId?: string; operationId?: string } | undefined;
+ if (running?.operationId === operationId) {
+ await topicModel.updateMetadata(metadata.topicId, { runningOperation: null });
+ }
+ } catch (e) {
+ log('[%s] abandoned op runningOperation cleanup failed (non-fatal): %O', operationId, e);
+ }
+ }
+
+ if (shouldDispatchAbandonedLifecycle) {
+ try {
+ await new CompletionLifecycle(
+ this.db,
+ metadata.userId,
+ metadata.workspaceId,
+ ).dispatchHooks(operationId, finalState, 'error', {
+ skipErrorMessageWrite: result.assistantMessageUpdated,
+ });
+ } catch (e) {
+ log('[%s] abandoned op lifecycle dispatch failed (non-fatal): %O', operationId, e);
+ }
+ }
+ }
+
// Resolve sub-agent → parent linkage. The watchdog killed this op without
// firing its onComplete bridge, so a parent parked on `callSubAgent` would
// otherwise wait on this slot forever. We surface the ids the caller needs
@@ -293,8 +329,7 @@ export class AbandonOperationService {
topicModel = new TopicModel(this.db, op.userId, op.workspaceId ?? undefined);
const topic = await topicModel.findById(op.topicId);
const running = topic?.metadata?.runningOperation as
- | { assistantMessageId?: string; operationId?: string }
- | undefined;
+ { assistantMessageId?: string; operationId?: string } | undefined;
if (running?.operationId && running.operationId !== operationId) return undefined;
diff --git a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts
index 612ecec092a..3a4addf8272 100644
--- a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts
@@ -39,6 +39,13 @@ vi.mock('@/database/models/agentOperation', () => ({
})),
}));
+const dispatchHooksMock = vi.fn().mockResolvedValue(undefined);
+vi.mock('../CompletionLifecycle', () => ({
+ CompletionLifecycle: vi.fn().mockImplementation(() => ({
+ dispatchHooks: dispatchHooksMock,
+ })),
+}));
+
const findThreadMock = vi.fn().mockResolvedValue(null);
vi.mock('@/database/models/thread', () => ({
ThreadModel: vi.fn().mockImplementation(() => ({ findById: findThreadMock })),
@@ -82,6 +89,7 @@ const buildDb = (overrides: { assistantRow?: any; operationRow?: any } = {}) =>
describe('AbandonOperationService', () => {
beforeEach(() => {
messageUpdateMock.mockClear();
+ dispatchHooksMock.mockClear();
findOperationMock.mockReset().mockResolvedValue(null);
recordCompletionMock.mockClear();
findThreadMock.mockReset().mockResolvedValue(null);
@@ -238,6 +246,14 @@ describe('AbandonOperationService', () => {
{ stepIndex: 1, stepType: 'call_tool' },
],
});
+ topicFindByIdMock.mockResolvedValue({
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'msg_assist_1',
+ operationId: 'op_x',
+ },
+ },
+ });
const svc = new AbandonOperationService({} as any, {
coordinator: coord as any,
@@ -273,11 +289,54 @@ describe('AbandonOperationService', () => {
type: 'AgentRuntimeError',
}),
});
+ expect(topicUpdateMetadataMock).toHaveBeenCalledWith('tpc_x', { runningOperation: null });
+ expect(dispatchHooksMock).toHaveBeenCalledWith(
+ 'op_x',
+ expect.objectContaining({
+ error: expect.objectContaining({
+ message: expect.stringContaining('inactivity_5m'),
+ type: 'AgentRuntimeError',
+ }),
+ status: 'error',
+ }),
+ 'error',
+ { skipErrorMessageWrite: true },
+ );
// Coordinator state cleaned
expect(coord.deleteAgentOperation).toHaveBeenCalledWith('op_x');
});
+ it.each(['done', 'error', 'interrupted'])(
+ 'skips abandoned lifecycle dispatch for terminal coordinator state %s',
+ async (status) => {
+ const coord = buildCoordinator({
+ loadAgentState: vi.fn().mockResolvedValue(stateWith({ status })),
+ });
+ const store = buildStore();
+ store.loadPartial.mockResolvedValue(null);
+ topicFindByIdMock.mockResolvedValue({
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'msg_assist_1',
+ operationId: 'op_x',
+ },
+ },
+ });
+
+ const svc = new AbandonOperationService({} as any, {
+ coordinator: coord as any,
+ snapshotStore: store as any,
+ });
+
+ const result = await svc.finalizeAbandoned('op_x', 'inactivity_5m');
+
+ expect(result.found).toBe(true);
+ expect(topicUpdateMetadataMock).toHaveBeenCalledWith('tpc_x', { runningOperation: null });
+ expect(dispatchHooksMock).not.toHaveBeenCalled();
+ },
+ );
+
it('skips snapshot finalize when no partial exists but still updates message', async () => {
const coord = buildCoordinator({
loadAgentState: vi.fn().mockResolvedValue(stateWith()),
@@ -397,6 +456,7 @@ describe('AbandonOperationService', () => {
userId: 'user_x',
workspaceId: 'ws_1',
});
+ expect(dispatchHooksMock).not.toHaveBeenCalled();
// Coordinator state is kept alive so the durable parent-resume can still
// resolve this op's userId; it expires via its own Redis TTL.
expect(coord.deleteAgentOperation).not.toHaveBeenCalled();