🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { AgentRuntimeHost } from '../transport';
import type { AgentInstruction, AgentState } from '../types';
import { finish } from './finish';
import { resolveAbortedTools, resolveBlockedTools } from './resolveTools';
const createBlockedInstruction = (
toolCall: ReturnType<typeof createToolCall>,
): Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> => ({
payload: {
parentMessageId: 'assistant-msg-1',
toolsCalling: [toolCall],
},
type: 'resolve_blocked_tools',
});
const createState = (overrides?: Partial<AgentState>): AgentState => ({
cost: {
calculatedAt: '2026-07-07T00:00:00.000Z',
currency: 'USD',
llm: { byModel: [], currency: 'USD', total: 0 },
tools: { byTool: [], currency: 'USD', total: 0 },
total: 0,
},
createdAt: '2026-07-07T00:00:00.000Z',
lastModified: '2026-07-07T00:00:00.000Z',
maxSteps: 100,
messages: [],
origin: {
agentId: 'agent-1',
threadId: 'thread-1',
topicId: 'topic-1',
},
operationId: 'op-1',
status: 'running',
stepCount: 0,
toolManifestMap: {},
usage: {
humanInteraction: {
approvalRequests: 0,
promptRequests: 0,
selectRequests: 0,
totalWaitingTimeMs: 0,
},
llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },
tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },
},
...overrides,
});
const createToolCall = (id = 'tool-call-1') => ({
apiName: 'search',
arguments: '{"query":"test"}',
id,
identifier: 'web-search',
type: 'default' as const,
});
describe('resolveTools executors', () => {
let createToolMessage: ReturnType<typeof vi.fn>;
let findToolMessageIdByToolCallId: ReturnType<typeof vi.fn>;
/** `tool_call_id → row id` the store already holds. */
let toolRows: Map<string, { id: string; parentId: string }>;
let publishError: ReturnType<typeof vi.fn>;
let publishEvent: ReturnType<typeof vi.fn>;
let host: AgentRuntimeHost;
beforeEach(() => {
toolRows = new Map();
createToolMessage = vi.fn().mockImplementation(async (params: any) => {
if (params?.tool_call_id) {
toolRows.set(params.tool_call_id, { id: 'tool-msg-1', parentId: params.parentId });
}
return { id: 'tool-msg-1' };
});
findToolMessageIdByToolCallId = vi
.fn()
.mockImplementation(async (toolCallId: string, parentMessageId: string) => {
const row = toolRows.get(toolCallId);
return row && row.parentId === parentMessageId ? row.id : undefined;
});
publishError = vi.fn().mockResolvedValue(undefined);
publishEvent = vi.fn().mockResolvedValue(undefined);
host = {
operation: {
operationId: 'op-1',
stepIndex: 2,
},
transports: {
messages: {
createAssistantMessage: vi.fn(),
createToolMessage,
deleteMessage: vi.fn(),
findById: vi.fn(),
findToolMessageIdByToolCallId,
query: vi.fn(),
update: vi.fn(),
updatePluginState: vi.fn(),
updateToolMessage: vi.fn(),
},
stream: {
publishChunk: vi.fn(),
publishError,
publishEvent,
},
},
} as unknown as AgentRuntimeHost;
});
it.each([undefined, false, true])(
'includes finish state only when the run opts in (%s)',
async (includeFinalState) => {
const state = createState({ host: { includeFinalState } });
const result = await finish(host)({ type: 'finish', reason: 'completed' }, state);
const event = publishEvent.mock.calls[0][0];
expect(event.data.finalState !== undefined).toBe(includeFinalState === true);
if (includeFinalState) expect(event.data.finalState.status).toBe('done');
expect(result.newState.status).toBe('done');
expect(result.events).toContainEqual(
expect.objectContaining({ type: 'done', finalState: result.newState }),
);
},
);
it('persists blocked tools as rejected tool messages and continues', async () => {
const instruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> =
createBlockedInstruction(createToolCall());
const result = await resolveBlockedTools(host)(instruction, createState());
expect(createToolMessage).toHaveBeenCalledWith(
expect.objectContaining({
content: 'Blocked by security/privacy.',
parentId: 'assistant-msg-1',
pluginError: 'blocked_by_security_privacy',
pluginIntervention: {
rejectedReason: 'blocked_by_security_privacy',
status: 'rejected',
},
role: 'tool',
tool_call_id: 'tool-call-1',
}),
);
expect(publishEvent).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
isSuccess: false,
phase: 'tool_execution',
}),
stepIndex: 2,
type: 'tool_end',
}),
);
expect(result.events).toContainEqual(
expect.objectContaining({ id: 'tool-call-1', type: 'tool_result' }),
);
expect(result.nextContext?.phase).toBe('tools_batch_result');
expect(result.nextContext?.payload).toMatchObject({
parentMessageId: 'tool-msg-1',
toolCount: 1,
});
expect(result.newState.messages).toContainEqual(
expect.objectContaining({ id: 'tool-msg-1', role: 'tool' }),
);
});
it('writes the per-call blocked content when one is given for the call id', async () => {
const instruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> = {
payload: {
blockedContent: 'generic rejection',
blockedContentByCallId: { 'tool-call-1': 'rejection naming tool-call-1' },
blockedReason: 'tool_arguments_empty',
parentMessageId: 'assistant-msg-1',
toolsCalling: [createToolCall()],
},
type: 'resolve_blocked_tools',
};
const result = await resolveBlockedTools(host)(instruction, createState());
expect(host.transports.messages.createToolMessage).toHaveBeenCalledWith(
expect.objectContaining({ content: 'rejection naming tool-call-1' }),
);
expect(result.newState.messages).toContainEqual(
expect.objectContaining({ content: 'rejection naming tool-call-1', role: 'tool' }),
);
});
// Without this write the rejection is lost: state messages are rebuilt from
// the DB every step, and conversation-flow only collects a tool row whose
// parent assistant lists the matching call.
it('advertises unresolvable calls on the parent assistant and counts the round', async () => {
const instruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> = {
payload: {
blockedContent: 'Tool call rejected: no available tool is named searchh.',
blockedReason: 'tool_name_unresolved',
parentMessageId: 'assistant-msg-1',
toolsCalling: [createToolCall()],
unresolvedToolNames: true,
},
type: 'resolve_blocked_tools',
};
const result = await resolveBlockedTools(host)(instruction, createState());
expect(host.transports.messages.update).toHaveBeenCalledWith('assistant-msg-1', {
tools: [createToolCall()],
});
expect(result.newState.unresolvedToolFeedbackRounds).toBe(1);
});
it('accumulates unresolvable rounds across steps of one operation', async () => {
const instruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> = {
payload: {
parentMessageId: 'assistant-msg-1',
toolsCalling: [createToolCall()],
unresolvedToolNames: true,
},
type: 'resolve_blocked_tools',
};
const result = await resolveBlockedTools(host)(
instruction,
createState({ unresolvedToolFeedbackRounds: 1 }),
);
expect(result.newState.unresolvedToolFeedbackRounds).toBe(2);
});
describe('stop note on the parent reply', () => {
const stopInstruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> = {
payload: {
parentMessageId: 'assistant-msg-1',
parentNote: 'Stopped after 3 consecutive replies called tools that do not exist.',
toolsCalling: [createToolCall()],
unresolvedToolNames: true,
},
type: 'resolve_blocked_tools',
};
it('appends the note to the text the reply already has', async () => {
host.transports.messages.findById = vi
.fn()
.mockResolvedValue({ content: 'Running the script now.', id: 'assistant-msg-1' });
await resolveBlockedTools(host)(stopInstruction, createState());
expect(host.transports.messages.update).toHaveBeenCalledWith('assistant-msg-1', {
content:
'Running the script now.\n\nStopped after 3 consecutive replies called tools that do not exist.',
tools: [createToolCall()],
});
});
// The completion lifecycle reads the final assistant text from the runtime
// state and only recovers the row when that text is empty, so a reply that
// already carried text must carry the note in state as well.
it('mirrors the note into the runtime state reply', async () => {
host.transports.messages.findById = vi
.fn()
.mockResolvedValue({ content: 'Running the script now.', id: 'assistant-msg-1' });
const result = await resolveBlockedTools(host)(
stopInstruction,
createState({
messages: [
{ content: 'Running the script now.', id: 'assistant-msg-1', role: 'assistant' },
],
}),
);
const reply = result.newState.messages.find((message) => message.id === 'assistant-msg-1');
expect(reply?.content).toBe(
'Running the script now.\n\nStopped after 3 consecutive replies called tools that do not exist.',
);
});
// Image replies store serialized content parts; overwriting them with
// text would drop the images.
it('leaves a multimodal reply content alone', async () => {
host.transports.messages.findById = vi.fn().mockResolvedValue({
content: '[{"type":"image"}]',
id: 'assistant-msg-1',
metadata: { isMultimodal: true },
});
await resolveBlockedTools(host)(stopInstruction, createState());
expect(host.transports.messages.update).toHaveBeenCalledWith('assistant-msg-1', {
tools: [createToolCall()],
});
});
});
it('leaves the parent untouched for ordinary blocked tools', async () => {
const instruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> =
createBlockedInstruction(createToolCall());
const result = await resolveBlockedTools(host)(instruction, createState());
expect(host.transports.messages.update).not.toHaveBeenCalled();
expect(result.newState.unresolvedToolFeedbackRounds).toBeUndefined();
});
it('fails loudly when the parent assistant cannot be updated', async () => {
const failure = new Error('db down');
host.transports.messages.update = vi.fn().mockRejectedValue(failure);
const instruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> = {
payload: {
parentMessageId: 'assistant-msg-1',
toolsCalling: [createToolCall()],
unresolvedToolNames: true,
},
type: 'resolve_blocked_tools',
};
await expect(resolveBlockedTools(host)(instruction, createState())).rejects.toThrow('db down');
expect(createToolMessage).not.toHaveBeenCalled();
});
it('persists a caller-provided blocked reason and content', async () => {
const instruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> = {
payload: {
blockedContent: 'Tool is outside the current execution scope.',
blockedReason: 'tool_not_allowed',
parentMessageId: 'assistant-msg-1',
toolsCalling: [createToolCall()],
},
type: 'resolve_blocked_tools',
};
const result = await resolveBlockedTools(host)(instruction, createState());
expect(createToolMessage).toHaveBeenCalledWith(
expect.objectContaining({
content: 'Tool is outside the current execution scope.',
pluginError: 'tool_not_allowed',
pluginIntervention: {
rejectedReason: 'tool_not_allowed',
status: 'rejected',
},
pluginState: { reason: 'tool_not_allowed', type: 'blocked' },
}),
);
expect(result.events).toContainEqual({
id: 'tool-call-1',
result: {
content: 'Tool is outside the current execution scope.',
error: 'tool_not_allowed',
executionTime: 0,
state: { reason: 'tool_not_allowed', type: 'blocked' },
success: false,
},
type: 'tool_result',
});
});
it('persists aborted tools and completes the operation as user_aborted', async () => {
const instruction: Extract<AgentInstruction, { type: 'resolve_aborted_tools' }> = {
payload: {
parentMessageId: 'assistant-msg-1',
toolsCalling: [createToolCall('tool-call-1'), createToolCall('tool-call-2')],
},
type: 'resolve_aborted_tools',
};
const result = await resolveAbortedTools(host)(instruction, createState());
expect(createToolMessage).toHaveBeenCalledTimes(2);
expect(createToolMessage).toHaveBeenCalledWith(
expect.objectContaining({
content: 'Tool execution was aborted by user.',
parentId: 'assistant-msg-1',
pluginIntervention: { status: 'aborted' },
role: 'tool',
tool_call_id: 'tool-call-1',
}),
);
expect(result.newState.status).toBe('done');
expect(result.newState.messages).toHaveLength(2);
expect(result.newState.messages).toEqual([
expect.objectContaining({ id: 'tool-msg-1', tool_call_id: 'tool-call-1' }),
expect.objectContaining({ id: 'tool-msg-1', tool_call_id: 'tool-call-2' }),
]);
expect(result.events).toContainEqual(
expect.objectContaining({
reason: 'user_aborted',
reasonDetail: 'User aborted operation with pending tool calls',
type: 'done',
}),
);
expect(publishEvent).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({ phase: 'tools_aborted' }),
type: 'step_start',
}),
);
expect(publishEvent).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({ phase: 'execution_complete', reason: 'user_aborted' }),
type: 'step_complete',
}),
);
});
it('settles an already-persisted pending row in place instead of inserting a duplicate', async () => {
// Aborting a parked approval: the pause already wrote one tool row per
// pending call. Inserting fresh aborted rows here would duplicate every
// tool in the turn AND leave the originals `pending`, so the approval cards
// survive the Stop that was supposed to clear them.
const updateToolMessage = vi.fn().mockResolvedValue(undefined);
const updateToolIntervention = vi.fn().mockResolvedValue(undefined);
host.transports.messages.updateToolMessage = updateToolMessage;
host.transports.messages.updateToolIntervention = updateToolIntervention;
// A single approval resume uses the pending row itself as parentMessageId,
// while the row's real parent remains the assistant that requested it.
toolRows.set('tool-call-1', { id: 'pending-msg-1', parentId: 'assistant-msg-1' });
const instruction: Extract<AgentInstruction, { type: 'resolve_aborted_tools' }> = {
payload: {
existingToolMessageIds: { 'tool-call-1': 'pending-msg-1' },
parentMessageId: 'pending-msg-1',
toolsCalling: [createToolCall('tool-call-1'), createToolCall('tool-call-2')],
},
type: 'resolve_aborted_tools',
};
const result = await resolveAbortedTools(host)(instruction, createState());
expect(updateToolMessage).toHaveBeenCalledWith('pending-msg-1', {
content: 'Tool execution was aborted by user.',
});
expect(updateToolIntervention).toHaveBeenCalledWith('pending-msg-1', { status: 'aborted' });
expect(findToolMessageIdByToolCallId).toHaveBeenCalledTimes(1);
expect(findToolMessageIdByToolCallId).toHaveBeenCalledWith('tool-call-2', 'pending-msg-1');
// The call with no existing row still gets one created — mixed batches are
// resolved per call, not all-or-nothing.
expect(createToolMessage).toHaveBeenCalledTimes(1);
expect(createToolMessage).toHaveBeenCalledWith(
expect.objectContaining({ tool_call_id: 'tool-call-2' }),
);
expect(result.newState.messages).toEqual([
expect.objectContaining({ id: 'pending-msg-1', tool_call_id: 'tool-call-1' }),
expect.objectContaining({ id: 'tool-msg-1', tool_call_id: 'tool-call-2' }),
]);
expect(result.newState.status).toBe('done');
});
it('publishes and rethrows persist errors', async () => {
const error = new Error('database went away');
createToolMessage.mockRejectedValueOnce(error);
const instruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> =
createBlockedInstruction(createToolCall());
await expect(resolveBlockedTools(host)(instruction, createState())).rejects.toThrow(
'database went away',
);
expect(publishError).toHaveBeenCalledWith({
error,
phase: 'tool_message_persist',
stepIndex: 2,
});
});
});