pipeline.test.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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. conversation: Record<string, unknown> = { id: 1311, labels: [], custom_attributes: {} };
  21. async getConversation(): Promise<Record<string, unknown>> {
  22. return this.conversation;
  23. }
  24. async addLabel(conversationId: number, label: string): Promise<void> {
  25. this.labels.push({ conversationId, label });
  26. }
  27. async setCustomAttributes(conversationId: number, attrs: Record<string, unknown>): Promise<void> {
  28. this.attributes.push({ conversationId, attrs });
  29. const existing = (this.conversation.custom_attributes ?? {}) as Record<string, unknown>;
  30. this.conversation.custom_attributes = { ...existing, ...attrs };
  31. }
  32. async unassignConversation(conversationId: number): Promise<boolean> {
  33. this.unassigned.push(conversationId);
  34. return true;
  35. }
  36. async sendOutgoingMessage(conversationId: number, content: string): Promise<unknown> {
  37. this.sentMessages.push({ conversationId, content });
  38. return {};
  39. }
  40. }
  41. class FakeFlowise {
  42. calls: unknown[] = [];
  43. constructor(private readonly result: FlowiseResult) {}
  44. async predict(payload: unknown): Promise<FlowiseResult> {
  45. this.calls.push(payload);
  46. return this.result;
  47. }
  48. }
  49. function evt(overrides: Partial<SupportMessageEvent> = {}): SupportMessageEvent {
  50. return {
  51. source: 'chatwoot',
  52. channel: 'email',
  53. conversationId: 1311,
  54. messageId: `m-${Math.random().toString(36).slice(2)}`,
  55. inboxId: 1,
  56. content: 'Czy macie gaz R134a?',
  57. subject: 'Pytanie',
  58. senderEmail: 'klient@example.com',
  59. senderName: 'Klient Testowy',
  60. senderId: '332',
  61. labels: [],
  62. customAttributes: {},
  63. additionalAttributes: {},
  64. attachmentCount: 0,
  65. needsConversationFetch: false,
  66. ...overrides,
  67. };
  68. }
  69. const deps = (chatwoot: FakeChatwoot, flowise: FakeFlowise) => ({
  70. chatwoot: chatwoot as unknown as ChatwootClient,
  71. flowise: flowise as unknown as FlowiseClient,
  72. });
  73. before(() => applyTestConfig({ DATABASE_URL: dbUrl }));
  74. beforeEach(async () => {
  75. await db().ticket.deleteMany({});
  76. await db().auditEvent.deleteMany({});
  77. await db().processedMessage.deleteMany({});
  78. });
  79. after(async () => {
  80. await disconnectDb();
  81. });
  82. test('a normal question is answered and marked replied', async () => {
  83. const chatwoot = new FakeChatwoot();
  84. const flowise = new FakeFlowise({ type: 'reply', text: 'Tak, mamy.', actions: null });
  85. const event = evt();
  86. await claimMessage(event.source, event.messageId, event.conversationId);
  87. const outcome = await processMessageEvent(event, deps(chatwoot, flowise));
  88. assert.equal(outcome.action, 'reply');
  89. assert.equal(chatwoot.sentMessages.length, 1);
  90. assert.equal(chatwoot.sentMessages[0]?.content, 'Tak, mamy.');
  91. const row = await db().processedMessage.findUnique({
  92. where: { source_messageId: { source: 'chatwoot', messageId: event.messageId } },
  93. });
  94. assert.equal(row?.status, 'replied');
  95. });
  96. test('a conversation already in ticket mode never reaches Flowise', async () => {
  97. const chatwoot = new FakeChatwoot();
  98. const flowise = new FakeFlowise({ type: 'reply', text: 'nie powinno wyjść', actions: null });
  99. const event = evt({ labels: ['ticket'] });
  100. await claimMessage(event.source, event.messageId, event.conversationId);
  101. const outcome = await processMessageEvent(event, deps(chatwoot, flowise));
  102. assert.deepEqual(outcome, { action: 'skipped', reason: 'ticket_mode' });
  103. assert.equal(flowise.calls.length, 0);
  104. assert.equal(chatwoot.sentMessages.length, 0);
  105. });
  106. test('a ticket_number custom attribute also stops the AI', async () => {
  107. const chatwoot = new FakeChatwoot();
  108. const flowise = new FakeFlowise({ type: 'reply', text: 'x', actions: null });
  109. const event = evt({ customAttributes: { ticket_number: 'EKS-20260820-1311' } });
  110. await claimMessage(event.source, event.messageId, event.conversationId);
  111. const outcome = await processMessageEvent(event, deps(chatwoot, flowise));
  112. assert.equal(outcome.action, 'skipped');
  113. assert.equal(flowise.calls.length, 0);
  114. });
  115. test('spam is blocked before Flowise and recorded', async () => {
  116. const chatwoot = new FakeChatwoot();
  117. const flowise = new FakeFlowise({ type: 'reply', text: 'x', actions: null });
  118. const event = evt({ senderEmail: 'mailer-daemon@example.com' });
  119. await claimMessage(event.source, event.messageId, event.conversationId);
  120. const outcome = await processMessageEvent(event, deps(chatwoot, flowise));
  121. assert.equal(outcome.action, 'spam');
  122. assert.equal(flowise.calls.length, 0, 'the spam gate must sit in front of the LLM');
  123. const row = await db().processedMessage.findUnique({
  124. where: { source_messageId: { source: 'chatwoot', messageId: event.messageId } },
  125. });
  126. assert.equal(row?.status, 'spam');
  127. });
  128. test('a handoff action creates a ticket, labels it and replies with the number', async () => {
  129. const chatwoot = new FakeChatwoot();
  130. const flowise = new FakeFlowise({
  131. type: 'handoff',
  132. text: 'Przekazuję sprawę do supportu.',
  133. actions: [{ type: 'handoff' }],
  134. });
  135. const event = evt();
  136. await claimMessage(event.source, event.messageId, event.conversationId);
  137. const outcome = await processMessageEvent(event, deps(chatwoot, flowise));
  138. assert.equal(outcome.action, 'handoff');
  139. assert.match((outcome as { ticketNumber: string }).ticketNumber, /^EKS-\d{8}-1311$/);
  140. assert.ok(chatwoot.labels.some((l) => l.label === 'ticket'));
  141. assert.ok(chatwoot.attributes.some((a) => 'ticket_number' in a.attrs));
  142. assert.equal(chatwoot.sentMessages.length, 1);
  143. assert.match(chatwoot.sentMessages[0]?.content ?? '', /EKS-\d{8}-1311/);
  144. });
  145. test('two handoffs for one conversation reuse the same ticket number', async () => {
  146. const chatwoot = new FakeChatwoot();
  147. const first = evt({ messageId: 'h1' });
  148. const second = evt({ messageId: 'h2' });
  149. await claimMessage(first.source, first.messageId, first.conversationId);
  150. await claimMessage(second.source, second.messageId, second.conversationId);
  151. const flowise = new FakeFlowise({ type: 'handoff', text: 'ok', actions: [{ type: 'handoff' }] });
  152. const a = await processMessageEvent(first, deps(chatwoot, flowise));
  153. // The second message would normally be stopped by the ticket-mode check; call
  154. // createTicket directly to prove the idempotency of the ticket itself.
  155. const { createTicket } = await import('../../src/domain/ticketService.js');
  156. const b = await createTicket(1311, 'retry', chatwoot as unknown as ChatwootClient);
  157. assert.equal((a as { ticketNumber: string }).ticketNumber, b.ticketNumber);
  158. assert.equal(b.status, 'existing');
  159. assert.equal(await db().ticket.count({ where: { conversationId: 1311 } }), 1);
  160. });
  161. test('an empty Flowise answer is recorded as failed and nothing is sent', async () => {
  162. const chatwoot = new FakeChatwoot();
  163. const flowise = new FakeFlowise({ type: 'unknown', text: null, actions: null });
  164. const event = evt();
  165. await claimMessage(event.source, event.messageId, event.conversationId);
  166. const outcome = await processMessageEvent(event, deps(chatwoot, flowise));
  167. assert.equal(outcome.action, 'no_reply');
  168. assert.equal(chatwoot.sentMessages.length, 0);
  169. const row = await db().processedMessage.findUnique({
  170. where: { source_messageId: { source: 'chatwoot', messageId: event.messageId } },
  171. });
  172. assert.equal(row?.status, 'failed');
  173. });
  174. test('the conversation is fetched when the webhook omitted labels', async () => {
  175. const chatwoot = new FakeChatwoot();
  176. chatwoot.conversation = { id: 1311, labels: ['ticket'], custom_attributes: {} };
  177. const flowise = new FakeFlowise({ type: 'reply', text: 'x', actions: null });
  178. const event = evt({ needsConversationFetch: true, labels: [] });
  179. await claimMessage(event.source, event.messageId, event.conversationId);
  180. const outcome = await processMessageEvent(event, deps(chatwoot, flowise));
  181. assert.equal(outcome.action, 'skipped');
  182. assert.equal(flowise.calls.length, 0);
  183. });
  184. test('the Flowise payload keeps the contract the custom tools depend on', () => {
  185. const payload = buildFlowisePayload(evt());
  186. assert.match(payload.question, /\[CONTACT_INFO\]/);
  187. assert.match(payload.question, /contact_email: klient@example\.com/);
  188. assert.match(payload.question, /Czy macie gaz R134a\?/);
  189. assert.equal(payload.overrideConfig.sessionId, 'chatwoot:1311');
  190. assert.equal(payload.overrideConfig.conversationId, 1311);
  191. assert.equal(payload.overrideConfig.inboxId, 1);
  192. assert.equal(payload.overrideConfig.tenantId, 'easyklima');
  193. assert.equal(payload.overrideConfig.channel, 'email');
  194. assert.equal(payload.metadata.source, 'chatwoot');
  195. assert.equal(payload.metadata.messageType, 'incoming');
  196. });