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.

🧪 test(agent): consolidate backend execution inputs [stack 02] (#22554)

Innei30df1970e2c2
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
index 570050d241b..fd797c749e7 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
@@ -1,9 +1,20 @@
import { describe, expect, it, vi } from 'vitest';
+import type { AgentRuntimeCoordinatorOptions } from '../AgentRuntimeCoordinator';
import { AgentRuntimeCoordinator } from '../AgentRuntimeCoordinator';
import { createAgentStateManager, createStreamEventManager } from '../factory';
import { VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY } from '../visibleOutputEnd';
+const resolverOptions = (
+ stateManager: AgentRuntimeCoordinatorOptions['stateManager'],
+ streamEventManager: AgentRuntimeCoordinatorOptions['streamEventManager'],
+ uiMessagesResolver: AgentRuntimeCoordinatorOptions['uiMessagesResolver'],
+) => ({
+ stateManager,
+ streamEventManager,
+ uiMessagesResolver,
+});
+
// Mock factory module to avoid Redis/env access
vi.mock('../factory', () => ({
createAgentStateManager: vi.fn(),
@@ -611,11 +622,9 @@ describe('AgentRuntimeCoordinator', () => {
resolveUiMessages = resolve;
}),
);
- const coordinatorWithResolver = new AgentRuntimeCoordinator({
- stateManager: mockStateManager,
- streamEventManager: mockStreamManager,
- uiMessagesResolver: resolver,
- });
+ const coordinatorWithResolver = new AgentRuntimeCoordinator(
+ resolverOptions(mockStateManager, mockStreamManager, resolver),
+ );
const previousState = { status: 'running', stepCount: 3 };
const newState = { status: 'done', stepCount: 5 };
@@ -641,11 +650,9 @@ describe('AgentRuntimeCoordinator', () => {
it('passes resolver result through saveAgentState terminal publish', async () => {
const uiMessages = [{ id: 'msg_1', role: 'user' }] as any[];
const resolver = vi.fn().mockResolvedValue(uiMessages);
- const coordinatorWithResolver = new AgentRuntimeCoordinator({
- stateManager: mockStateManager,
- streamEventManager: mockStreamManager,
- uiMessagesResolver: resolver,
- });
+ const coordinatorWithResolver = new AgentRuntimeCoordinator(
+ resolverOptions(mockStateManager, mockStreamManager, resolver),
+ );
const previousState = { status: 'running', stepCount: 3 };
const newState = { status: 'done', stepCount: 5 };
@@ -666,11 +673,9 @@ describe('AgentRuntimeCoordinator', () => {
it('passes resolver result through saveStepResult terminal publish', async () => {
const uiMessages = [{ id: 'msg_a', role: 'assistantGroup' }] as any[];
const resolver = vi.fn().mockResolvedValue(uiMessages);
- const coordinatorWithResolver = new AgentRuntimeCoordinator({
- stateManager: mockStateManager,
- streamEventManager: mockStreamManager,
- uiMessagesResolver: resolver,
- });
+ const coordinatorWithResolver = new AgentRuntimeCoordinator(
+ resolverOptions(mockStateManager, mockStreamManager, resolver),
+ );
const stepResult = {
executionTime: 100,
@@ -720,11 +725,9 @@ describe('AgentRuntimeCoordinator', () => {
it('publishes with uiMessages=undefined when resolver rejects (must never fail the surrounding save)', async () => {
const resolver = vi.fn().mockRejectedValue(new Error('db down'));
- const coordinatorWithResolver = new AgentRuntimeCoordinator({
- stateManager: mockStateManager,
- streamEventManager: mockStreamManager,
- uiMessagesResolver: resolver,
- });
+ const coordinatorWithResolver = new AgentRuntimeCoordinator(
+ resolverOptions(mockStateManager, mockStreamManager, resolver),
+ );
const previousState = { status: 'running', stepCount: 3 };
const newState = { status: 'error', stepCount: 5 };
@@ -768,11 +771,9 @@ describe('AgentRuntimeCoordinator', () => {
// content, so the resolver is skipped entirely for status='interrupted'.
it('skips uiMessages on saveAgentState when status=interrupted', async () => {
const resolver = vi.fn().mockResolvedValue([{ id: 'placeholder', role: 'assistant' }]);
- const coordinatorWithResolver = new AgentRuntimeCoordinator({
- stateManager: mockStateManager,
- streamEventManager: mockStreamManager,
- uiMessagesResolver: resolver,
- });
+ const coordinatorWithResolver = new AgentRuntimeCoordinator(
+ resolverOptions(mockStateManager, mockStreamManager, resolver),
+ );
const previousState = { status: 'running', stepCount: 3 };
const newState = { status: 'interrupted', stepCount: 3 };
@@ -794,11 +795,9 @@ describe('AgentRuntimeCoordinator', () => {
it('skips uiMessages on saveStepResult when stepResult.newState.status=interrupted', async () => {
const resolver = vi.fn().mockResolvedValue([{ id: 'placeholder', role: 'assistant' }]);
- const coordinatorWithResolver = new AgentRuntimeCoordinator({
- stateManager: mockStateManager,
- streamEventManager: mockStreamManager,
- uiMessagesResolver: resolver,
- });
+ const coordinatorWithResolver = new AgentRuntimeCoordinator(
+ resolverOptions(mockStateManager, mockStreamManager, resolver),
+ );
const stepResult = {
executionTime: 100,
diff --git a/apps/server/src/modules/AgentRuntime/adapters/afterToolControlPipeline.test.ts b/apps/server/src/modules/AgentRuntime/adapters/afterToolControlPipeline.test.ts
index 8f8638bc26f..be3f48b7984 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/afterToolControlPipeline.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/afterToolControlPipeline.test.ts
@@ -13,6 +13,40 @@ import { HookDispatcher } from '@/server/services/agentRuntime/hooks';
import type { RuntimeExecutorContext } from '../context';
import { ServerToolTransport } from './ServerToolTransport';
+const protectedToolRow = (plugin: ChatToolPayload) => ({
+ id: 'protected-row',
+ parentId: 'original-assistant',
+ role: 'tool',
+ tool_call_id: 'native-1',
+ content: '',
+ plugin,
+ pluginIntervention: { operationId: 'original-op', status: 'approved' },
+});
+
+const protectedSingleToolEvent = (
+ toolCalling: ChatToolPayload,
+): Parameters<NonNullable<ReturnType<typeof createAgentRuntimeExecutors>['call_tool']>>[0] => ({
+ type: 'call_tool',
+ payload: {
+ parentMessageId: 'protected-row',
+ skipCreateToolMessage: true,
+ toolCalling,
+ },
+});
+
+const protectedBatchToolEvent = (
+ toolCalling: ChatToolPayload,
+): Parameters<
+ NonNullable<ReturnType<typeof createAgentRuntimeExecutors>['call_tools_batch']>
+>[0] => ({
+ type: 'call_tools_batch',
+ payload: {
+ parentMessageId: 'assistant',
+ toolsCalling: [toolCalling],
+ existingToolMessageIds: { 'native-1': 'protected-row' },
+ },
+});
+
const { archive, dispatchClient, fetchHook, getEmailsByIds, queueMode } = vi.hoisted(() => ({
archive: vi.fn(async (result) => result),
dispatchClient: vi.fn(),
@@ -527,15 +561,7 @@ describe('afterToolCall control pipeline', () => {
'keeps the original result control after a %s approval creates a hook-less continuation',
async (mode) => {
const fixture = setup([]);
- fixture.rows.push({
- id: 'protected-row',
- parentId: 'original-assistant',
- role: 'tool',
- tool_call_id: 'native-1',
- content: '',
- plugin: call(),
- pluginIntervention: { operationId: 'original-op', status: 'approved' },
- });
+ fixture.rows.push(protectedToolRow(call()));
fixture.loadState.mockResolvedValue({
...fixture.state,
operationId: 'original-op',
@@ -545,26 +571,9 @@ describe('afterToolCall control pipeline', () => {
fetchHook.mockImplementation(async () => response('deny'));
const result =
mode === 'single'
- ? await fixture.executors.call_tool!(
- {
- type: 'call_tool',
- payload: {
- parentMessageId: 'protected-row',
- skipCreateToolMessage: true,
- toolCalling: call(),
- },
- },
- fixture.state,
- )
+ ? await fixture.executors.call_tool!(protectedSingleToolEvent(call()), fixture.state)
: await fixture.executors.call_tools_batch!(
- {
- type: 'call_tools_batch',
- payload: {
- parentMessageId: 'assistant',
- toolsCalling: [call()],
- existingToolMessageIds: { 'native-1': 'protected-row' },
- },
- },
+ protectedBatchToolEvent(call()),
fixture.state,
);
expect(fixture.execute).toHaveBeenCalledTimes(1);
@@ -587,15 +596,7 @@ describe('afterToolCall control pipeline', () => {
vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'afterToolCall');
vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolCall');
const fixture = setup([]);
- fixture.rows.push({
- id: 'protected-row',
- parentId: 'original-assistant',
- role: 'tool',
- tool_call_id: 'native-1',
- content: '',
- plugin: call(),
- pluginIntervention: { operationId: 'original-op', status: 'approved' },
- });
+ fixture.rows.push(protectedToolRow(call()));
fixture.loadState.mockResolvedValue({
...fixture.state,
operationId: 'original-op',
@@ -603,29 +604,9 @@ describe('afterToolCall control pipeline', () => {
});
fetchHook.mockImplementation(async () => response('allow'));
if (mode === 'single') {
- await fixture.executors.call_tool!(
- {
- type: 'call_tool',
- payload: {
- parentMessageId: 'protected-row',
- skipCreateToolMessage: true,
- toolCalling: call(),
- },
- },
- fixture.state,
- );
+ await fixture.executors.call_tool!(protectedSingleToolEvent(call()), fixture.state);
} else {
- await fixture.executors.call_tools_batch!(
- {
- type: 'call_tools_batch',
- payload: {
- parentMessageId: 'assistant',
- toolsCalling: [call()],
- existingToolMessageIds: { 'native-1': 'protected-row' },
- },
- },
- fixture.state,
- );
+ await fixture.executors.call_tools_batch!(protectedBatchToolEvent(call()), fixture.state);
}
expect(fetchHook.mock.calls.map(([url]) => url)).toEqual([
'https://hooks.example/control',
@@ -643,40 +624,12 @@ describe('afterToolCall control pipeline', () => {
'publishes a %s result when the environment control has been removed',
async (mode) => {
const fixture = setup([]);
- fixture.rows.push({
- id: 'protected-row',
- parentId: 'original-assistant',
- role: 'tool',
- tool_call_id: 'native-1',
- content: '',
- plugin: call(),
- pluginIntervention: { operationId: 'original-op', status: 'approved' },
- });
+ fixture.rows.push(protectedToolRow(call()));
fixture.loadState.mockResolvedValue({ ...fixture.state, operationId: 'original-op' });
if (mode === 'single') {
- await fixture.executors.call_tool!(
- {
- type: 'call_tool',
- payload: {
- parentMessageId: 'protected-row',
- skipCreateToolMessage: true,
- toolCalling: call(),
- },
- },
- fixture.state,
- );
+ await fixture.executors.call_tool!(protectedSingleToolEvent(call()), fixture.state);
} else {
- await fixture.executors.call_tools_batch!(
- {
- type: 'call_tools_batch',
- payload: {
- parentMessageId: 'assistant',
- toolsCalling: [call()],
- existingToolMessageIds: { 'native-1': 'protected-row' },
- },
- },
- fixture.state,
- );
+ await fixture.executors.call_tools_batch!(protectedBatchToolEvent(call()), fixture.state);
}
expect(fetchHook).not.toHaveBeenCalled();
expect(archive).toHaveBeenCalled();
@@ -690,15 +643,7 @@ describe('afterToolCall control pipeline', () => {
it('does not trust tool state to bypass a continuation’s additional control', async () => {
const fixture = setup([control('new-policy')]);
- fixture.rows.push({
- id: 'protected-row',
- parentId: 'original-assistant',
- role: 'tool',
- tool_call_id: 'native-1',
- content: '',
- plugin: call(),
- pluginIntervention: { operationId: 'original-op', status: 'approved' },
- });
+ fixture.rows.push(protectedToolRow(call()));
fixture.loadState.mockResolvedValue({
...fixture.state,
operationId: 'original-op',
@@ -712,14 +657,7 @@ describe('afterToolCall control pipeline', () => {
response(String(url).endsWith('/original-policy') ? 'allow' : 'deny'),
);
const result = await fixture.executors.call_tool!(
- {
- type: 'call_tool',
- payload: {
- parentMessageId: 'protected-row',
- skipCreateToolMessage: true,
- toolCalling: call(),
- },
- },
+ protectedSingleToolEvent(call()),
fixture.state,
);
expect(fetchHook.mock.calls.map(([url]) => url)).toEqual([
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.test.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.test.ts
index 317bbc2a2f3..892b289d580 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.test.ts
@@ -9,6 +9,23 @@ import { createServerModelParamsProviders } from '@/server/modules/Mecha/ModelPa
import type { RuntimeExecutorContext } from '../context';
import { resolveServerCallLlmContextHints } from './serverCallLlmContextHints';
+const contextHintsInput = (
+ ctx: RuntimeExecutorContext,
+ llmPayload: CallLLMPayload,
+): Parameters<typeof resolveServerCallLlmContextHints>[0] => ({
+ ctx,
+ world: { agent: { chatConfig: {} } },
+ llmPayload,
+ model: 'gpt-4',
+ provider: 'openai',
+});
+
+const topicReasoningConfig = () => ({
+ metadata: { reasoningConfig: { reasoningEffort: 'high' } },
+ model: 'gpt-4',
+ provider: 'openai',
+});
+
const loadModelsMock = vi.hoisted(() => vi.fn());
const findByIdAndProviderMock = vi.hoisted(() => vi.fn());
const getModelReasoningConfigMock = vi.hoisted(() => vi.fn());
@@ -276,19 +293,11 @@ describe('resolveServerCallLlmContextHints - topic reasoning pin', () => {
it('should let the topic pin win over the model-instance config', async () => {
getModelReasoningConfigMock.mockResolvedValue({ reasoningEffort: 'low' });
- findTopicByIdMock.mockResolvedValue({
- metadata: { reasoningConfig: { reasoningEffort: 'high' } },
- model: 'gpt-4',
- provider: 'openai',
- });
+ findTopicByIdMock.mockResolvedValue(topicReasoningConfig());
- const hints = await resolveServerCallLlmContextHints({
- ctx: ctxWithTopic(),
- world: { agent: { chatConfig: {} } },
- llmPayload,
- model: 'gpt-4',
- provider: 'openai',
- });
+ const hints = await resolveServerCallLlmContextHints(
+ contextHintsInput(ctxWithTopic(), llmPayload),
+ );
expect(findTopicByIdMock).toHaveBeenCalledWith('topic-1');
expect(getModelReasoningConfigMock).not.toHaveBeenCalled();
@@ -296,19 +305,9 @@ describe('resolveServerCallLlmContextHints - topic reasoning pin', () => {
});
it('should read share-visitor topics too (they carry a senderId)', async () => {
- findTopicByIdMock.mockResolvedValue({
- metadata: { reasoningConfig: { reasoningEffort: 'high' } },
- model: 'gpt-4',
- provider: 'openai',
- });
+ findTopicByIdMock.mockResolvedValue(topicReasoningConfig());
- await resolveServerCallLlmContextHints({
- ctx: ctxWithTopic(),
- world: { agent: { chatConfig: {} } },
- llmPayload,
- model: 'gpt-4',
- provider: 'openai',
- });
+ await resolveServerCallLlmContextHints(contextHintsInput(ctxWithTopic(), llmPayload));
expect(topicModelCtorMock).toHaveBeenCalledWith(
expect.anything(),
@@ -327,13 +326,9 @@ describe('resolveServerCallLlmContextHints - topic reasoning pin', () => {
provider: 'openai',
});
- const hints = await resolveServerCallLlmContextHints({
- ctx: ctxWithTopic(),
- world: { agent: { chatConfig: {} } },
- llmPayload,
- model: 'gpt-4',
- provider: 'openai',
- });
+ const hints = await resolveServerCallLlmContextHints(
+ contextHintsInput(ctxWithTopic(), llmPayload),
+ );
expect(getModelReasoningConfigMock).not.toHaveBeenCalled();
expect(hints.resolvedExtendParams).toEqual({});
@@ -347,13 +342,9 @@ describe('resolveServerCallLlmContextHints - topic reasoning pin', () => {
provider: 'openai',
});
- const hints = await resolveServerCallLlmContextHints({
- ctx: ctxWithTopic(),
- world: { agent: { chatConfig: {} } },
- llmPayload,
- model: 'gpt-4',
- provider: 'openai',
- });
+ const hints = await resolveServerCallLlmContextHints(
+ contextHintsInput(ctxWithTopic(), llmPayload),
+ );
expect(getModelReasoningConfigMock).toHaveBeenCalledWith('gpt-4', 'openai');
expect(hints.resolvedExtendParams).toEqual({ reasoning_effort: 'low' });
@@ -363,23 +354,15 @@ describe('resolveServerCallLlmContextHints - topic reasoning pin', () => {
getModelReasoningConfigMock.mockResolvedValue({ reasoningEffort: 'low' });
findTopicByIdMock.mockResolvedValue({ metadata: {}, model: 'gpt-4', provider: 'openai' });
- const hints = await resolveServerCallLlmContextHints({
- ctx: ctxWithTopic(),
- world: { agent: { chatConfig: {} } },
- llmPayload,
- model: 'gpt-4',
- provider: 'openai',
- });
+ const hints = await resolveServerCallLlmContextHints(
+ contextHintsInput(ctxWithTopic(), llmPayload),
+ );
expect(hints.resolvedExtendParams).toEqual({ reasoning_effort: 'low' });
});
it('should still let explicit sub-agent overrides win over the topic pin', async () => {
- findTopicByIdMock.mockResolvedValue({
- metadata: { reasoningConfig: { reasoningEffort: 'high' } },
- model: 'gpt-4',
- provider: 'openai',
- });
+ findTopicByIdMock.mockResolvedValue(topicReasoningConfig());
const hints = await resolveServerCallLlmContextHints({
ctx: ctxWithTopic(),
@@ -467,13 +450,9 @@ describe('resolveServerCallLlmContextHints - model-instance reasoning config', (
it('should apply the user model-instance reasoning config', async () => {
getModelReasoningConfigMock.mockResolvedValue({ reasoningEffort: 'high' });
- const hints = await resolveServerCallLlmContextHints({
- ctx: createCtx(),
- world: { agent: { chatConfig: {} } },
- llmPayload,
- model: 'gpt-4',
- provider: 'openai',
- });
+ const hints = await resolveServerCallLlmContextHints(
+ contextHintsInput(createCtx(), llmPayload),
+ );
expect(getModelReasoningConfigMock).toHaveBeenCalledWith('gpt-4', 'openai');
expect(hints.resolvedExtendParams).toEqual({ reasoning_effort: 'high' });
@@ -525,13 +504,9 @@ describe('resolveServerCallLlmContextHints - model-instance reasoning config', (
findByIdAndProviderMock.mockResolvedValue({ settings: { extendParams: [] } });
getModelReasoningConfigMock.mockResolvedValue({ reasoningEffort: 'high' });
- const hints = await resolveServerCallLlmContextHints({
- ctx: createCtx(),
- world: { agent: { chatConfig: {} } },
- llmPayload,
- model: 'gpt-4',
- provider: 'openai',
- });
+ const hints = await resolveServerCallLlmContextHints(
+ contextHintsInput(createCtx(), llmPayload),
+ );
expect(getModelReasoningConfigMock).not.toHaveBeenCalled();
expect(hints.resolvedExtendParams).toEqual({});
@@ -704,11 +679,7 @@ describe('resolveServerCallLlmContextHints - frozen operation facts', () => {
it('reads no model source on a step and keeps the effort the run started with', async () => {
// What the user changed after the run started — none of it may be read.
getModelReasoningConfigMock.mockResolvedValue({ reasoningEffort: 'high' });
- findTopicByIdMock.mockResolvedValue({
- metadata: { reasoningConfig: { reasoningEffort: 'high' } },
- model: 'gpt-4',
- provider: 'openai',
- });
+ findTopicByIdMock.mockResolvedValue(topicReasoningConfig());
const hints = await resolveServerCallLlmContextHints({
ctx: frozenCtx(),
diff --git a/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts b/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts
index 3f113602113..9655452b296 100644
--- a/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts
+++ b/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts
@@ -19,6 +19,18 @@ import { describe, expect, it } from 'vitest';
import { createServerAgentToolsEngine, createServerToolsEngine } from '../index';
import { type InstalledPlugin, type ServerAgentToolsContext } from '../types';
+const serverToolInput = (toolIds: string[]) => ({
+ toolIds,
+ model: 'gpt-4',
+ provider: 'openai',
+});
+
+const deepseekToolInput = () => ({
+ model: 'deepseek-chat',
+ provider: 'deepseek',
+ toolIds: [],
+});
+
// Mock installed plugins
const mockInstalledPlugins: InstalledPlugin[] = [
{
@@ -333,11 +345,7 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [LocalSystemManifest.identifier],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(serverToolInput([LocalSystemManifest.identifier]));
// LocalSystem should be filtered out (disabled) on server
expect(result.enabledToolIds).not.toContain(LocalSystemManifest.identifier);
@@ -618,11 +626,7 @@ describe('createServerAgentToolsEngine', () => {
provider: 'deepseek',
});
- const result = engine.generateToolsDetailed({
- model: 'deepseek-chat',
- provider: 'deepseek',
- toolIds: [],
- });
+ const result = engine.generateToolsDetailed(deepseekToolInput());
// lobe-agent is in alwaysOnToolIds, so its core capabilities are on for every agent-mode turn.
expect(result.enabledToolIds).toContain(LobeAgentManifest.identifier);
@@ -643,11 +647,7 @@ describe('createServerAgentToolsEngine', () => {
provider: 'deepseek',
});
- const result = engine.generateToolsDetailed({
- model: 'deepseek-chat',
- provider: 'deepseek',
- toolIds: [],
- });
+ const result = engine.generateToolsDetailed(deepseekToolInput());
expect(result.enabledToolIds).not.toContain(LobeAgentManifest.identifier);
expect(result.enabledManifests).not.toContainEqual(
@@ -664,11 +664,7 @@ describe('createServerAgentToolsEngine', () => {
provider: 'deepseek',
});
- const result = engine.generateToolsDetailed({
- model: 'deepseek-chat',
- provider: 'deepseek',
- toolIds: [],
- });
+ const result = engine.generateToolsDetailed(deepseekToolInput());
// lobe-agent's other capabilities (plan / todo / visual-media) stay on...
expect(result.enabledToolIds).toContain(LobeAgentManifest.identifier);
@@ -691,11 +687,7 @@ describe('createServerAgentToolsEngine', () => {
provider: 'deepseek',
});
- const result = engine.generateToolsDetailed({
- model: 'deepseek-chat',
- provider: 'deepseek',
- toolIds: [],
- });
+ const result = engine.generateToolsDetailed(deepseekToolInput());
// lobe-skills is always-on, so the resolved manifest is what the model sees.
const skills = result.enabledManifests.find((m) => m.identifier === SkillsManifest.identifier);
@@ -716,11 +708,7 @@ describe('createServerAgentToolsEngine', () => {
provider: 'deepseek',
});
- const result = engine.generateToolsDetailed({
- model: 'deepseek-chat',
- provider: 'deepseek',
- toolIds: [],
- });
+ const result = engine.generateToolsDetailed(deepseekToolInput());
const lobeAgent = result.enabledManifests.find(
(m) => m.identifier === LobeAgentManifest.identifier,
@@ -775,11 +763,7 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(serverToolInput([]));
expect(result.enabledToolIds).toContain(GroupManagementManifest.identifier);
// group-agent-builder has no server runtime, so it is deliberately NOT
@@ -796,11 +780,7 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(serverToolInput([]));
expect(result.enabledToolIds).not.toContain(GroupManagementManifest.identifier);
expect(result.enabledToolIds).not.toContain(GroupAgentBuilderManifest.identifier);
@@ -925,11 +905,9 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [LocalSystemManifest.identifier],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(
+ serverToolInput([LocalSystemManifest.identifier]),
+ );
expect(result.enabledToolIds).not.toContain(LocalSystemManifest.identifier);
});
@@ -944,11 +922,9 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [LocalSystemManifest.identifier],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(
+ serverToolInput([LocalSystemManifest.identifier]),
+ );
expect(result.enabledToolIds).toContain(LocalSystemManifest.identifier);
});
@@ -963,11 +939,9 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [LocalSystemManifest.identifier],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(
+ serverToolInput([LocalSystemManifest.identifier]),
+ );
expect(result.enabledToolIds).not.toContain(LocalSystemManifest.identifier);
});
@@ -982,11 +956,9 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [LocalSystemManifest.identifier],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(
+ serverToolInput([LocalSystemManifest.identifier]),
+ );
expect(result.enabledToolIds).not.toContain(LocalSystemManifest.identifier);
});
@@ -1004,11 +976,9 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [LocalSystemManifest.identifier],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(
+ serverToolInput([LocalSystemManifest.identifier]),
+ );
expect(result.enabledToolIds).not.toContain(LocalSystemManifest.identifier);
});
@@ -1026,11 +996,9 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [LocalSystemManifest.identifier],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(
+ serverToolInput([LocalSystemManifest.identifier]),
+ );
expect(result.enabledToolIds).not.toContain(LocalSystemManifest.identifier);
});
@@ -1045,11 +1013,7 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(serverToolInput([]));
expect(result.enabledToolIds).toContain(CloudSandboxManifest.identifier);
});
@@ -1062,11 +1026,7 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(serverToolInput([]));
expect(result.enabledToolIds).not.toContain(CloudSandboxManifest.identifier);
});
@@ -1081,11 +1041,7 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(serverToolInput([]));
expect(result.enabledToolIds).not.toContain(CloudSandboxManifest.identifier);
});
@@ -1105,11 +1061,7 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(serverToolInput([]));
expect(result.enabledToolIds).toContain(CloudSandboxManifest.identifier);
});
@@ -1124,11 +1076,7 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(serverToolInput([]));
expect(result.enabledToolIds).toContain(CloudSandboxManifest.identifier);
});
@@ -1149,11 +1097,9 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [RemoteDeviceManifest.identifier],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(
+ serverToolInput([RemoteDeviceManifest.identifier]),
+ );
expect(result.enabledToolIds).toContain(RemoteDeviceManifest.identifier);
});
@@ -1168,11 +1114,9 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [RemoteDeviceManifest.identifier],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(
+ serverToolInput([RemoteDeviceManifest.identifier]),
+ );
expect(result.enabledToolIds).not.toContain(RemoteDeviceManifest.identifier);
});
@@ -1190,11 +1134,9 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [RemoteDeviceManifest.identifier],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(
+ serverToolInput([RemoteDeviceManifest.identifier]),
+ );
expect(result.enabledToolIds).not.toContain(RemoteDeviceManifest.identifier);
});
@@ -1212,11 +1154,9 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [RemoteDeviceManifest.identifier],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(
+ serverToolInput([RemoteDeviceManifest.identifier]),
+ );
expect(result.enabledToolIds).not.toContain(RemoteDeviceManifest.identifier);
});
@@ -1231,11 +1171,9 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [RemoteDeviceManifest.identifier],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(
+ serverToolInput([RemoteDeviceManifest.identifier]),
+ );
expect(result.enabledToolIds).not.toContain(RemoteDeviceManifest.identifier);
});
@@ -1257,11 +1195,9 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [RemoteDeviceManifest.identifier],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(
+ serverToolInput([RemoteDeviceManifest.identifier]),
+ );
expect(result.enabledToolIds).not.toContain(RemoteDeviceManifest.identifier);
});
@@ -1284,11 +1220,9 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [RemoteDeviceManifest.identifier],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(
+ serverToolInput([RemoteDeviceManifest.identifier]),
+ );
expect(result.enabledToolIds).not.toContain(RemoteDeviceManifest.identifier);
});
@@ -1309,11 +1243,9 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [RemoteDeviceManifest.identifier],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(
+ serverToolInput([RemoteDeviceManifest.identifier]),
+ );
expect(result.enabledToolIds).toContain(RemoteDeviceManifest.identifier);
});
@@ -1332,11 +1264,9 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [RemoteDeviceManifest.identifier],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(
+ serverToolInput([RemoteDeviceManifest.identifier]),
+ );
expect(result.enabledToolIds).not.toContain(RemoteDeviceManifest.identifier);
});
@@ -1355,11 +1285,9 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [LocalSystemManifest.identifier, RemoteDeviceManifest.identifier],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(
+ serverToolInput([LocalSystemManifest.identifier, RemoteDeviceManifest.identifier]),
+ );
expect(result.enabledToolIds).not.toContain(LocalSystemManifest.identifier);
expect(result.enabledToolIds).toContain(RemoteDeviceManifest.identifier);
@@ -1377,11 +1305,9 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [LocalSystemManifest.identifier, RemoteDeviceManifest.identifier],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(
+ serverToolInput([LocalSystemManifest.identifier, RemoteDeviceManifest.identifier]),
+ );
expect(result.enabledToolIds).toContain(LocalSystemManifest.identifier);
expect(result.enabledToolIds).not.toContain(RemoteDeviceManifest.identifier);
@@ -1401,11 +1327,9 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [LocalSystemManifest.identifier],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(
+ serverToolInput([LocalSystemManifest.identifier]),
+ );
expect(result.enabledToolIds).not.toContain(LocalSystemManifest.identifier);
});
@@ -1420,11 +1344,9 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [RemoteDeviceManifest.identifier],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(
+ serverToolInput([RemoteDeviceManifest.identifier]),
+ );
expect(result.enabledToolIds).not.toContain(RemoteDeviceManifest.identifier);
});
@@ -1442,11 +1364,9 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [LocalSystemManifest.identifier, RemoteDeviceManifest.identifier],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(
+ serverToolInput([LocalSystemManifest.identifier, RemoteDeviceManifest.identifier]),
+ );
expect(result.enabledToolIds).not.toContain(LocalSystemManifest.identifier);
expect(result.enabledToolIds).not.toContain(RemoteDeviceManifest.identifier);
@@ -1543,11 +1463,9 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [LocalSystemManifest.identifier],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(
+ serverToolInput([LocalSystemManifest.identifier]),
+ );
expect(result.enabledToolIds).toContain(LocalSystemManifest.identifier);
});
@@ -1563,11 +1481,9 @@ describe('createServerAgentToolsEngine', () => {
provider: 'openai',
});
- const result = engine.generateToolsDetailed({
- toolIds: [RemoteDeviceManifest.identifier],
- model: 'gpt-4',
- provider: 'openai',
- });
+ const result = engine.generateToolsDetailed(
+ serverToolInput([RemoteDeviceManifest.identifier]),
+ );
expect(result.enabledToolIds).toContain(RemoteDeviceManifest.identifier);
});
diff --git a/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts b/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts
index ca7be477bdf..a336722177f 100644
--- a/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts
+++ b/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts
@@ -8,6 +8,25 @@ import { after } from '@/server/utils/scheduleAfterResponse';
import { runStep, runStepHealth } from '../runStep';
+const runningStepResult = (continuation: unknown) => ({
+ continuation,
+ nextStepScheduled: false,
+ state: { status: 'running', stepCount: 3 },
+ success: true,
+});
+
+const finishedStepResult = (state: unknown) => ({
+ nextStepScheduled: false,
+ state,
+ success: true,
+});
+
+const initialDoneResult = () => ({
+ nextStepScheduled: false,
+ state: { cost: { total: 0 }, status: 'done', stepCount: 1 },
+ success: true,
+});
+
const mockGetOperationMetadata = vi.fn();
const mockLoadInlineResume = vi.fn();
const mockClearInlineResume = vi.fn();
@@ -316,11 +335,7 @@ describe('runStep handler', () => {
// in-process `execSubAgent` fork callback. A bare runtime here makes
// `lobe-agent.callSubAgent` fail with SUB_AGENT_UNAVAILABLE.
mockGetOperationMetadata.mockResolvedValue({ userId: 'user-1', workspaceId: 'ws-1' });
- mockExecuteStep.mockResolvedValue({
- nextStepScheduled: false,
- state: { cost: { total: 0 }, status: 'done', stepCount: 1 },
- success: true,
- });
+ mockExecuteStep.mockResolvedValue(initialDoneResult());
const { ctx } = buildContext({ body: validBody });
await runStep(ctx);
@@ -340,11 +355,7 @@ describe('runStep handler', () => {
let deadlineSeen: number | undefined;
mockExecuteStep.mockImplementation(async () => {
deadlineSeen = getInvocationDeadline();
- return {
- nextStepScheduled: false,
- state: { cost: { total: 0 }, status: 'done', stepCount: 1 },
- success: true,
- };
+ return initialDoneResult();
});
const startedAt = Date.now();
@@ -358,11 +369,7 @@ describe('runStep handler', () => {
it('kicks the opportunistic stale-operation sweep on a valid delivery', async () => {
mockGetOperationMetadata.mockResolvedValue({ userId: 'user-1' });
- mockExecuteStep.mockResolvedValue({
- nextStepScheduled: false,
- state: { cost: { total: 0 }, status: 'done', stepCount: 1 },
- success: true,
- });
+ mockExecuteStep.mockResolvedValue(initialDoneResult());
const { ctx } = buildContext({ body: validBody });
const res = await runStep(ctx);
@@ -382,11 +389,7 @@ describe('runStep handler', () => {
userId: 'user-owner',
workspaceId: 'ws-1',
});
- mockExecuteStep.mockResolvedValue({
- nextStepScheduled: false,
- state: { cost: { total: 0 }, status: 'done', stepCount: 1 },
- success: true,
- });
+ mockExecuteStep.mockResolvedValue(initialDoneResult());
const { ctx } = buildContext({ body: validBody });
await runStep(ctx);
@@ -596,23 +599,14 @@ describe('runStep inline step loop', () => {
it('runs consecutive steps in one invocation instead of re-queueing each one', async () => {
// The whole point of the loop: three steps, zero queue round-trips.
mockExecuteStep
- .mockResolvedValueOnce({
- continuation: continuationFor(3),
- nextStepScheduled: false,
- state: { status: 'running', stepCount: 3 },
- success: true,
- })
+ .mockResolvedValueOnce(runningStepResult(continuationFor(3)))
.mockResolvedValueOnce({
continuation: continuationFor(4),
nextStepScheduled: false,
state: { status: 'running', stepCount: 4 },
success: true,
})
- .mockResolvedValueOnce({
- nextStepScheduled: false,
- state: doneState,
- success: true,
- });
+ .mockResolvedValueOnce(finishedStepResult(doneState));
const { ctx, getCaptures } = buildContext({ body: validBody });
const res = await runStep(ctx);
@@ -633,12 +627,7 @@ describe('runStep inline step loop', () => {
// Human input / approvals / retry counters describe THIS delivery. Replaying
// them on an inlined step would re-apply an approval that already ran.
mockExecuteStep
- .mockResolvedValueOnce({
- continuation: continuationFor(3),
- nextStepScheduled: false,
- state: { status: 'running', stepCount: 3 },
- success: true,
- })
+ .mockResolvedValueOnce(runningStepResult(continuationFor(3)))
.mockResolvedValueOnce({ nextStepScheduled: false, state: doneState, success: true });
const { ctx } = buildContext({
@@ -662,12 +651,7 @@ describe('runStep inline step loop', () => {
it('holds one lock owner across every inlined step and releases it once', async () => {
mockExecuteStep
- .mockResolvedValueOnce({
- continuation: continuationFor(3),
- nextStepScheduled: false,
- state: { status: 'running', stepCount: 3 },
- success: true,
- })
+ .mockResolvedValueOnce(runningStepResult(continuationFor(3)))
.mockResolvedValueOnce({ nextStepScheduled: false, state: doneState, success: true });
const { ctx } = buildContext({ body: validBody });
@@ -688,12 +672,7 @@ describe('runStep inline step loop', () => {
mockExecuteStep.mockImplementation(async () => {
// Burn the whole inline budget inside the first step.
clock += 600_000;
- return {
- continuation: pending,
- nextStepScheduled: false,
- state: { status: 'running', stepCount: 3 },
- success: true,
- };
+ return runningStepResult(pending);
});
const { ctx, getCaptures } = buildContext({ body: validBody });
@@ -727,11 +706,7 @@ describe('runStep inline step loop', () => {
// nothing queued behind it — the inline loop never published a message.
const parked = continuationFor(7);
mockLoadInlineResume.mockResolvedValue(parked);
- mockExecuteStep.mockResolvedValue({
- nextStepScheduled: false,
- state: doneState,
- success: true,
- });
+ mockExecuteStep.mockResolvedValue(finishedStepResult(doneState));
const { ctx, getCaptures } = buildContext({ body: validBody });
await runStep(ctx);
@@ -748,11 +723,7 @@ describe('runStep inline step loop', () => {
// lets the stale-delivery guard ACK the step, and the approval never
// becomes available.
mockLoadInlineResume.mockResolvedValue(continuationFor(7));
- mockExecuteStep.mockResolvedValue({
- nextStepScheduled: false,
- state: doneState,
- success: true,
- });
+ mockExecuteStep.mockResolvedValue(finishedStepResult(doneState));
const { ctx } = buildContext({ body: validBody, retried: '2' });
await runStep(ctx);
@@ -795,11 +766,7 @@ describe('runStep inline step loop', () => {
{ verifyAsyncToolBarrier: true },
];
mockLoadInlineResume.mockResolvedValue(continuationFor(7));
- mockExecuteStep.mockResolvedValue({
- nextStepScheduled: false,
- state: doneState,
- success: true,
- });
+ mockExecuteStep.mockResolvedValue(finishedStepResult(doneState));
for (const payload of purposeful) {
mockExecuteStep.mockClear();
@@ -820,11 +787,7 @@ describe('runStep inline step loop', () => {
// parks k+1, then be told its step is stale. Clearing unconditionally there
// would delete the live worker's newer recovery pointer.
mockLoadInlineResume.mockResolvedValue(continuationFor(7));
- mockExecuteStep.mockResolvedValue({
- nextStepScheduled: false,
- state: doneState,
- success: true,
- });
+ mockExecuteStep.mockResolvedValue(finishedStepResult(doneState));
const { ctx } = buildContext({ body: validBody });
await runStep(ctx);
@@ -838,12 +801,7 @@ describe('runStep inline step loop', () => {
// bring back the false "over budget" rejection.
flushOverride.settled = false;
const pending = continuationFor(3);
- mockExecuteStep.mockResolvedValueOnce({
- continuation: pending,
- nextStepScheduled: false,
- state: { status: 'running', stepCount: 3 },
- success: true,
- });
+ mockExecuteStep.mockResolvedValueOnce(runningStepResult(pending));
try {
const { ctx, getCaptures } = buildContext({ body: validBody });
@@ -876,12 +834,7 @@ describe('runStep inline step loop', () => {
events.push('step 2 settled');
});
events.push('step 2 done');
- return {
- continuation: continuationFor(3),
- nextStepScheduled: false,
- state: { status: 'running', stepCount: 3 },
- success: true,
- };
+ return runningStepResult(continuationFor(3));
})
.mockImplementationOnce(async () => {
events.push('step 3 started');
@@ -898,11 +851,7 @@ describe('runStep inline step loop', () => {
// After a deadline hand-off the queued message carries the same index the
// envelope named. That delivery is authoritative, payload and all.
mockLoadInlineResume.mockResolvedValue(continuationFor(2));
- mockExecuteStep.mockResolvedValue({
- nextStepScheduled: false,
- state: doneState,
- success: true,
- });
+ mockExecuteStep.mockResolvedValue(finishedStepResult(doneState));
const { ctx } = buildContext({ body: { ...validBody, humanInput: 'yes' } });
await runStep(ctx);
@@ -920,12 +869,7 @@ describe('runStep inline step loop', () => {
const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => clock);
mockExecuteStep.mockImplementation(async () => {
clock += 600_000;
- return {
- continuation: continuationFor(3),
- nextStepScheduled: false,
- state: { status: 'running', stepCount: 3 },
- success: true,
- };
+ return runningStepResult(continuationFor(3));
});
const { ctx } = buildContext({ body: validBody });
@@ -951,12 +895,7 @@ describe('runStep inline step loop', () => {
it('stops the loop and reports success when another worker takes the lock mid-run', async () => {
mockExecuteStep
- .mockResolvedValueOnce({
- continuation: continuationFor(3),
- nextStepScheduled: false,
- state: { status: 'running', stepCount: 3 },
- success: true,
- })
+ .mockResolvedValueOnce(runningStepResult(continuationFor(3)))
.mockResolvedValueOnce({ locked: true, nextStepScheduled: false, state: {}, success: false });
const { ctx, getCaptures } = buildContext({ body: validBody });
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.execGroupSubAgentTask.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.execGroupSubAgentTask.test.ts
index 7eece903a2a..2bc4446981d 100644
--- a/apps/server/src/routers/lambda/__tests__/aiAgent.execGroupSubAgentTask.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.execGroupSubAgentTask.test.ts
@@ -8,6 +8,21 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { aiAgentRouter } from '../aiAgent';
import { cleanupTestUser, createTestUser } from './integration/setup';
+const subAgentInput = (agentId: string, groupId: string, topicId: string) => ({
+ agentId,
+ groupId,
+ instruction: 'Test instruction',
+ parentMessageId: 'parent-msg-1',
+ topicId,
+});
+
+const subAgentLaunchResponse = () => ({
+ assistantMessageId: 'assistant-msg-1',
+ operationId: 'op-123',
+ success: true,
+ threadId: 'thread-123',
+});
+
// Mock getServerDB to return our test database instance
let testDB: LobeChatDatabase;
vi.mock('@/database/core/db-adaptor', () => ({
@@ -107,22 +122,11 @@ describe('aiAgentRouter.execSubAgentTask', () => {
describe('successful execution', () => {
it('should call service method with correct parameters', async () => {
- mockExecGroupSubAgentTask.mockResolvedValue({
- assistantMessageId: 'assistant-msg-1',
- operationId: 'op-123',
- success: true,
- threadId: 'thread-123',
- });
+ mockExecGroupSubAgentTask.mockResolvedValue(subAgentLaunchResponse());
const caller = aiAgentRouter.createCaller(createTestContext());
- await caller.execSubAgentTask({
- agentId: testAgentId,
- groupId: testGroupId,
- instruction: 'Test instruction',
- parentMessageId: 'parent-msg-1',
- topicId: testTopicId,
- });
+ await caller.execSubAgentTask(subAgentInput(testAgentId, testGroupId, testTopicId));
expect(mockExecGroupSubAgentTask).toHaveBeenCalledWith(
{
@@ -165,12 +169,7 @@ describe('aiAgentRouter.execSubAgentTask', () => {
});
it('should pass parent operation metadata to the service', async () => {
- mockExecGroupSubAgentTask.mockResolvedValue({
- assistantMessageId: 'assistant-msg-1',
- operationId: 'op-123',
- success: true,
- threadId: 'thread-123',
- });
+ mockExecGroupSubAgentTask.mockResolvedValue(subAgentLaunchResponse());
const caller = aiAgentRouter.createCaller(createTestContext());
await caller.execSubAgentTask({
@@ -193,22 +192,13 @@ describe('aiAgentRouter.execSubAgentTask', () => {
});
it('should return result from service', async () => {
- mockExecGroupSubAgentTask.mockResolvedValue({
- assistantMessageId: 'assistant-msg-1',
- operationId: 'op-123',
- success: true,
- threadId: 'thread-123',
- });
+ mockExecGroupSubAgentTask.mockResolvedValue(subAgentLaunchResponse());
const caller = aiAgentRouter.createCaller(createTestContext());
- const result = await caller.execSubAgentTask({
- agentId: testAgentId,
- groupId: testGroupId,
- instruction: 'Test instruction',
- parentMessageId: 'parent-msg-1',
- topicId: testTopicId,
- });
+ const result = await caller.execSubAgentTask(
+ subAgentInput(testAgentId, testGroupId, testTopicId),
+ );
expect(result).toEqual({
assistantMessageId: 'assistant-msg-1',
@@ -219,12 +209,7 @@ describe('aiAgentRouter.execSubAgentTask', () => {
});
it('should pass timeout parameter when provided', async () => {
- mockExecGroupSubAgentTask.mockResolvedValue({
- assistantMessageId: 'assistant-msg-1',
- operationId: 'op-123',
- success: true,
- threadId: 'thread-123',
- });
+ mockExecGroupSubAgentTask.mockResolvedValue(subAgentLaunchResponse());
const caller = aiAgentRouter.createCaller(createTestContext());
@@ -315,13 +300,7 @@ describe('aiAgentRouter.execSubAgentTask', () => {
const caller = aiAgentRouter.createCaller(createTestContext());
await expect(
- caller.execSubAgentTask({
- agentId: testAgentId,
- groupId: testGroupId,
- instruction: 'Test instruction',
- parentMessageId: 'parent-msg-1',
- topicId: testTopicId,
- }),
+ caller.execSubAgentTask(subAgentInput(testAgentId, testGroupId, testTopicId)),
).rejects.toThrow('Agent not found');
});
@@ -331,13 +310,7 @@ describe('aiAgentRouter.execSubAgentTask', () => {
const caller = aiAgentRouter.createCaller(createTestContext());
await expect(
- caller.execSubAgentTask({
- agentId: testAgentId,
- groupId: testGroupId,
- instruction: 'Test instruction',
- parentMessageId: 'parent-msg-1',
- topicId: testTopicId,
- }),
+ caller.execSubAgentTask(subAgentInput(testAgentId, testGroupId, testTopicId)),
).rejects.toThrow('Failed to execute sub-agent task: Database connection failed');
});
});
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.getTaskStatus.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.getTaskStatus.test.ts
index 79058244962..beb4bd9628d 100644
--- a/apps/server/src/routers/lambda/__tests__/aiAgent.getTaskStatus.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.getTaskStatus.test.ts
@@ -16,6 +16,18 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { aiAgentRouter } from '../aiAgent';
import { cleanupTestUser, createTestUser } from './integration/setup';
+const threadTaskInput = (threadId: string) => ({
+ threadId,
+});
+
+const completedThreadState = (status: (typeof ThreadStatus)['Completed']) => ({
+ status,
+ metadata: {
+ operationId: 'op-test-123',
+ completedAt: '2024-01-01T00:00:00Z',
+ },
+});
+
// Mock getServerDB to return our test database instance
let testDB: LobeChatDatabase;
vi.mock('@/database/core/db-adaptor', () => ({
@@ -134,9 +146,7 @@ describe('aiAgentRouter.getSubAgentTaskStatus', () => {
it('should return task status from Thread table', async () => {
const caller = aiAgentRouter.createCaller(createTestContext());
- const result = await caller.getSubAgentTaskStatus({
- threadId: testThreadId,
- });
+ const result = await caller.getSubAgentTaskStatus(threadTaskInput(testThreadId));
expect(result.status).toBe('processing');
expect(result.taskDetail).toBeDefined();
@@ -172,9 +182,7 @@ describe('aiAgentRouter.getSubAgentTaskStatus', () => {
const caller = aiAgentRouter.createCaller(createTestContext());
- const result = await caller.getSubAgentTaskStatus({
- threadId: testThreadId,
- });
+ const result = await caller.getSubAgentTaskStatus(threadTaskInput(testThreadId));
expect(result.status).toBe('completed');
expect(result.completedAt).toBe('2024-01-01T00:00:00Z');
@@ -205,9 +213,7 @@ describe('aiAgentRouter.getSubAgentTaskStatus', () => {
const caller = aiAgentRouter.createCaller(createTestContext());
- const result = await caller.getSubAgentTaskStatus({
- threadId: testThreadId,
- });
+ const result = await caller.getSubAgentTaskStatus(threadTaskInput(testThreadId));
expect(result.status).toBe(expectedTaskStatus);
},
@@ -230,9 +236,7 @@ describe('aiAgentRouter.getSubAgentTaskStatus', () => {
const caller = aiAgentRouter.createCaller(createTestContext());
- const result = await caller.getSubAgentTaskStatus({
- threadId: testThreadId,
- });
+ const result = await caller.getSubAgentTaskStatus(threadTaskInput(testThreadId));
expect(result.status).toBe('processing');
expect(result.stepCount).toBe(3);
@@ -336,9 +340,7 @@ describe('aiAgentRouter.getSubAgentTaskStatus', () => {
const caller = aiAgentRouter.createCaller(createTestContext());
- const result = await caller.getSubAgentTaskStatus({
- threadId: testThreadId,
- });
+ const result = await caller.getSubAgentTaskStatus(threadTaskInput(testThreadId));
expect(result.taskDetail?.totalToolCalls).toBe(5);
expect(result.taskDetail?.totalTokens).toBe(8358);
@@ -362,9 +364,7 @@ describe('aiAgentRouter.getSubAgentTaskStatus', () => {
const caller = aiAgentRouter.createCaller(createTestContext());
- const result = await caller.getSubAgentTaskStatus({
- threadId: testThreadId,
- });
+ const result = await caller.getSubAgentTaskStatus(threadTaskInput(testThreadId));
expect(result.status).toBe('processing');
expect(result.usage).toEqual({ total_tokens: 500 });
@@ -383,9 +383,7 @@ describe('aiAgentRouter.getSubAgentTaskStatus', () => {
const caller = aiAgentRouter.createCaller(createTestContext());
- await caller.getSubAgentTaskStatus({
- threadId: testThreadId,
- });
+ await caller.getSubAgentTaskStatus(threadTaskInput(testThreadId));
// Should not call Redis for completed tasks
expect(mockGetOperationStatus).not.toHaveBeenCalled();
@@ -412,9 +410,7 @@ describe('aiAgentRouter.getSubAgentTaskStatus', () => {
const caller = aiAgentRouter.createCaller(createTestContext());
- const result = await caller.getSubAgentTaskStatus({
- threadId: testThreadId,
- });
+ const result = await caller.getSubAgentTaskStatus(threadTaskInput(testThreadId));
expect(result.status).toBe('failed');
expect(result.error).toMatchObject({
@@ -443,9 +439,7 @@ describe('aiAgentRouter.getSubAgentTaskStatus', () => {
const caller = aiAgentRouter.createCaller(createTestContext());
- const result = await caller.getSubAgentTaskStatus({
- threadId: testThreadId,
- });
+ const result = await caller.getSubAgentTaskStatus(threadTaskInput(testThreadId));
expect(result.status).toBe('failed');
expect(result.error).toBe('Tool execution failed');
@@ -478,9 +472,7 @@ describe('aiAgentRouter.getSubAgentTaskStatus', () => {
const caller = aiAgentRouter.createCaller(createTestContext());
- const result = await caller.getSubAgentTaskStatus({
- threadId: testThreadId,
- });
+ const result = await caller.getSubAgentTaskStatus(threadTaskInput(testThreadId));
expect(result.taskDetail).toEqual({
threadId: testThreadId,
@@ -543,20 +535,12 @@ describe('aiAgentRouter.getSubAgentTaskStatus', () => {
// Update thread to completed status
await serverDB
.update(threads)
- .set({
- status: ThreadStatus.Completed,
- metadata: {
- operationId: 'op-test-123',
- completedAt: '2024-01-01T00:00:00Z',
- },
- })
+ .set(completedThreadState(ThreadStatus.Completed))
.where(eq(threads.id, testThreadId));
const caller = aiAgentRouter.createCaller(createTestContext());
- const result = await caller.getSubAgentTaskStatus({
- threadId: testThreadId,
- });
+ const result = await caller.getSubAgentTaskStatus(threadTaskInput(testThreadId));
expect(result.status).toBe('completed');
expect(result.result).toBe('This is the final result of the task execution.');
@@ -587,9 +571,7 @@ describe('aiAgentRouter.getSubAgentTaskStatus', () => {
const caller = aiAgentRouter.createCaller(createTestContext());
- const result = await caller.getSubAgentTaskStatus({
- threadId: testThreadId,
- });
+ const result = await caller.getSubAgentTaskStatus(threadTaskInput(testThreadId));
expect(result.status).toBe('failed');
expect(result.result).toBe('Partial result before failure.');
@@ -610,9 +592,7 @@ describe('aiAgentRouter.getSubAgentTaskStatus', () => {
// Thread is in processing status (default from beforeEach)
const caller = aiAgentRouter.createCaller(createTestContext());
- const result = await caller.getSubAgentTaskStatus({
- threadId: testThreadId,
- });
+ const result = await caller.getSubAgentTaskStatus(threadTaskInput(testThreadId));
expect(result.status).toBe('processing');
expect(result.result).toBeUndefined();
@@ -622,20 +602,12 @@ describe('aiAgentRouter.getSubAgentTaskStatus', () => {
// Update thread to completed status without any messages
await serverDB
.update(threads)
- .set({
- status: ThreadStatus.Completed,
- metadata: {
- operationId: 'op-test-123',
- completedAt: '2024-01-01T00:00:00Z',
- },
- })
+ .set(completedThreadState(ThreadStatus.Completed))
.where(eq(threads.id, testThreadId));
const caller = aiAgentRouter.createCaller(createTestContext());
- const result = await caller.getSubAgentTaskStatus({
- threadId: testThreadId,
- });
+ const result = await caller.getSubAgentTaskStatus(threadTaskInput(testThreadId));
expect(result.status).toBe('completed');
expect(result.result).toBeUndefined();
@@ -659,9 +631,7 @@ describe('aiAgentRouter.getSubAgentTaskStatus', () => {
const caller = aiAgentRouter.createCaller(createTestContext());
- const result = await caller.getSubAgentTaskStatus({
- threadId: testThreadId,
- });
+ const result = await caller.getSubAgentTaskStatus(threadTaskInput(testThreadId));
expect(result.status).toBe('processing');
expect(result.currentActivity).toEqual({
@@ -716,9 +686,7 @@ describe('aiAgentRouter.getSubAgentTaskStatus', () => {
const caller = aiAgentRouter.createCaller(createTestContext());
- const result = await caller.getSubAgentTaskStatus({
- threadId: testThreadId,
- });
+ const result = await caller.getSubAgentTaskStatus(threadTaskInput(testThreadId));
expect(result.status).toBe('processing');
expect(result.currentActivity?.type).toBe('tool_result');
@@ -742,9 +710,7 @@ describe('aiAgentRouter.getSubAgentTaskStatus', () => {
const caller = aiAgentRouter.createCaller(createTestContext());
- const result = await caller.getSubAgentTaskStatus({
- threadId: testThreadId,
- });
+ const result = await caller.getSubAgentTaskStatus(threadTaskInput(testThreadId));
expect(result.status).toBe('processing');
expect(result.currentActivity).toEqual({
@@ -767,9 +733,7 @@ describe('aiAgentRouter.getSubAgentTaskStatus', () => {
const caller = aiAgentRouter.createCaller(createTestContext());
- const result = await caller.getSubAgentTaskStatus({
- threadId: testThreadId,
- });
+ const result = await caller.getSubAgentTaskStatus(threadTaskInput(testThreadId));
expect(result.currentActivity?.contentPreview).toBe('A'.repeat(100));
});
@@ -788,20 +752,12 @@ describe('aiAgentRouter.getSubAgentTaskStatus', () => {
// Update thread to completed status
await serverDB
.update(threads)
- .set({
- status: ThreadStatus.Completed,
- metadata: {
- operationId: 'op-test-123',
- completedAt: '2024-01-01T00:00:00Z',
- },
- })
+ .set(completedThreadState(ThreadStatus.Completed))
.where(eq(threads.id, testThreadId));
const caller = aiAgentRouter.createCaller(createTestContext());
- const result = await caller.getSubAgentTaskStatus({
- threadId: testThreadId,
- });
+ const result = await caller.getSubAgentTaskStatus(threadTaskInput(testThreadId));
expect(result.status).toBe('completed');
expect(result.currentActivity).toBeUndefined();
@@ -810,9 +766,7 @@ describe('aiAgentRouter.getSubAgentTaskStatus', () => {
it('should not return currentActivity when no messages in thread', async () => {
const caller = aiAgentRouter.createCaller(createTestContext());
- const result = await caller.getSubAgentTaskStatus({
- threadId: testThreadId,
- });
+ const result = await caller.getSubAgentTaskStatus(threadTaskInput(testThreadId));
expect(result.status).toBe('processing');
expect(result.currentActivity).toBeUndefined();
diff --git a/apps/server/src/routers/lambda/__tests__/aiChat.test.ts b/apps/server/src/routers/lambda/__tests__/aiChat.test.ts
index 85900618f06..bede7cedc16 100644
--- a/apps/server/src/routers/lambda/__tests__/aiChat.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiChat.test.ts
@@ -14,6 +14,18 @@ import { AiChatService } from '@/server/services/aiChat';
import { aiChatRouter } from '../aiChat';
+const newChatInput = () => ({
+ agentId: 'agent-1',
+ newAssistantMessage: { model: 'gpt-4o', provider: 'openai' },
+ newTopic: { title: 'New Topic' },
+ newUserMessage: { content: 'hi' },
+ sessionId: 's1',
+});
+
+const objectGenerationRuntime = (generateObject: ReturnType<typeof vi.fn>) => ({
+ generateObject,
+});
+
const flushAsyncTasks = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
vi.mock('@/server/routers/lambda/_helpers/resolveContext', () => ({
@@ -953,13 +965,7 @@ describe('aiChatRouter', () => {
const caller = aiChatRouter.createCaller(mockCtx as any);
- await caller.sendMessageInServer({
- agentId: 'agent-1',
- newAssistantMessage: { model: 'gpt-4o', provider: 'openai' },
- newTopic: { title: 'New Topic' },
- newUserMessage: { content: 'hi' },
- sessionId: 's1',
- } as any);
+ await caller.sendMessageInServer(newChatInput() as any);
// Verify agentId is passed to topic creation
expect(mockCreateTopic).toHaveBeenCalledWith(
@@ -994,13 +1000,7 @@ describe('aiChatRouter', () => {
const caller = aiChatRouter.createCaller(mockCtx as any);
- await caller.sendMessageInServer({
- agentId: 'agent-1',
- newAssistantMessage: { model: 'gpt-4o', provider: 'openai' },
- newTopic: { title: 'New Topic' },
- newUserMessage: { content: 'hi' },
- sessionId: 's1',
- } as any);
+ await caller.sendMessageInServer(newChatInput() as any);
// Verify touchUpdatedAt was called with the agentId
expect(mockTouchUpdatedAt).toHaveBeenCalledWith('agent-1');
@@ -1036,13 +1036,7 @@ describe('aiChatRouter', () => {
const caller = aiChatRouter.createCaller(mockCtx as any);
- const res = await caller.sendMessageInServer({
- agentId: 'agent-1',
- newAssistantMessage: { model: 'gpt-4o', provider: 'openai' },
- newTopic: { title: 'New Topic' },
- newUserMessage: { content: 'hi' },
- sessionId: 's1',
- } as any);
+ const res = await caller.sendMessageInServer(newChatInput() as any);
expect(res.userMessageId).toBe('m-user');
expect(res.assistantMessageId).toBe('m-assistant');
@@ -1084,13 +1078,7 @@ describe('aiChatRouter', () => {
const caller = aiChatRouter.createCaller(mockCtx as any);
- const request = caller.sendMessageInServer({
- agentId: 'agent-1',
- newAssistantMessage: { model: 'gpt-4o', provider: 'openai' },
- newTopic: { title: 'New Topic' },
- newUserMessage: { content: 'hi' },
- sessionId: 's1',
- } as any);
+ const request = caller.sendMessageInServer(newChatInput() as any);
await flushAsyncTasks();
@@ -1176,9 +1164,9 @@ describe('aiChatRouter', () => {
const mockResult = { object: { name: 'John', age: 30 } };
const mockGenerateObject = vi.fn().mockResolvedValue(mockResult);
- vi.mocked(initModelRuntimeFromDB).mockResolvedValue({
- generateObject: mockGenerateObject,
- } as any);
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue(
+ objectGenerationRuntime(mockGenerateObject) as any,
+ );
const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);
@@ -1329,9 +1317,9 @@ describe('aiChatRouter', () => {
};
const mockGenerateObject = vi.fn().mockRejectedValue(accessError);
- vi.mocked(initModelRuntimeFromDB).mockResolvedValue({
- generateObject: mockGenerateObject,
- } as any);
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue(
+ objectGenerationRuntime(mockGenerateObject) as any,
+ );
const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);
@@ -1374,9 +1362,9 @@ describe('aiChatRouter', () => {
const { initModelRuntimeFromDB } = await import('@/server/modules/ModelRuntime');
const mockGenerateObject = vi.fn().mockRejectedValue(accessError);
- vi.mocked(initModelRuntimeFromDB).mockResolvedValue({
- generateObject: mockGenerateObject,
- } as any);
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue(
+ objectGenerationRuntime(mockGenerateObject) as any,
+ );
const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);
@@ -1404,9 +1392,9 @@ describe('aiChatRouter', () => {
const accessError = { error: {}, errorType };
const mockGenerateObject = vi.fn().mockRejectedValue(accessError);
- vi.mocked(initModelRuntimeFromDB).mockResolvedValue({
- generateObject: mockGenerateObject,
- } as any);
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue(
+ objectGenerationRuntime(mockGenerateObject) as any,
+ );
const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);
@@ -1432,9 +1420,9 @@ describe('aiChatRouter', () => {
};
const mockGenerateObject = vi.fn().mockRejectedValue(runtimeError);
- vi.mocked(initModelRuntimeFromDB).mockResolvedValue({
- generateObject: mockGenerateObject,
- } as any);
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue(
+ objectGenerationRuntime(mockGenerateObject) as any,
+ );
const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);
@@ -1461,9 +1449,9 @@ describe('aiChatRouter', () => {
const runtimeError = { errorType };
const mockGenerateObject = vi.fn().mockRejectedValue(runtimeError);
- vi.mocked(initModelRuntimeFromDB).mockResolvedValue({
- generateObject: mockGenerateObject,
- } as any);
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue(
+ objectGenerationRuntime(mockGenerateObject) as any,
+ );
const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);
@@ -1497,9 +1485,9 @@ describe('aiChatRouter', () => {
);
const mockGenerateObject = vi.fn().mockRejectedValue(providerError);
- vi.mocked(initModelRuntimeFromDB).mockResolvedValue({
- generateObject: mockGenerateObject,
- } as any);
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue(
+ objectGenerationRuntime(mockGenerateObject) as any,
+ );
const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);
@@ -1537,9 +1525,9 @@ describe('aiChatRouter', () => {
];
const mockGenerateObject = vi.fn().mockResolvedValue({ object: {} });
- vi.mocked(initModelRuntimeFromDB).mockResolvedValue({
- generateObject: mockGenerateObject,
- } as any);
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue(
+ objectGenerationRuntime(mockGenerateObject) as any,
+ );
const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);
@@ -1600,9 +1588,9 @@ describe('aiChatRouter', () => {
it('merges caller metadata over the default trigger and forwards tracing', async () => {
const { initModelRuntimeFromDB } = await import('@/server/modules/ModelRuntime');
const mockGenerateObject = vi.fn().mockResolvedValue({ completion: 'hi there' });
- vi.mocked(initModelRuntimeFromDB).mockResolvedValue({
- generateObject: mockGenerateObject,
- } as any);
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue(
+ objectGenerationRuntime(mockGenerateObject) as any,
+ );
const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);
const result = await caller.outputJSON({
@@ -1712,9 +1700,9 @@ describe('aiChatRouter', () => {
it('rejects a caller-supplied tracing.tracingId that is not a UUID', async () => {
const { initModelRuntimeFromDB } = await import('@/server/modules/ModelRuntime');
const mockGenerateObject = vi.fn();
- vi.mocked(initModelRuntimeFromDB).mockResolvedValue({
- generateObject: mockGenerateObject,
- } as any);
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue(
+ objectGenerationRuntime(mockGenerateObject) as any,
+ );
const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);
@@ -1733,9 +1721,9 @@ describe('aiChatRouter', () => {
it('honours caller-supplied tracing.tracingId instead of generating a new one', async () => {
const { initModelRuntimeFromDB } = await import('@/server/modules/ModelRuntime');
const mockGenerateObject = vi.fn().mockResolvedValue({ completion: 'ok' });
- vi.mocked(initModelRuntimeFromDB).mockResolvedValue({
- generateObject: mockGenerateObject,
- } as any);
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue(
+ objectGenerationRuntime(mockGenerateObject) as any,
+ );
const callerSuppliedId = '00000000-0000-4000-8000-000000000001';
const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);
diff --git a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts
index 73cb46bbe63..5d3efc11f90 100644
--- a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts
@@ -7,6 +7,16 @@ import { TopicModel } from '@/database/models/topic';
import { AbandonOperationService } from '../AbandonOperationService';
import { CompletionLifecycle } from '../CompletionLifecycle';
+const abandonDeps = (
+ coordinator: NonNullable<ConstructorParameters<typeof AbandonOperationService>[1]>['coordinator'],
+ snapshotStore: NonNullable<
+ ConstructorParameters<typeof AbandonOperationService>[1]
+ >['snapshotStore'],
+) => ({
+ coordinator,
+ snapshotStore,
+});
+
const buildStore = () => ({
get: vi.fn(),
getLatest: vi.fn(),
@@ -146,10 +156,7 @@ describe('AbandonOperationService', () => {
it('returns found:false when coordinator has no state', async () => {
const coord = buildCoordinator({ loadAgentState: vi.fn().mockResolvedValue(null) });
const store = buildStore();
- const svc = new AbandonOperationService({} as any, {
- coordinator: coord as any,
- snapshotStore: store as any,
- });
+ const svc = new AbandonOperationService({} as any, abandonDeps(coord as any, store as any));
const result = await svc.finalizeAbandoned('op_missing', 'inactivity_5m');
@@ -182,10 +189,7 @@ describe('AbandonOperationService', () => {
status: 'settled',
});
- const svc = new AbandonOperationService(db, {
- coordinator: coord as any,
- snapshotStore: store as any,
- });
+ const svc = new AbandonOperationService(db, abandonDeps(coord as any, store as any));
const result = await svc.finalizeAbandoned('op_x', 'inactivity_watchdog');
@@ -471,10 +475,7 @@ describe('AbandonOperationService', () => {
},
});
- const svc = new AbandonOperationService(db, {
- coordinator: coord as any,
- snapshotStore: store as any,
- });
+ const svc = new AbandonOperationService(db, abandonDeps(coord as any, store as any));
const result = await svc.finalizeAbandoned('op_done', 'inactivity_watchdog');
@@ -514,10 +515,7 @@ describe('AbandonOperationService', () => {
const result = await new AbandonOperationService(
buildDb({ operationRow: settledRow(status) }),
- {
- coordinator: coord as any,
- snapshotStore: store as any,
- },
+ abandonDeps(coord as any, store as any),
).finalizeAbandoned('op_x', 'inactivity_watchdog', options);
return { coord, result, store };
@@ -716,10 +714,7 @@ describe('AbandonOperationService', () => {
workspaceId: null,
},
}),
- {
- coordinator: coord as any,
- snapshotStore: buildPartiallessStore() as any,
- },
+ abandonDeps(coord as any, buildPartiallessStore() as any),
);
const result = await svc.finalizeAbandoned('op_child', 'inactivity_watchdog');
@@ -849,10 +844,7 @@ describe('AbandonOperationService', () => {
userId: 'user_x',
},
});
- const svc = new AbandonOperationService(db, {
- coordinator: coord as any,
- snapshotStore: store as any,
- });
+ const svc = new AbandonOperationService(db, abandonDeps(coord as any, store as any));
const result = await svc.finalizeAbandoned('op_old', 'inactivity_watchdog');
@@ -878,10 +870,7 @@ describe('AbandonOperationService', () => {
workspaceId: 'ws_x',
},
});
- const svc = new AbandonOperationService(db, {
- coordinator: coord as any,
- snapshotStore: store as any,
- });
+ const svc = new AbandonOperationService(db, abandonDeps(coord as any, store as any));
await svc.finalizeAbandoned('op_x', 'inactivity_watchdog');
@@ -933,10 +922,7 @@ describe('AbandonOperationService', () => {
{ stepIndex: 1, stepType: 'call_tool' },
],
});
- const svc = new AbandonOperationService({} as any, {
- coordinator: coord as any,
- snapshotStore: store as any,
- });
+ const svc = new AbandonOperationService({} as any, abandonDeps(coord as any, store as any));
const result = await svc.finalizeAbandoned('op_x', 'inactivity_5m');
@@ -992,10 +978,10 @@ describe('AbandonOperationService', () => {
loadAgentState: vi.fn().mockResolvedValue(stateWith()),
});
- await new AbandonOperationService(buildDb(), {
- coordinator: coord as any,
- snapshotStore: buildPartiallessStore() as any,
- }).finalizeAbandoned('op_x', 'stale_lease_redrive_exhausted', { settledAsAbandoned: true });
+ await new AbandonOperationService(
+ buildDb(),
+ abandonDeps(coord as any, buildPartiallessStore() as any),
+ ).finalizeAbandoned('op_x', 'stale_lease_redrive_exhausted', { settledAsAbandoned: true });
expect(dispatchHooksMock).toHaveBeenCalledWith(
'op_x',
@@ -1013,10 +999,7 @@ describe('AbandonOperationService', () => {
});
const store = buildStore();
store.loadPartial.mockResolvedValue(null);
- const svc = new AbandonOperationService({} as any, {
- coordinator: coord as any,
- snapshotStore: store as any,
- });
+ const svc = new AbandonOperationService({} as any, abandonDeps(coord as any, store as any));
const result = await svc.finalizeAbandoned('op_x', 'inactivity_5m');
@@ -1033,10 +1016,7 @@ describe('AbandonOperationService', () => {
const store = buildStore();
store.loadPartial.mockResolvedValue(null);
- const svc = new AbandonOperationService({} as any, {
- coordinator: coord as any,
- snapshotStore: store as any,
- });
+ const svc = new AbandonOperationService({} as any, abandonDeps(coord as any, store as any));
const result = await svc.finalizeAbandoned('op_x', 'inactivity_5m');
@@ -1054,10 +1034,7 @@ describe('AbandonOperationService', () => {
const store = buildStore();
store.loadPartial.mockResolvedValue({ steps: [], startedAt: 1 });
- const svc = new AbandonOperationService({} as any, {
- coordinator: coord as any,
- snapshotStore: store as any,
- });
+ const svc = new AbandonOperationService({} as any, abandonDeps(coord as any, store as any));
await svc.finalizeAbandoned('op_x', 'reason');
@@ -1075,10 +1052,7 @@ describe('AbandonOperationService', () => {
const store = buildStore();
store.loadPartial.mockResolvedValue({ steps: [{ stepIndex: 0 }], startedAt: 1 });
- const svc = new AbandonOperationService({} as any, {
- coordinator: coord as any,
- snapshotStore: store as any,
- });
+ const svc = new AbandonOperationService({} as any, abandonDeps(coord as any, store as any));
const result = await svc.finalizeAbandoned('op_x', 'reason');
@@ -1097,10 +1071,7 @@ describe('AbandonOperationService', () => {
store.loadPartial.mockResolvedValue({ steps: [{ stepIndex: 0 }], startedAt: 1 });
messageUpdateMock.mockRejectedValueOnce(new Error('db down'));
- const svc = new AbandonOperationService({} as any, {
- coordinator: coord as any,
- snapshotStore: store as any,
- });
+ const svc = new AbandonOperationService({} as any, abandonDeps(coord as any, store as any));
// Should not throw — both failure paths are caught & logged
const result = await svc.finalizeAbandoned('op_x', 'reason');
@@ -1135,10 +1106,7 @@ describe('AbandonOperationService', () => {
const store = buildStore();
store.loadPartial.mockResolvedValue(null);
- const svc = new AbandonOperationService({} as any, {
- coordinator: coord as any,
- snapshotStore: store as any,
- });
+ const svc = new AbandonOperationService({} as any, abandonDeps(coord as any, store as any));
const result = await svc.finalizeAbandoned('op_child', 'inactivity_watchdog');
@@ -1188,10 +1156,7 @@ describe('AbandonOperationService', () => {
const store = buildStore();
store.loadPartial.mockResolvedValue(null);
- const svc = new AbandonOperationService({} as any, {
- coordinator: coord as any,
- snapshotStore: store as any,
- });
+ const svc = new AbandonOperationService({} as any, abandonDeps(coord as any, store as any));
const result = await svc.finalizeAbandoned('op_child', 'inactivity_watchdog');
@@ -1224,10 +1189,7 @@ describe('AbandonOperationService', () => {
const store = buildStore();
store.loadPartial.mockResolvedValue(null);
- const svc = new AbandonOperationService({} as any, {
- coordinator: coord as any,
- snapshotStore: store as any,
- });
+ const svc = new AbandonOperationService({} as any, abandonDeps(coord as any, store as any));
const result = await svc.finalizeAbandoned('op_member', 'inactivity_watchdog');
@@ -1269,10 +1231,10 @@ describe('AbandonOperationService', () => {
const store = buildStore();
store.loadPartial.mockResolvedValue(null);
- await new AbandonOperationService({} as any, {
- coordinator: coord as any,
- snapshotStore: store as any,
- }).finalizeAbandoned('op_visitor', 'inactivity_5m');
+ await new AbandonOperationService(
+ {} as any,
+ abandonDeps(coord as any, store as any),
+ ).finalizeAbandoned('op_visitor', 'inactivity_5m');
expect(MessageModel).toHaveBeenCalledWith(expect.anything(), 'user_owner', 'ws_1', undefined, {
includeShareVisitor: true,
@@ -1296,10 +1258,10 @@ describe('AbandonOperationService', () => {
const store = buildStore();
store.loadPartial.mockResolvedValue(null);
- await new AbandonOperationService({} as any, {
- coordinator: coord as any,
- snapshotStore: store as any,
- }).finalizeAbandoned('op_x', 'inactivity_5m');
+ await new AbandonOperationService(
+ {} as any,
+ abandonDeps(coord as any, store as any),
+ ).finalizeAbandoned('op_x', 'inactivity_5m');
expect(MessageModel).toHaveBeenCalledWith(expect.anything(), 'user_x', undefined, undefined, {
includeShareVisitor: false,
@@ -1339,10 +1301,10 @@ describe('AbandonOperationService', () => {
status: 'settled',
});
- await new AbandonOperationService(db, {
- coordinator: coord as any,
- snapshotStore: store as any,
- }).finalizeAbandoned('op_ns', 'inactivity_watchdog');
+ await new AbandonOperationService(
+ db,
+ abandonDeps(coord as any, store as any),
+ ).finalizeAbandoned('op_ns', 'inactivity_watchdog');
expect(TopicModel).toHaveBeenCalledWith(expect.anything(), 'user_x', 'ws_1', undefined, {
includeShareVisitor: true,
@@ -1362,10 +1324,10 @@ describe('AbandonOperationService', () => {
const store = buildStore();
store.loadPartial.mockResolvedValue({ startedAt: 1, steps: [{ stepIndex: 0 }] });
- await new AbandonOperationService(buildDb(), {
- coordinator: coord as any,
- snapshotStore: store as any,
- }).finalizeAbandoned('op_x', 'inactivity_watchdog');
+ await new AbandonOperationService(
+ buildDb(),
+ abandonDeps(coord as any, store as any),
+ ).finalizeAbandoned('op_x', 'inactivity_watchdog');
expect(settleLiveMock).toHaveBeenCalledWith('op_x', 'error');
});
@@ -1378,10 +1340,10 @@ describe('AbandonOperationService', () => {
loadAgentState: vi.fn().mockResolvedValue(stateWith({ status: 'idle' })),
});
- await new AbandonOperationService(buildDb(), {
- coordinator: coord as any,
- snapshotStore: buildPartiallessStore() as any,
- }).finalizeAbandoned('op_idle', 'stale_lease');
+ await new AbandonOperationService(
+ buildDb(),
+ abandonDeps(coord as any, buildPartiallessStore() as any),
+ ).finalizeAbandoned('op_idle', 'stale_lease');
expect(dispatchHooksMock).not.toHaveBeenCalled();
expect(settleLiveMock).toHaveBeenCalledWith('op_idle', 'error');
@@ -1400,10 +1362,10 @@ describe('AbandonOperationService', () => {
),
});
- await new AbandonOperationService(buildDb(), {
- coordinator: coord as any,
- snapshotStore: buildPartiallessStore() as any,
- }).finalizeAbandoned('op_parked_child', 'inactivity_watchdog');
+ await new AbandonOperationService(
+ buildDb(),
+ abandonDeps(coord as any, buildPartiallessStore() as any),
+ ).finalizeAbandoned('op_parked_child', 'inactivity_watchdog');
expect(dispatchHooksMock).not.toHaveBeenCalled();
expect(settleLiveMock).toHaveBeenCalledWith('op_parked_child', 'error');
@@ -1423,10 +1385,10 @@ describe('AbandonOperationService', () => {
),
});
- const result = await new AbandonOperationService(buildDb(), {
- coordinator: coord as any,
- snapshotStore: buildPartiallessStore() as any,
- }).finalizeAbandoned('op_no_placeholder', 'stale_lease');
+ const result = await new AbandonOperationService(
+ buildDb(),
+ abandonDeps(coord as any, buildPartiallessStore() as any),
+ ).finalizeAbandoned('op_no_placeholder', 'stale_lease');
// Anchored to the tail, but written as a NEW assistant row: the tail is
// either the user's own turn — whose renderer never passes `error` to
@@ -1479,10 +1441,10 @@ describe('AbandonOperationService', () => {
loadAgentState: vi.fn().mockResolvedValue(stateWith()),
});
- await new AbandonOperationService(buildDb(), {
- coordinator: coord as any,
- snapshotStore: buildPartiallessStore() as any,
- }).finalizeAbandoned('op_x', 'stale_lease');
+ await new AbandonOperationService(
+ buildDb(),
+ abandonDeps(coord as any, buildPartiallessStore() as any),
+ ).finalizeAbandoned('op_x', 'stale_lease');
expect(latestSpineMessageIdMock).not.toHaveBeenCalled();
expect(messageCreateMock).not.toHaveBeenCalled();
@@ -1505,10 +1467,10 @@ describe('AbandonOperationService', () => {
),
});
- await new AbandonOperationService(buildDb(), {
- coordinator: coord as any,
- snapshotStore: buildPartiallessStore() as any,
- }).finalizeAbandoned('op_thread', 'stale_lease');
+ await new AbandonOperationService(
+ buildDb(),
+ abandonDeps(coord as any, buildPartiallessStore() as any),
+ ).finalizeAbandoned('op_thread', 'stale_lease');
expect(latestSpineMessageIdMock).toHaveBeenCalledWith({
threadId: 'thr_x',
@@ -1523,10 +1485,7 @@ describe('AbandonOperationService', () => {
const store = buildStore();
store.loadPartial.mockResolvedValue(null);
- const svc = new AbandonOperationService({} as any, {
- coordinator: coord as any,
- snapshotStore: store as any,
- });
+ const svc = new AbandonOperationService({} as any, abandonDeps(coord as any, store as any));
const result = await svc.finalizeAbandoned('op_x', 'reason');
diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
index 8a5c27605ff..3ab64fb2d48 100644
--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
@@ -13,6 +13,27 @@ import { AgentRuntimeService } from '../AgentRuntimeService';
import { CriticalAgentInterventionPersistenceError } from '../CompletionLifecycle';
import { hookDispatcher } from '../hooks';
+const runningOperationState = (lastModified: string) => ({
+ status: 'running',
+ stepCount: 5,
+ lastModified,
+ metadata: {},
+});
+
+const testRuntimeState = () => ({
+ metadata: {
+ agentConfig: {},
+ },
+ modelRuntimeConfig: { model: 'gpt-test', provider: 'lobehub' },
+ origin: {
+ userId: 'user-1',
+ },
+});
+
+const queueOptions = (scheduleMessage: ReturnType<typeof vi.fn>) => ({
+ queueService: { getImpl: () => ({}), scheduleMessage } as any,
+});
+
// Mock all heavy dependencies to isolate executeStep logic
vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'http://localhost:3010' } }));
vi.mock('@/database/models/message', () => ({
@@ -107,9 +128,7 @@ describe('AgentRuntimeService intervention continuation dispatch recovery', () =
'backfills durable preparation and a stable queue ACK from %s state',
async (status) => {
const scheduleMessage = vi.fn().mockResolvedValue('queue-message');
- const service = new AgentRuntimeService({} as any, 'user-1', {
- queueService: { getImpl: () => ({}), scheduleMessage } as any,
- });
+ const service = new AgentRuntimeService({} as any, 'user-1', queueOptions(scheduleMessage));
const coordinator = (service as any).coordinator;
coordinator.loadAgentState = vi.fn().mockResolvedValue(readyState(status));
const operationModel = (service as any).agentOperationModel;
@@ -145,9 +164,7 @@ describe('AgentRuntimeService intervention continuation dispatch recovery', () =
it('does not enqueue again when the exact durable queue ACK already exists', async () => {
const scheduleMessage = vi.fn();
- const service = new AgentRuntimeService({} as any, 'user-1', {
- queueService: { getImpl: () => ({}), scheduleMessage } as any,
- });
+ const service = new AgentRuntimeService({} as any, 'user-1', queueOptions(scheduleMessage));
const coordinator = (service as any).coordinator;
coordinator.loadAgentState = vi.fn().mockResolvedValue(readyState('running'));
const operationModel = (service as any).agentOperationModel;
@@ -175,9 +192,7 @@ describe('AgentRuntimeService intervention continuation dispatch recovery', () =
it('fails closed on a conflicting durable preparation marker', async () => {
const scheduleMessage = vi.fn();
- const service = new AgentRuntimeService({} as any, 'user-1', {
- queueService: { getImpl: () => ({}), scheduleMessage } as any,
- });
+ const service = new AgentRuntimeService({} as any, 'user-1', queueOptions(scheduleMessage));
const coordinator = (service as any).coordinator;
coordinator.loadAgentState = vi.fn().mockResolvedValue(readyState());
const operationModel = (service as any).agentOperationModel;
@@ -323,15 +338,7 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>
});
await (service as any).createAgentRuntime({
- agentState: {
- metadata: {
- agentConfig: {},
- },
- modelRuntimeConfig: { model: 'gpt-test', provider: 'lobehub' },
- origin: {
- userId: 'user-1',
- },
- },
+ agentState: testRuntimeState(),
operationId: 'op-workspace',
stepIndex: 0,
});
@@ -373,15 +380,7 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>
});
await (service as any).createAgentRuntime({
- agentState: {
- metadata: {
- agentConfig: {},
- },
- modelRuntimeConfig: { model: 'gpt-test', provider: 'lobehub' },
- origin: {
- userId: 'user-1',
- },
- },
+ agentState: testRuntimeState(),
operationId: 'op-custom-agent',
stepIndex: 0,
});
@@ -406,15 +405,7 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>
});
await (service as any).createAgentRuntime({
- agentState: {
- metadata: {
- agentConfig: {},
- },
- modelRuntimeConfig: { model: 'gpt-test', provider: 'lobehub' },
- origin: {
- userId: 'user-1',
- },
- },
+ agentState: testRuntimeState(),
operationId: 'op-graph-agent',
stepIndex: 0,
});
@@ -432,15 +423,7 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>
});
await (service as any).createAgentRuntime({
- agentState: {
- metadata: {
- agentConfig: {},
- },
- modelRuntimeConfig: { model: 'gpt-test', provider: 'lobehub' },
- origin: {
- userId: 'user-1',
- },
- },
+ agentState: testRuntimeState(),
operationId: 'op-general-agent',
stepIndex: 0,
});
@@ -523,12 +506,9 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>
const service = createService();
const coordinator = (service as any).coordinator;
- coordinator.loadAgentState = vi.fn().mockResolvedValue({
- status: 'running',
- stepCount: 5,
- lastModified: new Date().toISOString(),
- metadata: {},
- });
+ coordinator.loadAgentState = vi
+ .fn()
+ .mockResolvedValue(runningOperationState(new Date().toISOString()));
// The step will attempt to proceed (and fail due to mocked deps),
// but the key assertion is that it does NOT take the early-exit path
@@ -740,9 +720,7 @@ describe('AgentRuntimeService.executeStep - step idempotency (distributed lock)'
it('drops the buffered trace partial when it re-queues itself after losing the lock', async () => {
const scheduleMessage = vi.fn().mockResolvedValue('msg-1');
- const service = new AgentRuntimeService({} as any, 'user-1', {
- queueService: { getImpl: () => ({}), scheduleMessage } as any,
- });
+ const service = new AgentRuntimeService({} as any, 'user-1', queueOptions(scheduleMessage));
const coordinator = (service as any).coordinator;
coordinator.tryClaimStep = vi.fn().mockResolvedValue(false);
coordinator.loadAgentState = vi.fn().mockResolvedValue({ status: 'running', stepCount: 5 });
@@ -759,9 +737,7 @@ describe('AgentRuntimeService.executeStep - step idempotency (distributed lock)'
it('should re-queue the same step on its own backoff for a non-stale lock conflict', async () => {
const scheduleMessage = vi.fn().mockResolvedValue('msg-1');
- const service = new AgentRuntimeService({} as any, 'user-1', {
- queueService: { getImpl: () => ({}), scheduleMessage } as any,
- });
+ const service = new AgentRuntimeService({} as any, 'user-1', queueOptions(scheduleMessage));
const coordinator = (service as any).coordinator;
coordinator.tryClaimStep = vi.fn().mockResolvedValue(false);
coordinator.loadAgentState = vi.fn().mockResolvedValue({
@@ -790,9 +766,7 @@ describe('AgentRuntimeService.executeStep - step idempotency (distributed lock)'
it('should carry the delivery resume payload into the re-queued lock-conflict message', async () => {
const scheduleMessage = vi.fn().mockResolvedValue('msg-1');
- const service = new AgentRuntimeService({} as any, 'user-1', {
- queueService: { getImpl: () => ({}), scheduleMessage } as any,
- });
+ const service = new AgentRuntimeService({} as any, 'user-1', queueOptions(scheduleMessage));
const coordinator = (service as any).coordinator;
coordinator.tryClaimStep = vi.fn().mockResolvedValue(false);
coordinator.loadAgentState = vi.fn().mockResolvedValue({ status: 'running', stepCount: 5 });
@@ -819,9 +793,7 @@ describe('AgentRuntimeService.executeStep - step idempotency (distributed lock)'
it('should carry an async-tool resume flag into the re-queued lock-conflict message', async () => {
const scheduleMessage = vi.fn().mockResolvedValue('msg-1');
- const service = new AgentRuntimeService({} as any, 'user-1', {
- queueService: { getImpl: () => ({}), scheduleMessage } as any,
- });
+ const service = new AgentRuntimeService({} as any, 'user-1', queueOptions(scheduleMessage));
const coordinator = (service as any).coordinator;
coordinator.tryClaimStep = vi.fn().mockResolvedValue(false);
coordinator.loadAgentState = vi.fn().mockResolvedValue({ status: 'running', stepCount: 5 });
@@ -840,9 +812,7 @@ describe('AgentRuntimeService.executeStep - step idempotency (distributed lock)'
it('should back off exponentially across successive lock-conflict re-deliveries', async () => {
const scheduleMessage = vi.fn().mockResolvedValue('msg-1');
- const service = new AgentRuntimeService({} as any, 'user-1', {
- queueService: { getImpl: () => ({}), scheduleMessage } as any,
- });
+ const service = new AgentRuntimeService({} as any, 'user-1', queueOptions(scheduleMessage));
const coordinator = (service as any).coordinator;
coordinator.tryClaimStep = vi.fn().mockResolvedValue(false);
coordinator.loadAgentState = vi.fn().mockResolvedValue({ status: 'running', stepCount: 5 });
@@ -862,9 +832,7 @@ describe('AgentRuntimeService.executeStep - step idempotency (distributed lock)'
it('should fall back to a retryable response once the lock-conflict backoff is exhausted', async () => {
const scheduleMessage = vi.fn().mockResolvedValue('msg-1');
- const service = new AgentRuntimeService({} as any, 'user-1', {
- queueService: { getImpl: () => ({}), scheduleMessage } as any,
- });
+ const service = new AgentRuntimeService({} as any, 'user-1', queueOptions(scheduleMessage));
const coordinator = (service as any).coordinator;
coordinator.tryClaimStep = vi.fn().mockResolvedValue(false);
coordinator.loadAgentState = vi.fn().mockResolvedValue({ status: 'running', stepCount: 5 });
@@ -883,9 +851,7 @@ describe('AgentRuntimeService.executeStep - step idempotency (distributed lock)'
it('should stay retryable when re-queueing after a lock conflict fails', async () => {
const scheduleMessage = vi.fn().mockRejectedValue(new Error('qstash down'));
- const service = new AgentRuntimeService({} as any, 'user-1', {
- queueService: { getImpl: () => ({}), scheduleMessage } as any,
- });
+ const service = new AgentRuntimeService({} as any, 'user-1', queueOptions(scheduleMessage));
const coordinator = (service as any).coordinator;
coordinator.tryClaimStep = vi.fn().mockResolvedValue(false);
coordinator.loadAgentState = vi.fn().mockResolvedValue({ status: 'running', stepCount: 5 });
@@ -1004,12 +970,9 @@ describe('AgentRuntimeService.executeStep - step idempotency (distributed lock)'
const service = createService();
const coordinator = (service as any).coordinator;
coordinator.tryClaimStep = vi.fn().mockResolvedValue(true);
- coordinator.loadAgentState = vi.fn().mockResolvedValue({
- status: 'running',
- stepCount: 5,
- lastModified: new Date().toISOString(),
- metadata: {},
- });
+ coordinator.loadAgentState = vi
+ .fn()
+ .mockResolvedValue(runningOperationState(new Date().toISOString()));
// executeStep will hit an error internally (mocked deps are incomplete)
// but the catch block handles it and returns error state instead of throwing
@@ -1108,12 +1071,7 @@ describe('AgentRuntimeService.executeStep - Redis failure in error handler', ()
coordinator.loadAgentState = vi.fn().mockImplementation(function () {
loadCallCount++;
if (loadCallCount === 1) {
- return Promise.resolve({
- status: 'running',
- stepCount: 5,
- lastModified: new Date().toISOString(),
- metadata: {},
- });
+ return Promise.resolve(runningOperationState(new Date().toISOString()));
}
return Promise.reject(new Error('Reached the max retries per request limit (which is 3)'));
});
@@ -1166,12 +1124,7 @@ describe('AgentRuntimeService.executeStep - Redis failure in error handler', ()
coordinator.loadAgentState = vi.fn().mockImplementation(function () {
loadCallCount++;
if (loadCallCount === 1) {
- return Promise.resolve({
- status: 'running',
- stepCount: 5,
- lastModified: new Date().toISOString(),
- metadata: {},
- });
+ return Promise.resolve(runningOperationState(new Date().toISOString()));
}
return Promise.reject(new Error('Redis ECONNRESET'));
});
@@ -1222,12 +1175,7 @@ describe('AgentRuntimeService.executeStep - Redis failure in error handler', ()
coordinator.loadAgentState = vi.fn().mockImplementation(function () {
loadCallCount++;
if (loadCallCount === 1) {
- return Promise.resolve({
- status: 'running',
- stepCount: 5,
- lastModified: new Date().toISOString(),
- metadata: {},
- });
+ return Promise.resolve(runningOperationState(new Date().toISOString()));
}
return Promise.reject(new Error('Redis ECONNRESET'));
});
@@ -1269,12 +1217,7 @@ describe('AgentRuntimeService.executeStep - Redis failure in error handler', ()
coordinator.loadAgentState = vi.fn().mockImplementation(function () {
loadCallCount++;
if (loadCallCount === 1) {
- return Promise.resolve({
- status: 'running',
- stepCount: 5,
- lastModified: new Date().toISOString(),
- metadata: {},
- });
+ return Promise.resolve(runningOperationState(new Date().toISOString()));
}
return Promise.resolve(null);
});
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
index e679dccb0df..15e24e15738 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
@@ -12,6 +12,21 @@ import { enqueueAgentSignalSourceEvent } from '@/server/services/agentSignal';
import { AiAgentService } from '../index';
+const runtimeAgentConfig = (chatConfig: Record<string, unknown>, id: string, slug: string) => ({
+ chatConfig,
+ id,
+ model: 'gpt-4',
+ plugins: [],
+ provider: 'openai',
+ slug,
+ systemRole: '',
+});
+
+const inboxRunInput = () => ({
+ agentId: 'agent-inbox',
+ prompt: 'Hello',
+});
+
const {
mockCreateOperation,
mockGetAgentConfig,
@@ -440,10 +455,7 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {
systemRole: '', // empty in DB
});
- await service.execAgent({
- agentId: 'agent-inbox',
- prompt: 'Hello',
- });
+ await service.execAgent(inboxRunInput());
// Verify createOperation was called with agentConfig containing the runtime systemRole
expect(mockCreateOperation).toHaveBeenCalledTimes(1);
@@ -496,10 +508,7 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {
systemRole: customSystemRole, // user has customized
});
- await service.execAgent({
- agentId: 'agent-inbox',
- prompt: 'Hello',
- });
+ await service.execAgent(inboxRunInput());
const callArgs = mockCreateOperation.mock.calls[0][0];
expect(callArgs.agentConfig.systemRole).toBe(customSystemRole);
@@ -579,20 +588,9 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {
});
it('should inject self-feedback intent tool for Lobe AI when user gate is enabled', async () => {
- mockGetAgentConfig.mockResolvedValue({
- chatConfig: {},
- id: 'agent-inbox',
- model: 'gpt-4',
- plugins: [],
- provider: 'openai',
- slug: 'inbox',
- systemRole: '',
- });
+ mockGetAgentConfig.mockResolvedValue(runtimeAgentConfig({}, 'agent-inbox', 'inbox'));
- await service.execAgent({
- agentId: 'agent-inbox',
- prompt: 'Hello',
- });
+ await service.execAgent(inboxRunInput());
const callArgs = mockCreateOperation.mock.calls[0][0];
expect(callArgs.toolSet.enabledToolIds).toContain(SELF_FEEDBACK_INTENT_IDENTIFIER);
@@ -606,15 +604,7 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {
*/
it('decides the self-feedback intent tool from the preference the run already loaded', async () => {
mockGetUserPreference.mockResolvedValue({ lab: { enableSelfLearning: true } });
- mockGetAgentConfig.mockResolvedValue({
- chatConfig: {},
- id: 'agent-inbox',
- model: 'gpt-4',
- plugins: [],
- provider: 'openai',
- slug: 'inbox',
- systemRole: '',
- });
+ mockGetAgentConfig.mockResolvedValue(runtimeAgentConfig({}, 'agent-inbox', 'inbox'));
await service.execAgent({ agentId: 'agent-inbox', prompt: 'Hello' });
@@ -648,15 +638,9 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {
it('should not inject self-feedback intent tool for any agent when Labs Self-evolving is off', async () => {
mockIsAgentSignalEnabledForUser.mockResolvedValue(false);
- mockGetAgentConfig.mockResolvedValue({
- chatConfig: { selfIteration: { enabled: true } },
- id: 'agent-custom',
- model: 'gpt-4',
- plugins: [],
- provider: 'openai',
- slug: 'custom-agent',
- systemRole: '',
- });
+ mockGetAgentConfig.mockResolvedValue(
+ runtimeAgentConfig({ selfIteration: { enabled: true } }, 'agent-custom', 'custom-agent'),
+ );
await service.execAgent({ agentId: 'agent-custom', prompt: 'Hello' });
@@ -678,10 +662,7 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {
systemRole: '',
});
- await service.execAgent({
- agentId: 'agent-inbox',
- prompt: 'Hello',
- });
+ await service.execAgent(inboxRunInput());
const callArgs = mockCreateOperation.mock.calls[0][0];
expect(callArgs.toolSet.enabledToolIds).toContain(SELF_FEEDBACK_INTENT_IDENTIFIER);
@@ -699,10 +680,7 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {
systemRole: '',
});
- await service.execAgent({
- agentId: 'agent-inbox',
- prompt: 'Hello',
- });
+ await service.execAgent(inboxRunInput());
const callArgs = mockCreateOperation.mock.calls[0][0];
expect(callArgs.toolSet.enabledToolIds).toContain(SELF_FEEDBACK_INTENT_IDENTIFIER);
@@ -710,15 +688,9 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {
});
it('should inject self-feedback intent tool for custom agents with agent self-iteration', async () => {
- mockGetAgentConfig.mockResolvedValue({
- chatConfig: { selfIteration: { enabled: true } },
- id: 'agent-custom',
- model: 'gpt-4',
- plugins: [],
- provider: 'openai',
- slug: 'custom-agent',
- systemRole: '',
- });
+ mockGetAgentConfig.mockResolvedValue(
+ runtimeAgentConfig({ selfIteration: { enabled: true } }, 'agent-custom', 'custom-agent'),
+ );
await service.execAgent({
agentId: 'agent-custom',
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts
index e353cf46a9d..750a79b71cc 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts
@@ -3,6 +3,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AiAgentService } from '../index';
+const sonnetModelOverrides = () => ({
+ 'agent-1': { model: 'claude-sonnet-4-6', provider: 'anthropic' },
+});
+
const {
mockIsResourceAuthorOrAdmin,
mockCreateOperation,
@@ -449,9 +453,7 @@ describe('AiAgentService.execAgent - model/provider override', () => {
visibility: 'public',
});
mockGetPreference.mockResolvedValue({
- agentModelOverrides: {
- 'agent-1': { model: 'claude-sonnet-4-6', provider: 'anthropic' },
- },
+ agentModelOverrides: sonnetModelOverrides(),
agentModeOverrides: { 'agent-1': false },
});
service = new AiAgentService(mockDb, userId, { workspaceId: 'workspace-1' });
@@ -485,9 +487,7 @@ describe('AiAgentService.execAgent - model/provider override', () => {
agentDeviceOverrides: {
'agent-1': { boundDeviceId: 'member-device', executionTarget: 'local' },
},
- agentModelOverrides: {
- 'agent-1': { model: 'claude-sonnet-4-6', provider: 'anthropic' },
- },
+ agentModelOverrides: sonnetModelOverrides(),
agentModeOverrides: { 'agent-1': false },
});
service = new AiAgentService(mockDb, userId, { workspaceId: 'workspace-1' });
@@ -515,9 +515,7 @@ describe('AiAgentService.execAgent - model/provider override', () => {
workspaceId: 'workspace-1',
});
mockGetPreference.mockResolvedValue({
- agentModelOverrides: {
- 'agent-1': { model: 'claude-sonnet-4-6', provider: 'anthropic' },
- },
+ agentModelOverrides: sonnetModelOverrides(),
agentModeOverrides: { 'agent-1': false },
});
service = new AiAgentService(mockDb, userId, { workspaceId: 'workspace-1' });
@@ -549,9 +547,7 @@ describe('AiAgentService.execAgent - model/provider override', () => {
workspaceId: 'workspace-1',
});
mockGetPreference.mockResolvedValue({
- agentModelOverrides: {
- 'agent-1': { model: 'claude-sonnet-4-6', provider: 'anthropic' },
- },
+ agentModelOverrides: sonnetModelOverrides(),
agentModeOverrides: { 'agent-1': false },
});
service = new AiAgentService(mockDb, userId, { workspaceId: 'workspace-1' });
@@ -571,9 +567,7 @@ describe('AiAgentService.execAgent - model/provider override', () => {
visibility: 'private',
});
mockGetPreference.mockResolvedValue({
- agentModelOverrides: {
- 'agent-1': { model: 'claude-sonnet-4-6', provider: 'anthropic' },
- },
+ agentModelOverrides: sonnetModelOverrides(),
});
service = new AiAgentService(mockDb, userId, { workspaceId: 'workspace-1' });
@@ -613,9 +607,7 @@ describe('AiAgentService.execAgent - model/provider override', () => {
it('uses a retained caller preference when a legacy workspace model policy is missing', async () => {
mockGetAgentConfig.mockResolvedValue({ ...defaultAgentConfig, visibility: 'public' });
mockGetPreference.mockResolvedValue({
- agentModelOverrides: {
- 'agent-1': { model: 'claude-sonnet-4-6', provider: 'anthropic' },
- },
+ agentModelOverrides: sonnetModelOverrides(),
});
service = new AiAgentService(mockDb, userId, { workspaceId: 'workspace-1' });
@@ -633,9 +625,7 @@ describe('AiAgentService.execAgent - model/provider override', () => {
visibility: 'public',
});
mockGetPreference.mockResolvedValue({
- agentModelOverrides: {
- 'agent-1': { model: 'claude-sonnet-4-6', provider: 'anthropic' },
- },
+ agentModelOverrides: sonnetModelOverrides(),
});
service = new AiAgentService(mockDb, userId, { workspaceId: 'workspace-1' });
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.resume.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.resume.test.ts
index 59ba9729ad2..9246daee083 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.resume.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.resume.test.ts
@@ -3,6 +3,22 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AiAgentService } from '../index';
+const resumeParentMessage = () => ({
+ id: 'u1',
+ role: 'user',
+ sessionId: 'session-1',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+});
+
+const resumeAgentInput = (): Parameters<AiAgentService['execAgent']>[0] => ({
+ agentId: 'agent-1',
+ appContext: { sessionId: 'session-1', threadId: 'thread-1', topicId: 'topic-1' },
+ parentMessageId: 'u1',
+ prompt: 'ignored',
+ resume: true,
+});
+
const { mockCreateOperation, mockFindById, mockMessageCreate, mockMessageQuery, mockQueryTree } =
vi.hoisted(() => ({
mockCreateOperation: vi.fn(),
@@ -290,13 +306,7 @@ describe('AiAgentService.execAgent - resume mode', () => {
// branch; feeding it back makes the model continue the old answer
// ([U1, A1] -> continue) instead of producing a fresh one ([U1] -> A2).
it('regenerate: drops the anchor user message existing answer branch from history', async () => {
- mockFindById.mockResolvedValue({
- id: 'u1',
- role: 'user',
- sessionId: 'session-1',
- threadId: 'thread-1',
- topicId: 'topic-1',
- });
+ mockFindById.mockResolvedValue(resumeParentMessage());
mockMessageQuery.mockResolvedValue([
{ content: 'prior question', id: 'prior-u', role: 'user' },
@@ -312,13 +322,7 @@ describe('AiAgentService.execAgent - resume mode', () => {
{ id: 'a1', messageGroupId: null, parentId: 'u1' },
]);
- await service.execAgent({
- agentId: 'agent-1',
- appContext: { sessionId: 'session-1', threadId: 'thread-1', topicId: 'topic-1' },
- parentMessageId: 'u1',
- prompt: 'ignored',
- resume: true,
- });
+ await service.execAgent(resumeAgentInput());
const call = mockCreateOperation.mock.calls[0][0];
expect(call.initialMessages.map((m: any) => m.id)).toEqual(['prior-u', 'prior-a', 'u1']);
@@ -327,13 +331,7 @@ describe('AiAgentService.execAgent - resume mode', () => {
// Regression: regenerating a MIDDLE turn must also drop the turns that
// continued from it (they live on the old branch), so history ends at U1.
it('regenerate: drops later turns that continued from the anchor (middle-turn regenerate)', async () => {
- mockFindById.mockResolvedValue({
- id: 'u1',
- role: 'user',
- sessionId: 'session-1',
- threadId: 'thread-1',
- topicId: 'topic-1',
- });
+ mockFindById.mockResolvedValue(resumeParentMessage());
mockMessageQuery.mockResolvedValue([
{ content: 'the question', id: 'u1', role: 'user' },
@@ -348,13 +346,7 @@ describe('AiAgentService.execAgent - resume mode', () => {
{ id: 'a2', messageGroupId: null, parentId: 'u2' },
]);
- await service.execAgent({
- agentId: 'agent-1',
- appContext: { sessionId: 'session-1', threadId: 'thread-1', topicId: 'topic-1' },
- parentMessageId: 'u1',
- prompt: 'ignored',
- resume: true,
- });
+ await service.execAgent(resumeAgentInput());
const call = mockCreateOperation.mock.calls[0][0];
expect(call.initialMessages.map((m: any) => m.id)).toEqual(['u1']);
@@ -365,13 +357,7 @@ describe('AiAgentService.execAgent - resume mode', () => {
// `parentId`. Pruning must use the raw message tree so the group (whose members
// descend from the anchor) is dropped instead of being fed back as a summary.
it('regenerate: drops a compressedGroup node whose compacted members descend from the anchor', async () => {
- mockFindById.mockResolvedValue({
- id: 'u1',
- role: 'user',
- sessionId: 'session-1',
- threadId: 'thread-1',
- topicId: 'topic-1',
- });
+ mockFindById.mockResolvedValue(resumeParentMessage());
// `query` hides the grouped messages and injects a synthetic group node
// (id = group id, role = 'compressedGroup', no parentId).
@@ -391,13 +377,7 @@ describe('AiAgentService.execAgent - resume mode', () => {
{ id: 'a2', messageGroupId: 'grp-1', parentId: 'u2' },
]);
- await service.execAgent({
- agentId: 'agent-1',
- appContext: { sessionId: 'session-1', threadId: 'thread-1', topicId: 'topic-1' },
- parentMessageId: 'u1',
- prompt: 'ignored',
- resume: true,
- });
+ await service.execAgent(resumeAgentInput());
const call = mockCreateOperation.mock.calls[0][0];
expect(call.initialMessages.map((m: any) => m.id)).toEqual(['prior-u', 'prior-a', 'u1']);
@@ -406,13 +386,7 @@ describe('AiAgentService.execAgent - resume mode', () => {
// Guard: a compression group of PRIOR turns (not descended from the anchor)
// must be kept — it is legitimate earlier context.
it('regenerate: keeps a compressedGroup node whose members precede the anchor', async () => {
- mockFindById.mockResolvedValue({
- id: 'u1',
- role: 'user',
- sessionId: 'session-1',
- threadId: 'thread-1',
- topicId: 'topic-1',
- });
+ mockFindById.mockResolvedValue(resumeParentMessage());
mockMessageQuery.mockResolvedValue([
{ content: 'summary of early turns', id: 'grp-0', role: 'compressedGroup' },
@@ -426,13 +400,7 @@ describe('AiAgentService.execAgent - resume mode', () => {
{ id: 'a1', messageGroupId: null, parentId: 'u1' },
]);
- await service.execAgent({
- agentId: 'agent-1',
- appContext: { sessionId: 'session-1', threadId: 'thread-1', topicId: 'topic-1' },
- parentMessageId: 'u1',
- prompt: 'ignored',
- resume: true,
- });
+ await service.execAgent(resumeAgentInput());
const call = mockCreateOperation.mock.calls[0][0];
expect(call.initialMessages.map((m: any) => m.id)).toEqual(['grp-0', 'u1']);
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts
index 21fcd4fcc32..b7206df5992 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts
@@ -10,6 +10,21 @@ import {
import { AiAgentService } from '../index';
+const approvedResumeInput = (): NonNullable<
+ Parameters<AiAgentService['execAgent']>[0]['resumeApproval']
+> => ({
+ decision: 'approved',
+ parentMessageId: 'tool-msg-1',
+ toolCallId: 'call_xyz',
+});
+
+const stoppedApprovalInput = (): Parameters<AiAgentService['stopPendingApproval']>[0] => ({
+ batchId: 'batch-1',
+ operationId: 'op-parked-1',
+ toolMessageIds: ['tool-msg-1', 'tool-msg-2'],
+ topicId: 'topic-1',
+});
+
const {
mockCompleteGroupActionMember,
mockLoadGroupMemberBridge,
@@ -291,11 +306,7 @@ describe('AiAgentService.execAgent - resumeApproval', () => {
it('persists intervention=approved and seeds initialContext for human_approved_tool', async () => {
await service.execAgent({
...baseParams,
- resumeApproval: {
- decision: 'approved',
- parentMessageId: 'tool-msg-1',
- toolCallId: 'call_xyz',
- },
+ resumeApproval: approvedResumeInput(),
});
expect(mockResolveHumanApproval).toHaveBeenCalledWith(
@@ -339,11 +350,7 @@ describe('AiAgentService.execAgent - resumeApproval', () => {
await service.execAgent({
...baseParams,
approvalResolutionRequestId,
- resumeApproval: {
- decision: 'approved',
- parentMessageId: 'tool-msg-1',
- toolCallId: 'call_xyz',
- },
+ resumeApproval: approvedResumeInput(),
});
expect(mockResolveHumanApproval).toHaveBeenCalledWith(
@@ -377,11 +384,7 @@ describe('AiAgentService.execAgent - resumeApproval', () => {
await service.execAgent({
...baseParams,
approvalSourceOperationId: 'op-parked',
- resumeApproval: {
- decision: 'approved',
- parentMessageId: 'tool-msg-1',
- toolCallId: 'call_xyz',
- },
+ resumeApproval: approvedResumeInput(),
});
expect(mockCreateOperation.mock.invocationCallOrder[0]).toBeLessThan(
@@ -410,11 +413,7 @@ describe('AiAgentService.execAgent - resumeApproval', () => {
...baseParams,
approvalResolutionRequestId: '018fbd8e-7baf-7c6d-8000-000000000098',
approvalSourceOperationId: 'op-parked',
- resumeApproval: {
- decision: 'approved',
- parentMessageId: 'tool-msg-1',
- toolCallId: 'call_xyz',
- },
+ resumeApproval: approvedResumeInput(),
});
expect(result.success).toBe(true);
@@ -439,11 +438,7 @@ describe('AiAgentService.execAgent - resumeApproval', () => {
const result = await service.execAgent({
...baseParams,
approvalSourceOperationId: 'op-parked',
- resumeApproval: {
- decision: 'approved',
- parentMessageId: 'tool-msg-1',
- toolCallId: 'call_xyz',
- },
+ resumeApproval: approvedResumeInput(),
});
expect(mockCreateOperation).toHaveBeenCalledTimes(1);
@@ -532,11 +527,7 @@ describe('AiAgentService.execAgent - resumeApproval', () => {
await expect(
service.execAgent({
...baseParams,
- resumeApproval: {
- decision: 'approved',
- parentMessageId: 'tool-msg-1',
- toolCallId: 'call_xyz',
- },
+ resumeApproval: approvedResumeInput(),
}),
).rejects.toThrow('history unavailable');
@@ -581,11 +572,7 @@ describe('AiAgentService.execAgent - resumeApproval', () => {
...baseParams,
approvalResolutionRequestId,
approvalSourceOperationId: 'op-parked',
- resumeApproval: {
- decision: 'approved',
- parentMessageId: 'tool-msg-1',
- toolCallId: 'call_xyz',
- },
+ resumeApproval: approvedResumeInput(),
});
expect(mockEnsureInterventionContinuationStarted).not.toHaveBeenCalled();
@@ -649,11 +636,7 @@ describe('AiAgentService.execAgent - resumeApproval', () => {
...baseParams,
approvalResolutionRequestId,
approvalSourceOperationId: 'op-parked',
- resumeApproval: {
- decision: 'approved',
- parentMessageId: 'tool-msg-1',
- toolCallId: 'call_xyz',
- },
+ resumeApproval: approvedResumeInput(),
}),
).resolves.toMatchObject({
heteroType: null,
@@ -680,11 +663,7 @@ describe('AiAgentService.execAgent - resumeApproval', () => {
...baseParams,
approvalResolutionRequestId,
approvalSourceOperationId: 'op-parked',
- resumeApproval: {
- decision: 'approved',
- parentMessageId: 'tool-msg-1',
- toolCallId: 'call_xyz',
- },
+ resumeApproval: approvedResumeInput(),
topicStartReservationId: reservationId,
});
@@ -983,11 +962,7 @@ describe('AiAgentService.execAgent - resumeApproval', () => {
await expect(
service.execAgent({
...baseParams,
- resumeApproval: {
- decision: 'approved',
- parentMessageId: 'tool-msg-1',
- toolCallId: 'call_xyz',
- },
+ resumeApproval: approvedResumeInput(),
}),
).rejects.toThrow(/role='tool'/);
});
@@ -1001,11 +976,7 @@ describe('AiAgentService.execAgent - resumeApproval', () => {
await expect(
service.execAgent({
...baseParams,
- resumeApproval: {
- decision: 'approved',
- parentMessageId: 'tool-msg-1',
- toolCallId: 'call_xyz',
- },
+ resumeApproval: approvedResumeInput(),
}),
).rejects.toThrow(/toolCallId mismatch/);
});
@@ -1016,11 +987,7 @@ describe('AiAgentService.execAgent - resumeApproval', () => {
await expect(
service.execAgent({
...baseParams,
- resumeApproval: {
- decision: 'approved',
- parentMessageId: 'tool-msg-1',
- toolCallId: 'call_xyz',
- },
+ resumeApproval: approvedResumeInput(),
}),
).rejects.toThrow(/no plugin row/);
});
@@ -1175,12 +1142,7 @@ describe('AiAgentService.stopPendingApproval', () => {
};
mockLoadGroupMemberBridge.mockResolvedValue({ agentId: 'agt-carol', bridge });
- await service.stopPendingApproval({
- batchId: 'batch-1',
- operationId: 'op-parked-1',
- toolMessageIds: ['tool-msg-1', 'tool-msg-2'],
- topicId: 'topic-1',
- });
+ await service.stopPendingApproval(stoppedApprovalInput());
expect(mockCompleteGroupActionMember).toHaveBeenCalledWith({
...bridge,
@@ -1190,23 +1152,13 @@ describe('AiAgentService.stopPendingApproval', () => {
});
it('does not touch any bridge when the stopped run is not a group member', async () => {
- await service.stopPendingApproval({
- batchId: 'batch-1',
- operationId: 'op-parked-1',
- toolMessageIds: ['tool-msg-1', 'tool-msg-2'],
- topicId: 'topic-1',
- });
+ await service.stopPendingApproval(stoppedApprovalInput());
expect(mockCompleteGroupActionMember).not.toHaveBeenCalled();
});
it('settles every pending row in place and retires the parked operation', async () => {
- const result = await service.stopPendingApproval({
- batchId: 'batch-1',
- operationId: 'op-parked-1',
- toolMessageIds: ['tool-msg-1', 'tool-msg-2'],
- topicId: 'topic-1',
- });
+ const result = await service.stopPendingApproval(stoppedApprovalInput());
// In place: the approval pause already wrote these rows. Inserting fresh
// aborted rows would duplicate every tool AND leave the originals pending,
@@ -1288,14 +1240,9 @@ describe('AiAgentService.stopPendingApproval', () => {
topicId: id === 'tool-msg-2' ? 'other-topic' : 'topic-1',
}));
- await expect(
- service.stopPendingApproval({
- batchId: 'batch-1',
- operationId: 'op-parked-1',
- toolMessageIds: ['tool-msg-1', 'tool-msg-2'],
- topicId: 'topic-1',
- }),
- ).rejects.toThrow(/topicId does not match/);
+ await expect(service.stopPendingApproval(stoppedApprovalInput())).rejects.toThrow(
+ /topicId does not match/,
+ );
// Validation runs before any write, so a refused stop cannot half-clear the
// batch and strand the rest against a run that is already gone.
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.ts
index ac2404c4c11..631c2d50210 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.ts
@@ -4,6 +4,14 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AiAgentService } from '../index';
+const blueToolResumeInput = (): NonNullable<
+ Parameters<AiAgentService['execAgent']>[0]['resumeToolResult']
+> => ({
+ content: 'blue',
+ parentMessageId: 'tool-msg-1',
+ toolCallId: 'call_ask',
+});
+
const {
mockControlToolResult,
mockCreateOperation,
@@ -556,11 +564,7 @@ describe('AiAgentService.execAgent - resumeToolResult', () => {
it('does not persist pluginState when omitted', async () => {
await service.execAgent({
...baseParams,
- resumeToolResult: {
- content: 'blue',
- parentMessageId: 'tool-msg-1',
- toolCallId: 'call_ask',
- },
+ resumeToolResult: blueToolResumeInput(),
});
expect(mockResolveHumanApproval).toHaveBeenCalledWith(
@@ -576,11 +580,7 @@ describe('AiAgentService.execAgent - resumeToolResult', () => {
await expect(
service.execAgent({
...baseParams,
- resumeToolResult: {
- content: 'blue',
- parentMessageId: 'tool-msg-1',
- toolCallId: 'call_ask',
- },
+ resumeToolResult: blueToolResumeInput(),
}),
).rejects.toThrow(/role='tool'/);
});
@@ -591,11 +591,7 @@ describe('AiAgentService.execAgent - resumeToolResult', () => {
await expect(
service.execAgent({
...baseParams,
- resumeToolResult: {
- content: 'blue',
- parentMessageId: 'tool-msg-1',
- toolCallId: 'call_ask',
- },
+ resumeToolResult: blueToolResumeInput(),
}),
).rejects.toThrow(/toolCallId mismatch/);
});
@@ -606,11 +602,7 @@ describe('AiAgentService.execAgent - resumeToolResult', () => {
await expect(
service.execAgent({
...baseParams,
- resumeToolResult: {
- content: 'blue',
- parentMessageId: 'tool-msg-1',
- toolCallId: 'call_ask',
- },
+ resumeToolResult: blueToolResumeInput(),
}),
).rejects.toThrow(/no plugin row/);
});
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.topicWorkingDirectory.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.topicWorkingDirectory.test.ts
index a0349d912be..c6e9fab28db 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.topicWorkingDirectory.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.topicWorkingDirectory.test.ts
@@ -5,6 +5,18 @@ import type * as RedisLib from '@/server/modules/Redis';
import { AiAgentService } from '../index';
+const staleWorkspaceEntry = (workspaceScannedAt: number) => ({
+ path: '/repo/default',
+ workspace: { instructions: [], skills: [] },
+ workspaceScannedAt,
+});
+
+const topicRunInput = () => ({
+ agentId: 'agent-1',
+ appContext: { topicId: 'topic-1' },
+ prompt: 'Hello',
+});
+
/**
* A device-bound run resolves its working directory server-side (for
* `{{workingDirectory}}`, the tool cwd, and the workspace scan) — but the topic
@@ -328,13 +340,7 @@ describe('AiAgentService.execAgent - topic working directory binding', () => {
mockFindByDeviceId.mockResolvedValue({
defaultCwd: '/repo/default',
deviceId: DEVICE_ID,
- workingDirs: [
- {
- path: '/repo/default',
- workspace: { instructions: [], skills: [] },
- workspaceScannedAt: Date.now() - 2 * 60 * 60 * 1000,
- },
- ],
+ workingDirs: [staleWorkspaceEntry(Date.now() - 2 * 60 * 60 * 1000)],
});
mockGetAgentConfig.mockResolvedValue(
createAgentConfig({ boundDeviceId: DEVICE_ID, executionTarget: 'device' }),
@@ -356,13 +362,7 @@ describe('AiAgentService.execAgent - topic working directory binding', () => {
mockFindByDeviceId.mockResolvedValue({
defaultCwd: '/repo/default',
deviceId: DEVICE_ID,
- workingDirs: [
- {
- path: '/repo/default',
- workspace: { instructions: [], skills: [] },
- workspaceScannedAt: Date.now() - 2 * 60 * 60 * 1000,
- },
- ],
+ workingDirs: [staleWorkspaceEntry(Date.now() - 2 * 60 * 60 * 1000)],
});
mockGetAgentConfig.mockResolvedValue(
createAgentConfig({ boundDeviceId: DEVICE_ID, executionTarget: 'device' }),
@@ -381,11 +381,7 @@ describe('AiAgentService.execAgent - topic working directory binding', () => {
});
it('merges a directory the user added mid-scan instead of overwriting it', async () => {
- const staleEntry = {
- path: '/repo/default',
- workspace: { instructions: [], skills: [] },
- workspaceScannedAt: Date.now() - 2 * 60 * 60 * 1000,
- };
+ const staleEntry = staleWorkspaceEntry(Date.now() - 2 * 60 * 60 * 1000);
// The scan takes up to 30s; land a concurrent directory edit while it is
// in flight so the write-back has a newer list to merge into.
@@ -422,11 +418,7 @@ describe('AiAgentService.execAgent - topic working directory binding', () => {
});
it('does not resurrect a directory the user removed mid-scan', async () => {
- const staleEntry = {
- path: '/repo/default',
- workspace: { instructions: [], skills: [] },
- workspaceScannedAt: Date.now() - 2 * 60 * 60 * 1000,
- };
+ const staleEntry = staleWorkspaceEntry(Date.now() - 2 * 60 * 60 * 1000);
let scanStarted = false;
mockInitWorkspace.mockImplementation(async () => {
@@ -457,13 +449,7 @@ describe('AiAgentService.execAgent - topic working directory binding', () => {
mockFindByDeviceId.mockResolvedValue({
defaultCwd: '/repo/default',
deviceId: DEVICE_ID,
- workingDirs: [
- {
- path: '/repo/default',
- workspace: { instructions: [], skills: [] },
- workspaceScannedAt: Date.now() - 2 * 60 * 60 * 1000,
- },
- ],
+ workingDirs: [staleWorkspaceEntry(Date.now() - 2 * 60 * 60 * 1000)],
});
mockGetAgentConfig.mockResolvedValue(
createAgentConfig({ boundDeviceId: DEVICE_ID, executionTarget: 'device' }),
@@ -503,11 +489,7 @@ describe('AiAgentService.execAgent - topic working directory binding', () => {
}),
);
- await service.execAgent({
- agentId: 'agent-1',
- appContext: { topicId: 'topic-1' },
- prompt: 'Hello',
- });
+ await service.execAgent(topicRunInput());
expect(mockUpdateTopicMetadata).not.toHaveBeenCalledWith(
'topic-1',
@@ -558,11 +540,7 @@ describe('AiAgentService.execAgent - topic working directory binding', () => {
}),
);
- await service.execAgent({
- agentId: 'agent-1',
- appContext: { topicId: 'topic-1' },
- prompt: 'Hello',
- });
+ await service.execAgent(topicRunInput());
expect(mockUpdateTopicMetadata).toHaveBeenCalledWith('topic-1', {
workingDirectory: '/repo/two',
@@ -582,11 +560,7 @@ describe('AiAgentService.execAgent - topic working directory binding', () => {
createAgentConfig({ boundDeviceId: DEVICE_ID, executionTarget: 'device' }),
);
- await service.execAgent({
- agentId: 'agent-1',
- appContext: { topicId: 'topic-1' },
- prompt: 'Hello',
- });
+ await service.execAgent(topicRunInput());
expect(mockUpdateTopicMetadata).toHaveBeenCalledWith('topic-1', { boundDeviceId: DEVICE_ID });
});
@@ -597,11 +571,7 @@ describe('AiAgentService.execAgent - topic working directory binding', () => {
createAgentConfig({ boundDeviceId: DEVICE_ID, executionTarget: 'device' }),
);
- await service.execAgent({
- agentId: 'agent-1',
- appContext: { topicId: 'topic-1' },
- prompt: 'Hello',
- });
+ await service.execAgent(topicRunInput());
expect(mockUpdateTopicMetadata).toHaveBeenCalledWith('topic-1', { boundDeviceId: DEVICE_ID });
});
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.discoverableConnectors.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.discoverableConnectors.test.ts
index d5b80514a90..f31150c3894 100644
--- a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.discoverableConnectors.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.discoverableConnectors.test.ts
@@ -6,6 +6,14 @@ import { scheduleStaleConnectorToolsRefresh } from '@/server/services/connector/
import { discoverTools } from '../toolDiscovery';
+const explicitConnectorInput = (toolId: string) => ({
+ context: { isExplicitActivation: true },
+ model: 'test-model',
+ provider: 'test-provider',
+ skipDefaultTools: true,
+ toolIds: [toolId],
+});
+
vi.mock('@/business/client/model-bank/loadModels', () => ({
loadModels: vi.fn().mockResolvedValue([]),
}));
@@ -163,13 +171,7 @@ describe('discoverTools — unpinned custom MCP connectors', () => {
const result = await run({ ...options, sourceType: 'marketplace' });
expect(result.toolManifestMap[YINGMI]).toBeUndefined();
expect(result.toolsResult.enabledToolIds).not.toContain(YINGMI);
- const restored = result.toolsEngine!.generateToolsDetailed({
- context: { isExplicitActivation: true },
- model: 'test-model',
- provider: 'test-provider',
- skipDefaultTools: true,
- toolIds: [YINGMI],
- });
+ const restored = result.toolsEngine!.generateToolsDetailed(explicitConnectorInput(YINGMI));
expect(restored.enabledToolIds).not.toContain(YINGMI);
},
);
@@ -196,26 +198,14 @@ describe('discoverTools — unpinned custom MCP connectors', () => {
sourceType: 'marketplace',
});
expect(result.toolManifestMap[YINGMI]).toBeDefined();
- const activated = result.toolsEngine!.generateToolsDetailed({
- context: { isExplicitActivation: true },
- model: 'test-model',
- provider: 'test-provider',
- skipDefaultTools: true,
- toolIds: [YINGMI],
- });
+ const activated = result.toolsEngine!.generateToolsDetailed(explicitConnectorInput(YINGMI));
expect(activated.enabledToolIds).toContain(YINGMI);
});
it('keeps a completed marketplace install discoverable and explicitly activatable', async () => {
const result = await run({ installed: true, sourceType: 'marketplace' });
expect(result.toolManifestMap[YINGMI]).toBeDefined();
- const activated = result.toolsEngine!.generateToolsDetailed({
- context: { isExplicitActivation: true },
- model: 'test-model',
- provider: 'test-provider',
- skipDefaultTools: true,
- toolIds: [YINGMI],
- });
+ const activated = result.toolsEngine!.generateToolsDetailed(explicitConnectorInput(YINGMI));
expect(activated.enabledToolIds).toContain(YINGMI);
});
@@ -238,13 +228,7 @@ describe('discoverTools — unpinned custom MCP connectors', () => {
// The cross-turn restore in `operationPrep` re-checks historical
// activations through the engine with explicit activation.
- const restored = result.toolsEngine!.generateToolsDetailed({
- context: { isExplicitActivation: true },
- model: 'test-model',
- provider: 'test-provider',
- skipDefaultTools: true,
- toolIds: [YINGMI],
- });
+ const restored = result.toolsEngine!.generateToolsDetailed(explicitConnectorInput(YINGMI));
expect(restored.enabledToolIds).toContain(YINGMI);
// …and the wire name the model copies from history resolves again.