Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

test(agent-tools): cover every tool execute handler and ratchet thresholds

Yudhi Armyndharisd249230d4e43
diff --git a/docs/09-testing-strategy.md b/docs/09-testing-strategy.md
index 761f73d92..16f4b93b5 100644
--- a/docs/09-testing-strategy.md
+++ b/docs/09-testing-strategy.md
@@ -184,7 +184,7 @@ authoritative gate. Current policy:
| `src/common/storage/` | 75% | 80% | 80% | 77% |
| `src/common/utils/` | 86% | 92% | 92% | 91% |
| `src/config/` | 88% | 92% | 91% | 91% |
-| `src/core/agent-tools/` | 80% | 39% | 58% | 57% |
+| `src/core/agent-tools/` | 88% | 87% | 83% | 83% |
| `src/core/hooks/` | 81% | 73% | 85% | 84% |
| `src/core/plugins/` | 72% | 74% | 81% | 80% |
| `src/database/` | 69% | 69% | 72% | 72% |
diff --git a/package.json b/package.json
index ffb6ad399..61dc2bf41 100644
--- a/package.json
+++ b/package.json
@@ -205,10 +205,10 @@
"statements": 91
},
"./src/core/agent-tools/": {
- "branches": 80,
- "functions": 39,
- "lines": 58,
- "statements": 57
+ "branches": 88,
+ "functions": 87,
+ "lines": 83,
+ "statements": 83
},
"./src/core/hooks/": {
"branches": 81,
diff --git a/src/core/agent-tools/tools/contact.tools.spec.ts b/src/core/agent-tools/tools/contact.tools.spec.ts
new file mode 100644
index 000000000..01a1c3810
--- /dev/null
+++ b/src/core/agent-tools/tools/contact.tools.spec.ts
@@ -0,0 +1,105 @@
+import { invokeTool } from '../tool-invoker';
+import { contactTools } from './contact.tools';
+import type { AnyToolDescriptor } from '../tool-descriptor';
+import type { ContactService } from '../../../modules/contact/contact.service';
+import type { AuthService } from '../../../modules/auth/auth.service';
+
+// Covers every contactTools execute() handler via the real invokeTool path (auth → zod → handler).
+// agent-tools.module.ts is pure Nest wiring, stays at 0% coverage, and is intentionally not a target.
+
+function makeAuth(): Pick<AuthService, 'validateApiKey' | 'hasPermission'> {
+ return {
+ validateApiKey: jest.fn().mockResolvedValue({ id: 'k1', allowedSessions: null }),
+ hasPermission: jest.fn().mockReturnValue(true),
+ };
+}
+
+function makeTools(svc: ContactService): Map<string, AnyToolDescriptor> {
+ return new Map(contactTools(svc).map(t => [t.name, t]));
+}
+
+async function run(tool: AnyToolDescriptor, input: unknown): Promise<unknown> {
+ return invokeTool(tool, input, 'key', makeAuth() as unknown as AuthService);
+}
+
+describe('contactTools', () => {
+ it('ContactFindAll delegates to getContacts with paging', async () => {
+ const getContacts = jest.fn().mockResolvedValue([{ id: 'c1' }]);
+ const out = await run(makeTools({ getContacts } as unknown as ContactService).get('ContactFindAll')!, {
+ sessionId: 's1',
+ limit: 10,
+ offset: 5,
+ });
+ expect(getContacts).toHaveBeenCalledWith('s1', { limit: 10, offset: 5 });
+ expect(out).toEqual([{ id: 'c1' }]);
+ });
+
+ it('ContactFindOne delegates to getContactById', async () => {
+ const getContactById = jest.fn().mockResolvedValue({ id: 'c1' });
+ const out = await run(makeTools({ getContactById } as unknown as ContactService).get('ContactFindOne')!, {
+ sessionId: 's1',
+ contactId: '[email protected]',
+ });
+ expect(getContactById).toHaveBeenCalledWith('s1', '[email protected]');
+ expect(out).toEqual({ id: 'c1' });
+ });
+
+ it('ContactCheckNumber maps a found JID to exists:true', async () => {
+ const getNumberId = jest.fn().mockResolvedValue('[email protected]');
+ const out = await run(makeTools({ getNumberId } as unknown as ContactService).get('ContactCheckNumber')!, {
+ sessionId: 's1',
+ number: '628123',
+ });
+ expect(getNumberId).toHaveBeenCalledWith('s1', '628123');
+ expect(out).toEqual({ number: '628123', exists: true, whatsappId: '[email protected]' });
+ });
+
+ it('ContactCheckNumber maps a null JID to exists:false', async () => {
+ const getNumberId = jest.fn().mockResolvedValue(null);
+ const out = await run(makeTools({ getNumberId } as unknown as ContactService).get('ContactCheckNumber')!, {
+ sessionId: 's1',
+ number: '628123',
+ });
+ expect(out).toEqual({ number: '628123', exists: false, whatsappId: null });
+ });
+
+ it('ContactResolvePhone delegates to resolveContactPhone', async () => {
+ const resolveContactPhone = jest.fn().mockResolvedValue('628123');
+ const out = await run(makeTools({ resolveContactPhone } as unknown as ContactService).get('ContactResolvePhone')!, {
+ sessionId: 's1',
+ contactId: '12345@lid',
+ });
+ expect(resolveContactPhone).toHaveBeenCalledWith('s1', '12345@lid');
+ expect(out).toEqual({ contactId: '12345@lid', phone: '628123' });
+ });
+
+ it('ContactGetProfilePicture maps the service result to a url field', async () => {
+ const getProfilePicture = jest.fn().mockResolvedValue('https://example.com/pic.jpg');
+ const out = await run(
+ makeTools({ getProfilePicture } as unknown as ContactService).get('ContactGetProfilePicture')!,
+ { sessionId: 's1', contactId: '[email protected]' },
+ );
+ expect(getProfilePicture).toHaveBeenCalledWith('s1', '[email protected]');
+ expect(out).toEqual({ url: 'https://example.com/pic.jpg' });
+ });
+
+ it('ContactBlock delegates to blockContact and reports success', async () => {
+ const blockContact = jest.fn().mockResolvedValue(undefined);
+ const out = await run(makeTools({ blockContact } as unknown as ContactService).get('ContactBlock')!, {
+ sessionId: 's1',
+ contactId: '[email protected]',
+ });
+ expect(blockContact).toHaveBeenCalledWith('s1', '[email protected]');
+ expect(out).toEqual({ success: true, message: 'Contact blocked' });
+ });
+
+ it('ContactUnblock delegates to unblockContact and reports success', async () => {
+ const unblockContact = jest.fn().mockResolvedValue(undefined);
+ const out = await run(makeTools({ unblockContact } as unknown as ContactService).get('ContactUnblock')!, {
+ sessionId: 's1',
+ contactId: '[email protected]',
+ });
+ expect(unblockContact).toHaveBeenCalledWith('s1', '[email protected]');
+ expect(out).toEqual({ success: true, message: 'Contact unblocked' });
+ });
+});
diff --git a/src/core/agent-tools/tools/group.tools.spec.ts b/src/core/agent-tools/tools/group.tools.spec.ts
index f2fb157be..2b5a72988 100644
--- a/src/core/agent-tools/tools/group.tools.spec.ts
+++ b/src/core/agent-tools/tools/group.tools.spec.ts
@@ -71,3 +71,87 @@ describe('GroupAddParticipants', () => {
expect(out).toEqual({ success: true, message: 'Participants added', results });
});
});
+
+describe('groupTools execute handlers', () => {
+ it('GroupFindAll delegates to getGroups with paging', async () => {
+ const getGroups = jest.fn().mockResolvedValue([{ id: 'g1' }]);
+ const tool = groupTools({ getGroups } as unknown as GroupService).find(t => t.name === 'GroupFindAll')!;
+ const out = await invokeTool(
+ tool,
+ { sessionId: 's1', limit: 10, offset: 5 },
+ 'key',
+ makeAuth() as unknown as AuthService,
+ );
+ expect(getGroups).toHaveBeenCalledWith('s1', { limit: 10, offset: 5 });
+ expect(out).toEqual([{ id: 'g1' }]);
+ });
+
+ it('GroupFindOne delegates to getGroupInfo', async () => {
+ const getGroupInfo = jest.fn().mockResolvedValue({ id: 'g1' });
+ const tool = groupTools({ getGroupInfo } as unknown as GroupService).find(t => t.name === 'GroupFindOne')!;
+ const out = await invokeTool(
+ tool,
+ { sessionId: 's1', groupId: '[email protected]' },
+ 'key',
+ makeAuth() as unknown as AuthService,
+ );
+ expect(getGroupInfo).toHaveBeenCalledWith('s1', '[email protected]');
+ expect(out).toEqual({ id: 'g1' });
+ });
+
+ it('GroupGetInviteCode maps the code to code + link', async () => {
+ const getGroupInviteCode = jest.fn().mockResolvedValue('abc123');
+ const tool = groupTools({ getGroupInviteCode } as unknown as GroupService).find(
+ t => t.name === 'GroupGetInviteCode',
+ )!;
+ const out = await invokeTool(
+ tool,
+ { sessionId: 's1', groupId: '[email protected]' },
+ 'key',
+ makeAuth() as unknown as AuthService,
+ );
+ expect(getGroupInviteCode).toHaveBeenCalledWith('s1', '[email protected]');
+ expect(out).toEqual({ inviteCode: 'abc123', inviteLink: 'https://chat.whatsapp.com/abc123' });
+ });
+
+ it('GroupCreate delegates to createGroup', async () => {
+ const createGroup = jest.fn().mockResolvedValue({ id: 'g1' });
+ const tool = groupTools({ createGroup } as unknown as GroupService).find(t => t.name === 'GroupCreate')!;
+ const out = await invokeTool(
+ tool,
+ { sessionId: 's1', name: 'New group', participants: ['[email protected]'] },
+ 'key',
+ makeAuth() as unknown as AuthService,
+ );
+ expect(createGroup).toHaveBeenCalledWith('s1', 'New group', ['[email protected]']);
+ expect(out).toEqual({ id: 'g1' });
+ });
+
+ it('GroupSetSubject delegates to setGroupSubject and reports success', async () => {
+ const setGroupSubject = jest.fn().mockResolvedValue(undefined);
+ const tool = groupTools({ setGroupSubject } as unknown as GroupService).find(t => t.name === 'GroupSetSubject')!;
+ const out = await invokeTool(
+ tool,
+ { sessionId: 's1', groupId: '[email protected]', subject: 'Renamed' },
+ 'key',
+ makeAuth() as unknown as AuthService,
+ );
+ expect(setGroupSubject).toHaveBeenCalledWith('s1', '[email protected]', 'Renamed');
+ expect(out).toEqual({ success: true, message: 'Group subject updated' });
+ });
+
+ it('GroupSetDescription delegates to setGroupDescription and reports success', async () => {
+ const setGroupDescription = jest.fn().mockResolvedValue(undefined);
+ const tool = groupTools({ setGroupDescription } as unknown as GroupService).find(
+ t => t.name === 'GroupSetDescription',
+ )!;
+ const out = await invokeTool(
+ tool,
+ { sessionId: 's1', groupId: '[email protected]', description: 'About us' },
+ 'key',
+ makeAuth() as unknown as AuthService,
+ );
+ expect(setGroupDescription).toHaveBeenCalledWith('s1', '[email protected]', 'About us');
+ expect(out).toEqual({ success: true, message: 'Group description updated' });
+ });
+});
diff --git a/src/core/agent-tools/tools/message.tools.spec.ts b/src/core/agent-tools/tools/message.tools.spec.ts
new file mode 100644
index 000000000..03f05a149
--- /dev/null
+++ b/src/core/agent-tools/tools/message.tools.spec.ts
@@ -0,0 +1,303 @@
+import { invokeTool } from '../tool-invoker';
+import { messageTools } from './message.tools';
+import type { AnyToolDescriptor } from '../tool-descriptor';
+import type { MessageService } from '../../../modules/message/message.service';
+import type { AuthService } from '../../../modules/auth/auth.service';
+
+// Covers every messageTools execute() handler via the real invokeTool path (auth → zod → handler).
+// agent-tools.module.ts is pure Nest wiring, stays at 0% coverage, and is intentionally not a target.
+
+function makeAuth(): Pick<AuthService, 'validateApiKey' | 'hasPermission'> {
+ return {
+ validateApiKey: jest.fn().mockResolvedValue({ id: 'k1', allowedSessions: null }),
+ hasPermission: jest.fn().mockReturnValue(true),
+ };
+}
+
+function makeTools(svc: MessageService): Map<string, AnyToolDescriptor> {
+ return new Map(messageTools(svc).map(t => [t.name, t]));
+}
+
+async function run(tool: AnyToolDescriptor, input: unknown): Promise<unknown> {
+ return invokeTool(tool, input, 'key', makeAuth() as unknown as AuthService);
+}
+
+describe('messageTools', () => {
+ it('MessageList delegates to getMessages with the filter fields', async () => {
+ const getMessages = jest.fn().mockResolvedValue([{ id: 'm1' }]);
+ const tools = makeTools({ getMessages } as unknown as MessageService);
+ const out = await run(tools.get('MessageList')!, {
+ sessionId: 's1',
+ chatId: '[email protected]',
+ limit: 10,
+ offset: 5,
+ });
+ expect(getMessages).toHaveBeenCalledWith('s1', {
+ chatId: '[email protected]',
+ from: undefined,
+ limit: 10,
+ offset: 5,
+ });
+ expect(out).toEqual([{ id: 'm1' }]);
+ });
+
+ it('MessageHistory delegates to getChatHistory', async () => {
+ const getChatHistory = jest.fn().mockResolvedValue([{ id: 'm1' }]);
+ const tools = makeTools({ getChatHistory } as unknown as MessageService);
+ const out = await run(tools.get('MessageHistory')!, {
+ sessionId: 's1',
+ chatId: '[email protected]',
+ limit: 50,
+ includeMedia: true,
+ deep: true,
+ });
+ expect(getChatHistory).toHaveBeenCalledWith('s1', '[email protected]', 50, true, true);
+ expect(out).toEqual([{ id: 'm1' }]);
+ });
+
+ it('MessageGetReactions delegates to getMessageReactions', async () => {
+ const getMessageReactions = jest.fn().mockResolvedValue([{ emoji: '👍' }]);
+ const tools = makeTools({ getMessageReactions } as unknown as MessageService);
+ const out = await run(tools.get('MessageGetReactions')!, {
+ sessionId: 's1',
+ chatId: '[email protected]',
+ messageId: 'm1',
+ });
+ expect(getMessageReactions).toHaveBeenCalledWith('s1', '[email protected]', 'm1');
+ expect(out).toEqual([{ emoji: '👍' }]);
+ });
+
+ it('MessageSendText delegates to sendText and forwards linkPreview when set', async () => {
+ const sendText = jest.fn().mockResolvedValue({ id: 'm1' });
+ const tools = makeTools({ sendText } as unknown as MessageService);
+ const out = await run(tools.get('MessageSendText')!, {
+ sessionId: 's1',
+ chatId: '[email protected]',
+ text: 'hello',
+ linkPreview: false,
+ });
+ expect(sendText).toHaveBeenCalledWith('s1', { chatId: '[email protected]', text: 'hello', linkPreview: false });
+ expect(out).toEqual({ id: 'm1' });
+ });
+
+ it('MessageSendText omits linkPreview when unset', async () => {
+ const sendText = jest.fn().mockResolvedValue({ id: 'm1' });
+ const tools = makeTools({ sendText } as unknown as MessageService);
+ await run(tools.get('MessageSendText')!, {
+ sessionId: 's1',
+ chatId: '[email protected]',
+ text: 'hello',
+ });
+ expect(sendText).toHaveBeenCalledWith('s1', { chatId: '[email protected]', text: 'hello' });
+ });
+
+ it('MessageSendImage delegates to sendImage with the media fields', async () => {
+ const sendImage = jest.fn().mockResolvedValue({ id: 'm1' });
+ const tools = makeTools({ sendImage } as unknown as MessageService);
+ const out = await run(tools.get('MessageSendImage')!, {
+ sessionId: 's1',
+ chatId: '[email protected]',
+ url: 'https://example.com/pic.jpg',
+ filename: 'pic.jpg',
+ caption: 'look',
+ });
+ expect(sendImage).toHaveBeenCalledWith('s1', {
+ chatId: '[email protected]',
+ url: 'https://example.com/pic.jpg',
+ base64: undefined,
+ mimetype: undefined,
+ filename: 'pic.jpg',
+ caption: 'look',
+ });
+ expect(out).toEqual({ id: 'm1' });
+ });
+
+ it('MessageSendVideo delegates to sendVideo with the media fields', async () => {
+ const sendVideo = jest.fn().mockResolvedValue({ id: 'm1' });
+ const tools = makeTools({ sendVideo } as unknown as MessageService);
+ const out = await run(tools.get('MessageSendVideo')!, {
+ sessionId: 's1',
+ chatId: '[email protected]',
+ url: 'https://example.com/clip.mp4',
+ caption: 'watch',
+ });
+ expect(sendVideo).toHaveBeenCalledWith('s1', {
+ chatId: '[email protected]',
+ url: 'https://example.com/clip.mp4',
+ base64: undefined,
+ mimetype: undefined,
+ filename: undefined,
+ caption: 'watch',
+ });
+ expect(out).toEqual({ id: 'm1' });
+ });
+
+ it('MessageSendAudio delegates to sendAudio including the ptt flag', async () => {
+ const sendAudio = jest.fn().mockResolvedValue({ id: 'm1' });
+ const tools = makeTools({ sendAudio } as unknown as MessageService);
+ const out = await run(tools.get('MessageSendAudio')!, {
+ sessionId: 's1',
+ chatId: '[email protected]',
+ base64: 'QUJD',
+ mimetype: 'audio/ogg',
+ ptt: true,
+ });
+ expect(sendAudio).toHaveBeenCalledWith('s1', {
+ chatId: '[email protected]',
+ url: undefined,
+ base64: 'QUJD',
+ mimetype: 'audio/ogg',
+ filename: undefined,
+ caption: undefined,
+ ptt: true,
+ });
+ expect(out).toEqual({ id: 'm1' });
+ });
+
+ it('MessageSendDocument delegates to sendDocument with the media fields', async () => {
+ const sendDocument = jest.fn().mockResolvedValue({ id: 'm1' });
+ const tools = makeTools({ sendDocument } as unknown as MessageService);
+ const out = await run(tools.get('MessageSendDocument')!, {
+ sessionId: 's1',
+ chatId: '[email protected]',
+ base64: 'QUJD',
+ mimetype: 'application/pdf',
+ filename: 'doc.pdf',
+ });
+ expect(sendDocument).toHaveBeenCalledWith('s1', {
+ chatId: '[email protected]',
+ url: undefined,
+ base64: 'QUJD',
+ mimetype: 'application/pdf',
+ filename: 'doc.pdf',
+ caption: undefined,
+ });
+ expect(out).toEqual({ id: 'm1' });
+ });
+
+ it('MessageSendLocation delegates to sendLocation', async () => {
+ const sendLocation = jest.fn().mockResolvedValue({ id: 'm1' });
+ const tools = makeTools({ sendLocation } as unknown as MessageService);
+ const out = await run(tools.get('MessageSendLocation')!, {
+ sessionId: 's1',
+ chatId: '[email protected]',
+ latitude: -6.2,
+ longitude: 106.8,
+ description: 'Office',
+ address: 'Jl. Sudirman',
+ });
+ expect(sendLocation).toHaveBeenCalledWith('s1', {
+ chatId: '[email protected]',
+ latitude: -6.2,
+ longitude: 106.8,
+ description: 'Office',
+ address: 'Jl. Sudirman',
+ });
+ expect(out).toEqual({ id: 'm1' });
+ });
+
+ it('MessageSendContact delegates to sendContact', async () => {
+ const sendContact = jest.fn().mockResolvedValue({ id: 'm1' });
+ const tools = makeTools({ sendContact } as unknown as MessageService);
+ const out = await run(tools.get('MessageSendContact')!, {
+ sessionId: 's1',
+ chatId: '[email protected]',
+ contactName: 'Jane',
+ contactNumber: '628222',
+ });
+ expect(sendContact).toHaveBeenCalledWith('s1', {
+ chatId: '[email protected]',
+ contactName: 'Jane',
+ contactNumber: '628222',
+ });
+ expect(out).toEqual({ id: 'm1' });
+ });
+
+ it('MessageSendSticker delegates to sendSticker with the media fields', async () => {
+ const sendSticker = jest.fn().mockResolvedValue({ id: 'm1' });
+ const tools = makeTools({ sendSticker } as unknown as MessageService);
+ const out = await run(tools.get('MessageSendSticker')!, {
+ sessionId: 's1',
+ chatId: '[email protected]',
+ url: 'https://example.com/sticker.webp',
+ });
+ expect(sendSticker).toHaveBeenCalledWith('s1', {
+ chatId: '[email protected]',
+ url: 'https://example.com/sticker.webp',
+ base64: undefined,
+ mimetype: undefined,
+ filename: undefined,
+ caption: undefined,
+ });
+ expect(out).toEqual({ id: 'm1' });
+ });
+
+ it('MessageSendTemplate delegates to sendTemplate', async () => {
+ const sendTemplate = jest.fn().mockResolvedValue({ id: 'm1' });
+ const tools = makeTools({ sendTemplate } as unknown as MessageService);
+ const out = await run(tools.get('MessageSendTemplate')!, {
+ sessionId: 's1',
+ chatId: '[email protected]',
+ templateName: 'welcome',
+ vars: { name: 'Jane' },
+ });
+ expect(sendTemplate).toHaveBeenCalledWith('s1', {
+ chatId: '[email protected]',
+ templateId: undefined,
+ templateName: 'welcome',
+ vars: { name: 'Jane' },
+ });
+ expect(out).toEqual({ id: 'm1' });
+ });
+
+ it('MessageReply delegates to reply', async () => {
+ const reply = jest.fn().mockResolvedValue({ id: 'm2' });
+ const tools = makeTools({ reply } as unknown as MessageService);
+ const out = await run(tools.get('MessageReply')!, {
+ sessionId: 's1',
+ chatId: '[email protected]',
+ quotedMessageId: 'm1',
+ text: 'got it',
+ });
+ expect(reply).toHaveBeenCalledWith('s1', {
+ chatId: '[email protected]',
+ quotedMessageId: 'm1',
+ text: 'got it',
+ });
+ expect(out).toEqual({ id: 'm2' });
+ });
+
+ it('MessageForward delegates to forward', async () => {
+ const forward = jest.fn().mockResolvedValue({ id: 'm2' });
+ const tools = makeTools({ forward } as unknown as MessageService);
+ const out = await run(tools.get('MessageForward')!, {
+ sessionId: 's1',
+ fromChatId: '[email protected]',
+ toChatId: '[email protected]',
+ messageId: 'm1',
+ });
+ expect(forward).toHaveBeenCalledWith('s1', {
+ fromChatId: '[email protected]',
+ toChatId: '[email protected]',
+ messageId: 'm1',
+ });
+ expect(out).toEqual({ id: 'm2' });
+ });
+
+ it('MessageReact delegates to reactToMessage and maps the void result to success', async () => {
+ const reactToMessage = jest.fn().mockResolvedValue(undefined);
+ const tools = makeTools({ reactToMessage } as unknown as MessageService);
+ const out = (await run(tools.get('MessageReact')!, {
+ sessionId: 's1',
+ chatId: '[email protected]',
+ messageId: 'm1',
+ emoji: '👍',
+ })) as { success: boolean };
+ expect(reactToMessage).toHaveBeenCalledWith('s1', {
+ chatId: '[email protected]',
+ messageId: 'm1',
+ emoji: '👍',
+ });
+ expect(out).toEqual({ success: true });
+ });
+});
diff --git a/src/core/agent-tools/tools/session.tools.spec.ts b/src/core/agent-tools/tools/session.tools.spec.ts
new file mode 100644
index 000000000..5a001b0e9
--- /dev/null
+++ b/src/core/agent-tools/tools/session.tools.spec.ts
@@ -0,0 +1,117 @@
+import { invokeTool } from '../tool-invoker';
+import { sessionTools } from './session.tools';
+import type { AnyToolDescriptor } from '../tool-descriptor';
+import type { SessionService } from '../../../modules/session/session.service';
+import type { AuthService } from '../../../modules/auth/auth.service';
+
+// Covers every sessionTools execute() handler via the real invokeTool path (auth → zod → handler).
+// agent-tools.module.ts is pure Nest wiring, stays at 0% coverage, and is intentionally not a target.
+
+function makeAuth(): Pick<AuthService, 'validateApiKey' | 'hasPermission'> {
+ return {
+ validateApiKey: jest.fn().mockResolvedValue({ id: 'k1', allowedSessions: null }),
+ hasPermission: jest.fn().mockReturnValue(true),
+ };
+}
+
+function makeTools(svc: SessionService): Map<string, AnyToolDescriptor> {
+ return new Map(sessionTools(svc).map(t => [t.name, t]));
+}
+
+async function run(tool: AnyToolDescriptor, input: unknown): Promise<unknown> {
+ return invokeTool(tool, input, 'key', makeAuth() as unknown as AuthService);
+}
+
+describe('sessionTools', () => {
+ it('SessionFindAll scopes by the key allowedSessions and maps entities to DTOs', async () => {
+ const findAll = jest.fn().mockResolvedValue([{ id: 's1', name: 'main', status: 'ready' }]);
+ const isActive = jest.fn().mockReturnValue(true);
+ const out = (await run(makeTools({ findAll, isActive } as unknown as SessionService).get('SessionFindAll')!, {
+ limit: 5,
+ })) as Array<{ id: string; engineLoaded: boolean }>;
+ expect(findAll).toHaveBeenCalledWith(null, { limit: 5, offset: undefined });
+ expect(isActive).toHaveBeenCalledWith('s1');
+ expect(out).toEqual([expect.objectContaining({ id: 's1', engineLoaded: true })]);
+ });
+
+ it('SessionFindOne delegates to findOne and maps to the response DTO', async () => {
+ const findOne = jest.fn().mockResolvedValue({ id: 's1', name: 'main', status: 'ready' });
+ const isActive = jest.fn().mockReturnValue(false);
+ const out = (await run(makeTools({ findOne, isActive } as unknown as SessionService).get('SessionFindOne')!, {
+ sessionId: 's1',
+ })) as { id: string; engineLoaded: boolean };
+ expect(findOne).toHaveBeenCalledWith('s1');
+ expect(out.id).toBe('s1');
+ expect(out.engineLoaded).toBe(false);
+ });
+
+ it('SessionGetChats delegates to getChats with paging', async () => {
+ const getChats = jest.fn().mockResolvedValue([{ id: 'c1' }]);
+ const out = await run(makeTools({ getChats } as unknown as SessionService).get('SessionGetChats')!, {
+ sessionId: 's1',
+ limit: 20,
+ offset: 10,
+ });
+ expect(getChats).toHaveBeenCalledWith('s1', { limit: 20, offset: 10 });
+ expect(out).toEqual([{ id: 'c1' }]);
+ });
+
+ it('SessionGetStats scopes by the key allowedSessions', async () => {
+ const stats = { total: 2, active: 1, ready: 1, disconnected: 1 };
+ const getStats = jest.fn().mockResolvedValue(stats);
+ const out = await run(makeTools({ getStats } as unknown as SessionService).get('SessionGetStats')!, {});
+ expect(getStats).toHaveBeenCalledWith(null);
+ expect(out).toEqual(stats);
+ });
+
+ it('SessionSubscribePresence delegates to subscribeToPresence and reports success', async () => {
+ const subscribeToPresence = jest.fn().mockResolvedValue(undefined);
+ const out = await run(
+ makeTools({ subscribeToPresence } as unknown as SessionService).get('SessionSubscribePresence')!,
+ { sessionId: 's1', chatId: '[email protected]' },
+ );
+ expect(subscribeToPresence).toHaveBeenCalledWith('s1', '[email protected]');
+ expect(out).toEqual({ success: true });
+ });
+
+ it('SessionGetPresence delegates to getPresence and passes the result through', async () => {
+ const getPresence = jest.fn().mockResolvedValue({ presence: 'online' });
+ const out = await run(makeTools({ getPresence } as unknown as SessionService).get('SessionGetPresence')!, {
+ sessionId: 's1',
+ chatId: '[email protected]',
+ });
+ expect(getPresence).toHaveBeenCalledWith('s1', '[email protected]');
+ expect(out).toEqual({ presence: 'online' });
+ });
+
+ it('SessionMarkChatRead maps the sendSeen result to a success field', async () => {
+ const sendSeen = jest.fn().mockResolvedValue(true);
+ const out = await run(makeTools({ sendSeen } as unknown as SessionService).get('SessionMarkChatRead')!, {
+ sessionId: 's1',
+ chatId: '[email protected]',
+ });
+ expect(sendSeen).toHaveBeenCalledWith('s1', '[email protected]');
+ expect(out).toEqual({ success: true });
+ });
+
+ it('SessionMarkChatUnread maps the markUnread result to a success field', async () => {
+ const markUnread = jest.fn().mockResolvedValue(true);
+ const out = await run(makeTools({ markUnread } as unknown as SessionService).get('SessionMarkChatUnread')!, {
+ sessionId: 's1',
+ chatId: '[email protected]',
+ });
+ expect(markUnread).toHaveBeenCalledWith('s1', '[email protected]');
+ expect(out).toEqual({ success: true });
+ });
+
+ it('SessionSendChatState delegates to sendChatState and reports success', async () => {
+ const sendChatState = jest.fn().mockResolvedValue(undefined);
+ const out = await run(makeTools({ sendChatState } as unknown as SessionService).get('SessionSendChatState')!, {
+ sessionId: 's1',
+ chatId: '[email protected]',
+ state: 'typing',
+ });
+ expect(sendChatState).toHaveBeenCalledWith('s1', '[email protected]', 'typing');
+ expect(out).toEqual({ success: true });
+ });
+});