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.

♻️ refactor(bot): migrate Bot service to Agent Runtime Hooks framework (#13546)

Arvin Xue9d43cb43f69
diff --git a/src/server/services/agentRuntime/AgentRuntimeService.test.ts b/src/server/services/agentRuntime/AgentRuntimeService.test.ts
index 59c2d5f18c0..cf2f66313bf 100644
--- a/src/server/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/src/server/services/agentRuntime/AgentRuntimeService.test.ts
@@ -338,7 +338,6 @@ describe('AgentRuntimeService', () => {
...mockParams,
hooks: [{ handler: vi.fn(), id: 'hook-1', type: 'onComplete' }],
signal: controller.signal,
- stepCallbacks: { onComplete: vi.fn() },
}),
).rejects.toMatchObject({
message: 'startup aborted',
@@ -347,7 +346,6 @@ describe('AgentRuntimeService', () => {
expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();
expect(mockCoordinator.deleteAgentOperation).toHaveBeenCalledWith('test-operation-1');
- expect(service.getStepCallbacks('test-operation-1')).toBeUndefined();
expect(hookDispatcher.hasHooks('test-operation-1')).toBe(false);
});
});
@@ -464,22 +462,19 @@ describe('AgentRuntimeService', () => {
});
});
- it('should call onComplete with error in finalState when execution fails', async () => {
+ it('should dispatch onComplete hook with error in finalState when execution fails', async () => {
const error = new Error('Runtime error');
const mockRuntime = { step: vi.fn().mockRejectedValue(error) };
vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });
- // Register onComplete callback
- const mockOnComplete = vi.fn();
- service.registerStepCallbacks('test-operation-1', {
- onComplete: mockOnComplete,
- });
+ const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined);
await expect(service.executeStep(mockParams)).rejects.toThrow('Runtime error');
- // Verify onComplete is called with error in finalState as ChatMessageError
- // ChatErrorType.InternalServerError = 500
- expect(mockOnComplete).toHaveBeenCalledWith(
+ // Verify onComplete hooks dispatched with error in finalState as ChatMessageError
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'test-operation-1',
+ 'onComplete',
expect.objectContaining({
operationId: 'test-operation-1',
reason: 'error',
@@ -491,10 +486,13 @@ describe('AgentRuntimeService', () => {
}),
}),
}),
+ undefined,
);
+
+ dispatchSpy.mockRestore();
});
- it('should call onComplete with ChatCompletionErrorPayload in finalState', async () => {
+ it('should dispatch onComplete hook with ChatCompletionErrorPayload in finalState', async () => {
// Simulate LLM error format: { errorType: 'InvalidProviderAPIKey', error: { ... } }
const llmError = {
errorType: 'InvalidProviderAPIKey',
@@ -504,16 +502,14 @@ describe('AgentRuntimeService', () => {
const mockRuntime = { step: vi.fn().mockRejectedValue(llmError) };
vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });
- // Register onComplete callback
- const mockOnComplete = vi.fn();
- service.registerStepCallbacks('test-operation-1', {
- onComplete: mockOnComplete,
- });
+ const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined);
await expect(service.executeStep(mockParams)).rejects.toEqual(llmError);
// Verify error is formatted correctly with type from errorType
- expect(mockOnComplete).toHaveBeenCalledWith(
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'test-operation-1',
+ 'onComplete',
expect.objectContaining({
operationId: 'test-operation-1',
reason: 'error',
@@ -525,7 +521,10 @@ describe('AgentRuntimeService', () => {
}),
}),
}),
+ undefined,
);
+
+ dispatchSpy.mockRestore();
});
it('should save error state to coordinator for later retrieval (inMemory mode fix)', async () => {
@@ -665,8 +664,7 @@ describe('AgentRuntimeService', () => {
});
it('should extract tool output from data field for single tool_result', async () => {
- const mockOnAfterStep = vi.fn();
- service.registerStepCallbacks('test-operation-1', { onAfterStep: mockOnAfterStep });
+ const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined);
const mockStepResult = {
newState: { ...mockState, stepCount: 2, status: 'running' },
@@ -694,7 +692,9 @@ describe('AgentRuntimeService', () => {
await service.executeStep(mockParams);
- expect(mockOnAfterStep).toHaveBeenCalledWith(
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'test-operation-1',
+ 'afterStep',
expect.objectContaining({
toolsResult: [
expect.objectContaining({
@@ -704,12 +704,14 @@ describe('AgentRuntimeService', () => {
}),
],
}),
+ undefined,
);
+
+ dispatchSpy.mockRestore();
});
it('should extract tool output from data field for tools_batch_result', async () => {
- const mockOnAfterStep = vi.fn();
- service.registerStepCallbacks('test-operation-1', { onAfterStep: mockOnAfterStep });
+ const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined);
const mockStepResult = {
newState: { ...mockState, stepCount: 2, status: 'running' },
@@ -750,7 +752,9 @@ describe('AgentRuntimeService', () => {
await service.executeStep(mockParams);
- expect(mockOnAfterStep).toHaveBeenCalledWith(
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'test-operation-1',
+ 'afterStep',
expect.objectContaining({
toolsResult: [
expect.objectContaining({
@@ -765,12 +769,14 @@ describe('AgentRuntimeService', () => {
}),
],
}),
+ undefined,
);
+
+ dispatchSpy.mockRestore();
});
it('should handle tool result with undefined data', async () => {
- const mockOnAfterStep = vi.fn();
- service.registerStepCallbacks('test-operation-1', { onAfterStep: mockOnAfterStep });
+ const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined);
const mockStepResult = {
newState: { ...mockState, stepCount: 2, status: 'running' },
@@ -796,7 +802,9 @@ describe('AgentRuntimeService', () => {
await service.executeStep(mockParams);
- expect(mockOnAfterStep).toHaveBeenCalledWith(
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'test-operation-1',
+ 'afterStep',
expect.objectContaining({
toolsResult: [
expect.objectContaining({
@@ -806,7 +814,10 @@ describe('AgentRuntimeService', () => {
}),
],
}),
+ undefined,
);
+
+ dispatchSpy.mockRestore();
});
});
diff --git a/src/server/services/agentRuntime/AgentRuntimeService.ts b/src/server/services/agentRuntime/AgentRuntimeService.ts
index 936c9b4b4d5..55332fff2c6 100644
--- a/src/server/services/agentRuntime/AgentRuntimeService.ts
+++ b/src/server/services/agentRuntime/AgentRuntimeService.ts
@@ -32,7 +32,6 @@ import {
type StartExecutionParams,
type StartExecutionResult,
type StepCompletionReason,
- type StepLifecycleCallbacks,
type StepPresentationData,
} from './types';
@@ -127,11 +126,6 @@ export class AgentRuntimeService {
private queueService: QueueService | null;
private snapshotStore: ISnapshotStore | null;
private toolExecutionService: ToolExecutionService;
- /**
- * Step lifecycle callback registry
- * key: operationId, value: callbacks
- */
- private stepCallbacks: Map<string, StepLifecycleCallbacks> = new Map();
private get baseURL() {
const baseUrl = process.env.AGENT_RUNTIME_BASE_URL || appEnv.APP_URL || 'http://localhost:3010';
@@ -186,35 +180,6 @@ export class AgentRuntimeService {
}
}
- // ==================== Step Lifecycle Callbacks ====================
-
- /**
- * Register step lifecycle callbacks
- * @param operationId - Operation ID
- * @param callbacks - Callback function collection
- */
- registerStepCallbacks(operationId: string, callbacks: StepLifecycleCallbacks): void {
- this.stepCallbacks.set(operationId, callbacks);
- log('[%s] Registered step callbacks', operationId);
- }
-
- /**
- * Remove step lifecycle callbacks
- * @param operationId - Operation ID
- */
- unregisterStepCallbacks(operationId: string): void {
- this.stepCallbacks.delete(operationId);
- log('[%s] Unregistered step callbacks', operationId);
- }
-
- /**
- * Get step lifecycle callbacks
- * @param operationId - Operation ID
- */
- getStepCallbacks(operationId: string): StepLifecycleCallbacks | undefined {
- return this.stepCallbacks.get(operationId);
- }
-
// ==================== Operation Interruption ====================
/**
@@ -260,14 +225,10 @@ export class AgentRuntimeService {
initialMessages = [],
appContext,
toolSet,
- stepCallbacks,
hooks,
userInterventionConfig,
- completionWebhook,
- stepWebhook,
queueRetries,
queueRetryDelay,
- webhookDelivery,
botPlatformContext,
discordContext,
evalContext,
@@ -282,7 +243,6 @@ export class AgentRuntimeService {
const operationToolSet = toolSet;
let operationCreated = false;
- let stepCallbacksRegistered = false;
let hooksRegistered = false;
try {
@@ -315,7 +275,6 @@ export class AgentRuntimeService {
activeDeviceId,
agentConfig,
botPlatformContext,
- completionWebhook,
deviceSystemInfo,
discordContext,
evalContext,
@@ -323,13 +282,11 @@ export class AgentRuntimeService {
modelRuntimeConfig,
queueRetries,
queueRetryDelay,
- stepWebhook,
stream,
operationSkillSet,
userId,
userMemory,
userTimezone,
- webhookDelivery,
workingDirectory: agentConfig?.chatConfig?.runtimeEnv?.workingDirectory,
...appContext,
},
@@ -359,12 +316,6 @@ export class AgentRuntimeService {
// Save initial state
await this.coordinator.saveAgentState(operationId, initialState as any);
- // Register step lifecycle callbacks
- if (stepCallbacks) {
- this.registerStepCallbacks(operationId, stepCallbacks);
- stepCallbacksRegistered = true;
- }
-
// Register external hooks
if (hooks && hooks.length > 0) {
hookDispatcher.register(operationId, hooks);
@@ -416,10 +367,6 @@ export class AgentRuntimeService {
return { autoStarted, messageId, operationId, success: true };
} catch (error) {
if (isAbortError(error)) {
- if (stepCallbacksRegistered) {
- this.unregisterStepCallbacks(operationId);
- }
-
if (hooksRegistered) {
hookDispatcher.unregister(operationId);
}
@@ -455,8 +402,6 @@ export class AgentRuntimeService {
externalRetryCount = 0,
} = params;
- const callbacks = this.getStepCallbacks(operationId);
-
// ===== Distributed lock: prevent duplicate execution from QStash retries =====
const claimed = await this.coordinator.tryClaimStep(operationId, stepIndex, 35);
if (!claimed) {
@@ -527,19 +472,8 @@ export class AgentRuntimeService {
const reason = this.determineCompletionReason(agentState);
- // Trigger completion callback so eval run can finalize properly
- if (callbacks?.onComplete) {
- try {
- await callbacks.onComplete({
- finalState: agentState,
- operationId,
- reason,
- });
- this.unregisterStepCallbacks(operationId);
- } catch (callbackError) {
- log('[%s] onComplete callback error: %O', operationId, callbackError);
- }
- }
+ // Dispatch completion hooks so consumers (e.g., bot local-mode promise) can finalize
+ await this.dispatchCompletionHooks(operationId, agentState, reason);
return {
nextStepScheduled: false,
@@ -549,20 +483,6 @@ export class AgentRuntimeService {
};
}
- // Call onBeforeStep callback (legacy)
- if (callbacks?.onBeforeStep) {
- try {
- await callbacks.onBeforeStep({
- context,
- operationId,
- state: agentState,
- stepIndex,
- });
- } catch (callbackError) {
- log('[%s] onBeforeStep callback error: %O', operationId, callbackError);
- }
- }
-
// Dispatch beforeStep hooks
try {
const beforeStepMetadata = agentState?.metadata || {};
@@ -823,36 +743,43 @@ export class AgentRuntimeService {
totalTokens: totalTokensNum,
};
- // Call onAfterStep callback with presentation data (legacy)
- if (callbacks?.onAfterStep) {
- try {
- await callbacks.onAfterStep({
- ...stepPresentationData,
- operationId,
- shouldContinue,
- state: stepResult.newState,
- stepIndex,
- stepResult,
- });
- } catch (callbackError) {
- log('[%s] onAfterStep callback error: %O', operationId, callbackError);
- }
- }
-
- // Dispatch afterStep hooks
+ // Dispatch afterStep hooks (enriched with step presentation + tracking data)
try {
const metadata = stepResult.newState?.metadata || {};
+ const tracking = metadata._stepTracking || {};
+ const elapsedMs = stepResult.newState?.createdAt
+ ? Date.now() - new Date(stepResult.newState.createdAt).getTime()
+ : undefined;
await hookDispatcher.dispatch(
operationId,
'afterStep',
{
agentId: metadata?.agentId || '',
+ content,
+ elapsedMs,
+ executionTimeMs: stepPresentationData.executionTimeMs,
finalState: stepResult.newState,
+ lastLLMContent: tracking.lastLLMContent,
+ lastToolsCalling: tracking.lastToolsCalling,
operationId,
+ reasoning: stepPresentationData.reasoning,
shouldContinue,
status: stepResult.newState?.status,
+ stepCost: stepPresentationData.stepCost,
stepIndex,
+ stepType: stepPresentationData.stepType,
steps: stepResult.newState?.stepCount || 0,
+ thinking: stepPresentationData.thinking,
+ toolCalls: stepResult.newState?.usage?.tools?.totalCalls,
+ toolsCalling: stepPresentationData.toolsCalling,
+ toolsResult: stepPresentationData.toolsResult,
+ topicId: metadata?.topicId,
+ totalCost: stepPresentationData.totalCost,
+ totalInputTokens: stepPresentationData.totalInputTokens,
+ totalOutputTokens: stepPresentationData.totalOutputTokens,
+ totalSteps: stepPresentationData.totalSteps,
+ totalTokens: stepPresentationData.totalTokens,
+ totalToolCalls: (tracking.totalToolCalls ?? 0) + (toolsCalling?.length ?? 0),
userId: metadata?.userId || this.userId,
},
metadata._hooks,
@@ -965,12 +892,15 @@ export class AgentRuntimeService {
}
}
- // Update step tracking in state metadata and trigger step webhook
- if (stepResult.newState.metadata?.stepWebhook) {
+ // Update step tracking in state metadata for afterStep hooks (cross-step accumulator)
+ const hasAfterStepHooks = stepResult.newState.metadata?._hooks?.some(
+ (h: { type: string }) => h.type === 'afterStep',
+ );
+ if (hasAfterStepHooks && stepResult.newState.metadata) {
const prevTracking = stepResult.newState.metadata._stepTracking || {};
const newTotalToolCalls = (prevTracking.totalToolCalls ?? 0) + (toolsCalling?.length ?? 0);
- // Truncate content to 1800 chars to match Discord message limits
+ // Truncate content to 1800 chars to keep state small
const truncatedContent = content
? content.length > 1800
? content.slice(0, 1800) + '...'
@@ -986,13 +916,6 @@ export class AgentRuntimeService {
// Persist tracking state for next step
stepResult.newState.metadata._stepTracking = updatedTracking;
await this.coordinator.saveAgentState(operationId, stepResult.newState);
-
- // Fire step webhook (include shouldContinue so the callback knows
- // whether the agent is still running or about to complete)
- await this.triggerStepWebhook(stepResult.newState, operationId, {
- ...stepPresentationData,
- shouldContinue,
- } as unknown as Record<string, unknown>);
}
if (shouldContinue && stepResult.nextContext && this.queueService) {
@@ -1025,27 +948,9 @@ export class AgentRuntimeService {
if (!shouldContinue) {
const reason = this.determineCompletionReason(stepResult.newState);
- // Trigger completion webhook (fire-and-forget)
- await this.triggerCompletionWebhook(stepResult.newState, operationId, reason);
-
// Dispatch onComplete hooks
await this.dispatchCompletionHooks(operationId, stepResult.newState, reason);
- // Call onComplete callback (legacy)
- if (callbacks?.onComplete) {
- try {
- await callbacks.onComplete({
- finalState: stepResult.newState,
- operationId,
- reason,
- });
- // Clean up callbacks after operation completes
- this.unregisterStepCallbacks(operationId);
- } catch (callbackError) {
- log('[%s] onComplete callback error: %O', operationId, callbackError);
- }
- }
-
// Finalize tracing snapshot via injected snapshot store
if (this.snapshotStore) {
try {
@@ -1157,30 +1062,9 @@ export class AgentRuntimeService {
log('[%s] Failed to save error state (infra may be down): %O', operationId, saveError);
}
- // Trigger completion webhook on error (fire-and-forget)
- try {
- await this.triggerCompletionWebhook(finalStateWithError, operationId, 'error');
- } catch (webhookError) {
- log('[%s] Failed to trigger completion webhook: %O', operationId, webhookError);
- }
-
// Dispatch onComplete + onError hooks
await this.dispatchCompletionHooks(operationId, finalStateWithError, 'error');
- // Also call onComplete callback when execution fails (legacy)
- if (callbacks?.onComplete) {
- try {
- await callbacks.onComplete({
- finalState: finalStateWithError,
- operationId,
- reason: 'error',
- });
- this.unregisterStepCallbacks(operationId);
- } catch (callbackError) {
- log('[%s] onComplete callback error in catch: %O', operationId, callbackError);
- }
- }
-
throw error;
} finally {
// Release lock so legitimate retries or next operations can proceed.
@@ -1648,41 +1532,6 @@ export class AgentRuntimeService {
return { newState: state, nextContext: undefined };
}
- /**
- * Deliver a webhook payload via fetch or QStash.
- * Fire-and-forget: errors are logged but never thrown.
- */
- private async deliverWebhook(
- url: string,
- payload: Record<string, unknown>,
- delivery: 'fetch' | 'qstash' = 'fetch',
- operationId: string,
- ): Promise<void> {
- try {
- if (delivery === 'qstash') {
- const { Client } = await import('@upstash/qstash');
- const client = new Client({ token: process.env.QSTASH_TOKEN! });
- await client.publishJSON({
- body: payload,
- headers: {
- ...(process.env.VERCEL_AUTOMATION_BYPASS_SECRET && {
- 'x-vercel-protection-bypass': process.env.VERCEL_AUTOMATION_BYPASS_SECRET,
- }),
- },
- url,
- });
- } else {
- await fetch(url, {
- body: JSON.stringify(payload),
- headers: { 'Content-Type': 'application/json' },
- method: 'POST',
- });
- }
- } catch (error) {
- console.error('[%s] Webhook delivery failed (%s β†’ %s):', operationId, delivery, url, error);
- }
- }
-
/**
* Dispatch onComplete (and onError) hooks via HookDispatcher.
* Fire-and-forget: errors are logged but never thrown.
@@ -1695,7 +1544,7 @@ export class AgentRuntimeService {
try {
const metadata = state?.metadata || {};
- // Extract last assistant content (same as triggerCompletionWebhook)
+ // Extract last assistant content from state messages
const lastAssistantContent = state?.messages
?.slice()
.reverse()
@@ -1742,101 +1591,6 @@ export class AgentRuntimeService {
}
}
- /**
- * Trigger completion webhook if configured in state metadata.
- * Fire-and-forget: errors are logged but never thrown.
- */
- private async triggerCompletionWebhook(
- state: any,
- operationId: string,
- reason: StepCompletionReason,
- ): Promise<void> {
- const webhook = state.metadata?.completionWebhook;
- if (!webhook?.url) return;
-
- log('[%s] Triggering completion webhook: %s', operationId, webhook.url);
-
- const duration = state.createdAt ? Date.now() - new Date(state.createdAt).getTime() : undefined;
-
- // Extract last assistant content from state messages
- const lastAssistantContent = state.messages
- ?.slice()
- .reverse()
- .find(
- (m: { content?: string; role: string }) => m.role === 'assistant' && m.content,
- )?.content;
-
- // Extract first user prompt for downstream consumers (e.g., topic title summarization)
- const userPrompt = state.messages?.find(
- (m: { content?: string; role: string }) => m.role === 'user',
- )?.content;
-
- const delivery = state.metadata?.webhookDelivery || 'fetch';
-
- await this.deliverWebhook(
- webhook.url,
- {
- ...webhook.body,
- cost: state.cost?.total,
- duration,
- errorDetail: state.error,
- errorMessage: this.extractErrorMessage(state.error),
- lastAssistantContent,
- llmCalls: state.usage?.llm?.apiCalls,
- operationId,
- reason,
- status: state.status,
- steps: state.stepCount,
- toolCalls: state.usage?.tools?.totalCalls,
- topicId: state.metadata?.topicId,
- totalTokens: state.usage?.llm?.tokens?.total,
- type: 'completion',
- userId: state.metadata?.userId,
- userPrompt,
- },
- delivery,
- operationId,
- );
- }
-
- /**
- * Trigger step webhook if configured in state metadata.
- * Reads accumulated step tracking data and fires webhook with step presentation data.
- * Fire-and-forget: errors are logged but never thrown.
- */
- private async triggerStepWebhook(
- state: any,
- operationId: string,
- presentationData: Record<string, unknown>,
- ): Promise<void> {
- const webhook = state.metadata?.stepWebhook;
- if (!webhook?.url) return;
-
- log('[%s] Triggering step webhook: %s', operationId, webhook.url);
-
- const tracking = state.metadata?._stepTracking || {};
- const delivery = state.metadata?.webhookDelivery || 'fetch';
- const elapsedMs = state.createdAt
- ? Date.now() - new Date(state.createdAt).getTime()
- : undefined;
-
- await this.deliverWebhook(
- webhook.url,
- {
- ...webhook.body,
- ...presentationData,
- elapsedMs,
- lastLLMContent: tracking.lastLLMContent,
- lastToolsCalling: tracking.lastToolsCalling,
- operationId,
- totalToolCalls: tracking.totalToolCalls ?? 0,
- type: 'step',
- },
- delivery,
- operationId,
- );
- }
-
/**
* Extract a human-readable error message from the agent state error object.
* Handles both raw ChatCompletionErrorPayload (from runtime.step catch) and
@@ -2048,20 +1802,10 @@ export class AgentRuntimeService {
if (stepIndex >= maxSteps) {
log('[%s] Sync execution stopped: reached maxSteps (%d)', operationId, maxSteps);
- // If stopped due to executeSync's maxSteps limit, need to manually call onComplete
+ // If stopped due to executeSync's maxSteps limit, need to manually dispatch onComplete hooks
// Note: If stopped due to state.maxSteps being reached, onComplete has already been called in executeStep
- const callbacks = this.getStepCallbacks(operationId);
- if (callbacks?.onComplete && state.status !== 'done' && state.status !== 'error') {
- try {
- await callbacks.onComplete({
- finalState: state,
- operationId,
- reason: 'max_steps',
- });
- this.unregisterStepCallbacks(operationId);
- } catch (callbackError) {
- log('[%s] onComplete callback error in executeSync: %O', operationId, callbackError);
- }
+ if (state.status !== 'done' && state.status !== 'error') {
+ await this.dispatchCompletionHooks(operationId, state, 'max_steps');
}
}
diff --git a/src/server/services/agentRuntime/__tests__/completionWebhook.test.ts b/src/server/services/agentRuntime/__tests__/completionWebhook.test.ts
index 7f72e3d80a0..3cecc852b45 100644
--- a/src/server/services/agentRuntime/__tests__/completionWebhook.test.ts
+++ b/src/server/services/agentRuntime/__tests__/completionWebhook.test.ts
@@ -56,7 +56,7 @@ vi.mock('@/server/services/toolExecution/builtin', () => ({
})),
}));
-describe('AgentRuntimeService - Completion Webhook', () => {
+describe('AgentRuntimeService - Completion Hooks via createOperation', () => {
let service: AgentRuntimeService;
let stateManager: InMemoryAgentStateManager;
let streamEventManager: InMemoryStreamEventManager;
@@ -91,19 +91,26 @@ describe('AgentRuntimeService - Completion Webhook', () => {
});
});
- describe('createOperation persists completionWebhook', () => {
- it('should persist completionWebhook in state metadata', async () => {
- const operationId = 'webhook-op-1';
- const completionWebhook = {
- body: { runId: 'run-1', testCaseId: 'tc-1' },
- url: 'https://example.com/webhook',
- };
+ describe('createOperation persists hooks in metadata', () => {
+ it('should persist hooks in state metadata._hooks', async () => {
+ const operationId = 'hook-op-1';
+ const hooks = [
+ {
+ handler: vi.fn(),
+ id: 'test-completion',
+ type: 'onComplete' as const,
+ webhook: {
+ body: { runId: 'run-1', testCaseId: 'tc-1' },
+ url: 'https://example.com/webhook',
+ },
+ },
+ ];
await service.createOperation({
agentConfig: { model: 'gpt-4o', provider: 'openai' },
appContext: { agentId: 'test-agent' },
autoStart: false,
- completionWebhook,
+ hooks,
initialContext: makeContext(operationId),
initialMessages: [{ content: 'Hello', role: 'user' }],
modelRuntimeConfig: { model: 'gpt-4o', provider: 'openai' },
@@ -113,11 +120,20 @@ describe('AgentRuntimeService - Completion Webhook', () => {
});
const state = await stateManager.loadAgentState(operationId);
- expect(state?.metadata?.completionWebhook).toEqual(completionWebhook);
+ expect(state?.metadata?._hooks).toEqual([
+ expect.objectContaining({
+ id: 'test-completion',
+ type: 'onComplete',
+ webhook: {
+ body: { runId: 'run-1', testCaseId: 'tc-1' },
+ url: 'https://example.com/webhook',
+ },
+ }),
+ ]);
});
- it('should not have completionWebhook in metadata when not provided', async () => {
- const operationId = 'webhook-op-2';
+ it('should not have _hooks in metadata when no hooks provided', async () => {
+ const operationId = 'hook-op-2';
await service.createOperation({
agentConfig: { model: 'gpt-4o', provider: 'openai' },
@@ -132,18 +148,18 @@ describe('AgentRuntimeService - Completion Webhook', () => {
});
const state = await stateManager.loadAgentState(operationId);
- expect(state?.metadata?.completionWebhook).toBeUndefined();
+ expect(state?.metadata?._hooks).toBeUndefined();
});
});
- describe('executeStep triggers webhook', () => {
+ describe('webhook delivery through hooks', () => {
const fetchSpy = vi.fn().mockResolvedValue({ ok: true });
beforeEach(() => {
vi.stubGlobal('fetch', fetchSpy);
});
- const createOperationWithWebhook = async (
+ const createOperationWithHook = async (
operationId: string,
webhookUrl: string,
webhookBody?: Record<string, unknown>,
@@ -152,7 +168,14 @@ describe('AgentRuntimeService - Completion Webhook', () => {
agentConfig: { model: 'gpt-4o', provider: 'openai' },
appContext: { agentId: 'test-agent' },
autoStart: false,
- completionWebhook: { body: webhookBody, url: webhookUrl },
+ hooks: [
+ {
+ handler: vi.fn(),
+ id: 'test-completion',
+ type: 'onComplete' as const,
+ webhook: { body: webhookBody, url: webhookUrl },
+ },
+ ],
initialContext: makeContext(operationId),
initialMessages: [{ content: 'Hello', role: 'user' }],
modelRuntimeConfig: { model: 'gpt-4o', provider: 'openai' },
@@ -162,12 +185,12 @@ describe('AgentRuntimeService - Completion Webhook', () => {
});
};
- it('should trigger webhook when operation completes normally', async () => {
- const operationId = 'webhook-complete-1';
+ it('should persist webhook hook config for later delivery on completion', async () => {
+ const operationId = 'hook-complete-1';
const webhookUrl = 'https://example.com/on-complete';
const webhookBody = { runId: 'run-1', testCaseId: 'tc-1' };
- await createOperationWithWebhook(operationId, webhookUrl, webhookBody);
+ await createOperationWithHook(operationId, webhookUrl, webhookBody);
// Manually set state to simulate a step that produces 'done' status
const state = await stateManager.loadAgentState(operationId);
@@ -176,21 +199,22 @@ describe('AgentRuntimeService - Completion Webhook', () => {
status: 'done',
});
- // executeStep will call triggerCompletionWebhook when !shouldContinue
- // We need the step to actually produce a done state, but since we can't
- // easily mock the full runtime.step, we test the metadata persistence above
- // and verify the webhook method is correct through the type + metadata test.
-
- // Verify the webhook config is persisted for later use
+ // Verify the hook config is persisted for later use
const updatedState = await stateManager.loadAgentState(operationId);
- expect(updatedState?.metadata?.completionWebhook).toEqual({
- body: webhookBody,
- url: webhookUrl,
- });
+ expect(updatedState?.metadata?._hooks).toEqual([
+ expect.objectContaining({
+ id: 'test-completion',
+ type: 'onComplete',
+ webhook: {
+ body: webhookBody,
+ url: webhookUrl,
+ },
+ }),
+ ]);
});
- it('should NOT trigger webhook when no completionWebhook is configured', async () => {
- const operationId = 'webhook-none-1';
+ it('should NOT have hook config when no hooks are configured', async () => {
+ const operationId = 'hook-none-1';
await service.createOperation({
agentConfig: { model: 'gpt-4o', provider: 'openai' },
@@ -205,41 +229,33 @@ describe('AgentRuntimeService - Completion Webhook', () => {
});
const state = await stateManager.loadAgentState(operationId);
- expect(state?.metadata?.completionWebhook).toBeUndefined();
-
- // fetch should not be called for webhook since there's no webhook config
- // (It may still be called for other reasons in real execution)
+ expect(state?.metadata?._hooks).toBeUndefined();
});
it('should not throw when webhook fetch fails', async () => {
- const operationId = 'webhook-fail-1';
+ const operationId = 'hook-fail-1';
const webhookUrl = 'https://example.com/failing-webhook';
// Make fetch throw
fetchSpy.mockRejectedValueOnce(new Error('Network error'));
- await createOperationWithWebhook(operationId, webhookUrl, { runId: 'run-1' });
+ await createOperationWithHook(operationId, webhookUrl, { runId: 'run-1' });
- // Verify the webhook is stored β€” the triggerCompletionWebhook method
- // catches errors internally and doesn't throw
+ // Verify the hook is stored -- the hook dispatch catches errors internally
const state = await stateManager.loadAgentState(operationId);
- expect(state?.metadata?.completionWebhook?.url).toBe(webhookUrl);
+ expect(state?.metadata?._hooks?.[0]?.webhook?.url).toBe(webhookUrl);
});
});
- describe('triggerCompletionWebhook integration via executeSync', () => {
+ describe('hook payload structure', () => {
const fetchSpy = vi.fn().mockResolvedValue({ ok: true });
beforeEach(() => {
vi.stubGlobal('fetch', fetchSpy);
});
- it('should include webhook body fields plus operationId/reason/status in POST payload', async () => {
- // This test verifies the contract of what triggerCompletionWebhook sends.
- // Since triggerCompletionWebhook is private, we verify through the metadata
- // and the expected fetch call shape.
-
- const operationId = 'webhook-payload-test';
+ it('should include webhook body fields in the persisted hook config', async () => {
+ const operationId = 'hook-payload-test';
const webhookUrl = 'https://example.com/webhook';
const webhookBody = { runId: 'run-123', testCaseId: 'tc-456', userId: 'user-789' };
@@ -247,7 +263,14 @@ describe('AgentRuntimeService - Completion Webhook', () => {
agentConfig: { model: 'gpt-4o', provider: 'openai' },
appContext: { agentId: 'test-agent' },
autoStart: false,
- completionWebhook: { body: webhookBody, url: webhookUrl },
+ hooks: [
+ {
+ handler: vi.fn(),
+ id: 'test-completion',
+ type: 'onComplete' as const,
+ webhook: { body: webhookBody, url: webhookUrl },
+ },
+ ],
initialContext: makeContext(operationId),
initialMessages: [{ content: 'Hello', role: 'user' }],
modelRuntimeConfig: { model: 'gpt-4o', provider: 'openai' },
@@ -256,12 +279,13 @@ describe('AgentRuntimeService - Completion Webhook', () => {
userId,
});
- // Verify the persisted webhook contains the right structure
+ // Verify the persisted hook contains the right structure
const state = await stateManager.loadAgentState(operationId);
- const webhook = state?.metadata?.completionWebhook;
- expect(webhook).toBeDefined();
- expect(webhook.url).toBe(webhookUrl);
- expect(webhook.body).toEqual(webhookBody);
+ const hooks = state?.metadata?._hooks;
+ expect(hooks).toBeDefined();
+ expect(hooks).toHaveLength(1);
+ expect(hooks[0].webhook.url).toBe(webhookUrl);
+ expect(hooks[0].webhook.body).toEqual(webhookBody);
});
});
});
diff --git a/src/server/services/agentRuntime/__tests__/executeStep.test.ts b/src/server/services/agentRuntime/__tests__/executeStep.test.ts
index d588528706c..2d133b9b112 100644
--- a/src/server/services/agentRuntime/__tests__/executeStep.test.ts
+++ b/src/server/services/agentRuntime/__tests__/executeStep.test.ts
@@ -2,6 +2,7 @@
import { describe, expect, it, vi } from 'vitest';
import { AgentRuntimeService } from '../AgentRuntimeService';
+import { hookDispatcher } from '../hooks';
// Mock all heavy dependencies to isolate executeStep logic
vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'http://localhost:3010' } }));
@@ -81,7 +82,7 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>
});
}
- it('should call onComplete callback when skipping interrupted operation', async () => {
+ it('should dispatch onComplete hook when skipping interrupted operation', async () => {
const service = createService();
const coordinator = (service as any).coordinator;
@@ -91,8 +92,7 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>
lastModified: new Date().toISOString(),
});
- const onComplete = vi.fn();
- service.registerStepCallbacks('op-123', { onComplete });
+ const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined);
await service.executeStep({
operationId: 'op-123',
@@ -100,14 +100,20 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>
context: { phase: 'user_input' } as any,
});
- expect(onComplete).toHaveBeenCalledWith({
- finalState: expect.objectContaining({ status: 'interrupted' }),
- operationId: 'op-123',
- reason: 'interrupted',
- });
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'op-123',
+ 'onComplete',
+ expect.objectContaining({
+ operationId: 'op-123',
+ reason: 'interrupted',
+ }),
+ undefined,
+ );
+
+ dispatchSpy.mockRestore();
});
- it('should call onComplete with reason "done" when skipping done operation', async () => {
+ it('should dispatch onComplete hook with reason "done" when skipping done operation', async () => {
const service = createService();
const coordinator = (service as any).coordinator;
@@ -117,8 +123,7 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>
lastModified: new Date().toISOString(),
});
- const onComplete = vi.fn();
- service.registerStepCallbacks('op-456', { onComplete });
+ const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined);
await service.executeStep({
operationId: 'op-456',
@@ -126,14 +131,20 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>
context: { phase: 'user_input' } as any,
});
- expect(onComplete).toHaveBeenCalledWith({
- finalState: expect.objectContaining({ status: 'done' }),
- operationId: 'op-456',
- reason: 'done',
- });
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'op-456',
+ 'onComplete',
+ expect.objectContaining({
+ operationId: 'op-456',
+ reason: 'done',
+ }),
+ undefined,
+ );
+
+ dispatchSpy.mockRestore();
});
- it('should unregister callbacks after onComplete is called on early exit', async () => {
+ it('should unregister hooks after onComplete is dispatched on early exit', async () => {
const service = createService();
const coordinator = (service as any).coordinator;
@@ -143,8 +154,8 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>
lastModified: new Date().toISOString(),
});
- const onComplete = vi.fn();
- service.registerStepCallbacks('op-789', { onComplete });
+ const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined);
+ const unregisterSpy = vi.spyOn(hookDispatcher, 'unregister');
await service.executeStep({
operationId: 'op-789',
@@ -152,8 +163,11 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>
context: { phase: 'user_input' } as any,
});
- // Callbacks should be unregistered after onComplete
- expect(service.getStepCallbacks('op-789')).toBeUndefined();
+ // Hooks should be unregistered after completion dispatch
+ expect(unregisterSpy).toHaveBeenCalledWith('op-789');
+
+ dispatchSpy.mockRestore();
+ unregisterSpy.mockRestore();
});
it('should NOT skip step when operation status is "running"', async () => {
@@ -301,7 +315,7 @@ describe('AgentRuntimeService.executeStep - Redis failure in error handler', ()
return service;
};
- it('should still call onComplete when Redis fails in catch block (ECONNRESET scenario)', async () => {
+ it('should still dispatch onComplete hooks when Redis fails in catch block (ECONNRESET scenario)', async () => {
const service = createService();
const coordinator = (service as any).coordinator;
const streamManager = (service as any).streamManager;
@@ -336,10 +350,9 @@ describe('AgentRuntimeService.executeStep - Redis failure in error handler', ()
// saveAgentState fails (Redis is down)
coordinator.saveAgentState = vi.fn().mockRejectedValue(new Error('Redis ECONNRESET'));
- const onComplete = vi.fn();
- service.registerStepCallbacks('op-redis-fail', { onComplete });
+ const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined);
- // executeStep re-throws the original error after running callbacks
+ // executeStep re-throws the original error after running hooks
await expect(
service.executeStep({
operationId: 'op-redis-fail',
@@ -348,16 +361,21 @@ describe('AgentRuntimeService.executeStep - Redis failure in error handler', ()
}),
).rejects.toThrow();
- // onComplete MUST be called even when Redis is completely down
- expect(onComplete).toHaveBeenCalledWith(
+ // onComplete hooks MUST be dispatched even when Redis is completely down
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'op-redis-fail',
+ 'onComplete',
expect.objectContaining({
operationId: 'op-redis-fail',
reason: 'error',
}),
+ undefined,
);
+
+ dispatchSpy.mockRestore();
});
- it('should still trigger completion webhook when Redis fails in catch block', async () => {
+ it('should still dispatch onError hooks when Redis fails in catch block', async () => {
const service = createService();
const coordinator = (service as any).coordinator;
const streamManager = (service as any).streamManager;
@@ -388,12 +406,9 @@ describe('AgentRuntimeService.executeStep - Redis failure in error handler', ()
coordinator.saveAgentState = vi.fn().mockRejectedValue(new Error('Redis ECONNRESET'));
- // Spy on triggerCompletionWebhook
- const triggerSpy = vi
- .spyOn(service as any, 'triggerCompletionWebhook')
- .mockResolvedValue(undefined);
+ const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined);
- // executeStep re-throws the original error after running callbacks
+ // executeStep re-throws the original error after running hooks
await expect(
service.executeStep({
operationId: 'op-redis-webhook',
@@ -402,12 +417,18 @@ describe('AgentRuntimeService.executeStep - Redis failure in error handler', ()
}),
).rejects.toThrow();
- // Completion webhook MUST be triggered even when Redis is down
- expect(triggerSpy).toHaveBeenCalledWith(
- expect.objectContaining({ status: 'error' }),
+ // Both onComplete and onError hooks MUST be dispatched when reason is error
+ expect(dispatchSpy).toHaveBeenCalledWith(
'op-redis-webhook',
- 'error',
+ 'onError',
+ expect.objectContaining({
+ operationId: 'op-redis-webhook',
+ reason: 'error',
+ }),
+ undefined,
);
+
+ dispatchSpy.mockRestore();
});
it('should include stepCount in fallback error state when state reload fails', async () => {
@@ -511,15 +532,23 @@ describe('AgentRuntimeService.executeStep - Redis failure in error handler', ()
coordinator.tryClaimStep = vi.fn().mockResolvedValue(true);
- const stateWithWebhook = {
+ const stateWithHooks = {
status: 'running',
stepCount: 5,
lastModified: new Date().toISOString(),
- metadata: { completionWebhook: 'https://example.com/webhook' },
+ metadata: {
+ _hooks: [
+ {
+ id: 'test-hook',
+ type: 'onComplete',
+ webhook: { url: 'https://example.com/webhook' },
+ },
+ ],
+ },
};
- // loadAgentState always succeeds (returns state with webhook metadata)
- coordinator.loadAgentState = vi.fn().mockResolvedValue(stateWithWebhook);
+ // loadAgentState always succeeds (returns state with hook metadata)
+ coordinator.loadAgentState = vi.fn().mockResolvedValue(stateWithHooks);
// saveAgentState fails (write-only Redis failure)
coordinator.saveAgentState = vi.fn().mockRejectedValue(new Error('Redis write failed'));
@@ -532,8 +561,7 @@ describe('AgentRuntimeService.executeStep - Redis failure in error handler', ()
return Promise.reject(new Error('Redis ECONNRESET'));
});
- const onComplete = vi.fn();
- service.registerStepCallbacks('op-save-fail', { onComplete });
+ const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined);
await expect(
service.executeStep({
@@ -543,18 +571,28 @@ describe('AgentRuntimeService.executeStep - Redis failure in error handler', ()
}),
).rejects.toThrow();
- // onComplete must receive the full state with metadata (not a minimal fallback)
- expect(onComplete).toHaveBeenCalledWith(
+ // onComplete hooks must be dispatched with the full state including metadata
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'op-save-fail',
+ 'onComplete',
expect.objectContaining({
+ operationId: 'op-save-fail',
+ reason: 'error',
finalState: expect.objectContaining({
metadata: expect.objectContaining({
- completionWebhook: 'https://example.com/webhook',
+ _hooks: expect.arrayContaining([
+ expect.objectContaining({
+ id: 'test-hook',
+ webhook: { url: 'https://example.com/webhook' },
+ }),
+ ]),
}),
status: 'error',
}),
- operationId: 'op-save-fail',
- reason: 'error',
}),
+ expect.anything(),
);
+
+ dispatchSpy.mockRestore();
});
});
diff --git a/src/server/services/agentRuntime/__tests__/hooksIntegration.test.ts b/src/server/services/agentRuntime/__tests__/hooksIntegration.test.ts
new file mode 100644
index 00000000000..433baf9336e
--- /dev/null
+++ b/src/server/services/agentRuntime/__tests__/hooksIntegration.test.ts
@@ -0,0 +1,380 @@
+// @vitest-environment node
+/**
+ * Integration test: hooks e2e chain
+ *
+ * Verifies the full data flow from AgentRuntimeService.executeStep
+ * through HookDispatcher to hook handlers β€” with enriched step
+ * presentation data that bot consumers depend on.
+ *
+ * This catches payload format regressions that unit tests miss because
+ * they mock the dispatch layer.
+ */
+import { describe, expect, it, vi } from 'vitest';
+
+import { AgentRuntimeService } from '../AgentRuntimeService';
+import { hookDispatcher } from '../hooks';
+import type { AgentHookEvent } from '../hooks/types';
+
+// ── Mocks ──────────────────────────────────────────
+vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'http://localhost:3010' } }));
+vi.mock('@/database/models/message', () => ({
+ MessageModel: vi.fn().mockImplementation(() => ({})),
+}));
+vi.mock('@/server/modules/AgentRuntime', () => ({
+ AgentRuntimeCoordinator: vi.fn().mockImplementation(() => ({
+ createAgentOperation: vi.fn(),
+ getOperationMetadata: vi.fn(),
+ loadAgentState: vi.fn(),
+ releaseStepLock: vi.fn().mockResolvedValue(undefined),
+ saveAgentState: vi.fn(),
+ saveStepResult: vi.fn(),
+ tryClaimStep: vi.fn().mockResolvedValue(true),
+ })),
+ createStreamEventManager: vi.fn(() => ({
+ cleanupOperation: vi.fn(),
+ publishAgentRuntimeEnd: vi.fn(),
+ publishAgentRuntimeInit: vi.fn(),
+ publishStreamEvent: vi.fn(),
+ })),
+}));
+vi.mock('@/server/modules/AgentRuntime/RuntimeExecutors', () => ({
+ createRuntimeExecutors: vi.fn(() => ({})),
+}));
+vi.mock('@/server/services/mcp', () => ({ mcpService: {} }));
+vi.mock('@/server/services/queue', () => ({
+ QueueService: vi.fn().mockImplementation(() => ({
+ getImpl: vi.fn(() => ({})),
+ scheduleMessage: vi.fn(),
+ })),
+}));
+vi.mock('@/server/services/queue/impls', () => ({
+ LocalQueueServiceImpl: class {},
+ isQueueAgentRuntimeEnabled: vi.fn().mockReturnValue(false),
+}));
+vi.mock('@/server/services/toolExecution', () => ({
+ ToolExecutionService: vi.fn().mockImplementation(() => ({})),
+}));
+vi.mock('@/server/services/toolExecution/builtin', () => ({
+ BuiltinToolsExecutor: vi.fn().mockImplementation(() => ({})),
+}));
+vi.mock('@lobechat/builtin-tools/dynamicInterventionAudits', () => ({
+ dynamicInterventionAudits: [],
+}));
+
+describe('Hooks integration β€” afterStep event carries step presentation data', () => {
+ const createService = () => new AgentRuntimeService({} as any, 'user-1', { queueService: null });
+
+ it('should include content, stepType, totalTokens, toolsCalling in afterStep event', async () => {
+ const service = createService();
+ const coordinator = (service as any).coordinator;
+
+ // Simulate a running operation with afterStep hooks in metadata
+ coordinator.loadAgentState.mockResolvedValue({
+ createdAt: new Date().toISOString(),
+ lastModified: new Date().toISOString(),
+ messages: [{ content: 'Hello', role: 'user' }],
+ metadata: {
+ _hooks: [{ id: 'bot-step', type: 'afterStep', webhook: { url: '/test' } }],
+ agentId: 'agent-1',
+ userId: 'user-1',
+ },
+ operationId: 'op-1',
+ status: 'running',
+ stepCount: 0,
+ usage: { llm: { tokens: { total: 150 } }, tools: { totalCalls: 0 } },
+ });
+
+ // Mock runtime.step to return an LLM step with content
+ // nextContext.phase is NOT tool_result, so content is extracted from llm_result event
+ const stepResult = {
+ events: [{ result: { content: 'Let me search for that.' }, type: 'llm_result' }],
+ newState: {
+ cost: { total: 0.01 },
+ createdAt: new Date().toISOString(),
+ messages: [
+ { content: 'Hello', role: 'user' },
+ { content: 'Let me search for that.', role: 'assistant' },
+ ],
+ metadata: {
+ _hooks: [{ id: 'bot-step', type: 'afterStep', webhook: { url: '/test' } }],
+ agentId: 'agent-1',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ },
+ status: 'running',
+ stepCount: 1,
+ usage: {
+ llm: {
+ apiCalls: 1,
+ tokens: { input: 50, output: 100, total: 150 },
+ },
+ tools: { totalCalls: 0 },
+ },
+ },
+ nextContext: {
+ payload: { message: [{ content: 'Let me search for that.' }] },
+ phase: 'user_input',
+ session: { sessionId: 'op-1', status: 'running', stepCount: 1 },
+ },
+ };
+
+ vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({
+ runtime: { step: vi.fn().mockResolvedValue(stepResult) },
+ });
+
+ // Capture the actual hook event
+ const capturedEvents: AgentHookEvent[] = [];
+ const dispatchSpy = vi
+ .spyOn(hookDispatcher, 'dispatch')
+ .mockImplementation(async (_opId, type, event) => {
+ if (type === 'afterStep') capturedEvents.push(event);
+ });
+
+ await service.executeStep({
+ context: { phase: 'user_input' } as any,
+ operationId: 'op-1',
+ stepIndex: 0,
+ });
+
+ expect(capturedEvents).toHaveLength(1);
+ const event = capturedEvents[0];
+
+ // ── Core identification ──
+ expect(event.operationId).toBe('op-1');
+ expect(event.agentId).toBe('agent-1');
+ expect(event.userId).toBe('user-1');
+
+ // ── Step presentation data (what bot renderers need) ──
+ expect(event.content).toBe('Let me search for that.');
+ expect(event.stepType).toMatch(/call_llm|call_tool/);
+ expect(typeof event.executionTimeMs).toBe('number');
+ expect(event.totalTokens).toBe(150);
+ expect(event.totalCost).toBe(0.01);
+ expect(event.totalSteps).toBe(1);
+ expect(event.shouldContinue).toBe(true);
+ expect(event.topicId).toBe('topic-1');
+
+ // ── Tracking data (cross-step accumulator for bot progress) ──
+ expect(typeof event.totalToolCalls).toBe('number');
+ // elapsedMs should be calculated from state.createdAt
+ expect(typeof event.elapsedMs).toBe('number');
+
+ // ── Full state available for local mode consumers ──
+ expect(event.finalState).toBeDefined();
+ expect(event.finalState.status).toBe('running');
+
+ dispatchSpy.mockRestore();
+ });
+
+ it('should include toolsResult for tool_result phase', async () => {
+ const service = createService();
+ const coordinator = (service as any).coordinator;
+
+ coordinator.loadAgentState.mockResolvedValue({
+ createdAt: new Date().toISOString(),
+ lastModified: new Date().toISOString(),
+ messages: [],
+ metadata: {
+ _hooks: [{ id: 'bot-step', type: 'afterStep', webhook: { url: '/test' } }],
+ _stepTracking: { lastLLMContent: 'previous content', totalToolCalls: 1 },
+ agentId: 'agent-1',
+ userId: 'user-1',
+ },
+ operationId: 'op-2',
+ status: 'running',
+ stepCount: 1,
+ });
+
+ // stepResult.nextContext has tool_result phase β€” this is where toolsResult is extracted from
+ const stepResult = {
+ events: [{ type: 'done' }],
+ newState: {
+ createdAt: new Date().toISOString(),
+ messages: [],
+ metadata: {
+ _hooks: [{ id: 'bot-step', type: 'afterStep', webhook: { url: '/test' } }],
+ _stepTracking: { lastLLMContent: 'previous content', totalToolCalls: 1 },
+ agentId: 'agent-1',
+ userId: 'user-1',
+ },
+ status: 'running',
+ stepCount: 2,
+ usage: { llm: { tokens: { total: 200 } }, tools: { totalCalls: 1 } },
+ },
+ nextContext: {
+ payload: {
+ data: 'Search found 3 results',
+ toolCall: { apiName: 'search', id: 'tc-1', identifier: 'lobe-web-browsing' },
+ toolCallId: 'tc-1',
+ },
+ phase: 'tool_result',
+ session: { sessionId: 'op-2', status: 'running', stepCount: 2 },
+ },
+ };
+
+ vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({
+ runtime: { step: vi.fn().mockResolvedValue(stepResult) },
+ });
+
+ const capturedEvents: AgentHookEvent[] = [];
+ const dispatchSpy = vi
+ .spyOn(hookDispatcher, 'dispatch')
+ .mockImplementation(async (_opId, type, event) => {
+ if (type === 'afterStep') capturedEvents.push(event);
+ });
+
+ await service.executeStep({
+ context: { phase: 'user_input' } as any,
+ operationId: 'op-2',
+ stepIndex: 1,
+ });
+
+ expect(capturedEvents).toHaveLength(1);
+ const event = capturedEvents[0];
+
+ // Tool result extracted from stepResult.nextContext.payload
+ expect(event.toolsResult).toBeDefined();
+ expect(event.toolsResult).toEqual([
+ expect.objectContaining({
+ apiName: 'search',
+ identifier: 'lobe-web-browsing',
+ output: 'Search found 3 results',
+ }),
+ ]);
+
+ // Tracking data carries forward from previous steps
+ expect(event.lastLLMContent).toBe('previous content');
+ // totalToolCalls includes current step (1 previous + 0 new tool calls in this step)
+ expect(event.totalToolCalls).toBe(1);
+
+ dispatchSpy.mockRestore();
+ });
+});
+
+describe('Hooks integration β€” onComplete event for early-terminal states', () => {
+ const createService = () => new AgentRuntimeService({} as any, 'user-1', { queueService: null });
+
+ it('should dispatch onComplete with correct reason when operation is interrupted', async () => {
+ const service = createService();
+ const coordinator = (service as any).coordinator;
+
+ coordinator.loadAgentState.mockResolvedValue({
+ createdAt: new Date().toISOString(),
+ lastModified: new Date().toISOString(),
+ messages: [
+ { content: 'Hello', role: 'user' },
+ { content: 'I was working on it...', role: 'assistant' },
+ ],
+ metadata: { agentId: 'agent-1', userId: 'user-1' },
+ status: 'interrupted',
+ stepCount: 3,
+ usage: { llm: { apiCalls: 2, tokens: { total: 500 } }, tools: { totalCalls: 1 } },
+ });
+
+ const capturedEvents: AgentHookEvent[] = [];
+ const dispatchSpy = vi
+ .spyOn(hookDispatcher, 'dispatch')
+ .mockImplementation(async (_opId, type, event) => {
+ if (type === 'onComplete') capturedEvents.push(event);
+ });
+
+ await service.executeStep({
+ context: { phase: 'user_input' } as any,
+ operationId: 'op-interrupted',
+ stepIndex: 4,
+ });
+
+ expect(capturedEvents).toHaveLength(1);
+ const event = capturedEvents[0];
+
+ expect(event.reason).toBe('interrupted');
+ expect(event.operationId).toBe('op-interrupted');
+ expect(event.lastAssistantContent).toBe('I was working on it...');
+ expect(event.finalState).toBeDefined();
+
+ dispatchSpy.mockRestore();
+ });
+});
+
+describe('Hooks integration β€” afterStep event is compatible with renderStepProgress', () => {
+ const createService = () => new AgentRuntimeService({} as any, 'user-1', { queueService: null });
+
+ it('afterStep event fields map to RenderStepParams without undefined required fields', async () => {
+ const service = createService();
+ const coordinator = (service as any).coordinator;
+
+ coordinator.loadAgentState.mockResolvedValue({
+ createdAt: new Date().toISOString(),
+ lastModified: new Date().toISOString(),
+ messages: [],
+ metadata: {
+ _hooks: [{ id: 'bot-step', type: 'afterStep', webhook: { url: '/test' } }],
+ agentId: 'agent-1',
+ userId: 'user-1',
+ },
+ operationId: 'op-compat',
+ status: 'running',
+ stepCount: 0,
+ });
+
+ const stepResult = {
+ events: [{ type: 'done' }],
+ newState: {
+ createdAt: new Date().toISOString(),
+ messages: [{ content: 'Result', role: 'assistant' }],
+ metadata: {
+ _hooks: [{ id: 'bot-step', type: 'afterStep', webhook: { url: '/test' } }],
+ agentId: 'agent-1',
+ userId: 'user-1',
+ },
+ status: 'done',
+ stepCount: 1,
+ usage: { llm: { tokens: { total: 100 } } },
+ },
+ nextContext: null,
+ };
+
+ vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({
+ runtime: { step: vi.fn().mockResolvedValue(stepResult) },
+ });
+
+ const capturedEvents: AgentHookEvent[] = [];
+ const dispatchSpy = vi
+ .spyOn(hookDispatcher, 'dispatch')
+ .mockImplementation(async (_opId, type, event) => {
+ if (type === 'afterStep') capturedEvents.push(event);
+ });
+
+ await service.executeStep({
+ context: { phase: 'user_input' } as any,
+ operationId: 'op-compat',
+ stepIndex: 0,
+ });
+
+ expect(capturedEvents).toHaveLength(1);
+ const event = capturedEvents[0];
+
+ // Verify all fields needed by renderStepProgress are present and typed correctly
+ // These map to RenderStepParams = StepPresentationData + { elapsedMs, lastContent, lastToolsCalling, totalToolCalls }
+ expect(event.stepType).toBeDefined();
+ expect(['call_llm', 'call_tool']).toContain(event.stepType);
+ expect(typeof event.executionTimeMs).toBe('number');
+ expect(typeof event.totalSteps).toBe('number');
+ expect(typeof event.totalTokens).toBe('number');
+ expect(typeof event.totalCost).toBe('number');
+ expect(typeof event.totalInputTokens).toBe('number');
+ expect(typeof event.totalOutputTokens).toBe('number');
+ expect(typeof event.thinking).toBe('boolean');
+ // These can be undefined but must be present as keys
+ expect('content' in event).toBe(true);
+ expect('reasoning' in event).toBe(true);
+ expect('toolsCalling' in event).toBe(true);
+ expect('toolsResult' in event).toBe(true);
+ expect('elapsedMs' in event).toBe(true);
+ expect('lastLLMContent' in event).toBe(true);
+ expect('lastToolsCalling' in event).toBe(true);
+ expect('totalToolCalls' in event).toBe(true);
+
+ dispatchSpy.mockRestore();
+ });
+});
diff --git a/src/server/services/agentRuntime/__tests__/stepLifecycleCallbacks.test.ts b/src/server/services/agentRuntime/__tests__/stepLifecycleCallbacks.test.ts
deleted file mode 100644
index 25ac820db7a..00000000000
--- a/src/server/services/agentRuntime/__tests__/stepLifecycleCallbacks.test.ts
+++ /dev/null
@@ -1,346 +0,0 @@
-import { type AgentRuntimeContext } from '@lobechat/agent-runtime';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import {
- InMemoryAgentStateManager,
- InMemoryStreamEventManager,
-} from '@/server/modules/AgentRuntime';
-
-import { AgentRuntimeService } from '../AgentRuntimeService';
-import { type StepCompletionReason, type StepLifecycleCallbacks } from '../types';
-
-// Mock database models
-vi.mock('@/database/models/message', () => ({
- MessageModel: vi.fn().mockImplementation(() => ({
- create: vi.fn().mockResolvedValue({ id: 'msg-1' }),
- query: vi.fn().mockResolvedValue([]),
- update: vi.fn().mockResolvedValue({}),
- })),
-}));
-
-// Mock ModelRuntime
-vi.mock('@/server/modules/ModelRuntime', () => ({
- ApiKeyManager: vi.fn().mockImplementation(() => ({
- getAllApiKeys: vi.fn(),
- getApiKey: vi.fn(),
- })),
- initializeRuntimeOptions: vi.fn(),
- initModelRuntimeFromDB: vi.fn().mockResolvedValue({
- chat: vi.fn(),
- }),
-}));
-
-// Mock search service
-vi.mock('@/server/services/search', () => ({
- searchService: {
- search: vi.fn(),
- },
-}));
-
-// Mock MCP service
-vi.mock('@/server/services/mcp', () => ({
- mcpService: {
- executeCommand: vi.fn(),
- },
-}));
-
-// Mock tool execution service
-vi.mock('@/server/services/toolExecution', () => ({
- ToolExecutionService: vi.fn().mockImplementation(() => ({
- executeToolCall: vi.fn().mockResolvedValue({ result: 'success' }),
- })),
-}));
-
-vi.mock('@/server/services/toolExecution/builtin', () => ({
- BuiltinToolsExecutor: vi.fn().mockImplementation(() => ({
- execute: vi.fn(),
- })),
-}));
-
-describe('AgentRuntimeService - Step Lifecycle Callbacks', () => {
- let service: AgentRuntimeService;
- let stateManager: InMemoryAgentStateManager;
- let streamEventManager: InMemoryStreamEventManager;
-
- const mockDb = {} as any;
- const userId = 'test-user-id';
-
- beforeEach(() => {
- vi.clearAllMocks();
-
- // Create in-memory managers
- stateManager = new InMemoryAgentStateManager();
- streamEventManager = new InMemoryStreamEventManager();
-
- // Create service with in-memory implementations and no queue
- service = new AgentRuntimeService(mockDb, userId, {
- coordinatorOptions: {
- stateManager,
- streamEventManager,
- },
- queueService: null, // Disable queue for sync execution
- streamEventManager,
- });
- });
-
- describe('registerStepCallbacks', () => {
- it('should register callbacks for an operation', () => {
- const operationId = 'test-op-1';
- const callbacks: StepLifecycleCallbacks = {
- onAfterStep: vi.fn(),
- onBeforeStep: vi.fn(),
- onComplete: vi.fn(),
- };
-
- service.registerStepCallbacks(operationId, callbacks);
-
- const registered = service.getStepCallbacks(operationId);
- expect(registered).toBe(callbacks);
- });
-
- it('should overwrite existing callbacks if registered again', () => {
- const operationId = 'test-op-2';
- const callbacks1: StepLifecycleCallbacks = { onBeforeStep: vi.fn() };
- const callbacks2: StepLifecycleCallbacks = { onAfterStep: vi.fn() };
-
- service.registerStepCallbacks(operationId, callbacks1);
- service.registerStepCallbacks(operationId, callbacks2);
-
- const registered = service.getStepCallbacks(operationId);
- expect(registered).toBe(callbacks2);
- });
- });
-
- describe('unregisterStepCallbacks', () => {
- it('should remove registered callbacks', () => {
- const operationId = 'test-op-3';
- const callbacks: StepLifecycleCallbacks = { onBeforeStep: vi.fn() };
-
- service.registerStepCallbacks(operationId, callbacks);
- service.unregisterStepCallbacks(operationId);
-
- const registered = service.getStepCallbacks(operationId);
- expect(registered).toBeUndefined();
- });
-
- it('should not throw when unregistering non-existent callbacks', () => {
- expect(() => {
- service.unregisterStepCallbacks('non-existent-op');
- }).not.toThrow();
- });
- });
-
- describe('getStepCallbacks', () => {
- it('should return undefined for non-existent operation', () => {
- const registered = service.getStepCallbacks('non-existent-op');
- expect(registered).toBeUndefined();
- });
- });
-
- describe('createOperation with stepCallbacks', () => {
- it('should register callbacks when provided in createOperation params', async () => {
- const operationId = 'test-op-with-callbacks';
- const callbacks: StepLifecycleCallbacks = {
- onAfterStep: vi.fn(),
- onBeforeStep: vi.fn(),
- onComplete: vi.fn(),
- };
-
- const initialContext: AgentRuntimeContext = {
- payload: { message: [{ content: 'Hello' }] },
- phase: 'user_input',
- session: {
- messageCount: 1,
- sessionId: operationId,
- status: 'idle',
- stepCount: 0,
- },
- };
-
- await service.createOperation({
- agentConfig: { model: 'gpt-4o', provider: 'openai' },
- appContext: { agentId: 'test-agent' },
- autoStart: false,
- initialContext,
- initialMessages: [{ content: 'Hello', role: 'user' }],
- modelRuntimeConfig: { model: 'gpt-4o', provider: 'openai' },
- operationId,
- stepCallbacks: callbacks,
- toolSet: { manifestMap: {}, tools: [] },
- userId,
- });
-
- const registered = service.getStepCallbacks(operationId);
- expect(registered).toBe(callbacks);
- });
-
- it('should not register callbacks when not provided', async () => {
- const operationId = 'test-op-no-callbacks';
-
- const initialContext: AgentRuntimeContext = {
- payload: { message: [{ content: 'Hello' }] },
- phase: 'user_input',
- session: {
- messageCount: 1,
- sessionId: operationId,
- status: 'idle',
- stepCount: 0,
- },
- };
-
- await service.createOperation({
- agentConfig: { model: 'gpt-4o', provider: 'openai' },
- appContext: { agentId: 'test-agent' },
- autoStart: false,
- initialContext,
- initialMessages: [{ content: 'Hello', role: 'user' }],
- modelRuntimeConfig: { model: 'gpt-4o', provider: 'openai' },
- operationId,
- toolSet: { manifestMap: {}, tools: [] },
- userId,
- });
-
- const registered = service.getStepCallbacks(operationId);
- expect(registered).toBeUndefined();
- });
- });
-
- describe('callback invocation tracking', () => {
- it('should track callback calls with correct parameters', async () => {
- const operationId = 'callback-tracking-test';
-
- const onBeforeStepCalls: Array<{ operationId: string; stepIndex: number }> = [];
- const onAfterStepCalls: Array<{
- operationId: string;
- shouldContinue: boolean;
- stepIndex: number;
- }> = [];
- const onCompleteCalls: Array<{ operationId: string; reason: StepCompletionReason }> = [];
-
- const callbacks: StepLifecycleCallbacks = {
- onAfterStep: async (params) => {
- onAfterStepCalls.push({
- operationId: params.operationId,
- shouldContinue: params.shouldContinue,
- stepIndex: params.stepIndex,
- });
- },
- onBeforeStep: async (params) => {
- onBeforeStepCalls.push({
- operationId: params.operationId,
- stepIndex: params.stepIndex,
- });
- },
- onComplete: async (params) => {
- onCompleteCalls.push({
- operationId: params.operationId,
- reason: params.reason,
- });
- },
- };
-
- // Verify callbacks structure is correct
- expect(callbacks.onBeforeStep).toBeDefined();
- expect(callbacks.onAfterStep).toBeDefined();
- expect(callbacks.onComplete).toBeDefined();
-
- // Register callbacks
- service.registerStepCallbacks(operationId, callbacks);
-
- // Verify they are registered
- const registered = service.getStepCallbacks(operationId);
- expect(registered).toBe(callbacks);
- });
- });
-
- describe('callback error handling', () => {
- it('should not throw when onBeforeStep callback throws', async () => {
- const operationId = 'error-test-before';
- const callbacks: StepLifecycleCallbacks = {
- onBeforeStep: async () => {
- throw new Error('onBeforeStep error');
- },
- };
-
- service.registerStepCallbacks(operationId, callbacks);
-
- // The callback is registered, verify it exists
- const registered = service.getStepCallbacks(operationId);
- expect(registered).toBe(callbacks);
- expect(registered?.onBeforeStep).toBeDefined();
- });
-
- it('should not throw when onAfterStep callback throws', async () => {
- const operationId = 'error-test-after';
- const callbacks: StepLifecycleCallbacks = {
- onAfterStep: async () => {
- throw new Error('onAfterStep error');
- },
- };
-
- service.registerStepCallbacks(operationId, callbacks);
-
- // The callback is registered, verify it exists
- const registered = service.getStepCallbacks(operationId);
- expect(registered).toBe(callbacks);
- expect(registered?.onAfterStep).toBeDefined();
- });
-
- it('should not throw when onComplete callback throws', async () => {
- const operationId = 'error-test-complete';
- const callbacks: StepLifecycleCallbacks = {
- onComplete: async () => {
- throw new Error('onComplete error');
- },
- };
-
- service.registerStepCallbacks(operationId, callbacks);
-
- // The callback is registered, verify it exists
- const registered = service.getStepCallbacks(operationId);
- expect(registered).toBe(callbacks);
- expect(registered?.onComplete).toBeDefined();
- });
- });
-
- describe('partial callbacks', () => {
- it('should work with only onBeforeStep callback', async () => {
- const operationId = 'partial-before';
- const onBeforeStep = vi.fn();
- const callbacks: StepLifecycleCallbacks = { onBeforeStep };
-
- service.registerStepCallbacks(operationId, callbacks);
-
- const registered = service.getStepCallbacks(operationId);
- expect(registered?.onBeforeStep).toBe(onBeforeStep);
- expect(registered?.onAfterStep).toBeUndefined();
- expect(registered?.onComplete).toBeUndefined();
- });
-
- it('should work with only onAfterStep callback', async () => {
- const operationId = 'partial-after';
- const onAfterStep = vi.fn();
- const callbacks: StepLifecycleCallbacks = { onAfterStep };
-
- service.registerStepCallbacks(operationId, callbacks);
-
- const registered = service.getStepCallbacks(operationId);
- expect(registered?.onBeforeStep).toBeUndefined();
- expect(registered?.onAfterStep).toBe(onAfterStep);
- expect(registered?.onComplete).toBeUndefined();
- });
-
- it('should work with only onComplete callback', async () => {
- const operationId = 'partial-complete';
- const onComplete = vi.fn();
- const callbacks: StepLifecycleCallbacks = { onComplete };
-
- service.registerStepCallbacks(operationId, callbacks);
-
- const registered = service.getStepCallbacks(operationId);
- expect(registered?.onBeforeStep).toBeUndefined();
- expect(registered?.onAfterStep).toBeUndefined();
- expect(registered?.onComplete).toBe(onComplete);
- });
- });
-});
diff --git a/src/server/services/agentRuntime/hooks/types.ts b/src/server/services/agentRuntime/hooks/types.ts
index 3b4b7432e2d..5aa61c08149 100644
--- a/src/server/services/agentRuntime/hooks/types.ts
+++ b/src/server/services/agentRuntime/hooks/types.ts
@@ -56,13 +56,19 @@ export interface AgentHookWebhook {
export interface AgentHookEvent {
// Identification
agentId: string;
+ /** LLM text output (afterStep only) */
+ content?: string;
// Statistics
cost?: number;
duration?: number;
+ /** Elapsed time since operation started in ms (afterStep only) */
+ elapsedMs?: number;
// Content
errorDetail?: string;
errorMessage?: string;
+ /** Step execution time in ms (afterStep only) */
+ executionTimeMs?: number;
/**
* Full AgentState β€” only available in local mode.
@@ -71,6 +77,10 @@ export interface AgentHookEvent {
*/
finalState?: any;
lastAssistantContent?: string;
+ /** Last LLM content from previous steps β€” for showing context during tool execution (afterStep only) */
+ lastLLMContent?: string;
+ /** Last tools calling from previous steps (afterStep only) */
+ lastToolsCalling?: any;
llmCalls?: number;
// Caller-provided metadata (from webhook.body)
@@ -78,17 +88,37 @@ export interface AgentHookEvent {
operationId: string;
// Execution result
reason?: string; // 'done' | 'error' | 'interrupted' | 'max_steps' | 'cost_limit'
+ /** LLM reasoning / thinking content (afterStep only) */
+ reasoning?: string;
// Step-specific (for beforeStep/afterStep)
shouldContinue?: boolean;
status?: string; // 'done' | 'error' | 'interrupted' | 'waiting_for_human'
+ /** Step cost (afterStep only, LLM steps) */
+ stepCost?: number;
stepIndex?: number;
steps?: number;
stepType?: string; // 'call_llm' | 'call_tool'
+ /** Whether next step is LLM thinking (afterStep only) */
+ thinking?: boolean;
toolCalls?: number;
+ /** Tools the LLM decided to call (afterStep only) */
+ toolsCalling?: any;
+ /** Results from tool execution (afterStep only) */
+ toolsResult?: any;
topicId?: string;
+ /** Cumulative total cost (afterStep only) */
+ totalCost?: number;
+ /** Cumulative input tokens (afterStep only) */
+ totalInputTokens?: number;
+ /** Cumulative output tokens (afterStep only) */
+ totalOutputTokens?: number;
+ /** Total steps executed so far (afterStep only) */
+ totalSteps?: number;
totalTokens?: number;
+ /** Running total of tool calls across all steps (afterStep only) */
+ totalToolCalls?: number;
userId: string;
}
diff --git a/src/server/services/agentRuntime/types.ts b/src/server/services/agentRuntime/types.ts
index 205fa20b21c..5d74bf28b7a 100644
--- a/src/server/services/agentRuntime/types.ts
+++ b/src/server/services/agentRuntime/types.ts
@@ -144,15 +144,6 @@ export interface OperationCreationParams {
autoStart?: boolean;
/** Bot platform context for injecting platform capabilities (e.g. markdown support) */
botPlatformContext?: any;
- /**
- * Completion webhook configuration
- * When set, an HTTP POST will be fired when the operation completes (success or error).
- * The webhook is persisted in Redis state so it survives across QStash step boundaries.
- */
- completionWebhook?: {
- body?: Record<string, unknown>;
- url: string;
- };
/** Device system info for placeholder variable replacement in Local System systemRole */
deviceSystemInfo?: Record<string, string>;
/** Discord context for injecting channel/guild info into agent system message */
@@ -176,20 +167,6 @@ export interface OperationCreationParams {
queueRetryDelay?: string;
/** Abort startup before the first step is scheduled */
signal?: AbortSignal;
- /**
- * Step lifecycle callbacks
- * Used to inject custom logic at different stages of step execution
- */
- stepCallbacks?: StepLifecycleCallbacks;
- /**
- * Step webhook configuration
- * When set, an HTTP POST will be fired after each step completes.
- * Persisted in Redis state so it survives across QStash step boundaries.
- */
- stepWebhook?: {
- body?: Record<string, unknown>;
- url: string;
- };
/**
* Whether the LLM call should use streaming.
* Defaults to true. Set to false for non-streaming scenarios (e.g., bot integrations).
@@ -207,12 +184,6 @@ export interface OperationCreationParams {
userMemory?: ServerUserMemoryConfig;
/** User's timezone from settings (e.g. 'Asia/Shanghai') */
userTimezone?: string;
- /**
- * Webhook delivery method.
- * - 'fetch': plain HTTP POST (default)
- * - 'qstash': deliver via QStash publishJSON for guaranteed delivery
- */
- webhookDelivery?: 'fetch' | 'qstash';
}
export interface OperationCreationResult {
diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.ts
index f40182176a5..a61ebcc1ac7 100644
--- a/src/server/services/aiAgent/index.ts
+++ b/src/server/services/aiAgent/index.ts
@@ -94,14 +94,6 @@ interface InternalExecAgentParams extends ExecAgentParams {
botContext?: ChatTopicBotContext;
/** Bot platform context for injecting platform capabilities (e.g. markdown support) */
botPlatformContext?: any;
- /**
- * Completion webhook configuration
- * Persisted in Redis state, triggered via HTTP POST when the operation completes.
- */
- completionWebhook?: {
- body?: Record<string, unknown>;
- url: string;
- };
/** Cron job ID that triggered this execution (if trigger is 'cron') */
cronJobId?: string;
/** Disable all tools (no plugins, no system manifests). Useful for eval/benchmark scenarios. */
@@ -136,16 +128,6 @@ interface InternalExecAgentParams extends ExecAgentParams {
resume?: boolean;
/** Abort startup before the agent runtime operation is created */
signal?: AbortSignal;
- /** Step lifecycle callbacks for operation tracking (server-side only) */
- stepCallbacks?: StepLifecycleCallbacks;
- /**
- * Step webhook configuration
- * Persisted in Redis state, triggered via HTTP POST after each step completes.
- */
- stepWebhook?: {
- body?: Record<string, unknown>;
- url: string;
- };
/**
* Whether the LLM call should use streaming.
* Defaults to true. Set to false for non-streaming scenarios (e.g., bot integrations).
@@ -166,12 +148,6 @@ interface InternalExecAgentParams extends ExecAgentParams {
* Use { approvalMode: 'headless' } for async tasks that should never wait for human approval
*/
userInterventionConfig?: UserInterventionConfig;
- /**
- * Webhook delivery method.
- * - 'fetch': plain HTTP POST (default)
- * - 'qstash': deliver via QStash publishJSON for guaranteed delivery
- */
- webhookDelivery?: 'fetch' | 'qstash';
}
/**
@@ -247,7 +223,6 @@ export class AiAgentService {
instructions,
model: modelOverride,
provider: providerOverride,
- stepCallbacks,
stream,
title,
trigger,
@@ -258,11 +233,8 @@ export class AiAgentService {
initialStepCount,
signal,
userInterventionConfig,
- completionWebhook,
queueRetries,
queueRetryDelay,
- stepWebhook,
- webhookDelivery,
parentMessageId,
resume,
} = params;
@@ -1026,7 +998,6 @@ export class AiAgentService {
},
autoStart,
botPlatformContext,
- completionWebhook,
discordContext,
evalContext,
initialContext,
@@ -1037,8 +1008,6 @@ export class AiAgentService {
hooks,
operationId,
signal,
- stepCallbacks,
- stepWebhook,
queueRetries,
queueRetryDelay,
stream,
@@ -1052,7 +1021,6 @@ export class AiAgentService {
userId: this.userId,
userInterventionConfig,
userMemory,
- webhookDelivery,
});
log('execAgent: created operation %s (autoStarted: %s)', operationId, result.autoStarted);
diff --git a/src/server/services/bot/AgentBridgeService.ts b/src/server/services/bot/AgentBridgeService.ts
index 25fe144f486..e212c0b7895 100644
--- a/src/server/services/bot/AgentBridgeService.ts
+++ b/src/server/services/bot/AgentBridgeService.ts
@@ -3,12 +3,10 @@ import { RequestTrigger } from '@lobechat/types';
import type { Message, SentMessage, Thread } from 'chat';
import { emoji } from 'chat';
import debug from 'debug';
-import urlJoin from 'url-join';
import { TopicModel } from '@/database/models/topic';
import { UserModel } from '@/database/models/user';
import type { LobeChatDatabase } from '@/database/type';
-import { appEnv } from '@/envs/app';
import { createAbortError, isAbortError } from '@/server/services/agentRuntime/abort';
import { AiAgentService } from '@/server/services/aiAgent';
import { isQueueAgentRuntimeEnabled } from '@/server/services/queue/impls';
@@ -443,7 +441,10 @@ export class AgentBridgeService {
}
/**
- * Dispatch to queue-mode webhooks or local in-memory callbacks based on runtime mode.
+ * Execute agent with unified hooks β€” auto-adapts to local or queue mode.
+ *
+ * Local mode: hooks run in-process, Promise resolves when agent completes.
+ * Queue mode: hooks deliver via webhooks, returns immediately after startup.
*/
private async executeWithCallback(
thread: Thread<ThreadState>,
@@ -471,35 +472,9 @@ export class AgentBridgeService {
}
}
- const optsWithPlatform = { ...opts, botPlatformContext };
-
- if (isQueueAgentRuntimeEnabled()) {
- return this.executeWithWebhooks(thread, userMessage, optsWithPlatform);
- }
- return this.executeWithInMemoryCallbacks(thread, userMessage, optsWithPlatform);
- }
-
- /**
- * Queue mode: post initial message, configure step/completion webhooks,
- * then return immediately. Progress updates and final reply are handled
- * by the bot-callback webhook endpoint.
- */
- private async executeWithWebhooks(
- thread: Thread<ThreadState>,
- userMessage: Message,
- opts: {
- agentId: string;
- botContext?: ChatTopicBotContext;
- botPlatformContext?: { platformName: string; supportsMarkdown: boolean };
- channelContext?: DiscordChannelContext;
- client?: PlatformClient;
- topicId?: string;
- trigger?: string;
- },
- ): Promise<{ reply: string; topicId: string }> {
- const { agentId, botContext, botPlatformContext, channelContext, client, topicId, trigger } =
- opts;
+ const { agentId, botContext, channelContext, charLimit, client, displayToolCalls, topicId, trigger } = opts;
+ const queueMode = isQueueAgentRuntimeEnabled();
const aiAgentService = new AiAgentService(this.db, this.userId);
const timezone = await this.loadTimezone();
@@ -509,38 +484,100 @@ export class AgentBridgeService {
try {
progressMessage = await thread.post(renderStart(userMessage.text, { timezone }));
} catch (error) {
- log('executeWithWebhooks: failed to post initial placeholder message: %O', error);
+ log('executeWithCallback: failed to post initial placeholder message: %O', error);
}
- const progressMessageId: string | undefined = progressMessage?.id;
-
- // Build webhook URL for bot-callback endpoint
- // Prefer INTERNAL_APP_URL for server-to-server calls (bypasses CDN/proxy)
- const baseURL = appEnv.INTERNAL_APP_URL || appEnv.APP_URL;
- if (!baseURL) {
- throw new Error('APP_URL is required for queue mode bot webhooks');
- }
- const callbackUrl = urlJoin(baseURL, '/api/agent/webhooks/bot-callback');
+ const files = this.extractFiles(userMessage);
+ const prompt = this.formatPrompt(userMessage, client);
+ // Build webhook config for production mode
+ const callbackUrl = '/api/agent/webhooks/bot-callback';
const webhookBody = {
applicationId: botContext?.applicationId,
platformThreadId: botContext?.platformThreadId,
- progressMessageId,
+ progressMessageId: progressMessage?.id,
userMessageId: userMessage.id,
};
- const files = this.extractFiles(userMessage);
- const prompt = this.formatPrompt(userMessage, client);
-
log(
- 'executeWithWebhooks: agentId=%s, callbackUrl=%s, progressMessageId=%s, prompt=%s, files=%d',
+ 'executeWithCallback: agentId=%s, queueMode=%s, prompt=%s, files=%d',
agentId,
- callbackUrl,
- progressMessageId,
+ queueMode,
prompt.slice(0, 100),
files?.length ?? 0,
);
+ // In queue mode, return immediately after startup β€” hooks handle the rest via webhooks
+ if (queueMode) {
+ return this.executeWithHooksQueueMode(thread, userMessage, aiAgentService, {
+ agentId,
+ botContext,
+ botPlatformContext,
+ callbackUrl,
+ channelContext,
+ files,
+ progressMessage,
+ prompt,
+ topicId,
+ trigger,
+ webhookBody,
+ });
+ }
+
+ // In local mode, wrap in a Promise β€” hook handlers resolve/reject it in-process
+ return this.executeWithHooksLocalMode(thread, aiAgentService, {
+ agentId,
+ botContext,
+ botPlatformContext,
+ callbackUrl,
+ charLimit,
+ channelContext,
+ client,
+ displayToolCalls,
+ files,
+ progressMessage,
+ prompt,
+ topicId,
+ trigger,
+ webhookBody,
+ });
+ }
+
+ /**
+ * Queue mode: register hooks with webhook config, start agent, return immediately.
+ */
+ private async executeWithHooksQueueMode(
+ thread: Thread<ThreadState>,
+ userMessage: Message,
+ aiAgentService: AiAgentService,
+ opts: {
+ agentId: string;
+ botContext?: ChatTopicBotContext;
+ botPlatformContext?: { platformName: string; supportsMarkdown: boolean };
+ callbackUrl: string;
+ channelContext?: DiscordChannelContext;
+ files?: any;
+ progressMessage?: SentMessage;
+ prompt: string;
+ topicId?: string;
+ trigger?: string;
+ webhookBody: Record<string, unknown>;
+ },
+ ): Promise<{ reply: string; topicId: string }> {
+ const {
+ agentId,
+ botContext,
+ botPlatformContext,
+ callbackUrl,
+ channelContext,
+ files,
+ progressMessage,
+ prompt,
+ topicId,
+ trigger,
+ webhookBody,
+ } = opts;
+
let result: ExecAgentResult;
try {
result = await AgentBridgeService.runWithStartupSignal(thread.id, (signal) =>
@@ -550,25 +587,46 @@ export class AgentBridgeService {
autoStart: true,
botContext,
botPlatformContext,
- completionWebhook: { body: webhookBody, url: callbackUrl },
discordContext: channelContext
? { channel: channelContext.channel, guild: channelContext.guild }
: undefined,
files,
+ hooks: [
+ {
+ handler: async () => {
+ /* local handler not used in queue mode */
+ },
+ id: 'bot-step-progress',
+ type: 'afterStep',
+ webhook: {
+ body: { ...webhookBody, type: 'step' },
+ delivery: 'qstash',
+ url: callbackUrl,
+ },
+ },
+ {
+ handler: async () => {
+ /* local handler not used in queue mode */
+ },
+ id: 'bot-completion',
+ type: 'onComplete',
+ webhook: {
+ body: { ...webhookBody, type: 'completion', userPrompt: prompt },
+ delivery: 'qstash',
+ url: callbackUrl,
+ },
+ },
+ ],
prompt,
signal,
- stepWebhook: { body: webhookBody, url: callbackUrl },
title: '',
trigger,
userInterventionConfig: { approvalMode: 'headless' },
- webhookDelivery: 'qstash',
}),
);
} catch (error) {
- log('executeWithWebhooks: execAgent failed: %O', error);
+ log('executeWithCallback[queue]: execAgent failed: %O', error);
- // For stale topicId FK violations, re-throw so handleSubscribedMessage can clear
- // the cached topicId and retry as a fresh mention instead of showing a DB error.
const errMsg = error instanceof Error ? error.message : String(error);
if (errMsg.includes('Failed query') && errMsg.includes('topic_id')) {
throw error;
@@ -595,12 +653,11 @@ export class AgentBridgeService {
}
log(
- 'executeWithWebhooks: operationId=%s, topicId=%s (webhook mode, returning immediately)',
+ 'executeWithCallback[queue]: operationId=%s, topicId=%s (returning immediately)',
result.operationId,
result.topicId,
);
- // Track operationId so /stop can interrupt this execution
if (result.operationId) {
AgentBridgeService.activeOperations.set(thread.id, result.operationId);
@@ -609,67 +666,57 @@ export class AgentBridgeService {
await this.interruptTrackedOperation(thread.id, result.operationId);
} catch (error) {
log(
- 'executeWithWebhooks: deferred stop failed for thread=%s, operationId=%s: %O',
+ 'executeWithCallback[queue]: deferred stop failed for thread=%s: %O',
thread.id,
- result.operationId,
error,
);
}
}
}
- // Return immediately β€” progress/completion handled by webhooks
return { reply: '', topicId: result.topicId };
}
/**
- * Local mode: use in-memory step callbacks and wait for completion via Promise.
+ * Local mode: register hooks with in-process handlers, wait for completion via Promise.
*/
- private async executeWithInMemoryCallbacks(
+ private async executeWithHooksLocalMode(
thread: Thread<ThreadState>,
- userMessage: Message,
+ aiAgentService: AiAgentService,
opts: {
agentId: string;
botContext?: ChatTopicBotContext;
botPlatformContext?: { platformName: string; supportsMarkdown: boolean };
- channelContext?: DiscordChannelContext;
+ callbackUrl: string;
charLimit?: number;
+ channelContext?: DiscordChannelContext;
client?: PlatformClient;
displayToolCalls?: boolean;
+ files?: any;
+ progressMessage?: SentMessage;
+ prompt: string;
topicId?: string;
trigger?: string;
+ webhookBody: Record<string, unknown>;
},
): Promise<{ reply: string; topicId: string }> {
const {
agentId,
botContext,
botPlatformContext,
- channelContext,
+ callbackUrl,
charLimit,
+ channelContext,
client,
displayToolCalls,
+ files,
+ prompt,
topicId,
trigger,
+ webhookBody,
} = opts;
- const aiAgentService = new AiAgentService(this.db, this.userId);
- const timezone = await this.loadTimezone();
-
- await thread.startTyping();
-
- let progressMessage: SentMessage | undefined;
- try {
- progressMessage = await thread.post(renderStart(userMessage.text, { timezone }));
- } catch (error) {
- log('executeWithInMemoryCallbacks: failed to post initial placeholder message: %O', error);
- }
-
- // Track the last LLM content and tool calls for showing during tool execution
- let lastLLMContent = '';
- let lastToolsCalling:
- | Array<{ apiName: string; arguments?: string; identifier: string }>
- | undefined;
- let totalToolCalls = 0;
+ let { progressMessage } = opts;
let operationStartTime = 0;
return new Promise<{ reply: string; topicId: string }>((resolve, reject) => {
@@ -677,21 +724,10 @@ export class AgentBridgeService {
reject(new Error(`Agent execution timed out`));
}, EXECUTION_TIMEOUT);
- let assistantMessageId = '';
let resolvedTopicId = topicId ?? '';
const getElapsedMs = () => (operationStartTime > 0 ? Date.now() - operationStartTime : 0);
- const files = this.extractFiles(userMessage);
- const prompt = this.formatPrompt(userMessage, client);
-
- log(
- 'executeWithInMemoryCallbacks: agentId=%s, prompt=%s, files=%d',
- agentId,
- prompt.slice(0, 100),
- files?.length ?? 0,
- );
-
AgentBridgeService.runWithStartupSignal(thread.id, (signal) =>
aiAgentService.execAgent({
agentId,
@@ -703,163 +739,177 @@ export class AgentBridgeService {
? { channel: channelContext.channel, guild: channelContext.guild }
: undefined,
files,
- prompt,
- signal,
- title: '',
- stepCallbacks: {
- onAfterStep: async (stepData) => {
- const { content, shouldContinue, toolsCalling } = stepData;
- if (!shouldContinue || !progressMessage || displayToolCalls === false) return;
-
- if (toolsCalling) totalToolCalls += toolsCalling.length;
-
- const msgBody = renderStepProgress({
- ...stepData,
- elapsedMs: getElapsedMs(),
- lastContent: lastLLMContent,
- lastToolsCalling,
- totalToolCalls,
- });
-
- const stats = {
- elapsedMs: getElapsedMs(),
- totalCost: stepData.totalCost ?? 0,
- totalTokens: stepData.totalTokens ?? 0,
- };
- const formatted = client?.formatMarkdown?.(msgBody) ?? msgBody;
- const progressText = client?.formatReply?.(formatted, stats) ?? formatted;
-
- if (content) lastLLMContent = content;
- if (toolsCalling) lastToolsCalling = toolsCalling;
-
- try {
- progressMessage = await progressMessage.edit(progressText);
- } catch (error) {
- log('executeWithInMemoryCallbacks: failed to edit progress message: %O', error);
- }
- },
-
- onComplete: async ({ finalState, reason }) => {
- clearTimeout(timeout);
-
- log('onComplete: reason=%s, assistantMessageId=%s', reason, assistantMessageId);
+ hooks: [
+ {
+ handler: async (event) => {
+ if (!event.shouldContinue || !progressMessage || displayToolCalls === false) return;
+
+ const msgBody = renderStepProgress({
+ content: event.content,
+ elapsedMs: event.elapsedMs ?? getElapsedMs(),
+ executionTimeMs: event.executionTimeMs ?? 0,
+ lastContent: event.lastLLMContent,
+ lastToolsCalling: event.lastToolsCalling,
+ reasoning: event.reasoning,
+ stepType: (event.stepType as 'call_llm' | 'call_tool') ?? 'call_llm',
+ thinking: event.thinking ?? false,
+ toolsCalling: event.toolsCalling,
+ toolsResult: event.toolsResult,
+ totalCost: event.totalCost ?? 0,
+ totalInputTokens: event.totalInputTokens ?? 0,
+ totalOutputTokens: event.totalOutputTokens ?? 0,
+ totalSteps: event.totalSteps ?? 0,
+ totalTokens: event.totalTokens ?? 0,
+ totalToolCalls: event.totalToolCalls ?? 0,
+ });
+
+ const stats = {
+ elapsedMs: event.elapsedMs ?? getElapsedMs(),
+ totalCost: event.totalCost ?? 0,
+ totalTokens: event.totalTokens ?? 0,
+ };
+ const formatted = client?.formatMarkdown?.(msgBody) ?? msgBody;
+ const progressText = client?.formatReply?.(formatted, stats) ?? formatted;
- if (reason === 'error') {
- const errorMsg = extractErrorMessage(finalState.error);
try {
- const errorText = renderError(errorMsg);
- if (progressMessage) {
- await progressMessage.edit(errorText);
- } else {
- await thread.post(errorText);
- }
- } catch {
- // ignore send failure
+ progressMessage = await progressMessage.edit(progressText);
+ } catch (error) {
+ log('executeWithCallback[local]: failed to edit progress message: %O', error);
}
- reject(new Error(errorMsg));
- return;
- }
+ },
+ id: 'bot-step-progress',
+ type: 'afterStep' as const,
+ webhook: {
+ body: { ...webhookBody, type: 'step' },
+ delivery: 'qstash' as const,
+ url: callbackUrl,
+ },
+ },
+ {
+ handler: async (event) => {
+ clearTimeout(timeout);
- if (reason === 'interrupted') {
- if (progressMessage) {
+ const reason = event.reason;
+ log('onComplete: reason=%s', reason);
+
+ if (reason === 'error') {
+ const errorMsg = event.errorMessage || 'Agent execution failed';
try {
- await progressMessage.edit(renderStopped());
+ const errorText = renderError(errorMsg);
+ if (progressMessage) {
+ await progressMessage.edit(errorText);
+ } else {
+ await thread.post(errorText);
+ }
} catch {
- // ignore edit failure
+ // ignore send failure
}
+ reject(new Error(errorMsg));
+ return;
}
- resolve({ reply: '', topicId: resolvedTopicId });
- return;
- }
- try {
- // Extract reply from finalState.messages (accumulated across all steps)
- const lastAssistantContent = finalState.messages
- ?.slice()
- .reverse()
- .find(
- (m: { content?: string; role: string }) => m.role === 'assistant' && m.content,
- )?.content;
-
- if (lastAssistantContent) {
- const replyBody = renderFinalReply(lastAssistantContent);
- const replyStats = {
- elapsedMs: getElapsedMs(),
- llmCalls: finalState.usage?.llm?.apiCalls ?? 0,
- toolCalls: finalState.usage?.tools?.totalCalls ?? 0,
- totalCost: finalState.cost?.total ?? 0,
- totalTokens: finalState.usage?.llm?.tokens?.total ?? 0,
- };
- const formattedBody = client?.formatMarkdown?.(replyBody) ?? replyBody;
- const finalText =
- client?.formatReply?.(formattedBody, replyStats) ?? formattedBody;
-
- const chunks = splitMessage(finalText, charLimit);
+ if (reason === 'interrupted') {
+ if (progressMessage) {
+ try {
+ await progressMessage.edit(renderStopped());
+ } catch {
+ // ignore edit failure
+ }
+ }
+ resolve({ reply: '', topicId: resolvedTopicId });
+ return;
+ }
- try {
- if (progressMessage) {
- await progressMessage.edit(chunks[0]);
- // Post overflow chunks as follow-up messages
- for (let i = 1; i < chunks.length; i++) {
- await thread.post(chunks[i]);
- }
- } else {
- // No progress message (non-editable platform) β€” post all chunks as new messages
- for (const chunk of chunks) {
- await thread.post(chunk);
+ try {
+ const lastAssistantContent = event.lastAssistantContent;
+
+ if (lastAssistantContent) {
+ const replyBody = renderFinalReply(lastAssistantContent);
+ const replyStats = {
+ elapsedMs: event.duration ?? getElapsedMs(),
+ llmCalls: event.llmCalls ?? 0,
+ toolCalls: event.toolCalls ?? 0,
+ totalCost: event.cost ?? 0,
+ totalTokens: event.totalTokens ?? 0,
+ };
+ const formattedBody = client?.formatMarkdown?.(replyBody) ?? replyBody;
+ const finalText =
+ client?.formatReply?.(formattedBody, replyStats) ?? formattedBody;
+
+ const chunks = splitMessage(finalText, charLimit);
+
+ try {
+ if (progressMessage) {
+ await progressMessage.edit(chunks[0]);
+ for (let i = 1; i < chunks.length; i++) {
+ await thread.post(chunks[i]);
+ }
+ } else {
+ for (const chunk of chunks) {
+ await thread.post(chunk);
+ }
}
+ } catch (error) {
+ log('executeWithCallback[local]: failed to send final message: %O', error);
}
- } catch (error) {
- log('executeWithInMemoryCallbacks: failed to send final message: %O', error);
- }
- log(
- 'executeWithInMemoryCallbacks: got response from finalState (%d chars, %d chunks)',
- lastAssistantContent.length,
- chunks.length,
- );
- resolve({ reply: lastAssistantContent, topicId: resolvedTopicId });
-
- // Fire-and-forget: summarize topic title in DB (no Discord rename in local mode)
- if (resolvedTopicId && prompt) {
- const topicModel = new TopicModel(this.db, this.userId);
- topicModel
- .findById(resolvedTopicId)
- .then(async (topic) => {
- if (topic?.title) return;
-
- const systemAgent = new SystemAgentService(this.db, this.userId);
- const title = await systemAgent.generateTopicTitle({
- lastAssistantContent,
- userPrompt: prompt,
+ log(
+ 'executeWithCallback[local]: got response (%d chars, %d chunks)',
+ lastAssistantContent.length,
+ chunks.length,
+ );
+ resolve({ reply: lastAssistantContent, topicId: resolvedTopicId });
+
+ // Fire-and-forget: summarize topic title in DB
+ if (resolvedTopicId && prompt) {
+ const topicModel = new TopicModel(this.db, this.userId);
+ topicModel
+ .findById(resolvedTopicId)
+ .then(async (topic) => {
+ if (topic?.title) return;
+
+ const systemAgent = new SystemAgentService(this.db, this.userId);
+ const title = await systemAgent.generateTopicTitle({
+ lastAssistantContent,
+ userPrompt: prompt,
+ });
+ if (!title) return;
+
+ await topicModel.update(resolvedTopicId, { title });
+ })
+ .catch((error) => {
+ log(
+ 'executeWithCallback[local]: topic title summarization failed: %O',
+ error,
+ );
});
- if (!title) return;
-
- await topicModel.update(resolvedTopicId, { title });
- })
- .catch((error) => {
- log(
- 'executeWithInMemoryCallbacks: topic title summarization failed: %O',
- error,
- );
- });
+ }
+
+ return;
}
- return;
+ reject(new Error('Agent completed but no response content found'));
+ } catch (error) {
+ reject(error);
}
-
- reject(new Error('Agent completed but no response content found'));
- } catch (error) {
- reject(error);
- }
+ },
+ id: 'bot-completion',
+ type: 'onComplete' as const,
+ webhook: {
+ body: { ...webhookBody, type: 'completion', userPrompt: prompt },
+ delivery: 'qstash' as const,
+ url: callbackUrl,
+ },
},
- },
+ ],
+ prompt,
+ signal,
+ title: '',
trigger,
userInterventionConfig: { approvalMode: 'headless' },
}),
)
.then(async (result) => {
- assistantMessageId = result.assistantMessageId;
resolvedTopicId = result.topicId;
operationStartTime = new Date(result.createdAt).getTime();
@@ -872,7 +922,7 @@ export class AgentBridgeService {
renderError(result.error || 'Agent operation failed to start'),
);
} catch (error) {
- log('executeWithInMemoryCallbacks: failed to edit startup error: %O', error);
+ log('executeWithCallback[local]: failed to edit startup error: %O', error);
}
}
@@ -880,7 +930,6 @@ export class AgentBridgeService {
return;
}
- // Track operationId so /stop can interrupt this execution
if (result.operationId) {
AgentBridgeService.activeOperations.set(thread.id, result.operationId);
@@ -889,9 +938,8 @@ export class AgentBridgeService {
await this.interruptTrackedOperation(thread.id, result.operationId);
} catch (error) {
log(
- 'executeWithInMemoryCallbacks: deferred stop failed for thread=%s, operationId=%s: %O',
+ 'executeWithCallback[local]: deferred stop failed for thread=%s: %O',
thread.id,
- result.operationId,
error,
);
}
@@ -899,9 +947,8 @@ export class AgentBridgeService {
}
log(
- 'executeWithInMemoryCallbacks: operationId=%s, assistantMessageId=%s, topicId=%s',
+ 'executeWithCallback[local]: operationId=%s, topicId=%s',
result.operationId,
- result.assistantMessageId,
result.topicId,
);
})
@@ -913,7 +960,7 @@ export class AgentBridgeService {
try {
await progressMessage.edit(renderStopped(error.message));
} catch (editError) {
- log('executeWithInMemoryCallbacks: failed to edit stopped message: %O', editError);
+ log('executeWithCallback[local]: failed to edit stopped message: %O', editError);
}
}
@@ -925,7 +972,7 @@ export class AgentBridgeService {
try {
await progressMessage.edit(renderError(extractErrorMessage(error)));
} catch (editError) {
- log('executeWithInMemoryCallbacks: failed to edit startup error: %O', editError);
+ log('executeWithCallback[local]: failed to edit startup error: %O', editError);
}
}
diff --git a/src/server/services/bot/BotCallbackService.ts b/src/server/services/bot/BotCallbackService.ts
index d5a185af45e..7dbd5ec3d93 100644
--- a/src/server/services/bot/BotCallbackService.ts
+++ b/src/server/services/bot/BotCallbackService.ts
@@ -30,6 +30,10 @@ export interface BotCallbackBody {
elapsedMs?: number;
errorMessage?: string;
executionTimeMs?: number;
+ /** Hook ID from HookDispatcher (e.g. 'bot-step-progress', 'bot-completion') */
+ hookId?: string;
+ /** Hook type from HookDispatcher (e.g. 'afterStep', 'onComplete') */
+ hookType?: string;
lastAssistantContent?: string;
lastLLMContent?: string;
lastToolsCalling?: any;
diff --git a/src/server/services/bot/__tests__/AgentBridgeService.test.ts b/src/server/services/bot/__tests__/AgentBridgeService.test.ts
index fa1cc2713d0..26dc213ad1b 100644
--- a/src/server/services/bot/__tests__/AgentBridgeService.test.ts
+++ b/src/server/services/bot/__tests__/AgentBridgeService.test.ts
@@ -114,7 +114,7 @@ describe('AgentBridgeService', () => {
mockIsQueueAgentRuntimeEnabled.mockReturnValue(true);
});
- it('cleans up received reaction when queue-mode mention setup fails before callback handoff', async () => {
+ it('calls execAgent with hooks in queue mode for mention', async () => {
const service = new AgentBridgeService(FAKE_DB, USER_ID);
const thread = createThread();
const message = createMessage();
@@ -126,15 +126,19 @@ describe('AgentBridgeService', () => {
client,
});
- const [mentionReactionThreadId, mentionReactionMessageId, mentionReactionEmoji] =
- thread.adapter.removeReaction.mock.calls[0];
- expect(mentionReactionThreadId).toBe(THREAD_ID);
- expect(mentionReactionMessageId).toBe(MESSAGE_ID);
- expect(mentionReactionEmoji).toBeDefined();
- expect(mockExecAgent).not.toHaveBeenCalled();
+ // execAgent should be called with hooks (afterStep + onComplete)
+ expect(mockExecAgent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'agent-1',
+ hooks: expect.arrayContaining([
+ expect.objectContaining({ id: 'bot-step-progress', type: 'afterStep' }),
+ expect.objectContaining({ id: 'bot-completion', type: 'onComplete' }),
+ ]),
+ }),
+ );
});
- it('cleans up received reaction when queue-mode subscribed-message setup fails before callback handoff', async () => {
+ it('calls execAgent with hooks in queue mode for subscribed message', async () => {
const service = new AgentBridgeService(FAKE_DB, USER_ID);
const thread = createThread({ topicId: 'topic-1' });
const message = createMessage();
@@ -146,11 +150,26 @@ describe('AgentBridgeService', () => {
client,
});
- const [replyReactionThreadId, replyReactionMessageId, replyReactionEmoji] =
- thread.adapter.removeReaction.mock.calls[0];
- expect(replyReactionThreadId).toBe(THREAD_ID);
- expect(replyReactionMessageId).toBe(MESSAGE_ID);
- expect(replyReactionEmoji).toBeDefined();
- expect(mockExecAgent).not.toHaveBeenCalled();
+ // execAgent should be called with hooks containing webhook config
+ expect(mockExecAgent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ hooks: expect.arrayContaining([
+ expect.objectContaining({
+ id: 'bot-step-progress',
+ type: 'afterStep',
+ webhook: expect.objectContaining({
+ body: expect.objectContaining({ type: 'step', platformThreadId: THREAD_ID }),
+ }),
+ }),
+ expect.objectContaining({
+ id: 'bot-completion',
+ type: 'onComplete',
+ webhook: expect.objectContaining({
+ body: expect.objectContaining({ type: 'completion', platformThreadId: THREAD_ID }),
+ }),
+ }),
+ ]),
+ }),
+ );
});
});
diff --git a/src/server/services/bot/__tests__/BotCallbackService.test.ts b/src/server/services/bot/__tests__/BotCallbackService.test.ts
index 5d9d3e4a333..e77ad6b8f7b 100644
--- a/src/server/services/bot/__tests__/BotCallbackService.test.ts
+++ b/src/server/services/bot/__tests__/BotCallbackService.test.ts
@@ -759,4 +759,73 @@ describe('BotCallbackService', () => {
expect(mockFindById).not.toHaveBeenCalled();
});
});
+
+ describe('hook-based webhook payload compatibility', () => {
+ // These tests verify that payloads from HookDispatcher (which include
+ // hookId/hookType fields) are handled correctly by BotCallbackService.
+ // This is the critical contract between the hooks framework and the bot callback.
+
+ it('should handle step payload with hookId and hookType fields', async () => {
+ const body = makeBody({
+ content: 'thinking...',
+ executionTimeMs: 100,
+ hookId: 'bot-step-progress',
+ hookType: 'afterStep',
+ shouldContinue: true,
+ stepType: 'call_llm' as const,
+ thinking: true,
+ totalCost: 0.01,
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ totalSteps: 1,
+ totalTokens: 150,
+ type: 'step',
+ });
+
+ await service.handleCallback(body);
+
+ expect(mockEditMessage).toHaveBeenCalledWith('progress-msg-1', expect.any(String));
+ });
+
+ it('should handle completion payload with hookId and hookType fields', async () => {
+ const body = makeBody({
+ cost: 0.05,
+ duration: 5000,
+ hookId: 'bot-completion',
+ hookType: 'onComplete',
+ lastAssistantContent: 'Here is the answer',
+ llmCalls: 3,
+ reason: 'done',
+ toolCalls: 2,
+ totalTokens: 500,
+ type: 'completion',
+ userId: 'user-1',
+ userPrompt: 'test question',
+ });
+
+ await service.handleCallback(body);
+
+ expect(mockEditMessage).toHaveBeenCalledWith(
+ 'progress-msg-1',
+ expect.stringContaining('Here is the answer'),
+ );
+ });
+
+ it('should handle completion error payload from hooks', async () => {
+ const body = makeBody({
+ errorMessage: 'Rate limit exceeded',
+ hookId: 'bot-completion',
+ hookType: 'onComplete',
+ reason: 'error',
+ type: 'completion',
+ });
+
+ await service.handleCallback(body);
+
+ expect(mockEditMessage).toHaveBeenCalledWith(
+ 'progress-msg-1',
+ expect.stringContaining('Rate limit exceeded'),
+ );
+ });
+ });
});