pipeline.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. import { after, before, beforeEach, test } from 'node:test';
  2. import assert from 'node:assert/strict';
  3. import { prepareTestDatabase } from '../helpers/testServer.js';
  4. import { applyTestConfig } from '../helpers/testConfig.js';
  5. import type { SupportMessageEvent } from '../../src/domain/messageNormalizer.js';
  6. import type { ChatwootClient } from '../../src/clients/chatwootClient.js';
  7. import type { FlowiseClient, FlowiseResult } from '../../src/clients/flowiseClient.js';
  8. const dbUrl = prepareTestDatabase('test-pipeline');
  9. const { processMessageEvent, buildFlowisePayload } = await import(
  10. '../../src/domain/conversationPipeline.js'
  11. );
  12. const { db, disconnectDb } = await import('../../src/store/db.js');
  13. const { claimMessage } = await import('../../src/store/idempotencyStore.js');
  14. /** Records every Chatwoot side effect instead of performing it. */
  15. class FakeChatwoot {
  16. sentMessages: { conversationId: number; content: string }[] = [];
  17. labels: { conversationId: number; label: string }[] = [];
  18. attributes: { conversationId: number; attrs: Record<string, unknown> }[] = [];
  19. unassigned: number[] = [];
  20. statusUpdates: { conversationId: number; status: string }[] = [];
  21. conversation: Record<string, unknown> = { id: 1311, labels: [], custom_attributes: {} };
  22. async getConversation(): Promise<Record<string, unknown>> {
  23. return this.conversation;
  24. }
  25. async addLabel(conversationId: number, label: string): Promise<void> {
  26. this.labels.push({ conversationId, label });
  27. }
  28. async setCustomAttributes(conversationId: number, attrs: Record<string, unknown>): Promise<void> {
  29. this.attributes.push({ conversationId, attrs });
  30. const existing = (this.conversation.custom_attributes ?? {}) as Record<string, unknown>;
  31. this.conversation.custom_attributes = { ...existing, ...attrs };
  32. }
  33. async unassignConversation(conversationId: number): Promise<boolean> {
  34. this.unassigned.push(conversationId);
  35. return true;
  36. }
  37. async setConversationStatus(conversationId: number, status: 'open' | 'resolved' | 'pending'): Promise<boolean> {
  38. this.statusUpdates.push({ conversationId, status });
  39. return true;
  40. }
  41. async sendOutgoingMessage(conversationId: number, content: string): Promise<unknown> {
  42. this.sentMessages.push({ conversationId, content });
  43. return {};
  44. }
  45. }
  46. class FakeFlowise {
  47. calls: unknown[] = [];
  48. constructor(private readonly result: FlowiseResult) {}
  49. async predict(payload: unknown): Promise<FlowiseResult> {
  50. this.calls.push(payload);
  51. return this.result;
  52. }
  53. }
  54. function evt(overrides: Partial<SupportMessageEvent> = {}): SupportMessageEvent {
  55. return {
  56. source: 'chatwoot',
  57. channel: 'email',
  58. conversationId: 1311,
  59. messageId: `m-${Math.random().toString(36).slice(2)}`,
  60. inboxId: 1,
  61. content: 'Czy macie gaz R134a?',
  62. subject: 'Pytanie',
  63. senderEmail: 'klient@example.com',
  64. senderName: 'Klient Testowy',
  65. senderId: '332',
  66. labels: [],
  67. customAttributes: {},
  68. additionalAttributes: {},
  69. attachmentCount: 0,
  70. needsConversationFetch: false,
  71. ...overrides,
  72. };
  73. }
  74. const deps = (chatwoot: FakeChatwoot, flowise: FakeFlowise) => ({
  75. chatwoot: chatwoot as unknown as ChatwootClient,
  76. flowise: flowise as unknown as FlowiseClient,
  77. });
  78. before(() => applyTestConfig({ DATABASE_URL: dbUrl }));
  79. beforeEach(async () => {
  80. await db().ticket.deleteMany({});
  81. await db().auditEvent.deleteMany({});
  82. await db().processedMessage.deleteMany({});
  83. });
  84. after(async () => {
  85. await disconnectDb();
  86. });
  87. test('a normal question is answered and marked replied', async () => {
  88. const chatwoot = new FakeChatwoot();
  89. const flowise = new FakeFlowise({ type: 'reply', text: 'Tak, mamy.', actions: null });
  90. const event = evt();
  91. await claimMessage(event.source, event.messageId, event.conversationId);
  92. const outcome = await processMessageEvent(event, deps(chatwoot, flowise));
  93. assert.equal(outcome.action, 'reply');
  94. assert.equal(chatwoot.sentMessages.length, 1);
  95. assert.equal(chatwoot.sentMessages[0]?.content, 'Tak, mamy.');
  96. const row = await db().processedMessage.findUnique({
  97. where: { source_messageId: { source: 'chatwoot', messageId: event.messageId } },
  98. });
  99. assert.equal(row?.status, 'replied');
  100. });
  101. test('a conversation already in ticket mode never reaches Flowise', async () => {
  102. const chatwoot = new FakeChatwoot();
  103. const flowise = new FakeFlowise({ type: 'reply', text: 'nie powinno wyjść', actions: null });
  104. const event = evt({ labels: ['ticket'] });
  105. await claimMessage(event.source, event.messageId, event.conversationId);
  106. const outcome = await processMessageEvent(event, deps(chatwoot, flowise));
  107. assert.deepEqual(outcome, { action: 'skipped', reason: 'ticket_mode' });
  108. assert.equal(flowise.calls.length, 0);
  109. assert.equal(chatwoot.sentMessages.length, 0);
  110. });
  111. test('a ticket_number custom attribute also stops the AI', async () => {
  112. const chatwoot = new FakeChatwoot();
  113. const flowise = new FakeFlowise({ type: 'reply', text: 'x', actions: null });
  114. const event = evt({ customAttributes: { ticket_number: 'EKS-20260820-1311' } });
  115. await claimMessage(event.source, event.messageId, event.conversationId);
  116. const outcome = await processMessageEvent(event, deps(chatwoot, flowise));
  117. assert.equal(outcome.action, 'skipped');
  118. assert.equal(flowise.calls.length, 0);
  119. });
  120. test('spam is blocked before Flowise and recorded', async () => {
  121. const chatwoot = new FakeChatwoot();
  122. const flowise = new FakeFlowise({ type: 'reply', text: 'x', actions: null });
  123. const event = evt({ senderEmail: 'mailer-daemon@example.com' });
  124. await claimMessage(event.source, event.messageId, event.conversationId);
  125. const outcome = await processMessageEvent(event, deps(chatwoot, flowise));
  126. assert.equal(outcome.action, 'spam');
  127. assert.equal(flowise.calls.length, 0, 'the spam gate must sit in front of the LLM');
  128. const row = await db().processedMessage.findUnique({
  129. where: { source_messageId: { source: 'chatwoot', messageId: event.messageId } },
  130. });
  131. assert.equal(row?.status, 'spam');
  132. });
  133. test('configured AgentBot guard skips conversations assigned to the legacy user account', async () => {
  134. applyTestConfig({
  135. DATABASE_URL: dbUrl,
  136. CHATWOOT_REQUIRE_AGENT_BOT_ASSIGNMENT: 'true',
  137. CHATWOOT_REQUIRED_AGENT_BOT_ID: '1',
  138. });
  139. const chatwoot = new FakeChatwoot();
  140. chatwoot.conversation = {
  141. id: 1311,
  142. labels: [],
  143. custom_attributes: {},
  144. assignee_agent_bot_id: null,
  145. meta: { assignee_type: 'User', assignee: { id: 2, name: 'KlimBot' } },
  146. };
  147. const flowise = new FakeFlowise({ type: 'reply', text: 'nie powinno wyjść', actions: null });
  148. const event = evt();
  149. await claimMessage(event.source, event.messageId, event.conversationId);
  150. const outcome = await processMessageEvent(event, deps(chatwoot, flowise));
  151. assert.deepEqual(outcome, { action: 'skipped', reason: 'not_assigned_to_bot' });
  152. assert.equal(flowise.calls.length, 0);
  153. assert.equal(chatwoot.sentMessages.length, 0);
  154. applyTestConfig({ DATABASE_URL: dbUrl });
  155. });
  156. test('configured AgentBot guard allows conversations assigned to the Chatwoot AgentBot', async () => {
  157. applyTestConfig({
  158. DATABASE_URL: dbUrl,
  159. CHATWOOT_REQUIRE_AGENT_BOT_ASSIGNMENT: 'true',
  160. CHATWOOT_REQUIRED_AGENT_BOT_ID: '1',
  161. });
  162. const chatwoot = new FakeChatwoot();
  163. chatwoot.conversation = {
  164. id: 1311,
  165. labels: [],
  166. custom_attributes: {},
  167. assignee_agent_bot_id: 1,
  168. meta: { assignee_type: 'AgentBot', assignee: { id: 1, name: 'Agent' } },
  169. };
  170. const flowise = new FakeFlowise({ type: 'reply', text: 'OK od bota', actions: null });
  171. const event = evt();
  172. await claimMessage(event.source, event.messageId, event.conversationId);
  173. const outcome = await processMessageEvent(event, deps(chatwoot, flowise));
  174. assert.equal(outcome.action, 'reply');
  175. assert.equal(flowise.calls.length, 1);
  176. assert.equal(chatwoot.sentMessages[0]?.content, 'OK od bota');
  177. applyTestConfig({ DATABASE_URL: dbUrl });
  178. });
  179. test('a handoff action creates a ticket, labels it and replies with the number', async () => {
  180. const chatwoot = new FakeChatwoot();
  181. const flowise = new FakeFlowise({
  182. type: 'handoff',
  183. text: 'Przekazuję sprawę do supportu.',
  184. actions: [{ type: 'handoff' }],
  185. });
  186. const event = evt();
  187. await claimMessage(event.source, event.messageId, event.conversationId);
  188. const outcome = await processMessageEvent(event, deps(chatwoot, flowise));
  189. assert.equal(outcome.action, 'handoff');
  190. assert.match((outcome as { ticketNumber: string }).ticketNumber, /^EKS-\d{8}-1311$/);
  191. assert.ok(chatwoot.labels.some((l) => l.label === 'ticket'));
  192. assert.ok(chatwoot.attributes.some((a) => 'ticket_number' in a.attrs));
  193. assert.deepEqual(chatwoot.unassigned, [1311]);
  194. assert.deepEqual(chatwoot.statusUpdates, [{ conversationId: 1311, status: 'open' }]);
  195. assert.equal(chatwoot.sentMessages.length, 1);
  196. assert.match(chatwoot.sentMessages[0]?.content ?? '', /EKS-\d{8}-1311/);
  197. });
  198. test('two handoffs for one conversation reuse the same ticket number', async () => {
  199. const chatwoot = new FakeChatwoot();
  200. const first = evt({ messageId: 'h1' });
  201. const second = evt({ messageId: 'h2' });
  202. await claimMessage(first.source, first.messageId, first.conversationId);
  203. await claimMessage(second.source, second.messageId, second.conversationId);
  204. const flowise = new FakeFlowise({ type: 'handoff', text: 'ok', actions: [{ type: 'handoff' }] });
  205. const a = await processMessageEvent(first, deps(chatwoot, flowise));
  206. // The second message would normally be stopped by the ticket-mode check; call
  207. // createTicket directly to prove the idempotency of the ticket itself.
  208. const { createTicket } = await import('../../src/domain/ticketService.js');
  209. const b = await createTicket(1311, 'retry', chatwoot as unknown as ChatwootClient);
  210. assert.equal((a as { ticketNumber: string }).ticketNumber, b.ticketNumber);
  211. assert.equal(b.status, 'existing');
  212. assert.equal(await db().ticket.count({ where: { conversationId: 1311 } }), 1);
  213. });
  214. test('an empty Flowise answer is recorded as failed and nothing is sent', async () => {
  215. const chatwoot = new FakeChatwoot();
  216. const flowise = new FakeFlowise({ type: 'unknown', text: null, actions: null });
  217. const event = evt();
  218. await claimMessage(event.source, event.messageId, event.conversationId);
  219. const outcome = await processMessageEvent(event, deps(chatwoot, flowise));
  220. assert.equal(outcome.action, 'no_reply');
  221. assert.equal(chatwoot.sentMessages.length, 0);
  222. const row = await db().processedMessage.findUnique({
  223. where: { source_messageId: { source: 'chatwoot', messageId: event.messageId } },
  224. });
  225. assert.equal(row?.status, 'failed');
  226. });
  227. test('the conversation is fetched when the webhook omitted labels', async () => {
  228. const chatwoot = new FakeChatwoot();
  229. chatwoot.conversation = { id: 1311, labels: ['ticket'], custom_attributes: {} };
  230. const flowise = new FakeFlowise({ type: 'reply', text: 'x', actions: null });
  231. const event = evt({ needsConversationFetch: true, labels: [] });
  232. await claimMessage(event.source, event.messageId, event.conversationId);
  233. const outcome = await processMessageEvent(event, deps(chatwoot, flowise));
  234. assert.equal(outcome.action, 'skipped');
  235. assert.equal(flowise.calls.length, 0);
  236. });
  237. test('the Flowise payload keeps the contract the custom tools depend on', () => {
  238. const payload = buildFlowisePayload(evt());
  239. assert.match(payload.question, /\[CONTACT_INFO\]/);
  240. assert.match(payload.question, /contact_email: klient@example\.com/);
  241. assert.match(payload.question, /Czy macie gaz R134a\?/);
  242. assert.equal(payload.overrideConfig.sessionId, 'chatwoot:1311');
  243. assert.equal(payload.overrideConfig.conversationId, 1311);
  244. assert.equal(payload.overrideConfig.inboxId, 1);
  245. assert.equal(payload.overrideConfig.tenantId, 'easyklima');
  246. assert.equal(payload.overrideConfig.channel, 'email');
  247. assert.equal(payload.metadata.source, 'chatwoot');
  248. assert.equal(payload.metadata.messageType, 'incoming');
  249. });