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(agent): persist hetero lifecycle hooks on operation (#18408)

Arvin Xu623703bf46e7
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
index 854f6bd836f..91516c04ae3 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
@@ -1291,6 +1291,19 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>
// The non-serializable handler must be stripped (only webhook crosses the
// process boundary).
expect(seed.runningOperation.hooks[0]).not.toHaveProperty('handler');
+ expect(recordStartSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ metadata: expect.objectContaining({
+ assistantMessageId: expect.any(String),
+ _hooks: [
+ expect.objectContaining({
+ id: 'task-on-complete',
+ type: 'onComplete',
+ }),
+ ],
+ }),
+ }),
+ );
});
it('serializes the onComplete webhook hook onto runningOperation (device dispatch)', async () => {
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
index 822d9769a43..fdff84f4705 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
@@ -247,6 +247,12 @@ export const dispatchHeteroAgent = async (
// so hetero ops aren't visually distinct bare nanoids in the trace/op tables.
const operationId = `op_${Date.now()}_${resolvedAgentId}_${topicId}_${nanoid(8)}`;
+ // Hooks belong to this operation's lifecycle. Persist their serializable
+ // form on the durable operation row before dispatch; runningOperation below
+ // remains a compatibility mirror for older terminal consumers.
+ if (hooks?.length) hookDispatcher.register(operationId, hooks);
+ const serializedHooks = hookDispatcher.getSerializedHooks(operationId);
+
// Persist a first-class agent_operations row for the hetero run. The id is
// generated here (authoritative) and flows through to heteroIngest /
// heteroFinish unchanged. Without this row the run is invisible to the
@@ -263,6 +269,10 @@ export const dispatchHeteroAgent = async (
agentId: persistAgentId,
chatGroupId: appContext?.groupId ?? null,
maxSteps,
+ metadata: {
+ _hooks: serializedHooks,
+ assistantMessageId,
+ },
operationId,
parentOperationId,
provider: heteroType,
@@ -272,6 +282,7 @@ export const dispatchHeteroAgent = async (
trigger,
});
if (!operationPersisted) {
+ hookDispatcher.unregister(operationId);
throw new Error('Failed to persist heterogeneous agent operation');
}
@@ -449,11 +460,8 @@ export const dispatchHeteroAgent = async (
// runtime uses — driving the task lifecycle (onTopicComplete) and IM bot
// completion callbacks uniformly. The hetero block returns before
// AgentRuntimeService (which registers hooks for normal runs), so we do it
- // here. Local mode dispatches these in-memory handlers; queue mode
- // delivers the serialized webhooks persisted on runningOperation below.
- if (hooks?.length) hookDispatcher.register(operationId, hooks);
- const serializedHooks = hookDispatcher.getSerializedHooks(operationId);
-
+ // here. Local mode dispatches these in-memory handlers; queue mode delivers
+ // the serialized webhooks persisted on the operation row above.
// Seed topic.metadata.runningOperation so heteroIngest can validate the
// operation, and so every terminal site (heteroFinish, agentNotify done,
// dispatch failure) can re-fire the serialized hooks across a process
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
index 325c9f7897b..d6042294947 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
@@ -64,7 +64,11 @@ const createFakePersistenceHandler = () => {
return handler as unknown as HeterogeneousPersistenceHandler & typeof handler;
};
-const createFakeAgentOperationModel = () => ({ touchRunning: vi.fn(async () => true) });
+const createFakeAgentOperationModel = () => ({
+ findById: vi.fn(async () => null),
+ settleRunning: vi.fn(async () => true),
+ touchRunning: vi.fn(async () => true),
+});
const buildEvent = (
type: AgentStreamEvent['type'],
@@ -820,19 +824,28 @@ describe('HeterogeneousAgentService', () => {
},
};
- const makeService = (hooks: SerializedHook[] | undefined) => {
+ const makeService = (
+ hooks: SerializedHook[] | undefined,
+ options: { operationHooks?: SerializedHook[]; topicStatus?: 'missing' | 'settled' } = {},
+ ) => {
const topicModel = {
- // Mirror what execAgent persisted at dispatch: the serialized hooks live
- // under runningOperation. heteroFinish must read them from here.
+ // Keep covering the legacy topic mirror used by partially upgraded runs.
settleRunningOperation: vi.fn(async () => ({
assistantMessageId: undefined,
hooks,
- status: 'settled' as const,
+ status: options.topicStatus ?? ('settled' as const),
threadId: undefined,
})),
} as any;
const { manager } = createFakeStreamManager();
+ const agentOperationModel = createFakeAgentOperationModel();
+ agentOperationModel.findById.mockResolvedValue({
+ metadata: options.operationHooks
+ ? { _hooks: options.operationHooks, assistantMessageId: 'asst-op' }
+ : undefined,
+ } as any);
const service = new HeterogeneousAgentService({} as any, 'user-test', {
+ agentOperationModel: agentOperationModel as any,
persistenceHandler: createFakePersistenceHandler(),
snapshotStore: null,
streamEventManager: manager,
@@ -879,6 +892,26 @@ describe('HeterogeneousAgentService', () => {
});
});
+ it('delivers hooks from the operation when the stream terminal already cleared the topic', async () => {
+ const { service } = makeService(undefined, {
+ operationHooks: [taskHook],
+ topicStatus: 'missing',
+ });
+
+ await service.heteroFinish({
+ agentType: 'claude-code',
+ operationId: 'op-q',
+ result: 'success',
+ topicId: 'topic-q',
+ });
+
+ expect(mockPublishJSON).toHaveBeenCalledTimes(1);
+ expect(mockPublishJSON.mock.calls[0][0].body).toMatchObject({
+ hookId: 'task-on-complete',
+ topicId: 'topic-q',
+ });
+ });
+
it('negative control: delivers nothing when runningOperation.hooks is empty', async () => {
const { service } = makeService([]);
diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.ts
index 614cd2d138a..45ba9f75621 100644
--- a/apps/server/src/services/heterogeneousAgent/index.ts
+++ b/apps/server/src/services/heterogeneousAgent/index.ts
@@ -299,6 +299,22 @@ export class HeterogeneousAgentService {
let orchestrationRole: 'member' | 'supervisor' | undefined;
let staleActiveOperationId: string | undefined;
+ // The operation row is the durable lifecycle owner. The frontend may have
+ // already consumed the in-stream terminal event and cleared the topic's
+ // runningOperation marker before this explicit finish callback arrives.
+ try {
+ const operation = await this.agentOperationModel.findById(operationId);
+ const metadata = operation?.metadata as Record<string, unknown> | null | undefined;
+ const operationHooks = metadata?._hooks;
+ if (Array.isArray(operationHooks)) serializedHooks = operationHooks as SerializedHook[];
+ if (typeof metadata?.assistantMessageId === 'string') {
+ assistantMessageId = metadata.assistantMessageId;
+ }
+ isolationThreadId = operation?.threadId ?? undefined;
+ } catch (err) {
+ log('heteroFinish: failed to load operation lifecycle metadata (non-fatal): %O', err);
+ }
+
// `cancelled` is only an intermediate process signal. Keep the marker for
// the following success/error terminal callback, which owns completion.
if (result !== 'cancelled') {
@@ -309,8 +325,8 @@ export class HeterogeneousAgentService {
} else {
assistantMessageId = settled.assistantMessageId ?? assistantMessageId;
if (settled.status === 'settled') {
- serializedHooks = settled.hooks as SerializedHook[] | undefined;
- isolationThreadId = settled.threadId;
+ serializedHooks ??= settled.hooks as SerializedHook[] | undefined;
+ isolationThreadId = settled.threadId ?? isolationThreadId;
orchestrationRole = settled.orchestrationRole;
}
}