pipeline.test.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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('a handoff action creates a ticket, labels it and replies with the number', async () => {
  134. const chatwoot = new FakeChatwoot();
  135. const flowise = new FakeFlowise({
  136. type: 'handoff',
  137. text: 'Przekazuję sprawę do supportu.',
  138. actions: [{ type: 'handoff' }],
  139. });
  140. const event = evt();
  141. await claimMessage(event.source, event.messageId, event.conversationId);
  142. const outcome = await processMessageEvent(event, deps(chatwoot, flowise));
  143. assert.equal(outcome.action, 'handoff');
  144. assert.match((outcome as { ticketNumber: string }).ticketNumber, /^EKS-\d{8}-1311$/);
  145. assert.ok(chatwoot.labels.some((l) => l.label === 'ticket'));
  146. assert.ok(chatwoot.attributes.some((a) => 'ticket_number' in a.attrs));
  147. assert.deepEqual(chatwoot.unassigned, [1311]);
  148. assert.deepEqual(chatwoot.statusUpdates, [{ conversationId: 1311, status: 'open' }]);
  149. assert.equal(chatwoot.sentMessages.length, 1);
  150. assert.match(chatwoot.sentMessages[0]?.content ?? '', /EKS-\d{8}-1311/);
  151. });
  152. test('two handoffs for one conversation reuse the same ticket number', async () => {
  153. const chatwoot = new FakeChatwoot();
  154. const first = evt({ messageId: 'h1' });
  155. const second = evt({ messageId: 'h2' });
  156. await claimMessage(first.source, first.messageId, first.conversationId);
  157. await claimMessage(second.source, second.messageId, second.conversationId);
  158. const flowise = new FakeFlowise({ type: 'handoff', text: 'ok', actions: [{ type: 'handoff' }] });
  159. const a = await processMessageEvent(first, deps(chatwoot, flowise));
  160. // The second message would normally be stopped by the ticket-mode check; call
  161. // createTicket directly to prove the idempotency of the ticket itself.
  162. const { createTicket } = await import('../../src/domain/ticketService.js');
  163. const b = await createTicket(1311, 'retry', chatwoot as unknown as ChatwootClient);
  164. assert.equal((a as { ticketNumber: string }).ticketNumber, b.ticketNumber);
  165. assert.equal(b.status, 'existing');
  166. assert.equal(await db().ticket.count({ where: { conversationId: 1311 } }), 1);
  167. });
  168. test('an empty Flowise answer is recorded as failed and nothing is sent', async () => {
  169. const chatwoot = new FakeChatwoot();
  170. const flowise = new FakeFlowise({ type: 'unknown', text: null, 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, 'no_reply');
  175. assert.equal(chatwoot.sentMessages.length, 0);
  176. const row = await db().processedMessage.findUnique({
  177. where: { source_messageId: { source: 'chatwoot', messageId: event.messageId } },
  178. });
  179. assert.equal(row?.status, 'failed');
  180. });
  181. test('the conversation is fetched when the webhook omitted labels', async () => {
  182. const chatwoot = new FakeChatwoot();
  183. chatwoot.conversation = { id: 1311, labels: ['ticket'], custom_attributes: {} };
  184. const flowise = new FakeFlowise({ type: 'reply', text: 'x', actions: null });
  185. const event = evt({ needsConversationFetch: true, labels: [] });
  186. await claimMessage(event.source, event.messageId, event.conversationId);
  187. const outcome = await processMessageEvent(event, deps(chatwoot, flowise));
  188. assert.equal(outcome.action, 'skipped');
  189. assert.equal(flowise.calls.length, 0);
  190. });
  191. test('the Flowise payload keeps the contract the custom tools depend on', () => {
  192. const payload = buildFlowisePayload(evt());
  193. assert.match(payload.question, /\[CONTACT_INFO\]/);
  194. assert.match(payload.question, /contact_email: klient@example\.com/);
  195. assert.match(payload.question, /Czy macie gaz R134a\?/);
  196. assert.equal(payload.overrideConfig.sessionId, 'chatwoot:1311');
  197. assert.equal(payload.overrideConfig.conversationId, 1311);
  198. assert.equal(payload.overrideConfig.inboxId, 1);
  199. assert.equal(payload.overrideConfig.tenantId, 'easyklima');
  200. assert.equal(payload.overrideConfig.channel, 'email');
  201. assert.equal(payload.metadata.source, 'chatwoot');
  202. assert.equal(payload.metadata.messageType, 'incoming');
  203. });