@tiledesk/tiledesk-server 3.0.1 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/.circleci/config.yml +1 -1
  2. package/CHANGELOG.md +34 -0
  3. package/Dockerfile +3 -2
  4. package/Dockerfile-en +3 -2
  5. package/Dockerfile-jobs +3 -2
  6. package/Dockerfile-profiler +3 -2
  7. package/README.md +15 -0
  8. package/app.js +12 -1
  9. package/bin/quota-reset +68 -0
  10. package/bin/quota-restore +86 -0
  11. package/channels/chat21/chat21Handler.js +50 -34
  12. package/channels/chat21/chat21JoinTracker.js +43 -0
  13. package/config/database.js +5 -5
  14. package/config/native_mcp/native_mcp_servers.json +1 -0
  15. package/controllers/chatbot.controller.js +80 -27
  16. package/controllers/intents.controller.js +42 -0
  17. package/docs/superpowers/plans/2026-09-15-webhook-chatbot-hitl-chat21-ionic.md +468 -0
  18. package/docs/superpowers/plans/2026-09-15-webhook-chatbot-hitl-design-studio.md +1349 -0
  19. package/docs/superpowers/plans/2026-09-15-webhook-chatbot-hitl-server.md +1694 -0
  20. package/docs/superpowers/plans/2026-09-15-webhook-chatbot-hitl-tybot.md +789 -0
  21. package/docs/superpowers/plans/2026-09-29-hitl-known-limits-server.md +83 -0
  22. package/docs/superpowers/plans/2026-09-29-hitl-known-limits-tybot.md +76 -0
  23. package/docs/superpowers/plans/2026-09-29-hitl-participant-removal-chat21-ionic.md +97 -0
  24. package/docs/superpowers/plans/2026-09-29-hitl-participant-removal-design-studio.md +72 -0
  25. package/docs/superpowers/plans/2026-09-29-hitl-participant-removal-server.md +223 -0
  26. package/docs/superpowers/plans/2026-09-29-hitl-participant-removal-tybot.md +121 -0
  27. package/docs/superpowers/plans/2026-09-29-hitl-pre-branch-ports.md +65 -0
  28. package/docs/superpowers/plans/2026-09-30-flow-start-points-design-studio.md +88 -0
  29. package/docs/superpowers/plans/2026-09-30-flow-start-points-server.md +103 -0
  30. package/docs/superpowers/plans/2026-09-30-flow-start-points-tybot.md +43 -0
  31. package/docs/superpowers/plans/2026-10-01-scheduled-start-point-design-studio.md +80 -0
  32. package/docs/superpowers/plans/2026-10-01-scheduled-start-point-runtime.md +39 -0
  33. package/docs/superpowers/plans/2026-10-01-scheduled-start-point-server.md +106 -0
  34. package/docs/superpowers/specs/2026-09-15-webhook-chatbot-hitl-design.md +715 -0
  35. package/docs/superpowers/specs/2026-09-30-flow-start-points-design.md +156 -0
  36. package/docs/superpowers/specs/2026-10-01-scheduled-start-point-design.md +303 -0
  37. package/docs/superpowers/todo/2026-09-14-webhook-chatbot-shared-code-fixes.md +191 -0
  38. package/event/botEvent.js +12 -1
  39. package/event/emailEvent.js +3 -0
  40. package/event/messageEvent.js +44 -0
  41. package/jobs.js +10 -0
  42. package/jobsManager.js +19 -0
  43. package/middleware/errorHandler.js +6 -2
  44. package/models/analyticResult.js +1 -1
  45. package/models/channelConstants.js +3 -2
  46. package/models/quotaUsage.js +71 -0
  47. package/models/request.js +6 -0
  48. package/models/requestSnapshot.js +12 -0
  49. package/models/routerLogger.js +1 -1
  50. package/models/webhook.js +44 -0
  51. package/package.json +7 -5
  52. package/pubmodules/emailNotification/requestNotification.js +14 -22
  53. package/pubmodules/events/test/eventRoute.js +7 -6
  54. package/pubmodules/rules/conciergeBot.js +9 -4
  55. package/routes/auth.js +1 -12
  56. package/routes/campaigns.js +0 -13
  57. package/routes/dataTable.js +0 -3
  58. package/routes/faq_kb.js +12 -1
  59. package/routes/messagesRoot.js +0 -1
  60. package/routes/quotes.js +38 -1
  61. package/routes/request.js +81 -5
  62. package/routes/users.js +0 -1
  63. package/routes/webhook.js +160 -8
  64. package/routes/webhooks.js +276 -6
  65. package/routes/widgetLoader.js +6 -3
  66. package/services/QuoteManager.js +77 -16
  67. package/services/aiService.js +1 -1
  68. package/services/chatbotService.js +55 -1
  69. package/services/departmentService.js +60 -43
  70. package/services/dolphinSchedulerClient.js +116 -0
  71. package/services/emailService.js +6 -1
  72. package/services/hitlParticipantListener.js +260 -0
  73. package/services/participantInviteService.js +302 -0
  74. package/services/participantRemoveService.js +79 -0
  75. package/services/quotaSnapshotService.js +1167 -0
  76. package/services/requestService.js +102 -144
  77. package/services/scheduledStart/dolphinBackend.js +246 -0
  78. package/services/scheduledStart/schedulerBackend.js +101 -0
  79. package/services/scheduledStart/schedulerServiceClient.js +41 -0
  80. package/services/scheduledStartPublishListener.js +186 -0
  81. package/services/scheduledStartRules.js +173 -0
  82. package/services/scheduledStartService.js +130 -0
  83. package/services/startPointCleanupListener.js +30 -0
  84. package/services/startPointService.js +158 -0
  85. package/services/testWsService.js +1 -4
  86. package/services/updateRequestSnapshotQueued.js +8 -9
  87. package/services/webhookConversationService.js +185 -0
  88. package/services/webhookSettingsValidator.js +61 -0
  89. package/template/email/checkpointReachedEmail.html +5 -0
  90. package/test/agentPromptsRoute.test.js +3 -2
  91. package/test/agentTokensQuota.js +237 -0
  92. package/test/botEventHitlFallback.js +19 -0
  93. package/test/chat21HandlerJoinWiring.js +59 -0
  94. package/test/dataTablesRoute.test.js +10 -2
  95. package/test/dateUtils.test.js +0 -3
  96. package/test/departmentService.js +8 -12
  97. package/test/{fileRoute.js → deprecated/_deprecated_fileRoute} +2 -2
  98. package/test/{kbsettingsRoute.js → deprecated/_deprecated_kbsettingsRoute} +3 -3
  99. package/test/faqRoute.js +6 -1
  100. package/test/faqkbRoute.js +14 -10
  101. package/test/faqkbV3Route.js +1 -1
  102. package/test/filepRoute.js +4 -50
  103. package/test/hitlParticipantListener.js +446 -0
  104. package/test/hitlQueueWiring.js +191 -0
  105. package/test/hitlWaitingReset.js +124 -0
  106. package/test/inviteParticipantsRoute.js +492 -0
  107. package/test/kbRoute.js +1 -1
  108. package/test/messageRoute.js +33 -21
  109. package/test/nativemcp.test.js +7 -1
  110. package/test/openaiRoute.js +2 -8
  111. package/test/publishFailLoud.test.js +414 -0
  112. package/test/quotaSnapshots.js +1044 -0
  113. package/test/removeParticipantsRoute.js +186 -0
  114. package/test/requestService.js +24 -16
  115. package/test/requestServiceRemoveParticipant.js +144 -0
  116. package/test/requestVisibility.test.js +186 -0
  117. package/test/scheduledStartFacade.js +184 -0
  118. package/test/scheduledStartHandover.js +95 -0
  119. package/test/scheduledStartPublish.js +320 -0
  120. package/test/scheduledStartRoute.js +163 -0
  121. package/test/scheduledStartRules.js +177 -0
  122. package/test/scheduledStartRun.js +299 -0
  123. package/test/scheduledStartSchedulerBackend.js +116 -0
  124. package/test/scheduledStartService.js +290 -0
  125. package/test/startPointsCleanup.js +69 -0
  126. package/test/startPointsRegression.js +169 -0
  127. package/test/startPointsRoute.js +158 -0
  128. package/test/webhookConversationRoute.js +347 -0
  129. package/test/webhookConversationService.js +261 -0
  130. package/test/webhookConversationTestUtils.js +55 -0
  131. package/utils/aiUtils.js +95 -1
  132. package/utils/intentFieldNames.js +192 -0
  133. package/utils/quotaCliUtil.js +43 -0
  134. package/utils/requestVisibility.js +355 -0
  135. package/websocket/webSocketServer.js +36 -31
  136. /package/test/{imageRoute.js → deprecated/_deprecated_imageRoute} +0 -0
@@ -0,0 +1,124 @@
1
+ //During the test the env variable is set to test
2
+ process.env.NODE_ENV = 'test';
3
+ process.env.LOG_LEVEL = 'error';
4
+
5
+ const chai = require('chai');
6
+ const expect = chai.expect;
7
+ const config = require('../config/database');
8
+ const mongoose = require('mongoose');
9
+
10
+ // The `users` collection has a unique (non-sparse) index on the optional `phone` field
11
+ // (see models/user.js). Multiple users without a phone number collide on the shared
12
+ // `null` key - reproduced here once this file started signing up 4 users per full run
13
+ // (owner + the uninvited-agent test). Disable autoIndex so pre-existing environment
14
+ // state doesn't break this file.
15
+ mongoose.set('autoIndex', false);
16
+ mongoose.connect(config.databasetest);
17
+ require('../services/mongoose-cache-fn')(mongoose);
18
+
19
+ const userService = require('../services/userService');
20
+ const projectService = require('../services/projectService');
21
+ const faqService = require('../services/faqService');
22
+ const requestService = require('../services/requestService');
23
+ const messageService = require('../services/messageService');
24
+ const participantInviteService = require('../services/participantInviteService');
25
+ const Request = require('../models/request');
26
+ const Project_user = require('../models/project_user');
27
+ const RoleConstants = require('../models/roleConstants');
28
+ const { uniqueEmail, PWD, waitFor } = require('./webhookConversationTestUtils');
29
+
30
+ async function addUninvitedAgent(project, owner) {
31
+ const agent = await userService.signup(uniqueEmail('test-hitl-reset-uninvited'), PWD, 'Other', 'Agent');
32
+ await new Project_user({
33
+ id_project: project._id.toString(),
34
+ id_user: agent._id.toString(),
35
+ role: RoleConstants.AGENT,
36
+ roleType: RoleConstants.TYPE_AGENTS,
37
+ user_available: true,
38
+ createdBy: owner._id.toString(),
39
+ updatedBy: owner._id.toString()
40
+ }).save();
41
+ return agent;
42
+ }
43
+
44
+ async function waitingConversation() {
45
+ const owner = await userService.signup(uniqueEmail('test-hitl-reset'), PWD, 'Owner', 'User');
46
+ const project = await projectService.create('test-hitl-reset', owner._id);
47
+ const chatbot = await faqService.create(project._id, owner._id, { name: 'hitl-bot', type: 'tilebot', language: 'en', template: 'blank' });
48
+ const request_id = 'support-group-' + project._id + '-' + Date.now() + Math.floor(Math.random() * 1000);
49
+ await requestService.create({
50
+ request_id: request_id,
51
+ id_project: project._id.toString(),
52
+ first_text: '/start',
53
+ participants: ['bot_' + chatbot._id.toString()],
54
+ channel: { name: 'webhook' },
55
+ preflight: false,
56
+ createdBy: 'system'
57
+ });
58
+ await participantInviteService.invite(project._id.toString(), request_id, { members: [owner._id.toString()] });
59
+
60
+ return { owner, project, chatbot, request_id };
61
+ }
62
+
63
+ async function statusAfter(request_id, ms = 700) {
64
+ await new Promise((resolve) => setTimeout(resolve, ms));
65
+ return Request.findOne({ request_id: request_id }).lean().exec();
66
+ }
67
+
68
+ // The listener under test runs asynchronously off message.create (populateMessageWithRequest's
69
+ // own DB round-trips, then our findOneAndUpdate + populate chain). A fixed short sleep is racy
70
+ // when this file runs alongside other suites that keep the event loop and DB busier (observed
71
+ // as an occasional "expected 'pending' to equal 'open'" flake), so tests that expect the reset
72
+ // poll for it instead of sleeping a fixed amount.
73
+ async function waitForOpen(request_id, timeout = 6000) {
74
+ return waitFor(async () => {
75
+ const request = await Request.findOne({ request_id: request_id }).lean().exec();
76
+ return request.workingStatus === 'open' ? request : null;
77
+ }, { timeout, interval: 100 });
78
+ }
79
+
80
+ describe('HITL waiting reset', function () {
81
+
82
+ this.timeout(20000);
83
+
84
+ it('reopens the conversation when the invited human writes', async () => {
85
+ const ctx = await waitingConversation();
86
+
87
+ await messageService.send(ctx.owner._id.toString(), 'Owner User', ctx.request_id, 'Approve', ctx.project._id.toString(), ctx.owner._id.toString(), {});
88
+
89
+ const request = await waitForOpen(ctx.request_id);
90
+ expect(request.workingStatus).to.equal('open');
91
+ expect(request.attributes.hitl_waiting).to.equal(undefined);
92
+ });
93
+
94
+ it('reopens the conversation on an info message carrying an action (button click)', async () => {
95
+ const ctx = await waitingConversation();
96
+
97
+ await messageService.send(ctx.owner._id.toString(), 'Owner User', ctx.request_id, 'Approve', ctx.project._id.toString(), ctx.owner._id.toString(), { subtype: 'info', action: 'approve_block' });
98
+
99
+ const request = await waitForOpen(ctx.request_id);
100
+ expect(request.workingStatus).to.equal('open');
101
+ });
102
+
103
+ it('stays pending for bot messages and plain info messages', async () => {
104
+ const ctx = await waitingConversation();
105
+
106
+ await messageService.send('bot_' + ctx.chatbot._id.toString(), 'hitl-bot', ctx.request_id, 'Restart checkout-api?', ctx.project._id.toString(), 'system', {});
107
+ await messageService.send(ctx.owner._id.toString(), 'Owner User', ctx.request_id, 'Owner joined', ctx.project._id.toString(), 'system', { subtype: 'info' });
108
+
109
+ const request = await statusAfter(ctx.request_id);
110
+ expect(request.workingStatus).to.equal('pending');
111
+ expect(request.attributes.hitl_waiting).to.equal(true);
112
+ });
113
+
114
+ it('stays pending when a human who is not an invited participant writes', async () => {
115
+ const ctx = await waitingConversation();
116
+ const outsider = await addUninvitedAgent(ctx.project, ctx.owner);
117
+
118
+ await messageService.send(outsider._id.toString(), 'Other Agent', ctx.request_id, 'Hi, can I help?', ctx.project._id.toString(), outsider._id.toString(), {});
119
+
120
+ const request = await statusAfter(ctx.request_id);
121
+ expect(request.workingStatus).to.equal('pending');
122
+ expect(request.attributes.hitl_waiting).to.equal(true);
123
+ });
124
+ });
@@ -0,0 +1,492 @@
1
+ //During the test the env variable is set to test
2
+ process.env.NODE_ENV = 'test';
3
+ process.env.LOG_LEVEL = 'error';
4
+
5
+ const chai = require('chai');
6
+ const chaiHttp = require('chai-http');
7
+ const server = require('../app');
8
+ const expect = chai.expect;
9
+ chai.use(chaiHttp);
10
+
11
+ const userService = require('../services/userService');
12
+ const projectService = require('../services/projectService');
13
+ const departmentService = require('../services/departmentService');
14
+ const faqService = require('../services/faqService');
15
+ const requestService = require('../services/requestService');
16
+ const Project_user = require('../models/project_user');
17
+ const Request = require('../models/request');
18
+ const Department = require('../models/department');
19
+ const RoleConstants = require('../models/roleConstants');
20
+ const { uniqueEmail, PWD, waitFor } = require('./webhookConversationTestUtils');
21
+
22
+ async function addAgent(project, owner, { available = true, email } = {}) {
23
+ email = email || uniqueEmail('test-invite-agent');
24
+ const agent = await userService.signup(email, PWD, 'Agent', 'Smith');
25
+ await new Project_user({
26
+ id_project: project._id.toString(),
27
+ id_user: agent._id.toString(),
28
+ role: RoleConstants.AGENT,
29
+ roleType: RoleConstants.TYPE_AGENTS,
30
+ user_available: available,
31
+ createdBy: owner._id.toString(),
32
+ updatedBy: owner._id.toString()
33
+ }).save();
34
+ return { agent, email };
35
+ }
36
+
37
+ // beforeRequest(project, owner), when given, runs after the project exists and before the
38
+ // request is created (e.g. to set up a department and its agents so any project_user query
39
+ // that requestService.create() triggers along the way already sees them - see
40
+ // departmentService.getOperators's ~30s project_user query cache, cacheEnabler.project_user /
41
+ // cacheUtil.queryTTL). Its return value (an object) is merged into the returned context.
42
+ async function setup({ ownerAvailable = true, beforeRequest } = {}) {
43
+ const ownerEmail = uniqueEmail('test-invite-owner');
44
+ const owner = await userService.signup(ownerEmail, PWD, 'Owner', 'User');
45
+ const project = await projectService.create('test-invite-participants', owner._id);
46
+ if (!ownerAvailable) {
47
+ await Project_user.findOneAndUpdate({ id_project: project._id, id_user: owner._id }, { user_available: false }).exec();
48
+ }
49
+ const chatbot = await faqService.create(project._id, owner._id, { name: 'hitl-bot', type: 'tilebot', language: 'en', template: 'blank' });
50
+ const hookResult = beforeRequest ? await beforeRequest(project, owner) : undefined;
51
+ const request = await requestService.create({
52
+ request_id: 'support-group-' + project._id + '-' + Date.now() + Math.floor(Math.random() * 1000),
53
+ id_project: project._id.toString(),
54
+ first_text: '/start',
55
+ participants: ['bot_' + chatbot._id.toString()],
56
+ channel: { name: 'webhook' },
57
+ preflight: false,
58
+ createdBy: 'system'
59
+ });
60
+ return { owner, ownerEmail, project, chatbot, request, ...(hookResult || {}) };
61
+ }
62
+
63
+ function invite(ctx, body, auth) {
64
+ const req = chai.request(server).post('/' + ctx.project._id + '/requests/' + ctx.request.request_id + '/participants/invite');
65
+ if (auth && auth.jwt) {
66
+ req.set('Authorization', 'JWT ' + auth.jwt);
67
+ } else {
68
+ req.auth(ctx.ownerEmail, PWD);
69
+ }
70
+ return req.send(body);
71
+ }
72
+
73
+ describe('InviteParticipantsRoute', function () {
74
+
75
+ this.timeout(20000);
76
+
77
+ it('invites all named members that are active agents and keeps the bot', async () => {
78
+ const ctx = await setup();
79
+ const a1 = await addAgent(ctx.project, ctx.owner);
80
+ const a2 = await addAgent(ctx.project, ctx.owner, { available: false });
81
+
82
+ const res = await invite(ctx, { members: [a1.email, a2.agent._id.toString(), 'unknown@email.com'] });
83
+
84
+ expect(res).to.have.status(200);
85
+ expect(res.body.invited.map((i) => i.id_user).sort()).to.deep.equal([a1.agent._id.toString(), a2.agent._id.toString()].sort());
86
+ expect(res.body.invited.every((i) => i.already_participant === false)).to.equal(true);
87
+
88
+ // ConciergeBot (pubmodules/rules/conciergeBot.js) reacts to a human joining asynchronously
89
+ // (fire-and-forget); wait past that window so this assertion would catch it removing the bot.
90
+ await new Promise((resolve) => setTimeout(resolve, 1000));
91
+
92
+ const request = await Request.findOne({ request_id: ctx.request.request_id }).lean().exec();
93
+ expect(request.participants).to.include('bot_' + ctx.chatbot._id.toString());
94
+ expect(request.participants).to.include(a1.agent._id.toString());
95
+ expect(request.participants).to.include(a2.agent._id.toString());
96
+ expect(request.workingStatus).to.equal('pending');
97
+ expect(request.attributes.hitl_waiting).to.equal(true);
98
+ });
99
+
100
+ it('rejects an invite into a non-webhook conversation and leaves it unchanged', async () => {
101
+ const ctx = await setup();
102
+ await Request.updateOne({ request_id: ctx.request.request_id }, { $set: { 'channel.name': 'chat21' } }).exec();
103
+ const a1 = await addAgent(ctx.project, ctx.owner);
104
+
105
+ const res = await invite(ctx, { members: [a1.email] });
106
+
107
+ expect(res).to.have.status(422);
108
+ expect(res.body.success).to.equal(false);
109
+
110
+ const request = await Request.findOne({ request_id: ctx.request.request_id }).lean().exec();
111
+ expect(request.participants).to.deep.equal(['bot_' + ctx.chatbot._id.toString()]);
112
+ expect(request.workingStatus).to.not.equal('pending');
113
+ expect(request.attributes && request.attributes.hitl_waiting).to.not.equal(true);
114
+ });
115
+
116
+ it('still hands off (removes the bot) for non-webhook conversations', async () => {
117
+ const ctx = await setup();
118
+ await Request.updateOne({ request_id: ctx.request.request_id }, { $set: { 'channel.name': 'chat21' } }).exec();
119
+ const a1 = await addAgent(ctx.project, ctx.owner);
120
+
121
+ await requestService.addParticipantByRequestId(ctx.request.request_id, ctx.project._id.toString(), a1.agent._id.toString());
122
+
123
+ const request = await waitFor(async () => {
124
+ const current = await Request.findOne({ request_id: ctx.request.request_id }).lean().exec();
125
+ return current.participants.includes('bot_' + ctx.chatbot._id.toString()) ? null : current;
126
+ }, { timeout: 3000, interval: 100 });
127
+
128
+ expect(request.participants).to.not.include('bot_' + ctx.chatbot._id.toString());
129
+ expect(request.participants).to.include(a1.agent._id.toString());
130
+ });
131
+
132
+ it('falls back to the department when no member resolves', async () => {
133
+ const ctx = await setup();
134
+
135
+ const res = await invite(ctx, { members: ['nobody@email.com'] });
136
+
137
+ expect(res).to.have.status(200);
138
+ expect(res.body.invited).to.have.length(1);
139
+ expect(res.body.invited[0].id_user).to.equal(ctx.owner._id.toString());
140
+ });
141
+
142
+ it('invites exactly one available agent from a pooled department', async () => {
143
+ const ctx = await setup({
144
+ ownerAvailable: false,
145
+ beforeRequest: async (project, owner) => {
146
+ const department = await departmentService.create('SRE pooled', project._id, 'pooled', owner._id);
147
+ const a1 = await addAgent(project, owner);
148
+ const a2 = await addAgent(project, owner);
149
+ return { department, agents: [a1, a2] };
150
+ }
151
+ });
152
+
153
+ const res = await invite(ctx, { department_id: ctx.department._id.toString() });
154
+
155
+ expect(res).to.have.status(200);
156
+ expect(res.body.invited).to.have.length(1);
157
+ expect(ctx.agents.map((a) => a.agent._id.toString())).to.include(res.body.invited[0].id_user);
158
+ expect(res.body.department_id).to.equal(ctx.department._id.toString());
159
+ });
160
+
161
+ it('counts an already-present pooled agent as invited on re-invite', async () => {
162
+ const ctx = await setup({
163
+ ownerAvailable: false,
164
+ beforeRequest: async (project, owner) => {
165
+ const department = await departmentService.create('SRE pooled solo', project._id, 'pooled', owner._id);
166
+ const agent = await addAgent(project, owner);
167
+ return { department, agent };
168
+ }
169
+ });
170
+
171
+ const first = await invite(ctx, { department_id: ctx.department._id.toString() });
172
+ expect(first).to.have.status(200);
173
+ expect(first.body.invited).to.have.length(1);
174
+ expect(first.body.invited[0].id_user).to.equal(ctx.agent.agent._id.toString());
175
+ expect(first.body.invited[0].already_participant).to.equal(false);
176
+
177
+ const second = await invite(ctx, { department_id: ctx.department._id.toString() });
178
+
179
+ expect(second).to.have.status(200);
180
+ expect(second.body.invited).to.have.length(1);
181
+ expect(second.body.invited[0].id_user).to.equal(ctx.agent.agent._id.toString());
182
+ expect(second.body.invited[0].already_participant).to.equal(true);
183
+
184
+ const request = await Request.findOne({ request_id: ctx.request.request_id }).lean().exec();
185
+ expect(request.workingStatus).to.equal('pending');
186
+ });
187
+
188
+ it('invites the operator selected by an assigned department', async () => {
189
+ const ctx = await setup();
190
+
191
+ const res = await invite(ctx, {});
192
+
193
+ expect(res).to.have.status(200);
194
+ expect(res.body.invited).to.have.length(1);
195
+ expect(res.body.invited[0].id_user).to.equal(ctx.owner._id.toString());
196
+ });
197
+
198
+ it('returns an empty invite list with a reason when nobody is available', async () => {
199
+ const ctx = await setup({ ownerAvailable: false });
200
+
201
+ const res = await invite(ctx, {});
202
+
203
+ expect(res).to.have.status(200);
204
+ expect(res.body.invited).to.deep.equal([]);
205
+ expect(res.body.reason).to.equal('no_available_agents');
206
+ const request = await Request.findOne({ request_id: ctx.request.request_id }).lean().exec();
207
+ expect(request.workingStatus).to.not.equal('pending');
208
+ });
209
+
210
+ it('reports members that are already participants', async () => {
211
+ const ctx = await setup();
212
+ const a1 = await addAgent(ctx.project, ctx.owner);
213
+ await invite(ctx, { members: [a1.email] });
214
+
215
+ const res = await invite(ctx, { members: [a1.email] });
216
+
217
+ expect(res).to.have.status(200);
218
+ expect(res.body.invited).to.have.length(1);
219
+ expect(res.body.invited[0].already_participant).to.equal(true);
220
+ });
221
+
222
+ it('invites a member looked up by a 12-character email (not mistaken for an ObjectId)', async () => {
223
+ const ctx = await setup();
224
+ // mongoose.Types.ObjectId.isValid accepts any exact 12-character string, so an email of
225
+ // this length must still be resolved by email lookup, not treated as (and fail as) an id.
226
+ const twelveCharEmail = 'x' + Math.floor(10000 + Math.random() * 90000) + '@ab.io';
227
+ expect(twelveCharEmail).to.have.length(12);
228
+ const a1 = await addAgent(ctx.project, ctx.owner, { email: twelveCharEmail });
229
+
230
+ const res = await invite(ctx, { members: [twelveCharEmail] });
231
+
232
+ expect(res).to.have.status(200);
233
+ expect(res.body.invited).to.have.length(1);
234
+ expect(res.body.invited[0].id_user).to.equal(a1.agent._id.toString());
235
+ });
236
+
237
+ it('trims whitespace around member strings and ignores empty ones', async () => {
238
+ const ctx = await setup();
239
+ const a1 = await addAgent(ctx.project, ctx.owner);
240
+
241
+ const res = await invite(ctx, { members: [' ' + a1.email + ' ', '', ' '] });
242
+
243
+ expect(res).to.have.status(200);
244
+ expect(res.body.invited).to.have.length(1);
245
+ expect(res.body.invited[0].id_user).to.equal(a1.agent._id.toString());
246
+ });
247
+
248
+ it('rejects a non-string department_id with 422', async () => {
249
+ const ctx = await setup();
250
+
251
+ const res = await invite(ctx, { department_id: 123 });
252
+
253
+ expect(res).to.have.status(422);
254
+ expect(res.body.success).to.equal(false);
255
+ expect(res.body.error).to.equal('department_id must be a string');
256
+ });
257
+
258
+ it('rejects more than 50 members with 422 before any DB work', async () => {
259
+ const ctx = await setup();
260
+ const members = [];
261
+ for (let i = 0; i < 51; i++) {
262
+ members.push('nobody' + i + '@email.com');
263
+ }
264
+
265
+ const res = await invite(ctx, { members: members });
266
+
267
+ expect(res).to.have.status(422);
268
+ expect(res.body.success).to.equal(false);
269
+ expect(res.body.error).to.equal('Too many members (max 50)');
270
+ });
271
+
272
+ it('returns 409 for a closed request and 404 for an unknown request', async () => {
273
+ const ctx = await setup();
274
+ await Request.updateOne({ request_id: ctx.request.request_id }, { $set: { status: 1000 } }).exec();
275
+
276
+ const closed = await invite(ctx, {});
277
+ expect(closed).to.have.status(409);
278
+
279
+ const unknown = await chai.request(server)
280
+ .post('/' + ctx.project._id + '/requests/support-group-unknown/participants/invite')
281
+ .auth(ctx.ownerEmail, PWD)
282
+ .send({});
283
+ expect(unknown).to.have.status(404);
284
+ });
285
+
286
+ it('accepts the bot token of the same project and rejects a bot token of another project', async () => {
287
+ const ctx = await setup();
288
+ const other = await setup();
289
+
290
+ const ownJwt = await chai.request(server).get('/' + ctx.project._id + '/faq_kb/' + ctx.chatbot._id + '/jwt').auth(ctx.ownerEmail, PWD);
291
+ const otherJwt = await chai.request(server).get('/' + other.project._id + '/faq_kb/' + other.chatbot._id + '/jwt').auth(other.ownerEmail, PWD);
292
+
293
+ const allowed = await invite(ctx, {}, { jwt: ownJwt.body.jwt });
294
+ expect(allowed).to.have.status(200);
295
+
296
+ const denied = await invite(ctx, {}, { jwt: otherJwt.body.jwt });
297
+ expect(denied).to.have.status(403);
298
+ });
299
+
300
+ it('records the invited humans, the department and the fallback block', async () => {
301
+ const ctx = await setup({ ownerAvailable: false, beforeRequest: async (project, owner) => {
302
+ const department = await departmentService.create('SRE pooled', project._id, 'pooled', owner._id);
303
+ return { department, agents: [await addAgent(project, owner)] };
304
+ }});
305
+ const res = await invite(ctx, { department_id: ctx.department._id.toString(), fallback_intent: '#noone-id' });
306
+ expect(res).to.have.status(200);
307
+ const request = await Request.findOne({ request_id: ctx.request.request_id }).lean().exec();
308
+ expect(request.attributes.hitl_invited).to.deep.equal([res.body.invited[0].id_user]);
309
+ expect(request.attributes.hitl_department_id).to.equal(ctx.department._id.toString());
310
+ expect(request.attributes.hitl_fallback).to.deep.equal({ intent: '#noone-id' });
311
+ });
312
+
313
+ it('does not record HITL context when nobody is invited', async () => {
314
+ const ctx = await setup({ ownerAvailable: false });
315
+ const res = await invite(ctx, { fallback_intent: '#noone-id' });
316
+ expect(res.body.invited).to.have.length(0);
317
+ const request = await Request.findOne({ request_id: ctx.request.request_id }).lean().exec();
318
+ expect(request.attributes && request.attributes.hitl_fallback).to.equal(undefined);
319
+ expect(request.attributes && request.attributes.hitl_invited).to.equal(undefined);
320
+ });
321
+
322
+ it('stores the default department when members are invited by email', async () => {
323
+ const ctx = await setup();
324
+ const res = await invite(ctx, { members: [ctx.ownerEmail] });
325
+ expect(res).to.have.status(200);
326
+ const defaultDepartment = await Department.findOne({ id_project: ctx.project._id, default: true }).lean().exec();
327
+ const request = await Request.findOne({ request_id: ctx.request.request_id }).lean().exec();
328
+ expect(request.attributes.hitl_department_id).to.equal(defaultDepartment._id.toString());
329
+ expect(request.attributes.hitl_invited).to.include(ctx.owner._id.toString());
330
+ });
331
+
332
+ it('replaces the fallback of an earlier invite', async () => {
333
+ const ctx = await setup({ ownerAvailable: false });
334
+ const a1 = await addAgent(ctx.project, ctx.owner);
335
+ const attrs = async () => (await Request.findOne({ request_id: ctx.request.request_id }).lean().exec()).attributes;
336
+
337
+ expect(await invite(ctx, { members: [a1.email], fallback_intent: '#first-id' })).to.have.status(200);
338
+ expect((await attrs()).hitl_fallback).to.deep.equal({ intent: '#first-id' });
339
+
340
+ expect(await invite(ctx, { members: [a1.email] })).to.have.status(200);
341
+ expect((await attrs()).hitl_fallback).to.equal(undefined);
342
+
343
+ expect(await invite(ctx, { members: [a1.email], fallback_intent: '#second-id' })).to.have.status(200);
344
+ expect((await attrs()).hitl_fallback).to.deep.equal({ intent: '#second-id' });
345
+ });
346
+
347
+ it('does not pick a human who left from the department', async () => {
348
+ const ctx = await setup({
349
+ ownerAvailable: false,
350
+ beforeRequest: async (project, owner) => {
351
+ const department = await departmentService.create('SRE pooled leaver', project._id, 'pooled', owner._id);
352
+ const a = await addAgent(project, owner);
353
+ return { department, a };
354
+ }
355
+ });
356
+ const aId = ctx.a.agent._id.toString();
357
+ await Request.updateOne({ request_id: ctx.request.request_id }, { $set: { 'attributes.hitl_left': [aId] } }).exec();
358
+
359
+ const res = await invite(ctx, { department_id: ctx.department._id.toString() });
360
+ expect(res).to.have.status(200);
361
+ expect(res.body.invited).to.deep.equal([]);
362
+ expect(res.body.reason).to.equal('no_available_agents');
363
+
364
+ const explicit = await invite(ctx, { members: [ctx.a.email] });
365
+ expect(explicit).to.have.status(200);
366
+ expect(explicit.body.invited.map((i) => i.id_user)).to.deep.equal([aId]);
367
+ });
368
+
369
+ it('rejects a non-string fallback_intent with 422', async () => {
370
+ const ctx = await setup();
371
+ const res = await invite(ctx, { fallback_intent: 42 });
372
+ expect(res).to.have.status(422);
373
+ expect(res.body.error).to.equal('fallback_intent must be a string');
374
+ });
375
+ });
376
+
377
+ // The invite answers only after chat21 has joined the invited humans to the group, so the flow's
378
+ // next message (sent as soon as the invite returns) reaches them. chat21Handler.listen() is disabled
379
+ // in tests (channelManager), so only its participants.join listener is wired here, with a stubbed
380
+ // chat21.groups.join.
381
+ describe('InviteParticipantsRoute - waits for the chat21 join', function () {
382
+
383
+ this.timeout(20000);
384
+
385
+ const requestEvent = require('../event/requestEvent');
386
+ const chat21 = require('../channels/chat21/chat21Client');
387
+ const chat21Handler = require('../channels/chat21/chat21Handler');
388
+
389
+ let originalJoin;
390
+ let listener;
391
+ let joinBehaviour;
392
+ let joinCalls;
393
+ let originalTimeout;
394
+
395
+ before(() => {
396
+ originalJoin = chat21.groups.join;
397
+ originalTimeout = process.env.HITL_CHAT21_JOIN_TIMEOUT_MS;
398
+ chat21.groups.join = (member, groupId) => {
399
+ const call = { member, groupId, settled: false };
400
+ joinCalls.push(call);
401
+ return joinBehaviour(call);
402
+ };
403
+ listener = (data) => chat21Handler.onParticipantsJoin(data);
404
+ requestEvent.on('request.participants.join', listener);
405
+ });
406
+
407
+ after(() => {
408
+ chat21.groups.join = originalJoin;
409
+ requestEvent.removeListener('request.participants.join', listener);
410
+ if (originalTimeout === undefined) {
411
+ delete process.env.HITL_CHAT21_JOIN_TIMEOUT_MS;
412
+ } else {
413
+ process.env.HITL_CHAT21_JOIN_TIMEOUT_MS = originalTimeout;
414
+ }
415
+ });
416
+
417
+ beforeEach(() => {
418
+ joinCalls = [];
419
+ delete process.env.HITL_CHAT21_JOIN_TIMEOUT_MS;
420
+ });
421
+
422
+ function delayed(ms, fail) {
423
+ return (call) => new Promise((resolve, reject) => setTimeout(() => {
424
+ call.settled = true;
425
+ return fail ? reject(new Error('chat21 join failed')) : resolve({ ok: true });
426
+ }, ms));
427
+ }
428
+
429
+ it('answers only after the chat21 join of the invited member resolved', async () => {
430
+ joinBehaviour = delayed(400);
431
+ const ctx = await setup();
432
+ const a1 = await addAgent(ctx.project, ctx.owner);
433
+
434
+ const res = await invite(ctx, { members: [a1.email] });
435
+
436
+ expect(res).to.have.status(200);
437
+ const call = joinCalls.find((c) => c.member === a1.agent._id.toString());
438
+ expect(call, 'chat21 join called for the invited member').to.exist;
439
+ expect(call.groupId).to.equal(ctx.request.request_id);
440
+ expect(call.settled, 'join settled before the response').to.equal(true);
441
+ });
442
+
443
+ it('still answers 200 at about the timeout when the join is slower', async () => {
444
+ process.env.HITL_CHAT21_JOIN_TIMEOUT_MS = '300';
445
+ joinBehaviour = delayed(3000);
446
+ const ctx = await setup();
447
+ const a1 = await addAgent(ctx.project, ctx.owner);
448
+
449
+ const started = Date.now();
450
+ const res = await invite(ctx, { members: [a1.email] });
451
+ const elapsed = Date.now() - started;
452
+
453
+ expect(res).to.have.status(200);
454
+ expect(res.body.invited.map((i) => i.id_user)).to.deep.equal([a1.agent._id.toString()]);
455
+ const call = joinCalls.find((c) => c.member === a1.agent._id.toString());
456
+ expect(call, 'chat21 join called for the invited member').to.exist;
457
+ expect(call.settled, 'answered before the slow join settled').to.equal(false);
458
+ expect(elapsed).to.be.at.least(300);
459
+ expect(elapsed).to.be.below(2500);
460
+ });
461
+
462
+ it('still answers 200 when the join fails', async () => {
463
+ joinBehaviour = delayed(200, true);
464
+ const ctx = await setup();
465
+ const a1 = await addAgent(ctx.project, ctx.owner);
466
+
467
+ const res = await invite(ctx, { members: [a1.email] });
468
+
469
+ expect(res).to.have.status(200);
470
+ const call = joinCalls.find((c) => c.member === a1.agent._id.toString());
471
+ expect(call.settled, 'join settled before the response').to.equal(true);
472
+ const request = await Request.findOne({ request_id: ctx.request.request_id }).lean().exec();
473
+ expect(request.participants).to.include(a1.agent._id.toString());
474
+ });
475
+
476
+ it('does not wait for a member that was already a participant', async () => {
477
+ joinBehaviour = delayed(50);
478
+ const ctx = await setup();
479
+ const a1 = await addAgent(ctx.project, ctx.owner);
480
+ await invite(ctx, { members: [a1.email] });
481
+
482
+ joinCalls = [];
483
+ joinBehaviour = delayed(3000);
484
+ const started = Date.now();
485
+ const res = await invite(ctx, { members: [a1.email] });
486
+
487
+ expect(res).to.have.status(200);
488
+ expect(res.body.invited[0].already_participant).to.equal(true);
489
+ expect(joinCalls).to.have.length(0);
490
+ expect(Date.now() - started).to.be.below(2500);
491
+ });
492
+ });
package/test/kbRoute.js CHANGED
@@ -246,7 +246,7 @@ describe('KbRoute', () => {
246
246
  expect(res.body.embedding.name).to.equal('text-embedding-ada-002')
247
247
  expect(res.body.embedding.dimension).to.equal(1536)
248
248
  expect(res.body.embedding.api_key).to.equal('')
249
-
249
+
250
250
  done();
251
251
  })
252
252
  })