@webex/contact-center 3.12.0-next.12 → 3.12.0-next.121

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 (307) hide show
  1. package/.sdd/manifest.json +884 -0
  2. package/AGENTS.md +94 -0
  3. package/ai-docs/ARCHITECTURE.md +168 -0
  4. package/ai-docs/CONTRACTS.md +51 -0
  5. package/ai-docs/GETTING_STARTED.md +168 -0
  6. package/ai-docs/GLOSSARY.md +43 -0
  7. package/ai-docs/README.md +138 -0
  8. package/ai-docs/REVIEW_CHECKLIST.md +41 -0
  9. package/ai-docs/RULES.md +444 -0
  10. package/ai-docs/SECURITY.md +52 -0
  11. package/ai-docs/SERVICE_STATE.md +48 -0
  12. package/ai-docs/SPEC_INDEX.md +65 -0
  13. package/ai-docs/adr/0001-spec-source-policy.md +55 -0
  14. package/ai-docs/adr/README.md +8 -0
  15. package/ai-docs/adr/_adr-template.md +31 -0
  16. package/ai-docs/contact-center-spec.md +359 -0
  17. package/ai-docs/features/consult-transfer-list-policy/spec/feature-spec.md +362 -0
  18. package/ai-docs/features/generated-spec-conformance-fidelity-remediation/spec/feature-spec.md +117 -0
  19. package/ai-docs/features/residual-warning-coverage-completion/spec/feature-spec.md +203 -0
  20. package/ai-docs/features/validator-code-fidelity-drift-fix/spec/feature-spec.md +315 -0
  21. package/ai-docs/patterns/event-driven-patterns.md +485 -0
  22. package/ai-docs/patterns/testing-patterns.md +480 -0
  23. package/ai-docs/patterns/typescript-patterns.md +365 -0
  24. package/ai-docs/templates/README.md +102 -0
  25. package/ai-docs/templates/documentation/create-agents-md.md +240 -0
  26. package/ai-docs/templates/documentation/create-architecture-md.md +295 -0
  27. package/ai-docs/templates/existing-service/bug-fix.md +254 -0
  28. package/ai-docs/templates/existing-service/feature-enhancement.md +450 -0
  29. package/ai-docs/templates/new-method/00-master.md +80 -0
  30. package/ai-docs/templates/new-method/01-requirements.md +232 -0
  31. package/ai-docs/templates/new-method/02-implementation.md +295 -0
  32. package/ai-docs/templates/new-method/03-tests.md +201 -0
  33. package/ai-docs/templates/new-method/04-validation.md +141 -0
  34. package/ai-docs/templates/new-service/00-master.md +109 -0
  35. package/ai-docs/templates/new-service/01-pre-questions.md +159 -0
  36. package/ai-docs/templates/new-service/02-code-generation.md +346 -0
  37. package/ai-docs/templates/new-service/03-integration.md +178 -0
  38. package/ai-docs/templates/new-service/04-test-generation.md +205 -0
  39. package/ai-docs/templates/new-service/05-validation.md +145 -0
  40. package/dist/cc.js +808 -40
  41. package/dist/cc.js.map +1 -1
  42. package/dist/config.js +13 -0
  43. package/dist/config.js.map +1 -1
  44. package/dist/constants.js +27 -3
  45. package/dist/constants.js.map +1 -1
  46. package/dist/index.js +20 -5
  47. package/dist/index.js.map +1 -1
  48. package/dist/metrics/MetricsManager.js +16 -0
  49. package/dist/metrics/MetricsManager.js.map +1 -1
  50. package/dist/metrics/behavioral-events.js +205 -0
  51. package/dist/metrics/behavioral-events.js.map +1 -1
  52. package/dist/metrics/constants.js +43 -4
  53. package/dist/metrics/constants.js.map +1 -1
  54. package/dist/services/AddressBook.js +18 -15
  55. package/dist/services/AddressBook.js.map +1 -1
  56. package/dist/services/AnswerCallOnWebexService.js +202 -0
  57. package/dist/services/AnswerCallOnWebexService.js.map +1 -0
  58. package/dist/services/ApiAiAssistant.js +153 -8
  59. package/dist/services/ApiAiAssistant.js.map +1 -1
  60. package/dist/services/EntryPoint.js +46 -68
  61. package/dist/services/EntryPoint.js.map +1 -1
  62. package/dist/services/Queue.js +27 -22
  63. package/dist/services/Queue.js.map +1 -1
  64. package/dist/services/UserPreference.js +427 -0
  65. package/dist/services/UserPreference.js.map +1 -0
  66. package/dist/services/WebexCrossClientService.js +222 -0
  67. package/dist/services/WebexCrossClientService.js.map +1 -0
  68. package/dist/services/WxAppTelephonyMercurySync.js +108 -0
  69. package/dist/services/WxAppTelephonyMercurySync.js.map +1 -0
  70. package/dist/services/config/Util.js +6 -3
  71. package/dist/services/config/Util.js.map +1 -1
  72. package/dist/services/config/constants.js +33 -8
  73. package/dist/services/config/constants.js.map +1 -1
  74. package/dist/services/config/types.js +53 -9
  75. package/dist/services/config/types.js.map +1 -1
  76. package/dist/services/core/Err.js.map +1 -1
  77. package/dist/services/core/Utils.js +107 -32
  78. package/dist/services/core/Utils.js.map +1 -1
  79. package/dist/services/core/WebexRequest.js +6 -2
  80. package/dist/services/core/WebexRequest.js.map +1 -1
  81. package/dist/services/core/aqm-reqs.js +28 -14
  82. package/dist/services/core/aqm-reqs.js.map +1 -1
  83. package/dist/services/core/types.js.map +1 -1
  84. package/dist/services/core/websocket/WebSocketManager.js +2 -1
  85. package/dist/services/core/websocket/WebSocketManager.js.map +1 -1
  86. package/dist/services/core/websocket/types.js.map +1 -1
  87. package/dist/services/index.js +1 -1
  88. package/dist/services/index.js.map +1 -1
  89. package/dist/services/task/Task.js +754 -0
  90. package/dist/services/task/Task.js.map +1 -0
  91. package/dist/services/task/TaskFactory.js +49 -0
  92. package/dist/services/task/TaskFactory.js.map +1 -0
  93. package/dist/services/task/TaskManager.js +1053 -520
  94. package/dist/services/task/TaskManager.js.map +1 -1
  95. package/dist/services/task/TaskUtils.js +211 -27
  96. package/dist/services/task/TaskUtils.js.map +1 -1
  97. package/dist/services/task/WebexCallingUtils.js +70 -0
  98. package/dist/services/task/WebexCallingUtils.js.map +1 -0
  99. package/dist/services/task/constants.js +12 -2
  100. package/dist/services/task/constants.js.map +1 -1
  101. package/dist/services/task/contact.js +29 -0
  102. package/dist/services/task/contact.js.map +1 -1
  103. package/dist/services/task/dialer.js +78 -0
  104. package/dist/services/task/dialer.js.map +1 -1
  105. package/dist/services/task/digital/Digital.js +78 -0
  106. package/dist/services/task/digital/Digital.js.map +1 -0
  107. package/dist/services/task/state-machine/TaskStateMachine.js +954 -0
  108. package/dist/services/task/state-machine/TaskStateMachine.js.map +1 -0
  109. package/dist/services/task/state-machine/actions.js +572 -0
  110. package/dist/services/task/state-machine/actions.js.map +1 -0
  111. package/dist/services/task/state-machine/constants.js +161 -0
  112. package/dist/services/task/state-machine/constants.js.map +1 -0
  113. package/dist/services/task/state-machine/guards.js +379 -0
  114. package/dist/services/task/state-machine/guards.js.map +1 -0
  115. package/dist/services/task/state-machine/index.js +53 -0
  116. package/dist/services/task/state-machine/index.js.map +1 -0
  117. package/dist/services/task/state-machine/types.js +54 -0
  118. package/dist/services/task/state-machine/types.js.map +1 -0
  119. package/dist/services/task/state-machine/uiControlsComputer.js +703 -0
  120. package/dist/services/task/state-machine/uiControlsComputer.js.map +1 -0
  121. package/dist/services/task/taskDataNormalizer.js +99 -0
  122. package/dist/services/task/taskDataNormalizer.js.map +1 -0
  123. package/dist/services/task/types.js +228 -5
  124. package/dist/services/task/types.js.map +1 -1
  125. package/dist/services/task/voice/Voice.js +1447 -0
  126. package/dist/services/task/voice/Voice.js.map +1 -0
  127. package/dist/services/task/voice/WebRTC.js +152 -0
  128. package/dist/services/task/voice/WebRTC.js.map +1 -0
  129. package/dist/services/task/voice/wxAppVoiceMethods.js +354 -0
  130. package/dist/services/task/voice/wxAppVoiceMethods.js.map +1 -0
  131. package/dist/services/wxAppDiagnosticLogging.js +122 -0
  132. package/dist/services/wxAppDiagnosticLogging.js.map +1 -0
  133. package/dist/services/wxAppTelephonyUtils.js +19 -0
  134. package/dist/services/wxAppTelephonyUtils.js.map +1 -0
  135. package/dist/types/cc.d.ts +172 -5
  136. package/dist/types/config.d.ts +13 -0
  137. package/dist/types/constants.d.ts +25 -1
  138. package/dist/types/index.d.ts +24 -7
  139. package/dist/types/metrics/MetricsManager.d.ts +6 -0
  140. package/dist/types/metrics/constants.d.ts +38 -1
  141. package/dist/types/services/AddressBook.d.ts +2 -1
  142. package/dist/types/services/AnswerCallOnWebexService.d.ts +38 -0
  143. package/dist/types/services/ApiAiAssistant.d.ts +22 -4
  144. package/dist/types/services/EntryPoint.d.ts +7 -5
  145. package/dist/types/services/Queue.d.ts +5 -3
  146. package/dist/types/services/UserPreference.d.ts +118 -0
  147. package/dist/types/services/WebexCrossClientService.d.ts +32 -0
  148. package/dist/types/services/WxAppTelephonyMercurySync.d.ts +28 -0
  149. package/dist/types/services/config/constants.d.ts +29 -5
  150. package/dist/types/services/config/types.d.ts +184 -10
  151. package/dist/types/services/core/Err.d.ts +6 -0
  152. package/dist/types/services/core/Utils.d.ts +33 -13
  153. package/dist/types/services/core/WebexRequest.d.ts +1 -0
  154. package/dist/types/services/core/types.d.ts +2 -0
  155. package/dist/types/services/core/websocket/WebSocketManager.d.ts +1 -0
  156. package/dist/types/services/core/websocket/types.d.ts +1 -1
  157. package/dist/types/services/index.d.ts +1 -1
  158. package/dist/types/services/task/Task.d.ts +175 -0
  159. package/dist/types/services/task/TaskFactory.d.ts +13 -0
  160. package/dist/types/services/task/TaskUtils.d.ts +48 -2
  161. package/dist/types/services/task/WebexCallingUtils.d.ts +11 -0
  162. package/dist/types/services/task/constants.d.ts +10 -0
  163. package/dist/types/services/task/contact.d.ts +4 -0
  164. package/dist/types/services/task/dialer.d.ts +30 -0
  165. package/dist/types/services/task/digital/Digital.d.ts +22 -0
  166. package/dist/types/services/task/state-machine/TaskStateMachine.d.ts +1356 -0
  167. package/dist/types/services/task/state-machine/actions.d.ts +10 -0
  168. package/dist/types/services/task/state-machine/constants.d.ts +107 -0
  169. package/dist/types/services/task/state-machine/guards.d.ts +103 -0
  170. package/dist/types/services/task/state-machine/index.d.ts +13 -0
  171. package/dist/types/services/task/state-machine/types.d.ts +277 -0
  172. package/dist/types/services/task/state-machine/uiControlsComputer.d.ts +9 -0
  173. package/dist/types/services/task/taskDataNormalizer.d.ts +10 -0
  174. package/dist/types/services/task/types.d.ts +680 -66
  175. package/dist/types/services/task/voice/Voice.d.ts +227 -0
  176. package/dist/types/services/task/voice/WebRTC.d.ts +53 -0
  177. package/dist/types/services/task/voice/wxAppVoiceMethods.d.ts +55 -0
  178. package/dist/types/services/wxAppDiagnosticLogging.d.ts +51 -0
  179. package/dist/types/services/wxAppTelephonyUtils.d.ts +5 -0
  180. package/dist/types/types.d.ts +149 -8
  181. package/dist/types/utils/PageCache.d.ts +20 -3
  182. package/dist/types/webex.d.ts +1 -0
  183. package/dist/types.js +125 -4
  184. package/dist/types.js.map +1 -1
  185. package/dist/utils/PageCache.js +19 -5
  186. package/dist/utils/PageCache.js.map +1 -1
  187. package/dist/webex.js +14 -2
  188. package/dist/webex.js.map +1 -1
  189. package/package.json +16 -12
  190. package/src/cc.ts +986 -42
  191. package/src/config.ts +13 -0
  192. package/src/constants.ts +25 -1
  193. package/src/index.ts +25 -5
  194. package/src/metrics/MetricsManager.ts +16 -0
  195. package/src/metrics/ai-docs/AGENTS.md +350 -0
  196. package/src/metrics/ai-docs/ARCHITECTURE.md +338 -0
  197. package/src/metrics/ai-docs/metrics-spec.md +922 -0
  198. package/src/metrics/behavioral-events.ts +212 -0
  199. package/src/metrics/constants.ts +47 -4
  200. package/src/services/AddressBook.ts +17 -6
  201. package/src/services/AnswerCallOnWebexService.ts +239 -0
  202. package/src/services/ApiAiAssistant.ts +203 -8
  203. package/src/services/EntryPoint.ts +59 -60
  204. package/src/services/Queue.ts +29 -12
  205. package/src/services/UserPreference.ts +509 -0
  206. package/src/services/WebexCrossClientService.ts +293 -0
  207. package/src/services/WxAppTelephonyMercurySync.ts +142 -0
  208. package/src/services/agent/ai-docs/AGENTS.md +240 -0
  209. package/src/services/agent/ai-docs/ARCHITECTURE.md +304 -0
  210. package/src/services/agent/ai-docs/agent-spec.md +505 -0
  211. package/src/services/ai-docs/AGENTS.md +386 -0
  212. package/src/services/ai-docs/services-spec.md +497 -0
  213. package/src/services/config/Util.ts +6 -3
  214. package/src/services/config/ai-docs/AGENTS.md +255 -0
  215. package/src/services/config/ai-docs/ARCHITECTURE.md +426 -0
  216. package/src/services/config/ai-docs/config-spec.md +675 -0
  217. package/src/services/config/constants.ts +35 -7
  218. package/src/services/config/types.ts +186 -11
  219. package/src/services/core/Err.ts +3 -0
  220. package/src/services/core/Utils.ts +123 -37
  221. package/src/services/core/WebexRequest.ts +3 -1
  222. package/src/services/core/ai-docs/AGENTS.md +381 -0
  223. package/src/services/core/ai-docs/ARCHITECTURE.md +698 -0
  224. package/src/services/core/ai-docs/core-spec.md +787 -0
  225. package/src/services/core/aqm-reqs.ts +30 -15
  226. package/src/services/core/types.ts +2 -0
  227. package/src/services/core/websocket/WebSocketManager.ts +2 -0
  228. package/src/services/core/websocket/types.ts +1 -1
  229. package/src/services/index.ts +1 -1
  230. package/src/services/task/Task.ts +908 -0
  231. package/src/services/task/TaskFactory.ts +60 -0
  232. package/src/services/task/TaskManager.ts +1239 -608
  233. package/src/services/task/TaskUtils.ts +303 -25
  234. package/src/services/task/WebexCallingUtils.ts +136 -0
  235. package/src/services/task/ai-docs/AGENTS.md +457 -0
  236. package/src/services/task/ai-docs/ARCHITECTURE.md +595 -0
  237. package/src/services/task/ai-docs/task-spec.md +1470 -0
  238. package/src/services/task/constants.ts +10 -0
  239. package/src/services/task/contact.ts +30 -0
  240. package/src/services/task/dialer.ts +80 -0
  241. package/src/services/task/digital/Digital.ts +97 -0
  242. package/src/services/task/state-machine/TaskStateMachine.ts +1293 -0
  243. package/src/services/task/state-machine/actions.ts +741 -0
  244. package/src/services/task/state-machine/ai-docs/AGENTS.md +460 -0
  245. package/src/services/task/state-machine/ai-docs/ARCHITECTURE.md +1145 -0
  246. package/src/services/task/state-machine/ai-docs/task-state-machine-spec.md +2207 -0
  247. package/src/services/task/state-machine/constants.ts +172 -0
  248. package/src/services/task/state-machine/guards.ts +442 -0
  249. package/src/services/task/state-machine/index.ts +28 -0
  250. package/src/services/task/state-machine/types.ts +258 -0
  251. package/src/services/task/state-machine/uiControlsComputer.ts +1135 -0
  252. package/src/services/task/taskDataNormalizer.ts +137 -0
  253. package/src/services/task/types.ts +819 -70
  254. package/src/services/task/voice/Voice.ts +1809 -0
  255. package/src/services/task/voice/WebRTC.ts +191 -0
  256. package/src/services/task/voice/wxAppVoiceMethods.ts +516 -0
  257. package/src/services/wxAppDiagnosticLogging.ts +174 -0
  258. package/src/services/wxAppTelephonyUtils.ts +14 -0
  259. package/src/types.ts +199 -11
  260. package/src/utils/AGENTS.md +289 -0
  261. package/src/utils/PageCache.ts +38 -5
  262. package/src/utils/ai-docs/utils-spec.md +391 -0
  263. package/src/webex.js +2 -0
  264. package/test/unit/spec/cc.ts +1947 -124
  265. package/test/unit/spec/logger-proxy.ts +70 -0
  266. package/test/unit/spec/metrics/MetricsManager.ts +25 -0
  267. package/test/unit/spec/metrics/behavioral-events.ts +60 -0
  268. package/test/unit/spec/services/AddressBook.ts +37 -6
  269. package/test/unit/spec/services/AnswerCallOnWebexService.ts +264 -0
  270. package/test/unit/spec/services/ApiAiAssistant.ts +178 -20
  271. package/test/unit/spec/services/EntryPoint.ts +87 -40
  272. package/test/unit/spec/services/Queue.ts +123 -12
  273. package/test/unit/spec/services/UserPreference.ts +401 -0
  274. package/test/unit/spec/services/WebCallingService.ts +7 -1
  275. package/test/unit/spec/services/WebexCrossClientService.ts +467 -0
  276. package/test/unit/spec/services/WxAppTelephonyMercurySync.ts +136 -0
  277. package/test/unit/spec/services/config/Util.ts +85 -0
  278. package/test/unit/spec/services/config/index.ts +30 -30
  279. package/test/unit/spec/services/core/Utils.ts +425 -8
  280. package/test/unit/spec/services/core/WebexRequest.ts +3 -1
  281. package/test/unit/spec/services/core/aqm-reqs.ts +113 -1
  282. package/test/unit/spec/services/core/websocket/WebSocketManager.ts +66 -40
  283. package/test/unit/spec/services/task/AutoWrapup.ts +63 -0
  284. package/test/unit/spec/services/task/Task.ts +677 -0
  285. package/test/unit/spec/services/task/TaskFactory.ts +99 -0
  286. package/test/unit/spec/services/task/TaskManager.ts +1972 -1549
  287. package/test/unit/spec/services/task/TaskUtils.ts +235 -0
  288. package/test/unit/spec/services/task/WebexCallingUtils.ts +153 -0
  289. package/test/unit/spec/services/task/contact.ts +33 -0
  290. package/test/unit/spec/services/task/dialer.ts +190 -0
  291. package/test/unit/spec/services/task/digital/Digital.ts +105 -0
  292. package/test/unit/spec/services/task/state-machine/TaskStateMachine.ts +3459 -0
  293. package/test/unit/spec/services/task/state-machine/guards.ts +839 -0
  294. package/test/unit/spec/services/task/state-machine/types.ts +18 -0
  295. package/test/unit/spec/services/task/state-machine/uiControlsComputer.ts +3101 -0
  296. package/test/unit/spec/services/task/taskTestUtils.ts +87 -0
  297. package/test/unit/spec/services/task/voice/Voice.ts +1903 -0
  298. package/test/unit/spec/services/task/voice/WebRTC.ts +235 -0
  299. package/test/unit/spec/services/task/voice/wxAppVoiceMethods.ts +603 -0
  300. package/test/unit/spec/services/wxAppDiagnosticLogging.ts +143 -0
  301. package/umd/contact-center.min.js +2 -2
  302. package/umd/contact-center.min.js.map +1 -1
  303. package/dist/services/task/index.js +0 -1525
  304. package/dist/services/task/index.js.map +0 -1
  305. package/dist/types/services/task/index.d.ts +0 -650
  306. package/src/services/task/index.ts +0 -1801
  307. package/test/unit/spec/services/task/index.ts +0 -2184
@@ -5,16 +5,21 @@ import {CALL_EVENT_KEYS, CallingClientConfig, LINE_EVENTS} from '@webex/calling'
5
5
  import {CC_AGENT_EVENTS, CC_EVENTS} from '../../../../../src/services/config/types';
6
6
  import TaskManager from '../../../../../src/services/task/TaskManager';
7
7
  import * as contact from '../../../../../src/services/task/contact';
8
- import Task from '../../../../../src/services/task';
8
+ import Task from '../../../../../src/services/task/Task';
9
9
  import {TASK_EVENTS} from '../../../../../src/services/task/types';
10
+ import {TaskEvent} from '../../../../../src/services/task/state-machine';
11
+ import WebRTC from '../../../../../src/services/task/voice/WebRTC';
12
+ import {Profile} from '../../../../../src/services/config/types';
10
13
  import WebCallingService from '../../../../../src/services/WebCallingService';
11
14
  import config from '../../../../../src/config';
12
15
  import {CC_TASK_EVENTS} from '../../../../../src/services/config/types';
16
+ import TaskFactory from '../../../../../src/services/task/TaskFactory';
13
17
 
14
18
  describe('TaskManager', () => {
15
19
  let mockCall;
16
20
  let mockApiAIAssistant;
17
21
  let webSocketManagerMock;
22
+ let rtdWebSocketManagerMock;
18
23
  let onSpy;
19
24
  let offSpy;
20
25
  let taskManager;
@@ -24,6 +29,111 @@ describe('TaskManager', () => {
24
29
  let webex: WebexSDK;
25
30
  const taskId = '0ae913a4-c857-4705-8d49-76dd3dde75e4';
26
31
 
32
+ const createMockTask = (data = taskDataMock) => {
33
+ const task = new EventEmitter() as any;
34
+
35
+ const updateTaskData = jest.fn().mockImplementation((newData) => {
36
+ task.data = {...task.data, ...newData};
37
+ return task;
38
+ });
39
+
40
+ Object.assign(task, {
41
+ data,
42
+ accept: jest.fn(),
43
+ decline: jest.fn(),
44
+ updateTaskData,
45
+ unregisterWebCallListeners: jest.fn(),
46
+ cancelAutoWrapupTimer: jest.fn(),
47
+ });
48
+
49
+ const taskEventMap: Partial<Record<TaskEvent, string>> = {
50
+ [TaskEvent.TASK_INCOMING]: TASK_EVENTS.TASK_INCOMING,
51
+ [TaskEvent.TASK_OFFERED]: TASK_EVENTS.TASK_OFFER_CONTACT,
52
+ [TaskEvent.OFFER_CONSULT]: TASK_EVENTS.TASK_OFFER_CONSULT,
53
+ [TaskEvent.HYDRATE]: TASK_EVENTS.TASK_HYDRATE,
54
+ [TaskEvent.CONTACT_OWNER_CHANGED]: TASK_EVENTS.TASK_HYDRATE,
55
+ [TaskEvent.ASSIGN]: TASK_EVENTS.TASK_ASSIGNED,
56
+ [TaskEvent.HOLD_SUCCESS]: TASK_EVENTS.TASK_HOLD,
57
+ [TaskEvent.UNHOLD_SUCCESS]: TASK_EVENTS.TASK_RESUME,
58
+ [TaskEvent.CONSULT_CREATED]: TASK_EVENTS.TASK_CONSULT_CREATED,
59
+ [TaskEvent.CONSULTING_ACTIVE]: TASK_EVENTS.TASK_CONSULT_ACCEPTED,
60
+ [TaskEvent.CONSULT_END]: TASK_EVENTS.TASK_CONSULT_END,
61
+ [TaskEvent.CONSULT_FAILED]: CC_EVENTS.AGENT_CONSULT_FAILED,
62
+ [TaskEvent.CTQ_CANCEL]: TASK_EVENTS.TASK_CONSULT_QUEUE_CANCELLED,
63
+ [TaskEvent.CTQ_CANCEL_FAILED]: TASK_EVENTS.TASK_CONSULT_QUEUE_FAILED,
64
+ [TaskEvent.END]: TASK_EVENTS.TASK_END,
65
+ [TaskEvent.CONTACT_ENDED]: TASK_EVENTS.TASK_END,
66
+ [TaskEvent.ASSIGN_FAILED]: TASK_EVENTS.TASK_REJECT,
67
+ [TaskEvent.INVITE_FAILED]: TASK_EVENTS.TASK_REJECT,
68
+ [TaskEvent.RONA]: TASK_EVENTS.TASK_REJECT,
69
+ [TaskEvent.OUTBOUND_FAILED]: TASK_EVENTS.TASK_OUTDIAL_FAILED,
70
+ [TaskEvent.RECORDING_STARTED]: TASK_EVENTS.TASK_RECORDING_STARTED,
71
+ [TaskEvent.PAUSE_RECORDING]: TASK_EVENTS.TASK_RECORDING_PAUSED,
72
+ [TaskEvent.RESUME_RECORDING]: TASK_EVENTS.TASK_RECORDING_RESUMED,
73
+ [TaskEvent.WRAPUP_COMPLETE]: TASK_EVENTS.TASK_WRAPPEDUP,
74
+ };
75
+
76
+ task.sendStateMachineEvent = jest.fn().mockImplementation((event) => {
77
+ if (event.taskData) {
78
+ task.updateTaskData(event.taskData);
79
+ }
80
+
81
+ const mappedEvent = taskEventMap[event.type as TaskEvent];
82
+ if (mappedEvent) {
83
+ if (
84
+ [TaskEvent.ASSIGN_FAILED, TaskEvent.RONA, TaskEvent.INVITE_FAILED].includes(
85
+ event.type as TaskEvent
86
+ )
87
+ ) {
88
+ task.emit(mappedEvent, event.reason ?? event.taskData?.reason);
89
+ } else if (event.type === TaskEvent.OUTBOUND_FAILED) {
90
+ if (!event.taskData?.suppressOutdialFailedPopup) {
91
+ task.emit(mappedEvent, event.reason);
92
+ }
93
+ } else {
94
+ task.emit(mappedEvent, task);
95
+ }
96
+ }
97
+
98
+ if ([TaskEvent.ASSIGN, TaskEvent.CONSULTING_ACTIVE].includes(event.type as TaskEvent)) {
99
+ task.emit(TASK_EVENTS.TASK_MULTI_LOGIN_HYDRATE, task);
100
+ }
101
+
102
+ // Auto-answer is now handled at the Task layer (triggered by state machine actions)
103
+ if (
104
+ [TaskEvent.TASK_OFFERED, TaskEvent.OFFER_CONSULT].includes(event.type as TaskEvent) &&
105
+ (event.taskData?.isAutoAnswering === true || event.taskData?.isAutoAnswering === 'true')
106
+ ) {
107
+ Promise.resolve(task.accept())
108
+ .then(() => {
109
+ task.emit(TASK_EVENTS.TASK_AUTO_ANSWERED, task);
110
+ })
111
+ .catch(() => undefined);
112
+ }
113
+
114
+ // Cleanup is now emitted by state machine actions (Task layer).
115
+ // Simulate the TASK_CLEANUP emission for unit tests using mock tasks.
116
+ const eventType = event.type as TaskEvent;
117
+ const shouldCleanup =
118
+ eventType === TaskEvent.CONTACT_ENDED ||
119
+ eventType === TaskEvent.END ||
120
+ eventType === TaskEvent.TASK_WRAPUP ||
121
+ eventType === TaskEvent.WRAPUP_COMPLETE ||
122
+ eventType === TaskEvent.ASSIGN_FAILED ||
123
+ eventType === TaskEvent.INVITE_FAILED ||
124
+ eventType === TaskEvent.RONA ||
125
+ eventType === TaskEvent.OUTBOUND_FAILED ||
126
+ (eventType === TaskEvent.CONSULT_END && task.data?.isConsulted === true);
127
+
128
+ if (shouldCleanup) {
129
+ const removeFromCollection = eventType !== TaskEvent.CONTACT_ENDED;
130
+ task.emit(TASK_EVENTS.TASK_CLEANUP, task, {removeFromCollection});
131
+ }
132
+ });
133
+
134
+ return task;
135
+ };
136
+
27
137
  taskDataMock = {
28
138
  type: CC_EVENTS.AGENT_CONTACT_RESERVED,
29
139
  agentId: '723a8ffb-a26e-496d-b14a-ff44fb83b64f',
@@ -43,18 +153,21 @@ describe('TaskManager', () => {
43
153
  data: taskDataMock,
44
154
  };
45
155
 
156
+ const expectLastStateMachineEvent = (
157
+ spy: jest.SpyInstance | jest.Mock,
158
+ expectedType: TaskEvent
159
+ ) => {
160
+ expect(spy).toHaveBeenCalled();
161
+ const lastCall = spy.mock.calls[spy.mock.calls.length - 1] || [];
162
+ const event = lastCall[3]?.type ? lastCall[3] : lastCall[0];
163
+ expect(event?.type).toBe(expectedType);
164
+ return event;
165
+ };
166
+
46
167
  beforeEach(() => {
47
168
  contactMock = contact;
48
169
  webSocketManagerMock = new EventEmitter();
49
- mockApiAIAssistant = {
50
- sendEvent: jest.fn().mockResolvedValue({}),
51
- setAIFeatureFlags: jest.fn(),
52
- aiFeature: {
53
- realtimeTranscripts: {
54
- enable: true,
55
- },
56
- },
57
- };
170
+ rtdWebSocketManagerMock = new EventEmitter();
58
171
 
59
172
  webex = {
60
173
  logger: {
@@ -84,20 +197,25 @@ describe('TaskManager', () => {
84
197
  onSpy = jest.spyOn(webCallingService, 'on');
85
198
  offSpy = jest.spyOn(webCallingService, 'off');
86
199
 
87
- taskManager = new TaskManager(mockApiAIAssistant, contactMock, webCallingService, webSocketManagerMock);
88
- const taskMock = {
89
- emit: jest.fn(),
90
- accept: jest.fn(),
91
- decline: jest.fn(),
92
- updateTaskData: jest.fn().mockImplementation((updatedData) => {
93
- taskMock.data = {...taskMock.data, ...updatedData};
94
- return taskMock;
95
- }),
96
- data: taskDataMock,
200
+ mockApiAIAssistant = {
201
+ sendEvent: jest.fn().mockResolvedValue({}),
97
202
  };
98
- taskManager.taskCollection[taskId] = taskMock;
99
- taskManager.agentId = 'test-agent-id';
203
+
204
+ taskManager = new TaskManager(
205
+ mockApiAIAssistant as any,
206
+ contactMock,
207
+ webCallingService,
208
+ webSocketManagerMock as any,
209
+ rtdWebSocketManagerMock as any
210
+ );
211
+ taskManager.taskCollection[taskId] = createMockTask(taskDataMock);
212
+ (taskManager as any).setupTaskListeners?.(taskManager.taskCollection[taskId]);
100
213
  taskManager.call = mockCall;
214
+ taskManager.setAgentId('test-agent-id');
215
+
216
+ jest
217
+ .spyOn(TaskFactory, 'createTask')
218
+ .mockImplementation((contact, webCallingService, data, configFlags) => createMockTask(data));
101
219
  });
102
220
 
103
221
  afterEach(() => {
@@ -108,7 +226,8 @@ describe('TaskManager', () => {
108
226
  it('should initialize TaskManager and register listeners', () => {
109
227
  webSocketManagerMock.emit('message', JSON.stringify({data: taskDataMock}));
110
228
  const incomingCallCb = onSpy.mock.calls[0][1];
111
- const taskEmitSpy = jest.spyOn(taskManager, 'emit');
229
+ const incomingHandler = jest.fn();
230
+ taskManager.on(TASK_EVENTS.TASK_INCOMING, incomingHandler);
112
231
 
113
232
  expect(taskManager).toBeInstanceOf(TaskManager);
114
233
  expect(webCallingService.listenerCount(LINE_EVENTS.INCOMING_CALL)).toBe(1);
@@ -117,10 +236,8 @@ describe('TaskManager', () => {
117
236
 
118
237
  incomingCallCb(mockCall);
119
238
 
120
- expect(taskEmitSpy).toHaveBeenCalledWith(
121
- TASK_EVENTS.TASK_INCOMING,
122
- taskManager.getTask(taskId)
123
- );
239
+ expect(incomingHandler).toHaveBeenCalledWith(taskManager.getTask(taskId));
240
+ taskManager.off(TASK_EVENTS.TASK_INCOMING, incomingHandler);
124
241
  });
125
242
 
126
243
  it('should re-emit task related events', () => {
@@ -136,15 +253,32 @@ describe('TaskManager', () => {
136
253
 
137
254
  webSocketManagerMock.emit('message', JSON.stringify(dummyPayload));
138
255
 
139
- expect(taskEmitSpy).toHaveBeenCalledWith(dummyPayload.data.type, dummyPayload.data);
256
+ expect(taskEmitSpy).toHaveBeenCalledWith(
257
+ TASK_EVENTS.TASK_CONSULT_ACCEPTED,
258
+ taskManager.getTask(taskId)
259
+ );
140
260
  });
141
261
 
142
262
  it('should invoke sendEvent for configured start/stop backend events', () => {
263
+ taskManager.setConfigFlags({
264
+ isEndTaskEnabled: true,
265
+ isEndConsultEnabled: true,
266
+ webRtcEnabled: true,
267
+ autoWrapup: false,
268
+ aiFeature: {
269
+ id: 'ai-feature-1',
270
+ realtimeTranscripts: {
271
+ enable: true,
272
+ },
273
+ },
274
+ });
275
+
276
+ const interactionId = taskId;
143
277
  const message = (type: CC_EVENTS) =>
144
278
  JSON.stringify({
145
279
  data: {
146
280
  ...taskDataMock,
147
- taskId,
281
+ interactionId,
148
282
  type,
149
283
  },
150
284
  });
@@ -153,67 +287,114 @@ describe('TaskManager', () => {
153
287
  webSocketManagerMock.emit('message', message(CC_EVENTS.AGENT_CONSULTING));
154
288
  webSocketManagerMock.emit('message', message(CC_EVENTS.AGENT_CONSULT_CONFERENCED));
155
289
  webSocketManagerMock.emit('message', message(CC_EVENTS.AGENT_CONSULT_ENDED));
156
- webSocketManagerMock.emit('message', message(CC_EVENTS.AGENT_WRAPUP));
157
290
  webSocketManagerMock.emit('message', message(CC_EVENTS.PARTICIPANT_LEFT_CONFERENCE));
291
+ webSocketManagerMock.emit('message', message(CC_EVENTS.AGENT_WRAPUP));
158
292
 
159
293
  expect(mockApiAIAssistant.sendEvent).toHaveBeenCalledTimes(6);
160
294
  expect(mockApiAIAssistant.sendEvent).toHaveBeenCalledWith(
161
295
  'test-agent-id',
162
- taskId,
296
+ interactionId,
163
297
  'CUSTOM_EVENT',
164
298
  'GET_TRANSCRIPTS',
165
- 'START'
299
+ {action: 'START'}
166
300
  );
167
301
  expect(mockApiAIAssistant.sendEvent).toHaveBeenCalledWith(
168
302
  'test-agent-id',
169
- taskId,
303
+ interactionId,
170
304
  'CUSTOM_EVENT',
171
305
  'GET_TRANSCRIPTS',
172
- 'STOP'
306
+ {action: 'STOP'}
173
307
  );
174
308
  });
175
309
 
176
- it('should not invoke sendEvent for transcript events when realtime transcript feature is disabled', () => {
177
- mockApiAIAssistant.aiFeature = {
178
- realtimeTranscripts: {
179
- enable: false,
310
+ it('should not invoke sendEvent when realtime transcripts are disabled in aiFeature', () => {
311
+ taskManager.setConfigFlags({
312
+ isEndTaskEnabled: true,
313
+ isEndConsultEnabled: true,
314
+ webRtcEnabled: true,
315
+ autoWrapup: false,
316
+ aiFeature: {
317
+ id: 'ai-feature-1',
318
+ realtimeTranscripts: {
319
+ enable: false,
320
+ },
180
321
  },
181
- };
182
- mockApiAIAssistant.setAIFeatureFlags(mockApiAIAssistant.aiFeature);
322
+ });
183
323
 
184
324
  const message = (type: CC_EVENTS) =>
185
325
  JSON.stringify({
186
326
  data: {
187
327
  ...taskDataMock,
188
- taskId,
328
+ interactionId: taskId,
329
+ type,
330
+ },
331
+ });
332
+
333
+ webSocketManagerMock.emit('message', message(CC_EVENTS.AGENT_CONTACT_ASSIGNED));
334
+ webSocketManagerMock.emit('message', message(CC_EVENTS.AGENT_CONSULTING));
335
+
336
+ expect(mockApiAIAssistant.sendEvent).not.toHaveBeenCalled();
337
+ });
338
+
339
+ it('should not invoke sendEvent when realtime transcripts config is missing', () => {
340
+ taskManager.setConfigFlags({
341
+ isEndTaskEnabled: true,
342
+ isEndConsultEnabled: true,
343
+ webRtcEnabled: true,
344
+ autoWrapup: false,
345
+ aiFeature: {
346
+ id: 'ai-feature-1',
347
+ suggestedResponses: {
348
+ enable: true,
349
+ },
350
+ },
351
+ });
352
+
353
+ const message = (type: CC_EVENTS) =>
354
+ JSON.stringify({
355
+ data: {
356
+ ...taskDataMock,
357
+ interactionId: taskId,
189
358
  type,
190
359
  },
191
360
  });
192
361
 
193
362
  webSocketManagerMock.emit('message', message(CC_EVENTS.AGENT_CONTACT_ASSIGNED));
194
363
  webSocketManagerMock.emit('message', message(CC_EVENTS.AGENT_CONSULTING));
195
- webSocketManagerMock.emit('message', message(CC_EVENTS.AGENT_CONSULT_CONFERENCED));
196
- webSocketManagerMock.emit('message', message(CC_EVENTS.AGENT_CONSULT_ENDED));
197
- webSocketManagerMock.emit('message', message(CC_EVENTS.AGENT_WRAPUP));
198
- webSocketManagerMock.emit('message', message(CC_EVENTS.PARTICIPANT_LEFT_CONFERENCE));
199
364
 
200
365
  expect(mockApiAIAssistant.sendEvent).not.toHaveBeenCalled();
201
366
  });
202
367
 
203
- it('should emit REAL_TIME_TRANSCRIPTION from task object', () => {
368
+ it('should emit REAL_TIME_TRANSCRIPTION from RTD websocket payload', () => {
204
369
  const task = taskManager.getTask(taskId);
205
370
  const taskEmitSpy = jest.spyOn(task, 'emit');
206
371
  const realtimePayload = {
207
372
  data: {
208
- ...taskDataMock,
209
- type: CC_EVENTS.REAL_TIME_TRANSCRIPTION,
373
+ agentId: 'test-agent-id',
210
374
  data: {
211
- content: 'hello from transcript',
375
+ content: 'Thank you. Okay.',
376
+ conversationId: taskId,
377
+ isFinal: true,
378
+ languageCode: 'en-US',
379
+ messageId: '1',
380
+ orgId: 'org-id',
381
+ publishTimestamp: 1773807297475,
382
+ role: 'AGENT',
383
+ trackingId: 'tracking-id',
384
+ utteranceId: 'utterance-id',
212
385
  },
386
+ notifDetails: {
387
+ actionEvent: 'REAL_TIME_TRANSCRIPTION',
388
+ },
389
+ notifType: 'REAL_TIME_TRANSCRIPTION',
390
+ orgId: 'org-id',
213
391
  },
392
+ orgId: 'org-id',
393
+ trackingId: 'notifs_tracking-id',
394
+ type: 'REAL_TIME_TRANSCRIPTION',
214
395
  };
215
396
 
216
- webSocketManagerMock.emit('message', JSON.stringify(realtimePayload));
397
+ taskManager.handleRealtimeWebsocketEvent(JSON.stringify(realtimePayload));
217
398
 
218
399
  expect(taskEmitSpy).toHaveBeenCalledWith(
219
400
  CC_EVENTS.REAL_TIME_TRANSCRIPTION,
@@ -221,22 +402,37 @@ describe('TaskManager', () => {
221
402
  );
222
403
  });
223
404
 
224
- it('should emit REAL_TIME_TRANSCRIPTION from RTD websocket payload on task object', () => {
225
- const task = taskManager.getTask(taskId);
226
- const taskEmitSpy = jest.spyOn(task, 'emit');
405
+ it('should ignore RTD transcript events when task is not found', () => {
227
406
  const realtimePayload = {
228
407
  data: {
229
- notifType: CC_EVENTS.REAL_TIME_TRANSCRIPTION,
230
408
  data: {
231
- conversationId: taskId,
232
- content: 'hello from rtd websocket',
409
+ content: 'Thank you. Okay.',
410
+ conversationId: 'missing-task-id',
411
+ isFinal: true,
412
+ languageCode: 'en-US',
413
+ messageId: '1',
414
+ orgId: 'org-id',
415
+ publishTimestamp: 1773807297475,
416
+ role: 'AGENT',
417
+ trackingId: 'tracking-id',
418
+ utteranceId: 'utterance-id',
419
+ },
420
+ notifDetails: {
421
+ actionEvent: 'REAL_TIME_TRANSCRIPTION',
233
422
  },
423
+ notifType: 'REAL_TIME_TRANSCRIPTION',
424
+ orgId: 'org-id',
234
425
  },
426
+ orgId: 'org-id',
427
+ trackingId: 'notifs_tracking-id',
428
+ type: 'REAL_TIME_TRANSCRIPTION',
235
429
  };
236
430
 
431
+ const existingTaskEmitSpy = jest.spyOn(taskManager.getTask(taskId), 'emit');
432
+
237
433
  taskManager.handleRealtimeWebsocketEvent(JSON.stringify(realtimePayload));
238
434
 
239
- expect(taskEmitSpy).toHaveBeenCalledWith(CC_EVENTS.REAL_TIME_TRANSCRIPTION, realtimePayload.data);
435
+ expect(existingTaskEmitSpy).not.toHaveBeenCalled();
240
436
  });
241
437
 
242
438
  it('should not re-emit agent related events', () => {
@@ -254,7 +450,7 @@ describe('TaskManager', () => {
254
450
 
255
451
  webSocketManagerMock.emit('message', JSON.stringify(dummyPayload));
256
452
 
257
- expect(taskEmitSpy).not.toHaveBeenCalledWith(dummyPayload.data.type, dummyPayload.data);
453
+ expect(taskEmitSpy).not.toHaveBeenCalled();
258
454
  });
259
455
 
260
456
  it('should handle WebSocket message for AGENT_CONTACT_RESERVED and emit task:incoming for browser case', () => {
@@ -275,14 +471,12 @@ describe('TaskManager', () => {
275
471
  },
276
472
  };
277
473
 
278
- const taskIncomingSpy = jest.spyOn(taskManager, 'emit');
474
+ const incomingHandler = jest.fn();
475
+ taskManager.on(TASK_EVENTS.TASK_INCOMING, incomingHandler);
279
476
 
280
477
  webSocketManagerMock.emit('message', JSON.stringify(payload));
281
478
 
282
- expect(taskIncomingSpy).toHaveBeenCalledWith(
283
- TASK_EVENTS.TASK_INCOMING,
284
- taskManager.getTask(payload.data.interactionId)
285
- );
479
+ expect(incomingHandler).toHaveBeenCalledWith(taskManager.getTask(payload.data.interactionId));
286
480
  expect(taskManager.getTask(payload.data.interactionId)).toBe(taskManager.getTask(taskId));
287
481
  expect(taskManager.getAllTasks()).toHaveProperty(payload.data.interactionId);
288
482
 
@@ -307,6 +501,7 @@ describe('TaskManager', () => {
307
501
  taskManager.getTask(payload.data.interactionId),
308
502
  'emit'
309
503
  );
504
+ const taskManagerEmitSpy = jest.spyOn(taskManager, 'emit');
310
505
 
311
506
  webSocketManagerMock.emit('message', JSON.stringify(assignedPayload));
312
507
 
@@ -314,6 +509,10 @@ describe('TaskManager', () => {
314
509
  TASK_EVENTS.TASK_ASSIGNED,
315
510
  taskManager.getTask(taskId)
316
511
  );
512
+ expect(taskManagerEmitSpy).toHaveBeenCalledWith(
513
+ TASK_EVENTS.TASK_MULTI_LOGIN_HYDRATE,
514
+ taskManager.getTask(taskId)
515
+ );
317
516
  });
318
517
 
319
518
  it('should handle WebSocket message for AGENT_CONTACT_RESERVED and emit task:incoming for extension case', () => {
@@ -335,16 +534,64 @@ describe('TaskManager', () => {
335
534
  },
336
535
  };
337
536
 
338
- const taskIncomingSpy = jest.spyOn(taskManager, 'emit');
537
+ const incomingHandler = jest.fn();
538
+ taskManager.on(TASK_EVENTS.TASK_INCOMING, incomingHandler);
339
539
 
340
540
  webSocketManagerMock.emit('message', JSON.stringify(payload));
341
541
 
342
- expect(taskIncomingSpy).toHaveBeenCalledWith(
343
- TASK_EVENTS.TASK_INCOMING,
344
- taskManager.getTask(taskId)
345
- );
542
+ expect(incomingHandler).toHaveBeenCalledWith(taskManager.getTask(taskId));
346
543
  expect(taskManager.getTask(payload.data.interactionId)).toBe(taskManager.getTask(taskId));
347
544
  expect(taskManager.getAllTasks()).toHaveProperty(payload.data.interactionId);
545
+ taskManager.off(TASK_EVENTS.TASK_INCOMING, incomingHandler);
546
+ });
547
+
548
+ it('should send mapped events through the state machine without duplicate updates', () => {
549
+ webSocketManagerMock.emit('message', JSON.stringify(initalPayload));
550
+ const task = taskManager.getTask(taskId);
551
+ const updateSpy = task.updateTaskData as jest.Mock;
552
+ updateSpy.mockClear();
553
+ const sendSpy = task.sendStateMachineEvent as jest.Mock;
554
+ sendSpy.mockClear();
555
+ const cleanupSpy = jest.spyOn(taskManager as any, 'handleTaskCleanup');
556
+
557
+ const assignFailedPayload = {
558
+ data: {
559
+ ...initalPayload.data,
560
+ type: CC_EVENTS.AGENT_CONTACT_ASSIGN_FAILED,
561
+ reason: 'ASSIGN_FAILED',
562
+ },
563
+ };
564
+
565
+ webSocketManagerMock.emit('message', JSON.stringify(assignFailedPayload));
566
+
567
+ const stateMachineEvent = expectLastStateMachineEvent(sendSpy, TaskEvent.ASSIGN_FAILED);
568
+ expect(stateMachineEvent).toEqual({
569
+ type: TaskEvent.ASSIGN_FAILED,
570
+ reason: assignFailedPayload.data.reason,
571
+ });
572
+ expect(updateSpy).toHaveBeenCalledWith(assignFailedPayload.data);
573
+ expect(cleanupSpy).toHaveBeenCalledWith(task);
574
+ });
575
+
576
+ it('should update task data directly when no state machine mapping exists', () => {
577
+ webSocketManagerMock.emit('message', JSON.stringify(initalPayload));
578
+ const task = taskManager.getTask(taskId);
579
+ const updateSpy = task.updateTaskData as jest.Mock;
580
+ updateSpy.mockClear();
581
+ const sendSpy = task.sendStateMachineEvent as jest.Mock;
582
+ sendSpy.mockClear();
583
+
584
+ const participantMovedPayload = {
585
+ data: {
586
+ ...initalPayload.data,
587
+ type: CC_EVENTS.CONSULTED_PARTICIPANT_MOVING,
588
+ },
589
+ };
590
+
591
+ webSocketManagerMock.emit('message', JSON.stringify(participantMovedPayload));
592
+
593
+ expect(sendSpy).not.toHaveBeenCalled();
594
+ expect(updateSpy).toHaveBeenCalledWith(participantMovedPayload.data);
348
595
  });
349
596
 
350
597
  it('should return task by ID', () => {
@@ -429,12 +676,30 @@ describe('TaskManager', () => {
429
676
  it('test call listeners being switched off on call end', () => {
430
677
  webSocketManagerMock.emit('message', JSON.stringify(initalPayload));
431
678
 
432
- const taskEmitSpy = jest.spyOn(taskManager.getTask(taskId), 'emit');
433
- const webCallListenerSpy = jest.spyOn(
434
- taskManager.getTask(taskId),
435
- 'unregisterWebCallListeners'
436
- );
679
+ const webrtcTask = new WebRTC(contactMock, webCallingService, taskDataMock, {
680
+ isEndTaskEnabled: true,
681
+ isEndConsultEnabled: true,
682
+ });
683
+ (taskManager as any).taskCollection[taskId] = webrtcTask;
684
+ // TaskManager must listen to task-level cleanup events emitted by the state machine.
685
+ // This is normally wired when TaskManager creates the task via TaskFactory.
686
+ (taskManager as any).setupTaskListeners(webrtcTask);
687
+
688
+ const task = taskManager.getTask(taskId)!;
689
+ // This test doesn't validate UI controls; avoid requiring full interaction.media
690
+ // shape for WebRTC UI controls computation.
691
+ jest.spyOn(task as any, 'updateUiControls').mockImplementation(() => undefined);
692
+ const originalEmit = task.emit;
693
+ jest.spyOn(task, 'emit').mockImplementation((event, arg) => {
694
+ if (event === CC_EVENTS.CONTACT_ENDED) {
695
+ return;
696
+ }
697
+ return originalEmit.call(task, event, arg);
698
+ });
699
+
700
+ const webCallListenerSpy = jest.spyOn(task, 'unregisterWebCallListeners');
437
701
  const callOffSpy = jest.spyOn(mockCall, 'off');
702
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
438
703
  const payload = {
439
704
  data: {
440
705
  type: CC_EVENTS.CONTACT_ENDED,
@@ -452,10 +717,25 @@ describe('TaskManager', () => {
452
717
  },
453
718
  };
454
719
 
720
+ // Ensure the state machine is hydrated into a connected state before CONTACT_ENDED
721
+ const hydratePayload = {
722
+ data: {
723
+ ...payload.data,
724
+ type: CC_EVENTS.AGENT_CONTACT,
725
+ interaction: {state: 'connected', mediaType: 'telephony'},
726
+ },
727
+ };
728
+
729
+ taskManager.getTask(taskId).data = hydratePayload.data;
730
+ webSocketManagerMock.emit('message', JSON.stringify(hydratePayload));
731
+
455
732
  taskManager.getTask(taskId).data = payload.data;
456
- const task = taskManager.getTask(taskId);
457
733
  webSocketManagerMock.emit('message', JSON.stringify(payload));
458
- expect(taskEmitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_END, task);
734
+ const stateMachineEvent = expectLastStateMachineEvent(
735
+ sendStateMachineEventSpy,
736
+ TaskEvent.CONTACT_ENDED
737
+ );
738
+ expect(stateMachineEvent?.taskData.wrapUpRequired).toBe(false);
459
739
  expect(webCallListenerSpy).toHaveBeenCalledWith();
460
740
  expect(callOffSpy).toHaveBeenCalledWith(
461
741
  CALL_EVENT_KEYS.REMOTE_MEDIA,
@@ -466,12 +746,13 @@ describe('TaskManager', () => {
466
746
  expect(offSpy.mock.calls.length).toBe(2); // 1 for incoming call and 1 for remote media
467
747
  expect(offSpy).toHaveBeenCalledWith(CALL_EVENT_KEYS.REMOTE_MEDIA, offSpy.mock.calls[0][1]);
468
748
  expect(offSpy).toHaveBeenCalledWith(LINE_EVENTS.INCOMING_CALL, offSpy.mock.calls[1][1]);
749
+ sendStateMachineEventSpy.mockRestore();
469
750
  });
470
751
 
471
752
  it('should emit TASK_END event with wrapupRequired on regular call end', () => {
472
753
  webSocketManagerMock.emit('message', JSON.stringify(initalPayload));
473
-
474
- const taskEmitSpy = jest.spyOn(taskManager.getTask(taskId), 'emit');
754
+ const task = taskManager.getTask(taskId);
755
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
475
756
  const payload = {
476
757
  data: {
477
758
  type: CC_EVENTS.CONTACT_ENDED,
@@ -486,20 +767,25 @@ describe('TaskManager', () => {
486
767
  destAgentId: 'ebeb893b-ba67-4f36-8418-95c7492b28c2',
487
768
  owner: '723a8ffb-a26e-496d-b14a-ff44fb83b64f',
488
769
  queueMgr: 'aqm',
770
+ agentsPendingWrapUp: ['test-agent-id'],
489
771
  },
490
772
  };
491
773
 
492
- taskManager.getTask(taskId).updateTaskData(payload.data);
774
+ task.updateTaskData(payload.data);
493
775
  webSocketManagerMock.emit('message', JSON.stringify(payload));
494
- expect(taskEmitSpy).toHaveBeenCalledWith(CC_EVENTS.CONTACT_ENDED, {...payload.data});
495
- expect(taskEmitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_END, taskManager.getTask(taskId));
776
+ const stateMachineEvent = expectLastStateMachineEvent(
777
+ sendStateMachineEventSpy,
778
+ TaskEvent.CONTACT_ENDED
779
+ );
780
+ expect(stateMachineEvent?.taskData.wrapUpRequired).toBe(true);
781
+ sendStateMachineEventSpy.mockRestore();
496
782
  });
497
783
 
498
784
  it('should emit TASK_REJECT event on AGENT_INVITE_FAILED event', () => {
499
785
  webSocketManagerMock.emit('message', JSON.stringify(initalPayload));
500
786
 
501
- const taskEmitSpy = jest.spyOn(taskManager.getTask(taskId), 'emit');
502
- const metricsTrackSpy = jest.spyOn(taskManager.metricsManager, 'trackEvent');
787
+ const task = taskManager.getTask(taskId);
788
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
503
789
  const payload = {
504
790
  data: {
505
791
  type: CC_EVENTS.AGENT_INVITE_FAILED,
@@ -518,35 +804,40 @@ describe('TaskManager', () => {
518
804
  },
519
805
  };
520
806
 
521
- taskManager.getTask(taskId).updateTaskData(payload.data);
807
+ task.updateTaskData(payload.data);
522
808
  webSocketManagerMock.emit('message', JSON.stringify(payload));
523
- expect(taskEmitSpy).toHaveBeenCalledWith(CC_EVENTS.AGENT_INVITE_FAILED, {...payload.data});
524
- expect(taskEmitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_REJECT, payload.data.reason);
525
- // Verify the correct metric event name is used for AGENT_INVITE_FAILED
526
- expect(metricsTrackSpy).toHaveBeenCalled();
527
- expect(metricsTrackSpy.mock.calls[0][0]).toBe('Agent Invite Failed');
809
+ const stateMachineEvent = expectLastStateMachineEvent(
810
+ sendStateMachineEventSpy,
811
+ TaskEvent.INVITE_FAILED
812
+ );
813
+ expect(stateMachineEvent?.reason).toBe(payload.data.reason);
814
+ sendStateMachineEventSpy.mockRestore();
528
815
  });
529
816
 
530
- it('should not emit TASK_HYDRATE if task is already present in taskManager', () => {
817
+ it('should emit TASK_HYDRATE even if task is already present in taskManager', () => {
531
818
  const payload = {
532
819
  data: {
533
820
  ...initalPayload.data,
534
821
  type: CC_EVENTS.AGENT_CONTACT,
535
822
  },
536
823
  };
537
- const taskEmitSpy = jest.spyOn(taskManager, 'emit');
824
+ const existingTask = taskManager.getTask(taskId);
825
+ const sendStateMachineEventSpy = jest.spyOn(existingTask, 'sendStateMachineEvent');
538
826
  webSocketManagerMock.emit('message', JSON.stringify(payload));
539
827
 
540
- expect(taskEmitSpy).not.toHaveBeenCalledWith(
541
- TASK_EVENTS.TASK_HYDRATE,
542
- taskManager.getTask(taskId)
828
+ const stateMachineEvent = expectLastStateMachineEvent(
829
+ sendStateMachineEventSpy,
830
+ TaskEvent.HYDRATE
543
831
  );
832
+ expect(stateMachineEvent?.taskData).toEqual(payload.data);
833
+ expect(existingTask).toBe(taskManager.getTask(taskId));
544
834
  expect(taskManager.taskCollection[payload.data.interactionId]).toBe(
545
835
  taskManager.getTask(taskId)
546
836
  );
837
+ sendStateMachineEventSpy.mockRestore();
547
838
  });
548
839
 
549
- it('should emit TASK_INCOMING event on AGENT_CONTACT event if task is new and not in the taskManager ', () => {
840
+ it('should emit TASK_HYDRATE event on AGENT_CONTACT when task is created from payload', () => {
550
841
  taskManager.taskCollection = [];
551
842
  const payload = {
552
843
  data: {
@@ -556,13 +847,15 @@ describe('TaskManager', () => {
556
847
  },
557
848
  };
558
849
 
559
- const taskEmitSpy = jest.spyOn(taskManager, 'emit');
560
850
  webSocketManagerMock.emit('message', JSON.stringify(payload));
561
851
 
562
- expect(taskEmitSpy).toHaveBeenCalledWith(
563
- TASK_EVENTS.TASK_INCOMING,
564
- taskManager.getTask(taskId)
852
+ const createdTask = taskManager.getTask(taskId);
853
+ const sendStateMachineEventSpy = createdTask.sendStateMachineEvent as jest.Mock;
854
+ const stateMachineEvent = expectLastStateMachineEvent(
855
+ sendStateMachineEventSpy,
856
+ TaskEvent.HYDRATE
565
857
  );
858
+ expect(stateMachineEvent?.taskData).toEqual(payload.data);
566
859
  expect(taskManager.taskCollection[payload.data.interactionId]).toBe(
567
860
  taskManager.getTask(taskId)
568
861
  );
@@ -577,10 +870,15 @@ describe('TaskManager', () => {
577
870
  },
578
871
  };
579
872
 
580
- const taskEmitSpy = jest.spyOn(taskManager, 'emit');
581
873
  webSocketManagerMock.emit('message', JSON.stringify(payload));
582
874
 
583
- expect(taskEmitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_HYDRATE, taskManager.getTask(taskId));
875
+ const createdTask = taskManager.getTask(taskId);
876
+ const sendStateMachineEventSpy = createdTask.sendStateMachineEvent as jest.Mock;
877
+ const stateMachineEvent = expectLastStateMachineEvent(
878
+ sendStateMachineEventSpy,
879
+ TaskEvent.HYDRATE
880
+ );
881
+ expect(stateMachineEvent?.taskData).toEqual(payload.data);
584
882
  expect(taskManager.taskCollection[payload.data.interactionId]).toBe(
585
883
  taskManager.getTask(taskId)
586
884
  );
@@ -653,7 +951,7 @@ describe('TaskManager', () => {
653
951
  expect(createdTask.data.isConferenceInProgress).toBe(false);
654
952
  });
655
953
 
656
- it('should emit TASK_END event on AGENT_WRAPUP event', () => {
954
+ it('should emit TASK_WRAPUP event on AGENT_WRAPUP event', () => {
657
955
  webSocketManagerMock.emit('message', JSON.stringify(initalPayload));
658
956
 
659
957
  const wrapupPayload = {
@@ -675,13 +973,15 @@ describe('TaskManager', () => {
675
973
  };
676
974
 
677
975
  const task = taskManager.getTask(taskId);
678
- const updateTaskDataSpy = jest.spyOn(task, 'updateTaskData');
679
- const taskEmitSpy = jest.spyOn(task, 'emit');
976
+ const updateTaskDataSpy = task.updateTaskData as jest.Mock;
977
+ updateTaskDataSpy.mockClear();
978
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
680
979
 
681
980
  webSocketManagerMock.emit('message', JSON.stringify(wrapupPayload));
682
981
 
683
982
  expect(updateTaskDataSpy).toHaveBeenCalledWith(wrapupPayload.data);
684
- expect(taskEmitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_END, task);
983
+ expectLastStateMachineEvent(sendStateMachineEventSpy, TaskEvent.TASK_WRAPUP);
984
+ sendStateMachineEventSpy.mockRestore();
685
985
  });
686
986
 
687
987
  it('should emit TASK_HOLD event on AGENT_CONTACT_HELD event', () => {
@@ -704,13 +1004,20 @@ describe('TaskManager', () => {
704
1004
  },
705
1005
  };
706
1006
 
707
- const taskEmitSpy = jest.spyOn(taskManager.getTask(taskId), 'emit');
708
- const taskUpdateTaskDataSpy = jest.spyOn(taskManager.getTask(taskId), 'updateTaskData');
1007
+ const task = taskManager.getTask(taskId);
1008
+ const taskUpdateTaskDataSpy = task.updateTaskData as jest.Mock;
1009
+ taskUpdateTaskDataSpy.mockClear();
1010
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
709
1011
 
710
1012
  webSocketManagerMock.emit('message', JSON.stringify(payload));
711
1013
 
712
1014
  expect(taskUpdateTaskDataSpy).toHaveBeenCalledWith(payload.data);
713
- expect(taskEmitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_HOLD, taskManager.getTask(taskId));
1015
+ const stateMachineEvent = expectLastStateMachineEvent(
1016
+ sendStateMachineEventSpy,
1017
+ TaskEvent.HOLD_SUCCESS
1018
+ );
1019
+ expect(stateMachineEvent?.taskData).toEqual(payload.data);
1020
+ sendStateMachineEventSpy.mockRestore();
714
1021
  });
715
1022
 
716
1023
  it('should emit TASK_RESUME event on AGENT_CONTACT_UNHELD event', () => {
@@ -733,11 +1040,18 @@ describe('TaskManager', () => {
733
1040
  },
734
1041
  };
735
1042
 
736
- const taskEmitSpy = jest.spyOn(taskManager.getTask(taskId), 'emit');
737
- const taskUpdateTaskDataSpy = jest.spyOn(taskManager.getTask(taskId), 'updateTaskData');
1043
+ const task = taskManager.getTask(taskId);
1044
+ const taskUpdateTaskDataSpy = task.updateTaskData as jest.Mock;
1045
+ taskUpdateTaskDataSpy.mockClear();
1046
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
738
1047
  webSocketManagerMock.emit('message', JSON.stringify(payload));
739
1048
  expect(taskUpdateTaskDataSpy).toHaveBeenCalledWith(payload.data);
740
- expect(taskEmitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_RESUME, taskManager.getTask(taskId));
1049
+ const stateMachineEvent = expectLastStateMachineEvent(
1050
+ sendStateMachineEventSpy,
1051
+ TaskEvent.UNHOLD_SUCCESS
1052
+ );
1053
+ expect(stateMachineEvent?.taskData).toEqual(payload.data);
1054
+ sendStateMachineEventSpy.mockRestore();
741
1055
  });
742
1056
 
743
1057
  it('handle AGENT_CONSULT_CREATED event', () => {
@@ -750,17 +1064,16 @@ describe('TaskManager', () => {
750
1064
 
751
1065
  webSocketManagerMock.emit('message', JSON.stringify(initalPayload));
752
1066
  const task = taskManager.getTask(taskId);
753
- const taskUpdateTaskDataSpy = jest.spyOn(task, 'updateTaskData');
754
- const taskEmitSpy = jest.spyOn(task, 'emit');
1067
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
755
1068
 
756
1069
  webSocketManagerMock.emit('message', JSON.stringify(payload));
757
1070
 
758
- expect(taskUpdateTaskDataSpy).toHaveBeenCalledWith({
759
- ...payload.data,
760
- isConsulted: false,
761
- });
762
- expect(task.data.isConsulted).toBe(false);
763
- expect(taskEmitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_CONSULT_CREATED, task);
1071
+ const stateMachineEvent = expectLastStateMachineEvent(
1072
+ sendStateMachineEventSpy,
1073
+ TaskEvent.CONSULT_CREATED
1074
+ );
1075
+ expect(stateMachineEvent?.taskData).toEqual({...payload.data, isConsulted: false});
1076
+ sendStateMachineEventSpy.mockRestore();
764
1077
  });
765
1078
 
766
1079
  it('handle AGENT_OFFER_CONTACT event', () => {
@@ -773,11 +1086,17 @@ describe('TaskManager', () => {
773
1086
 
774
1087
  webSocketManagerMock.emit('message', JSON.stringify(initalPayload));
775
1088
 
776
- const taskUpdateTaskDataSpy = jest.spyOn(taskManager.getTask(taskId), 'updateTaskData');
1089
+ const task = taskManager.getTask(taskId);
1090
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
777
1091
 
778
1092
  webSocketManagerMock.emit('message', JSON.stringify(payload));
779
1093
 
780
- expect(taskUpdateTaskDataSpy).toHaveBeenCalledWith(payload.data);
1094
+ const stateMachineEvent = expectLastStateMachineEvent(
1095
+ sendStateMachineEventSpy,
1096
+ TaskEvent.TASK_OFFERED
1097
+ );
1098
+ expect(stateMachineEvent?.taskData).toEqual(payload.data);
1099
+ sendStateMachineEventSpy.mockRestore();
781
1100
  });
782
1101
 
783
1102
  describe('Auto-Answer Functionality', () => {
@@ -787,8 +1106,8 @@ describe('TaskManager', () => {
787
1106
 
788
1107
  const task = taskManager.getTask(taskId);
789
1108
  const taskEmitSpy = jest.spyOn(task, 'emit');
790
- const taskManagerEmitSpy = jest.spyOn(taskManager, 'emit');
791
1109
  const taskAcceptSpy = jest.spyOn(task, 'accept').mockResolvedValue(undefined);
1110
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
792
1111
 
793
1112
  // Step 2: Trigger AGENT_OFFER_CONTACT with auto-answer
794
1113
  const autoAnswerPayload = {
@@ -812,9 +1131,14 @@ describe('TaskManager', () => {
812
1131
  // Verify accept was called
813
1132
  expect(taskAcceptSpy).toHaveBeenCalledTimes(1);
814
1133
 
815
- // Verify BOTH events were emitted
816
- expect(taskManagerEmitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_OFFER_CONTACT, task);
1134
+ const stateMachineEvent = expectLastStateMachineEvent(
1135
+ sendStateMachineEventSpy,
1136
+ TaskEvent.TASK_OFFERED
1137
+ );
1138
+ expect(stateMachineEvent?.taskData).toEqual(autoAnswerPayload.data);
1139
+ // Verify task auto-answer event was emitted
817
1140
  expect(taskEmitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_AUTO_ANSWERED, task);
1141
+ sendStateMachineEventSpy.mockRestore();
818
1142
  });
819
1143
 
820
1144
  it('should NOT emit TASK_AUTO_ANSWERED event when auto-answer fails', async () => {
@@ -860,6 +1184,7 @@ describe('TaskManager', () => {
860
1184
  const task = taskManager.getTask(taskId);
861
1185
  const taskEmitSpy = jest.spyOn(task, 'emit');
862
1186
  const taskAcceptSpy = jest.spyOn(task, 'accept').mockResolvedValue(undefined);
1187
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
863
1188
 
864
1189
  // Step 2: Trigger AGENT_OFFER_CONSULT with auto-answer
865
1190
  const consultAutoAnswerPayload = {
@@ -884,12 +1209,20 @@ describe('TaskManager', () => {
884
1209
  // Verify accept was called
885
1210
  expect(taskAcceptSpy).toHaveBeenCalledTimes(1);
886
1211
 
887
- // Verify BOTH events were emitted
888
- expect(taskEmitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_OFFER_CONSULT, task);
1212
+ const stateMachineEvent = expectLastStateMachineEvent(
1213
+ sendStateMachineEventSpy,
1214
+ TaskEvent.OFFER_CONSULT
1215
+ );
1216
+ expect(stateMachineEvent?.taskData).toEqual({
1217
+ ...consultAutoAnswerPayload.data,
1218
+ isConsulted: true,
1219
+ });
1220
+ // Verify task auto-answer event was emitted
889
1221
  expect(taskEmitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_AUTO_ANSWERED, task);
890
1222
 
891
1223
  // Verify isConsulted flag is set correctly
892
1224
  expect(task.data.isConsulted).toBe(true);
1225
+ sendStateMachineEventSpy.mockRestore();
893
1226
  });
894
1227
 
895
1228
  it('should NOT emit TASK_AUTO_ANSWERED when isAutoAnswering is false', async () => {
@@ -930,24 +1263,20 @@ describe('TaskManager', () => {
930
1263
  });
931
1264
  });
932
1265
 
933
- it('should NOT remove OUTDIAL task from taskCollection on AGENT_OUTBOUND_FAILED when terminated (wrap-up flow)', () => {
1266
+ it('should remove OUTDIAL task from taskCollection on AGENT_OUTBOUND_FAILED when terminated', () => {
934
1267
  const task = taskManager.getTask(taskId);
935
- task.updateTaskData = jest.fn().mockImplementation((newData) => {
936
- task.data = {
937
- ...task.data,
938
- ...newData,
939
- interaction: {
940
- ...task.data.interaction,
941
- ...newData.interaction,
942
- outboundType: 'OUTDIAL',
943
- state: 'new',
944
- isTerminated: true,
945
- },
946
- };
947
- return task;
1268
+ Object.assign(task.data, {
1269
+ interaction: {
1270
+ ...task.data.interaction,
1271
+ outboundType: 'OUTDIAL',
1272
+ state: 'new',
1273
+ isTerminated: true,
1274
+ },
1275
+ agentsPendingWrapUp: ['agent-123'],
948
1276
  });
949
1277
  task.unregisterWebCallListeners = jest.fn();
950
1278
  const removeTaskSpy = jest.spyOn(taskManager, 'removeTaskFromCollection');
1279
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
951
1280
 
952
1281
  const payload = {
953
1282
  data: {
@@ -960,6 +1289,7 @@ describe('TaskManager', () => {
960
1289
  state: 'new',
961
1290
  isTerminated: true,
962
1291
  },
1292
+ agentsPendingWrapUp: ['agent-123'],
963
1293
  interactionId: taskId,
964
1294
  orgId: '6ecef209-9a34-4ed1-a07a-7ddd1dbe925a',
965
1295
  trackingId: '575c0ec2-618c-42af-a61c-53aeb0a221ee',
@@ -974,23 +1304,61 @@ describe('TaskManager', () => {
974
1304
 
975
1305
  webSocketManagerMock.emit('message', JSON.stringify(payload));
976
1306
 
977
- expect(taskManager.getTask(taskId)).toBeDefined();
978
- expect(removeTaskSpy).not.toHaveBeenCalled();
1307
+ webSocketManagerMock.emit('message', JSON.stringify(payload));
1308
+
1309
+ expect(taskManager.getTask(taskId)).toBeUndefined();
1310
+ expect(removeTaskSpy).toHaveBeenCalled();
1311
+ const stateMachineEvent = expectLastStateMachineEvent(
1312
+ sendStateMachineEventSpy,
1313
+ TaskEvent.OUTBOUND_FAILED
1314
+ );
1315
+ expect(stateMachineEvent?.reason).toBe('CUSTOMER_BUSY');
1316
+ sendStateMachineEventSpy.mockRestore();
979
1317
  });
980
1318
 
981
1319
  it('should emit TASK_OUTDIAL_FAILED event on AGENT_OUTBOUND_FAILED', () => {
982
1320
  const task = taskManager.getTask(taskId);
983
- task.updateTaskData = jest.fn().mockReturnValue(task);
984
- const taskEmitSpy = jest.spyOn(task, 'emit');
1321
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
1322
+ const payload = {
1323
+ data: {
1324
+ type: CC_EVENTS.AGENT_OUTBOUND_FAILED,
1325
+ interactionId: taskId,
1326
+ reason: 'CUSTOMER_BUSY',
1327
+ },
1328
+ };
1329
+ webSocketManagerMock.emit('message', JSON.stringify(payload));
1330
+ const stateMachineEvent = expectLastStateMachineEvent(
1331
+ sendStateMachineEventSpy,
1332
+ TaskEvent.OUTBOUND_FAILED
1333
+ );
1334
+ expect(stateMachineEvent?.reason).toBe('CUSTOMER_BUSY');
1335
+ sendStateMachineEventSpy.mockRestore();
1336
+ });
1337
+
1338
+ it('should pass taskData in OUTBOUND_FAILED event for shouldWrapUp guard evaluation', () => {
1339
+ const task = taskManager.getTask(taskId);
1340
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
985
1341
  const payload = {
986
1342
  data: {
987
1343
  type: CC_EVENTS.AGENT_OUTBOUND_FAILED,
988
1344
  interactionId: taskId,
989
1345
  reason: 'CUSTOMER_BUSY',
1346
+ agentsPendingWrapUp: ['agent-123'],
1347
+ interaction: {
1348
+ outboundType: 'OUTDIAL',
1349
+ isTerminated: true,
1350
+ },
990
1351
  },
991
1352
  };
992
1353
  webSocketManagerMock.emit('message', JSON.stringify(payload));
993
- expect(taskEmitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_OUTDIAL_FAILED, 'CUSTOMER_BUSY');
1354
+ const stateMachineEvent = expectLastStateMachineEvent(
1355
+ sendStateMachineEventSpy,
1356
+ TaskEvent.OUTBOUND_FAILED
1357
+ );
1358
+ expect(stateMachineEvent?.taskData).toBeDefined();
1359
+ expect(stateMachineEvent?.taskData?.agentsPendingWrapUp).toEqual(['agent-123']);
1360
+ expect(stateMachineEvent?.taskData?.interaction?.outboundType).toBe('OUTDIAL');
1361
+ sendStateMachineEventSpy.mockRestore();
994
1362
  });
995
1363
 
996
1364
  it('should handle AGENT_OUTBOUND_FAILED gracefully when task is undefined', () => {
@@ -1008,23 +1376,15 @@ describe('TaskManager', () => {
1008
1376
  });
1009
1377
 
1010
1378
  it('should NOT remove OUTDIAL task on CONTACT_ENDED when agentsPendingWrapUp exists', () => {
1011
- const agentId = '723a8ffb-a26e-496d-b14a-ff44fb83b64f';
1012
- taskManager.setAgentId(agentId);
1013
-
1014
1379
  const task = taskManager.getTask(taskId);
1015
- task.updateTaskData = jest.fn().mockImplementation((newData) => {
1016
- task.data = {
1017
- ...task.data,
1018
- ...newData,
1019
- interaction: {
1020
- ...task.data.interaction,
1021
- outboundType: 'OUTDIAL',
1022
- state: 'new',
1023
- mediaType: 'telephony',
1024
- },
1025
- agentsPendingWrapUp: [agentId],
1026
- };
1027
- return task;
1380
+ Object.assign(task.data, {
1381
+ interaction: {
1382
+ ...task.data.interaction,
1383
+ outboundType: 'OUTDIAL',
1384
+ state: 'new',
1385
+ mediaType: 'telephony',
1386
+ },
1387
+ agentsPendingWrapUp: ['test-agent-id'],
1028
1388
  });
1029
1389
  task.unregisterWebCallListeners = jest.fn();
1030
1390
  const removeTaskSpy = jest.spyOn(taskManager, 'removeTaskFromCollection');
@@ -1038,7 +1398,7 @@ describe('TaskManager', () => {
1038
1398
  state: 'new',
1039
1399
  mediaType: 'telephony',
1040
1400
  },
1041
- agentsPendingWrapUp: [agentId],
1401
+ agentsPendingWrapUp: ['test-agent-id'],
1042
1402
  },
1043
1403
  };
1044
1404
 
@@ -1050,19 +1410,14 @@ describe('TaskManager', () => {
1050
1410
 
1051
1411
  it('should remove OUTDIAL task on CONTACT_ENDED when agentsPendingWrapUp is empty', () => {
1052
1412
  const task = taskManager.getTask(taskId);
1053
- task.updateTaskData = jest.fn().mockImplementation((newData) => {
1054
- task.data = {
1055
- ...task.data,
1056
- ...newData,
1057
- interaction: {
1058
- ...task.data.interaction,
1059
- outboundType: 'OUTDIAL',
1060
- state: 'new',
1061
- mediaType: 'telephony',
1062
- },
1063
- agentsPendingWrapUp: [],
1064
- };
1065
- return task;
1413
+ Object.assign(task.data, {
1414
+ interaction: {
1415
+ ...task.data.interaction,
1416
+ outboundType: 'OUTDIAL',
1417
+ state: 'new',
1418
+ mediaType: 'telephony',
1419
+ },
1420
+ agentsPendingWrapUp: [],
1066
1421
  });
1067
1422
  task.unregisterWebCallListeners = jest.fn();
1068
1423
  const removeTaskSpy = jest.spyOn(taskManager, 'removeTaskFromCollection');
@@ -1087,19 +1442,13 @@ describe('TaskManager', () => {
1087
1442
 
1088
1443
  it('should remove OUTDIAL task on CONTACT_ENDED when agentsPendingWrapUp is undefined', () => {
1089
1444
  const task = taskManager.getTask(taskId);
1090
- task.updateTaskData = jest.fn().mockImplementation((newData) => {
1091
- task.data = {
1092
- ...task.data,
1093
- ...newData,
1094
- interaction: {
1095
- ...task.data.interaction,
1096
- outboundType: 'OUTDIAL',
1097
- state: 'new',
1098
- mediaType: 'telephony',
1099
- },
1100
- // agentsPendingWrapUp is undefined
1101
- };
1102
- return task;
1445
+ Object.assign(task.data, {
1446
+ interaction: {
1447
+ ...task.data.interaction,
1448
+ outboundType: 'OUTDIAL',
1449
+ state: 'new',
1450
+ mediaType: 'telephony',
1451
+ },
1103
1452
  });
1104
1453
  task.unregisterWebCallListeners = jest.fn();
1105
1454
  const removeTaskSpy = jest.spyOn(taskManager, 'removeTaskFromCollection');
@@ -1122,300 +1471,393 @@ describe('TaskManager', () => {
1122
1471
  expect(removeTaskSpy).toHaveBeenCalled();
1123
1472
  });
1124
1473
 
1125
- it('should handle CONTACT_ENDED gracefully when task is undefined', () => {
1474
+ it('should map non-wxApp agent-terminated OUTDIAL ContactEnded to CONTACT_ENDED (not OUTBOUND_FAILED)', () => {
1475
+ const task = taskManager.getTask(taskId);
1476
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
1477
+ const outdialFailedSpy = jest.fn();
1478
+ task.on(TASK_EVENTS.TASK_OUTDIAL_FAILED, outdialFailedSpy);
1479
+
1126
1480
  const payload = {
1127
1481
  data: {
1128
1482
  type: CC_EVENTS.CONTACT_ENDED,
1129
- interactionId: 'non-existent-task-id',
1483
+ interactionId: taskId,
1484
+ terminatingParty: 'Agent',
1130
1485
  interaction: {
1131
- state: 'new',
1486
+ outboundType: 'OUTDIAL',
1487
+ state: 'wrapUp',
1488
+ mediaType: 'telephony',
1132
1489
  },
1490
+ agentsPendingWrapUp: ['test-agent-id'],
1133
1491
  },
1134
1492
  };
1135
- // Should not throw error when task doesn't exist
1136
- expect(() => {
1137
- webSocketManagerMock.emit('message', JSON.stringify(payload));
1138
- }).not.toThrow();
1139
- });
1140
1493
 
1141
- describe('wrapUpRequired logic in CONTACT_ENDED event', () => {
1142
- const agentId = '723a8ffb-a26e-496d-b14a-ff44fb83b64f';
1494
+ webSocketManagerMock.emit('message', JSON.stringify(payload));
1143
1495
 
1144
- beforeEach(() => {
1145
- // Set the agent ID on taskManager
1146
- taskManager.setAgentId(agentId);
1147
- });
1496
+ expectLastStateMachineEvent(sendStateMachineEventSpy, TaskEvent.CONTACT_ENDED);
1497
+ expect(outdialFailedSpy).not.toHaveBeenCalled();
1498
+ sendStateMachineEventSpy.mockRestore();
1499
+ });
1148
1500
 
1149
- it('should set wrapUpRequired to true when agent is in agentsPendingWrapUp array', () => {
1150
- const task = taskManager.getTask(taskId);
1151
- task.updateTaskData = jest.fn().mockImplementation((newData) => {
1152
- task.data = {
1153
- ...task.data,
1154
- ...newData,
1155
- };
1156
- return task;
1157
- });
1158
- task.unregisterWebCallListeners = jest.fn();
1501
+ it('should map non-wxApp agent-terminated OUTDIAL AgentOutboundFailed to OUTBOUND_FAILED with popup suppressed', () => {
1502
+ const task = taskManager.getTask(taskId);
1503
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
1504
+ const outdialFailedSpy = jest.fn();
1505
+ task.on(TASK_EVENTS.TASK_OUTDIAL_FAILED, outdialFailedSpy);
1159
1506
 
1160
- const payload = {
1161
- data: {
1162
- type: CC_EVENTS.CONTACT_ENDED,
1163
- interactionId: taskId,
1164
- interaction: {
1165
- state: 'connected',
1166
- mediaType: 'telephony',
1167
- },
1168
- agentsPendingWrapUp: [agentId, 'other-agent-id'],
1507
+ const payload = {
1508
+ data: {
1509
+ type: CC_EVENTS.AGENT_OUTBOUND_FAILED,
1510
+ interactionId: taskId,
1511
+ terminatingParty: 'Agent',
1512
+ reason: 'AGENT_ENDS',
1513
+ interaction: {
1514
+ outboundType: 'OUTDIAL',
1515
+ state: 'wrapUp',
1516
+ mediaType: 'telephony',
1169
1517
  },
1170
- };
1518
+ agentsPendingWrapUp: ['test-agent-id'],
1519
+ },
1520
+ };
1171
1521
 
1172
- webSocketManagerMock.emit('message', JSON.stringify(payload));
1173
-
1174
- expect(task.updateTaskData).toHaveBeenCalledWith(
1175
- expect.objectContaining({
1176
- wrapUpRequired: true,
1177
- })
1178
- );
1179
- });
1522
+ webSocketManagerMock.emit('message', JSON.stringify(payload));
1180
1523
 
1181
- it('should set wrapUpRequired to false when agent is not in agentsPendingWrapUp array', () => {
1182
- const task = taskManager.getTask(taskId);
1183
- task.updateTaskData = jest.fn().mockImplementation((newData) => {
1184
- task.data = {
1185
- ...task.data,
1186
- ...newData,
1187
- };
1188
- return task;
1189
- });
1190
- task.unregisterWebCallListeners = jest.fn();
1524
+ const stateMachineEvent = expectLastStateMachineEvent(
1525
+ sendStateMachineEventSpy,
1526
+ TaskEvent.OUTBOUND_FAILED
1527
+ );
1528
+ expect(stateMachineEvent?.reason).toBe('AGENT_ENDS');
1529
+ expect(stateMachineEvent?.taskData?.suppressOutdialFailedPopup).toBe(true);
1530
+ expect(outdialFailedSpy).not.toHaveBeenCalled();
1531
+ sendStateMachineEventSpy.mockRestore();
1532
+ });
1191
1533
 
1192
- const payload = {
1193
- data: {
1194
- type: CC_EVENTS.CONTACT_ENDED,
1195
- interactionId: taskId,
1196
- interaction: {
1197
- state: 'connected',
1198
- mediaType: 'telephony',
1534
+ it('should map wxApp agent-terminated OUTDIAL AgentOutboundFailed to OUTBOUND_FAILED with AGENT_ENDS', () => {
1535
+ const task = taskManager.getTask(taskId);
1536
+ task.uiControlConfig = {enableWxBetterTogether: true};
1537
+ task.data = {
1538
+ ...task.data,
1539
+ agentId: 'test-agent-id',
1540
+ interaction: {
1541
+ ...task.data.interaction,
1542
+ outboundType: 'OUTDIAL',
1543
+ participants: {
1544
+ 'test-agent-id': {
1545
+ id: 'test-agent-id',
1546
+ deviceType: 'wxApp',
1547
+ deviceId: 'device-1',
1548
+ deviceCallId: 'call-1',
1199
1549
  },
1200
- agentsPendingWrapUp: ['other-agent-id', 'another-agent-id'],
1201
1550
  },
1202
- };
1551
+ },
1552
+ };
1553
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
1554
+ const outdialFailedSpy = jest.fn();
1555
+ task.on(TASK_EVENTS.TASK_OUTDIAL_FAILED, outdialFailedSpy);
1203
1556
 
1204
- webSocketManagerMock.emit('message', JSON.stringify(payload));
1557
+ const payload = {
1558
+ data: {
1559
+ type: CC_EVENTS.AGENT_OUTBOUND_FAILED,
1560
+ interactionId: taskId,
1561
+ terminatingParty: 'Agent',
1562
+ reason: 'AGENT_ENDS',
1563
+ interaction: {
1564
+ outboundType: 'OUTDIAL',
1565
+ state: 'wrapUp',
1566
+ mediaType: 'telephony',
1567
+ participants: {
1568
+ 'test-agent-id': {
1569
+ id: 'test-agent-id',
1570
+ deviceType: 'wxApp',
1571
+ deviceId: 'device-1',
1572
+ deviceCallId: 'call-1',
1573
+ },
1574
+ },
1575
+ },
1576
+ agentsPendingWrapUp: ['test-agent-id'],
1577
+ },
1578
+ };
1205
1579
 
1206
- expect(task.updateTaskData).toHaveBeenCalledWith(
1207
- expect.objectContaining({
1208
- wrapUpRequired: false,
1209
- })
1210
- );
1211
- });
1580
+ webSocketManagerMock.emit('message', JSON.stringify(payload));
1212
1581
 
1213
- it('should set wrapUpRequired to false when agentsPendingWrapUp is an empty array', () => {
1214
- const task = taskManager.getTask(taskId);
1215
- task.updateTaskData = jest.fn().mockImplementation((newData) => {
1216
- task.data = {
1217
- ...task.data,
1218
- ...newData,
1219
- };
1220
- return task;
1221
- });
1222
- task.unregisterWebCallListeners = jest.fn();
1582
+ const stateMachineEvent = expectLastStateMachineEvent(
1583
+ sendStateMachineEventSpy,
1584
+ TaskEvent.OUTBOUND_FAILED
1585
+ );
1586
+ expect(stateMachineEvent?.reason).toBe('AGENT_ENDS');
1587
+ expect(outdialFailedSpy).toHaveBeenCalledWith('AGENT_ENDS');
1588
+ sendStateMachineEventSpy.mockRestore();
1589
+ });
1223
1590
 
1224
- const payload = {
1225
- data: {
1226
- type: CC_EVENTS.CONTACT_ENDED,
1227
- interactionId: taskId,
1228
- interaction: {
1229
- state: 'connected',
1230
- mediaType: 'telephony',
1591
+ it('should map wxApp agent-terminated OUTDIAL ContactEnded to OUTBOUND_FAILED with AGENT_ENDS', () => {
1592
+ const task = taskManager.getTask(taskId);
1593
+ task.uiControlConfig = {enableWxBetterTogether: true};
1594
+ task.data = {
1595
+ ...task.data,
1596
+ agentId: 'test-agent-id',
1597
+ interaction: {
1598
+ ...task.data.interaction,
1599
+ outboundType: 'OUTDIAL',
1600
+ participants: {
1601
+ 'test-agent-id': {
1602
+ id: 'test-agent-id',
1603
+ deviceType: 'wxApp',
1604
+ deviceId: 'device-1',
1605
+ deviceCallId: 'call-1',
1231
1606
  },
1232
- agentsPendingWrapUp: [],
1233
1607
  },
1234
- };
1608
+ },
1609
+ };
1610
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
1611
+ const outdialFailedSpy = jest.fn();
1612
+ task.on(TASK_EVENTS.TASK_OUTDIAL_FAILED, outdialFailedSpy);
1235
1613
 
1236
- webSocketManagerMock.emit('message', JSON.stringify(payload));
1614
+ const payload = {
1615
+ data: {
1616
+ type: CC_EVENTS.CONTACT_ENDED,
1617
+ interactionId: taskId,
1618
+ terminatingParty: 'Agent',
1619
+ interaction: {
1620
+ outboundType: 'OUTDIAL',
1621
+ state: 'wrapUp',
1622
+ mediaType: 'telephony',
1623
+ participants: {
1624
+ 'test-agent-id': {
1625
+ id: 'test-agent-id',
1626
+ deviceType: 'wxApp',
1627
+ deviceId: 'device-1',
1628
+ deviceCallId: 'call-1',
1629
+ },
1630
+ },
1631
+ },
1632
+ agentsPendingWrapUp: ['test-agent-id'],
1633
+ },
1634
+ };
1237
1635
 
1238
- expect(task.updateTaskData).toHaveBeenCalledWith(
1239
- expect.objectContaining({
1240
- wrapUpRequired: false,
1241
- })
1242
- );
1243
- });
1636
+ webSocketManagerMock.emit('message', JSON.stringify(payload));
1244
1637
 
1245
- it('should set wrapUpRequired to false when agentsPendingWrapUp is undefined', () => {
1246
- const task = taskManager.getTask(taskId);
1247
- task.updateTaskData = jest.fn().mockImplementation((newData) => {
1248
- task.data = {
1249
- ...task.data,
1250
- ...newData,
1251
- };
1252
- return task;
1253
- });
1254
- task.unregisterWebCallListeners = jest.fn();
1638
+ const stateMachineEvent = expectLastStateMachineEvent(
1639
+ sendStateMachineEventSpy,
1640
+ TaskEvent.OUTBOUND_FAILED
1641
+ );
1642
+ expect(stateMachineEvent?.reason).toBe('AGENT_ENDS');
1643
+ expect(stateMachineEvent?.taskData?.wrapUpRequired).toBe(true);
1644
+ expect(outdialFailedSpy).toHaveBeenCalledWith('AGENT_ENDS');
1645
+ sendStateMachineEventSpy.mockRestore();
1646
+ });
1255
1647
 
1256
- const payload = {
1257
- data: {
1258
- type: CC_EVENTS.CONTACT_ENDED,
1259
- interactionId: taskId,
1260
- interaction: {
1261
- state: 'connected',
1262
- mediaType: 'telephony',
1648
+ it('should map offer-stage OUTDIAL decline ContactEnded to CONTACT_ENDED (not wrapup)', () => {
1649
+ const task = taskManager.getTask(taskId);
1650
+ task.stateMachineService = {
1651
+ getSnapshot: () => ({value: 'OFFERED'}),
1652
+ };
1653
+ task.uiControlConfig = {enableWxBetterTogether: true, wxAppAnswerPending: false};
1654
+ task.data = {
1655
+ ...task.data,
1656
+ agentId: 'test-agent-id',
1657
+ interaction: {
1658
+ ...task.data.interaction,
1659
+ outboundType: 'OUTDIAL',
1660
+ participants: {
1661
+ 'test-agent-id': {
1662
+ id: 'test-agent-id',
1663
+ deviceType: 'wxApp',
1664
+ deviceId: 'device-1',
1665
+ deviceCallId: 'call-1',
1263
1666
  },
1264
- // agentsPendingWrapUp is not defined
1265
1667
  },
1266
- };
1668
+ },
1669
+ };
1670
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
1671
+ const outdialFailedSpy = jest.fn();
1672
+ task.on(TASK_EVENTS.TASK_OUTDIAL_FAILED, outdialFailedSpy);
1267
1673
 
1268
- webSocketManagerMock.emit('message', JSON.stringify(payload));
1674
+ const payload = {
1675
+ data: {
1676
+ type: CC_EVENTS.CONTACT_ENDED,
1677
+ interactionId: taskId,
1678
+ terminatingParty: 'Agent',
1679
+ interaction: {
1680
+ outboundType: 'OUTDIAL',
1681
+ state: 'wrapUp',
1682
+ mediaType: 'telephony',
1683
+ },
1684
+ agentsPendingWrapUp: [],
1685
+ },
1686
+ };
1269
1687
 
1270
- expect(task.updateTaskData).toHaveBeenCalledWith(
1271
- expect.objectContaining({
1272
- wrapUpRequired: false,
1273
- })
1274
- );
1275
- });
1688
+ webSocketManagerMock.emit('message', JSON.stringify(payload));
1276
1689
 
1277
- it('should set wrapUpRequired to false when agentsPendingWrapUp is null', () => {
1278
- const task = taskManager.getTask(taskId);
1279
- task.updateTaskData = jest.fn().mockImplementation((newData) => {
1280
- task.data = {
1281
- ...task.data,
1282
- ...newData,
1283
- };
1284
- return task;
1285
- });
1286
- task.unregisterWebCallListeners = jest.fn();
1690
+ expectLastStateMachineEvent(sendStateMachineEventSpy, TaskEvent.CONTACT_ENDED);
1691
+ expect(outdialFailedSpy).not.toHaveBeenCalled();
1692
+ sendStateMachineEventSpy.mockRestore();
1693
+ });
1287
1694
 
1288
- const payload = {
1289
- data: {
1290
- type: CC_EVENTS.CONTACT_ENDED,
1291
- interactionId: taskId,
1292
- interaction: {
1293
- state: 'connected',
1294
- mediaType: 'telephony',
1695
+ it('should map post-accept OUTDIAL ContactEnded to OUTBOUND_FAILED when still OFFERED with wxAppAnswerPending', () => {
1696
+ const task = taskManager.getTask(taskId);
1697
+ task.stateMachineService = {
1698
+ getSnapshot: () => ({value: 'OFFERED'}),
1699
+ };
1700
+ task.uiControlConfig = {enableWxBetterTogether: true, wxAppAnswerPending: true};
1701
+ task.data = {
1702
+ ...task.data,
1703
+ agentId: 'test-agent-id',
1704
+ interaction: {
1705
+ ...task.data.interaction,
1706
+ outboundType: 'OUTDIAL',
1707
+ participants: {
1708
+ 'test-agent-id': {
1709
+ id: 'test-agent-id',
1710
+ deviceType: 'wxApp',
1711
+ deviceId: 'device-1',
1712
+ deviceCallId: 'call-1',
1295
1713
  },
1296
- agentsPendingWrapUp: null,
1297
1714
  },
1298
- };
1299
-
1300
- webSocketManagerMock.emit('message', JSON.stringify(payload));
1301
-
1302
- expect(task.updateTaskData).toHaveBeenCalledWith(
1303
- expect.objectContaining({
1304
- wrapUpRequired: false,
1305
- })
1306
- );
1307
- });
1308
-
1309
- it('should set wrapUpRequired correctly when agent is the only one in agentsPendingWrapUp', () => {
1310
- const task = taskManager.getTask(taskId);
1311
- task.updateTaskData = jest.fn().mockImplementation((newData) => {
1312
- task.data = {
1313
- ...task.data,
1314
- ...newData,
1315
- };
1316
- return task;
1317
- });
1318
- task.unregisterWebCallListeners = jest.fn();
1715
+ },
1716
+ };
1717
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
1718
+ const outdialFailedSpy = jest.fn();
1719
+ task.on(TASK_EVENTS.TASK_OUTDIAL_FAILED, outdialFailedSpy);
1319
1720
 
1320
- const payload = {
1321
- data: {
1322
- type: CC_EVENTS.CONTACT_ENDED,
1323
- interactionId: taskId,
1324
- interaction: {
1325
- state: 'connected',
1326
- mediaType: 'telephony',
1721
+ const payload = {
1722
+ data: {
1723
+ type: CC_EVENTS.CONTACT_ENDED,
1724
+ interactionId: taskId,
1725
+ terminatingParty: 'Agent',
1726
+ interaction: {
1727
+ outboundType: 'OUTDIAL',
1728
+ state: 'offered',
1729
+ mediaType: 'telephony',
1730
+ participants: {
1731
+ 'test-agent-id': {
1732
+ id: 'test-agent-id',
1733
+ deviceType: 'wxApp',
1734
+ deviceId: 'device-1',
1735
+ deviceCallId: 'call-1',
1736
+ },
1327
1737
  },
1328
- agentsPendingWrapUp: [agentId],
1329
1738
  },
1330
- };
1739
+ },
1740
+ };
1331
1741
 
1332
- webSocketManagerMock.emit('message', JSON.stringify(payload));
1742
+ webSocketManagerMock.emit('message', JSON.stringify(payload));
1333
1743
 
1334
- expect(task.updateTaskData).toHaveBeenCalledWith(
1335
- expect.objectContaining({
1336
- wrapUpRequired: true,
1337
- })
1338
- );
1339
- });
1744
+ const stateMachineEvent = expectLastStateMachineEvent(
1745
+ sendStateMachineEventSpy,
1746
+ TaskEvent.OUTBOUND_FAILED
1747
+ );
1748
+ expect(stateMachineEvent?.reason).toBe('AGENT_ENDS');
1749
+ expect(outdialFailedSpy).toHaveBeenCalledWith('AGENT_ENDS');
1750
+ sendStateMachineEventSpy.mockRestore();
1751
+ });
1340
1752
 
1341
- it('should work correctly for different interaction states when agent is in agentsPendingWrapUp', () => {
1342
- const task = taskManager.getTask(taskId);
1343
- task.updateTaskData = jest.fn().mockImplementation((newData) => {
1344
- task.data = {
1345
- ...task.data,
1346
- ...newData,
1347
- interaction: {
1348
- ...task.data.interaction,
1349
- ...newData.interaction,
1753
+ it('should map post-accept agent-terminated OUTDIAL ContactEnded to OUTBOUND_FAILED when CONNECTED', () => {
1754
+ const task = taskManager.getTask(taskId);
1755
+ task.stateMachineService = {
1756
+ getSnapshot: () => ({value: 'CONNECTED'}),
1757
+ };
1758
+ task.uiControlConfig = {enableWxBetterTogether: true};
1759
+ task.data = {
1760
+ ...task.data,
1761
+ agentId: 'test-agent-id',
1762
+ interaction: {
1763
+ ...task.data.interaction,
1764
+ outboundType: 'OUTDIAL',
1765
+ participants: {
1766
+ 'test-agent-id': {
1767
+ id: 'test-agent-id',
1768
+ deviceType: 'wxApp',
1769
+ deviceId: 'device-1',
1770
+ deviceCallId: 'call-1',
1350
1771
  },
1351
- };
1352
- return task;
1353
- });
1354
- task.unregisterWebCallListeners = jest.fn();
1772
+ },
1773
+ },
1774
+ };
1775
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
1776
+ const outdialFailedSpy = jest.fn();
1777
+ task.on(TASK_EVENTS.TASK_OUTDIAL_FAILED, outdialFailedSpy);
1355
1778
 
1356
- // Test with 'connected' state
1357
- const payloadConnected = {
1358
- data: {
1359
- type: CC_EVENTS.CONTACT_ENDED,
1360
- interactionId: taskId,
1361
- interaction: {
1362
- state: 'connected',
1363
- mediaType: 'telephony',
1779
+ const payload = {
1780
+ data: {
1781
+ type: CC_EVENTS.CONTACT_ENDED,
1782
+ interactionId: taskId,
1783
+ terminatingParty: 'Agent',
1784
+ interaction: {
1785
+ outboundType: 'OUTDIAL',
1786
+ state: 'wrapUp',
1787
+ mediaType: 'telephony',
1788
+ participants: {
1789
+ 'test-agent-id': {
1790
+ id: 'test-agent-id',
1791
+ deviceType: 'wxApp',
1792
+ deviceId: 'device-1',
1793
+ deviceCallId: 'call-1',
1794
+ },
1364
1795
  },
1365
- agentsPendingWrapUp: [agentId],
1366
1796
  },
1367
- };
1797
+ agentsPendingWrapUp: ['test-agent-id'],
1798
+ },
1799
+ };
1368
1800
 
1369
- webSocketManagerMock.emit('message', JSON.stringify(payloadConnected));
1801
+ webSocketManagerMock.emit('message', JSON.stringify(payload));
1370
1802
 
1371
- // First call should set wrapUpRequired to true
1372
- expect(task.updateTaskData).toHaveBeenNthCalledWith(
1373
- 1,
1374
- expect.objectContaining({
1375
- wrapUpRequired: true,
1376
- })
1377
- );
1803
+ const stateMachineEvent = expectLastStateMachineEvent(
1804
+ sendStateMachineEventSpy,
1805
+ TaskEvent.OUTBOUND_FAILED
1806
+ );
1807
+ expect(stateMachineEvent?.reason).toBe('AGENT_ENDS');
1808
+ expect(outdialFailedSpy).toHaveBeenCalledWith('AGENT_ENDS');
1809
+ sendStateMachineEventSpy.mockRestore();
1810
+ });
1378
1811
 
1379
- // Test with 'held' state to verify it still works regardless of state
1380
- const payloadHeld = {
1381
- data: {
1382
- type: CC_EVENTS.CONTACT_ENDED,
1383
- interactionId: taskId,
1384
- interaction: {
1385
- state: 'held',
1386
- mediaType: 'telephony',
1387
- },
1388
- agentsPendingWrapUp: [agentId],
1812
+ it('should map customer-terminated OUTDIAL ContactEnded to CONTACT_ENDED (no AGENT_ENDS remap)', () => {
1813
+ const task = taskManager.getTask(taskId);
1814
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
1815
+
1816
+ const payload = {
1817
+ data: {
1818
+ type: CC_EVENTS.CONTACT_ENDED,
1819
+ interactionId: taskId,
1820
+ terminatingParty: 'Customer',
1821
+ interaction: {
1822
+ outboundType: 'OUTDIAL',
1823
+ state: 'new',
1824
+ mediaType: 'telephony',
1389
1825
  },
1390
- };
1826
+ agentsPendingWrapUp: ['test-agent-id'],
1827
+ },
1828
+ };
1391
1829
 
1392
- webSocketManagerMock.emit('message', JSON.stringify(payloadHeld));
1830
+ webSocketManagerMock.emit('message', JSON.stringify(payload));
1393
1831
 
1394
- // Second call should also set wrapUpRequired to true
1395
- expect(task.updateTaskData).toHaveBeenNthCalledWith(
1396
- 2,
1397
- expect.objectContaining({
1398
- wrapUpRequired: true,
1399
- })
1400
- );
1401
- });
1832
+ expectLastStateMachineEvent(sendStateMachineEventSpy, TaskEvent.CONTACT_ENDED);
1833
+ sendStateMachineEventSpy.mockRestore();
1402
1834
  });
1403
1835
 
1404
- it('should remove OUTDIAL task from taskCollection on AGENT_CONTACT_ASSIGN_FAILED when NOT terminated (user-declined)', () => {
1405
- const task = taskManager.getTask(taskId);
1406
- task.updateTaskData = jest.fn().mockImplementation((newData) => {
1407
- task.data = {
1408
- ...task.data,
1409
- ...newData,
1836
+ it('should handle CONTACT_ENDED gracefully when task is undefined', () => {
1837
+ const payload = {
1838
+ data: {
1839
+ type: CC_EVENTS.CONTACT_ENDED,
1840
+ interactionId: 'non-existent-task-id',
1410
1841
  interaction: {
1411
- ...task.data.interaction,
1412
- ...newData.interaction,
1413
- outboundType: 'OUTDIAL',
1414
1842
  state: 'new',
1415
- isTerminated: false,
1416
1843
  },
1417
- };
1418
- return task;
1844
+ },
1845
+ };
1846
+ // Should not throw error when task doesn't exist
1847
+ expect(() => {
1848
+ webSocketManagerMock.emit('message', JSON.stringify(payload));
1849
+ }).not.toThrow();
1850
+ });
1851
+
1852
+ it('should remove OUTDIAL task from taskCollection on AGENT_CONTACT_ASSIGN_FAILED when NOT terminated (user-declined)', () => {
1853
+ const task = taskManager.getTask(taskId);
1854
+ Object.assign(task.data, {
1855
+ interaction: {
1856
+ ...task.data.interaction,
1857
+ outboundType: 'OUTDIAL',
1858
+ state: 'new',
1859
+ isTerminated: false,
1860
+ },
1419
1861
  });
1420
1862
  task.unregisterWebCallListeners = jest.fn();
1421
1863
  const removeTaskSpy = jest.spyOn(taskManager, 'removeTaskFromCollection');
@@ -1459,20 +1901,16 @@ describe('TaskManager', () => {
1459
1901
 
1460
1902
  webSocketManagerMock.emit('message', JSON.stringify(initalPayload));
1461
1903
  const task = taskManager.getTask(taskId);
1462
- task.updateTaskData = jest.fn().mockImplementation((newData) => {
1463
- task.data = {...newData, isConsulted: true};
1464
- return task;
1465
- });
1466
- const taskEmitSpy = jest.spyOn(task, 'emit');
1904
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
1467
1905
 
1468
1906
  webSocketManagerMock.emit('message', JSON.stringify(payload));
1469
1907
 
1470
- expect(task.updateTaskData).toHaveBeenCalledWith({
1471
- ...payload.data,
1472
- isConsulted: true,
1473
- });
1474
- expect(task.data.isConsulted).toBe(true);
1475
- expect(taskEmitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_OFFER_CONSULT, task);
1908
+ const stateMachineEvent = expectLastStateMachineEvent(
1909
+ sendStateMachineEventSpy,
1910
+ TaskEvent.OFFER_CONSULT
1911
+ );
1912
+ expect(stateMachineEvent?.taskData).toEqual({...payload.data, isConsulted: true});
1913
+ sendStateMachineEventSpy.mockRestore();
1476
1914
  });
1477
1915
 
1478
1916
  it('should emit TASK_CONSULT_ACCEPTED event on AGENT_CONSULTING event', () => {
@@ -1491,19 +1929,18 @@ describe('TaskManager', () => {
1491
1929
  };
1492
1930
 
1493
1931
  webSocketManagerMock.emit('message', JSON.stringify(initalPayload));
1494
- taskManager.getTask(taskId).updateTaskData = jest.fn().mockImplementation((newData) => {
1495
- taskManager.getTask(taskId).data = {...newData, isConsulted: true};
1496
- return taskManager.getTask(taskId);
1497
- });
1498
1932
 
1499
- const taskEmitSpy = jest.spyOn(taskManager.getTask(taskId), 'emit');
1933
+ const task = taskManager.getTask(taskId);
1934
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
1935
+
1500
1936
  webSocketManagerMock.emit('message', JSON.stringify(initialConsultingPayload));
1501
1937
  webSocketManagerMock.emit('message', JSON.stringify(consultingPayload));
1502
- expect(taskManager.getTask(taskId).data.isConsulted).toBe(true);
1503
- expect(taskEmitSpy).toHaveBeenCalledWith(
1504
- TASK_EVENTS.TASK_CONSULT_ACCEPTED,
1505
- taskManager.getTask(taskId)
1938
+ const stateMachineEvent = expectLastStateMachineEvent(
1939
+ sendStateMachineEventSpy,
1940
+ TaskEvent.CONSULTING_ACTIVE
1506
1941
  );
1942
+ expect(stateMachineEvent?.taskData).toEqual(consultingPayload.data);
1943
+ sendStateMachineEventSpy.mockRestore();
1507
1944
  });
1508
1945
 
1509
1946
  it('should emit TASK_CONSULT_ENDED event on AGENT_CONSULT_ENDED event', () => {
@@ -1515,14 +1952,16 @@ describe('TaskManager', () => {
1515
1952
  };
1516
1953
 
1517
1954
  webSocketManagerMock.emit('message', JSON.stringify(initalPayload));
1518
- const taskEmitSpy = jest.spyOn(taskManager.getTask(taskId), 'emit');
1519
- const taskUpdateTaskDataSpy = jest.spyOn(taskManager.getTask(taskId), 'updateTaskData');
1955
+ taskManager.getTask(taskId).data.isConsulted = true;
1956
+ const task = taskManager.getTask(taskId);
1957
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
1520
1958
  webSocketManagerMock.emit('message', JSON.stringify(payload));
1521
- expect(taskUpdateTaskDataSpy).toHaveBeenCalledWith(payload.data);
1522
- expect(taskEmitSpy).toHaveBeenCalledWith(
1523
- TASK_EVENTS.TASK_CONSULT_END,
1524
- taskManager.getTask(taskId)
1959
+ const stateMachineEvent = expectLastStateMachineEvent(
1960
+ sendStateMachineEventSpy,
1961
+ TaskEvent.CONSULT_END
1525
1962
  );
1963
+ expect(stateMachineEvent?.taskData).toEqual(payload.data);
1964
+ sendStateMachineEventSpy.mockRestore();
1526
1965
  });
1527
1966
 
1528
1967
  it('should emit TASK_CONSULT_ENDED event and remove currentTask when on AGENT_CONSULT_ENDED event when requested for a consult', () => {
@@ -1535,19 +1974,14 @@ describe('TaskManager', () => {
1535
1974
 
1536
1975
  webSocketManagerMock.emit('message', JSON.stringify(initalPayload));
1537
1976
 
1538
- taskManager.getTask(taskId).updateTaskData = jest.fn().mockImplementation((newData) => {
1539
- taskManager.getTask(taskId).data = {...newData, isConsulted: true};
1540
- return taskManager.getTask(taskId);
1541
- });
1977
+ taskManager.getTask(taskId).data.isConsulted = true;
1542
1978
  const task = taskManager.getTask(taskId);
1543
1979
 
1544
- const taskEmitSpy = jest.spyOn(taskManager.getTask(taskId), 'emit');
1545
- const taskUpdateTaskDataSpy = jest.spyOn(taskManager.getTask(taskId), 'updateTaskData');
1980
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
1546
1981
  webSocketManagerMock.emit('message', JSON.stringify(payload));
1547
- expect(taskUpdateTaskDataSpy).toHaveBeenCalledWith(payload.data);
1548
- expect(taskEmitSpy).toHaveBeenCalledWith(CC_EVENTS.AGENT_CONSULT_ENDED, payload.data);
1549
- expect(taskEmitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_CONSULT_END, task);
1982
+ expectLastStateMachineEvent(sendStateMachineEventSpy, TaskEvent.CONSULT_END);
1550
1983
  expect(taskManager.getTask(taskId)).toBeUndefined(); // Ensure task is removed from the task collection after the consult ends
1984
+ sendStateMachineEventSpy.mockRestore();
1551
1985
  });
1552
1986
 
1553
1987
  it('should emit TASK_CANCELLED event on AGENT_CTQ_CANCELLED event', () => {
@@ -1559,14 +1993,15 @@ describe('TaskManager', () => {
1559
1993
  };
1560
1994
 
1561
1995
  webSocketManagerMock.emit('message', JSON.stringify(initalPayload));
1562
- const taskEmitSpy = jest.spyOn(taskManager.getTask(taskId), 'emit');
1563
- const taskUpdateTaskDataSpy = jest.spyOn(taskManager.getTask(taskId), 'updateTaskData');
1996
+ const task = taskManager.getTask(taskId);
1997
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
1564
1998
  webSocketManagerMock.emit('message', JSON.stringify(payload));
1565
- expect(taskUpdateTaskDataSpy).toHaveBeenCalledWith(payload.data);
1566
- expect(taskEmitSpy).toHaveBeenCalledWith(
1567
- TASK_EVENTS.TASK_CONSULT_QUEUE_CANCELLED,
1568
- taskManager.getTask(taskId)
1999
+ const stateMachineEvent = expectLastStateMachineEvent(
2000
+ sendStateMachineEventSpy,
2001
+ TaskEvent.CTQ_CANCEL
1569
2002
  );
2003
+ expect(stateMachineEvent?.taskData).toEqual(payload.data);
2004
+ sendStateMachineEventSpy.mockRestore();
1570
2005
  });
1571
2006
 
1572
2007
  it('should handle AGENT_CONSULT_FAILED event', () => {
@@ -1580,9 +2015,15 @@ describe('TaskManager', () => {
1580
2015
  webSocketManagerMock.emit('message', JSON.stringify(initalPayload));
1581
2016
 
1582
2017
  // Always spy on the updated task object after CONTACT_RESERVED is emitted
1583
- const taskUpdateTaskDataSpy = jest.spyOn(taskManager.getTask(taskId), 'updateTaskData');
2018
+ const task = taskManager.getTask(taskId);
2019
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
1584
2020
  webSocketManagerMock.emit('message', JSON.stringify(payload));
1585
- expect(taskUpdateTaskDataSpy).toHaveBeenCalledWith(payload.data);
2021
+ const stateMachineEvent = expectLastStateMachineEvent(
2022
+ sendStateMachineEventSpy,
2023
+ TaskEvent.CONSULT_FAILED
2024
+ );
2025
+ expect(stateMachineEvent?.taskData).toEqual(payload.data);
2026
+ sendStateMachineEventSpy.mockRestore();
1586
2027
  });
1587
2028
 
1588
2029
  it('should emit TASK_CONSULT_QUEUE_FAILED on AGENT_CTQ_CANCEL_FAILED event', () => {
@@ -1594,14 +2035,15 @@ describe('TaskManager', () => {
1594
2035
  };
1595
2036
 
1596
2037
  webSocketManagerMock.emit('message', JSON.stringify(initalPayload));
1597
- const taskEmitSpy = jest.spyOn(taskManager.getTask(taskId), 'emit');
1598
- const taskUpdateTaskDataSpy = jest.spyOn(taskManager.getTask(taskId), 'updateTaskData');
2038
+ const task = taskManager.getTask(taskId);
2039
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
1599
2040
  webSocketManagerMock.emit('message', JSON.stringify(payload));
1600
- expect(taskUpdateTaskDataSpy).toHaveBeenCalledWith(payload.data);
1601
- expect(taskEmitSpy).toHaveBeenCalledWith(
1602
- TASK_EVENTS.TASK_CONSULT_QUEUE_FAILED,
1603
- taskManager.getTask(taskId)
2041
+ const stateMachineEvent = expectLastStateMachineEvent(
2042
+ sendStateMachineEventSpy,
2043
+ TaskEvent.CTQ_CANCEL_FAILED
1604
2044
  );
2045
+ expect(stateMachineEvent?.taskData).toEqual(payload.data);
2046
+ sendStateMachineEventSpy.mockRestore();
1605
2047
  });
1606
2048
 
1607
2049
  it('should emit TASK_REJECT event on AGENT_CONTACT_OFFER_RONA event', () => {
@@ -1644,15 +2086,14 @@ describe('TaskManager', () => {
1644
2086
  };
1645
2087
 
1646
2088
  taskManager.taskCollection[taskId] = taskManager.getTask(taskId);
1647
- const taskEmitSpy = jest.spyOn(taskManager.getTask(taskId), 'emit');
1648
- const metricsTrackSpy = jest.spyOn(taskManager.metricsManager, 'trackEvent');
2089
+ const task = taskManager.getTask(taskId);
2090
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
1649
2091
 
1650
2092
  webSocketManagerMock.emit('message', JSON.stringify(ronaPayload));
1651
2093
 
1652
- expect(taskEmitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_REJECT, ronaPayload.data.reason);
1653
- // Verify the correct metric event name is used for AGENT_CONTACT_OFFER_RONA
1654
- expect(metricsTrackSpy).toHaveBeenCalled();
1655
- expect(metricsTrackSpy.mock.calls[0][0]).toBe('Agent RONA');
2094
+ const stateMachineEvent = expectLastStateMachineEvent(sendStateMachineEventSpy, TaskEvent.RONA);
2095
+ expect(stateMachineEvent?.reason).toBe(ronaPayload.data.reason);
2096
+ sendStateMachineEventSpy.mockRestore();
1656
2097
  });
1657
2098
 
1658
2099
  it('should emit TASK_REJECT event on AGENT_CONTACT_ASSIGN_FAILED event', () => {
@@ -1696,20 +2137,16 @@ describe('TaskManager', () => {
1696
2137
 
1697
2138
  taskManager.taskCollection[taskId] = taskManager.getTask(taskId);
1698
2139
  const task = taskManager.getTask(taskId);
1699
- const taskEmitSpy = jest.spyOn(task, 'emit');
1700
- const taskUpdateDataSpy = jest.spyOn(task, 'updateTaskData');
1701
- const metricsTrackSpy = jest.spyOn(taskManager.metricsManager, 'trackEvent');
2140
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
1702
2141
 
1703
2142
  webSocketManagerMock.emit('message', JSON.stringify(assignFailedPayload));
1704
2143
 
1705
- expect(taskUpdateDataSpy).toHaveBeenCalledWith(assignFailedPayload.data);
1706
- expect(taskEmitSpy).toHaveBeenCalledWith(
1707
- TASK_EVENTS.TASK_REJECT,
1708
- assignFailedPayload.data.reason
2144
+ const stateMachineEvent = expectLastStateMachineEvent(
2145
+ sendStateMachineEventSpy,
2146
+ TaskEvent.ASSIGN_FAILED
1709
2147
  );
1710
- // Verify the correct metric event name is used for AGENT_CONTACT_ASSIGN_FAILED
1711
- expect(metricsTrackSpy).toHaveBeenCalled();
1712
- expect(metricsTrackSpy.mock.calls[0][0]).toBe('Agent Contact Assign Failed');
2148
+ expect(stateMachineEvent?.reason).toBe(assignFailedPayload.data.reason);
2149
+ sendStateMachineEventSpy.mockRestore();
1713
2150
  });
1714
2151
 
1715
2152
  it('should remove currentTask from taskCollection on AGENT_WRAPPEDUP event', () => {
@@ -1732,11 +2169,12 @@ describe('TaskManager', () => {
1732
2169
 
1733
2170
  webSocketManagerMock.emit('message', JSON.stringify(initalPayload));
1734
2171
  const task = taskManager.getTask(taskId);
1735
- const taskEmitSpy = jest.spyOn(task, 'emit');
2172
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
1736
2173
 
1737
2174
  webSocketManagerMock.emit('message', JSON.stringify(payload));
1738
2175
 
1739
- expect(taskEmitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_WRAPPEDUP, task);
2176
+ expectLastStateMachineEvent(sendStateMachineEventSpy, TaskEvent.WRAPUP_COMPLETE);
2177
+ sendStateMachineEventSpy.mockRestore();
1740
2178
  expect(taskManager.getTask(taskId)).toBeUndefined();
1741
2179
  });
1742
2180
 
@@ -1762,7 +2200,8 @@ describe('TaskManager', () => {
1762
2200
  };
1763
2201
 
1764
2202
  const taskEmitSpy = jest.spyOn(taskManager.getTask(taskId), 'emit');
1765
- const taskUpdateTaskDataSpy = jest.spyOn(taskManager.getTask(taskId), 'updateTaskData');
2203
+ const taskUpdateTaskDataSpy = taskManager.getTask(taskId).updateTaskData as jest.Mock;
2204
+ taskUpdateTaskDataSpy.mockClear();
1766
2205
  webSocketManagerMock.emit('message', JSON.stringify(payload));
1767
2206
  expect(taskEmitSpy).not.toHaveBeenCalled();
1768
2207
  expect(taskUpdateTaskDataSpy).not.toHaveBeenCalled();
@@ -1771,7 +2210,9 @@ describe('TaskManager', () => {
1771
2210
  it('should emit TASK_CONSULTING event when agent is consulting', () => {
1772
2211
  webSocketManagerMock.emit('message', JSON.stringify(initalPayload));
1773
2212
  taskManager.getTask(taskId).data.isConsulted = false;
1774
- const taskEmitSpy = jest.spyOn(taskManager.getTask(taskId), 'emit');
2213
+ const task = taskManager.getTask(taskId);
2214
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
2215
+ const taskManagerEmitSpy = jest.spyOn(taskManager, 'emit');
1775
2216
  const consultingPayload = {
1776
2217
  data: {
1777
2218
  ...initalPayload.data,
@@ -1780,16 +2221,21 @@ describe('TaskManager', () => {
1780
2221
  },
1781
2222
  };
1782
2223
  webSocketManagerMock.emit('message', JSON.stringify(consultingPayload));
1783
- expect(taskEmitSpy).toHaveBeenCalledWith(CC_EVENTS.AGENT_CONSULTING, consultingPayload.data);
1784
- expect(taskEmitSpy).toHaveBeenCalledWith(
1785
- TASK_EVENTS.TASK_CONSULTING,
2224
+ expectLastStateMachineEvent(sendStateMachineEventSpy, TaskEvent.CONSULTING_ACTIVE);
2225
+ expect(taskManagerEmitSpy).toHaveBeenCalledWith(
2226
+ TASK_EVENTS.TASK_MULTI_LOGIN_HYDRATE,
1786
2227
  taskManager.getTask(taskId)
1787
2228
  );
2229
+ sendStateMachineEventSpy.mockRestore();
1788
2230
  });
1789
2231
 
1790
- it('should emit TASK_END event on AGENT_CONTACT_UNASSIGNED', () => {
2232
+ it('should update task data on AGENT_CONTACT_UNASSIGNED', () => {
1791
2233
  webSocketManagerMock.emit('message', JSON.stringify(initalPayload));
1792
- const taskEmitSpy = jest.spyOn(taskManager.getTask(taskId), 'emit');
2234
+ const task = taskManager.getTask(taskId);
2235
+ const sendStateMachineEventSpy = task.sendStateMachineEvent as jest.Mock;
2236
+ sendStateMachineEventSpy.mockClear();
2237
+ const updateTaskDataSpy = task.updateTaskData as jest.Mock;
2238
+ updateTaskDataSpy.mockClear();
1793
2239
  const unassignedPayload = {
1794
2240
  data: {
1795
2241
  type: CC_EVENTS.AGENT_CONTACT_UNASSIGNED,
@@ -1807,11 +2253,76 @@ describe('TaskManager', () => {
1807
2253
  },
1808
2254
  };
1809
2255
  webSocketManagerMock.emit('message', JSON.stringify(unassignedPayload));
1810
- expect(taskEmitSpy).toHaveBeenCalledWith(
1811
- CC_EVENTS.AGENT_CONTACT_UNASSIGNED,
1812
- unassignedPayload.data
2256
+ expect(sendStateMachineEventSpy).not.toHaveBeenCalled();
2257
+ expect(updateTaskDataSpy).toHaveBeenCalledWith(unassignedPayload.data);
2258
+ });
2259
+
2260
+ it('preserves consult fields from state context during consulting payload refresh', () => {
2261
+ const task = createMockTask({
2262
+ ...taskDataMock,
2263
+ interaction: {state: 'consulting'} as any,
2264
+ interactionId: taskId,
2265
+ });
2266
+ task.stateMachineService = {
2267
+ getSnapshot: () => ({
2268
+ value: 'CONSULTING',
2269
+ context: {
2270
+ consultDestinationAgentId: 'agent-preserved',
2271
+ consultDestinationType: 'agent',
2272
+ },
2273
+ }),
2274
+ };
2275
+
2276
+ const incomingTaskData = {
2277
+ ...taskDataMock,
2278
+ interaction: {state: 'consulting'} as any,
2279
+ interactionId: taskId,
2280
+ destAgentId: null,
2281
+ destinationType: null,
2282
+ };
2283
+
2284
+ (taskManager as any).updateTaskData(task, incomingTaskData);
2285
+
2286
+ expect(task.updateTaskData).toHaveBeenCalledWith(
2287
+ expect.objectContaining({
2288
+ destAgentId: 'agent-preserved',
2289
+ destinationType: 'agent',
2290
+ })
2291
+ );
2292
+ });
2293
+
2294
+ it('does not preserve stale consult fields once consult is no longer active', () => {
2295
+ const task = createMockTask({
2296
+ ...taskDataMock,
2297
+ interaction: {state: 'connected'} as any,
2298
+ interactionId: taskId,
2299
+ });
2300
+ task.stateMachineService = {
2301
+ getSnapshot: () => ({
2302
+ value: 'CONNECTED',
2303
+ context: {
2304
+ consultDestinationAgentId: 'agent-stale',
2305
+ consultDestinationType: 'agent',
2306
+ },
2307
+ }),
2308
+ };
2309
+
2310
+ const incomingTaskData = {
2311
+ ...taskDataMock,
2312
+ interaction: {state: 'connected'} as any,
2313
+ interactionId: taskId,
2314
+ destAgentId: null,
2315
+ destinationType: null,
2316
+ };
2317
+
2318
+ (taskManager as any).updateTaskData(task, incomingTaskData);
2319
+
2320
+ expect(task.updateTaskData).toHaveBeenCalledWith(
2321
+ expect.objectContaining({
2322
+ destAgentId: null,
2323
+ destinationType: null,
2324
+ })
1813
2325
  );
1814
- expect(taskEmitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_END, taskManager.getTask(taskId));
1815
2326
  });
1816
2327
 
1817
2328
  it('should handle chat interaction and emit TASK_INCOMING immediately', () => {
@@ -1823,16 +2334,16 @@ describe('TaskManager', () => {
1823
2334
  },
1824
2335
  };
1825
2336
 
1826
- const taskIncomingSpy = jest.spyOn(taskManager, 'emit');
1827
-
1828
2337
  // Simulate receiving a chat task
1829
2338
  webSocketManagerMock.emit('message', JSON.stringify(chatPayload));
1830
2339
 
1831
- // For non-telephony tasks, TASK_INCOMING should be emitted immediately
1832
- expect(taskIncomingSpy).toHaveBeenCalledWith(
1833
- TASK_EVENTS.TASK_INCOMING,
1834
- taskManager.getTask(chatPayload.data.interactionId)
2340
+ const chatTask = taskManager.getTask(chatPayload.data.interactionId);
2341
+ const sendStateMachineEventSpy = chatTask.sendStateMachineEvent as jest.Mock;
2342
+ const stateMachineEvent = expectLastStateMachineEvent(
2343
+ sendStateMachineEventSpy,
2344
+ TaskEvent.TASK_INCOMING
1835
2345
  );
2346
+ expect(stateMachineEvent?.taskData).toEqual(chatPayload.data);
1836
2347
  expect(taskManager.getAllTasks()).toHaveProperty(chatPayload.data.interactionId);
1837
2348
  });
1838
2349
 
@@ -1845,16 +2356,16 @@ describe('TaskManager', () => {
1845
2356
  },
1846
2357
  };
1847
2358
 
1848
- const taskIncomingSpy = jest.spyOn(taskManager, 'emit');
1849
-
1850
2359
  // Simulate receiving an email task
1851
2360
  webSocketManagerMock.emit('message', JSON.stringify(emailPayload));
1852
2361
 
1853
- // For non-telephony tasks, TASK_INCOMING should be emitted immediately
1854
- expect(taskIncomingSpy).toHaveBeenCalledWith(
1855
- TASK_EVENTS.TASK_INCOMING,
1856
- taskManager.getTask(emailPayload.data.interactionId)
2362
+ const emailTask = taskManager.getTask(emailPayload.data.interactionId);
2363
+ const sendStateMachineEventSpy = emailTask.sendStateMachineEvent as jest.Mock;
2364
+ const stateMachineEvent = expectLastStateMachineEvent(
2365
+ sendStateMachineEventSpy,
2366
+ TaskEvent.TASK_INCOMING
1857
2367
  );
2368
+ expect(stateMachineEvent?.taskData).toEqual(emailPayload.data);
1858
2369
  expect(taskManager.getAllTasks()).toHaveProperty(emailPayload.data.interactionId);
1859
2370
  });
1860
2371
 
@@ -1868,13 +2379,11 @@ describe('TaskManager', () => {
1868
2379
  },
1869
2380
  };
1870
2381
 
1871
- const taskIncomingSpy = jest.spyOn(taskManager, 'emit');
1872
2382
  webSocketManagerMock.emit('message', JSON.stringify(chatReservedPayload));
2383
+ const task = taskManager.getTask(chatReservedPayload.data.interactionId);
2384
+ const sendStateMachineEventSpy = task.sendStateMachineEvent as jest.Mock;
1873
2385
 
1874
- expect(taskIncomingSpy).toHaveBeenCalledWith(
1875
- TASK_EVENTS.TASK_INCOMING,
1876
- taskManager.getTask(chatReservedPayload.data.interactionId)
1877
- );
2386
+ expectLastStateMachineEvent(sendStateMachineEventSpy, TaskEvent.TASK_INCOMING);
1878
2387
 
1879
2388
  // 2. Chat task is assigned
1880
2389
  const chatAssignedPayload = {
@@ -1884,12 +2393,9 @@ describe('TaskManager', () => {
1884
2393
  },
1885
2394
  };
1886
2395
 
1887
- const task = taskManager.getTask(chatReservedPayload.data.interactionId);
1888
- const taskEmitSpy = jest.spyOn(task, 'emit');
1889
-
1890
2396
  webSocketManagerMock.emit('message', JSON.stringify(chatAssignedPayload));
1891
2397
 
1892
- expect(taskEmitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_ASSIGNED, task);
2398
+ expectLastStateMachineEvent(sendStateMachineEventSpy, TaskEvent.ASSIGN);
1893
2399
 
1894
2400
  // 3. Chat task is ended with state 'new' to trigger cleanup
1895
2401
  const chatEndedPayload = {
@@ -1897,12 +2403,15 @@ describe('TaskManager', () => {
1897
2403
  ...chatReservedPayload.data,
1898
2404
  type: CC_EVENTS.CONTACT_ENDED,
1899
2405
  interaction: {mediaType: 'chat', state: 'new'}, // Change to 'new' state
2406
+ wrapUpRequired: false,
1900
2407
  },
1901
2408
  };
1902
2409
 
2410
+ // Simulate state on the task to allow cleanup logic
2411
+ task.data.interaction.state = 'new';
1903
2412
  webSocketManagerMock.emit('message', JSON.stringify(chatEndedPayload));
1904
2413
 
1905
- expect(taskEmitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_END, task);
2414
+ expectLastStateMachineEvent(sendStateMachineEventSpy, TaskEvent.CONTACT_ENDED);
1906
2415
  // Verify task is removed since it was in a 'new' state
1907
2416
  expect(taskManager.getTask(chatReservedPayload.data.interactionId)).toBeUndefined();
1908
2417
  });
@@ -1991,13 +2500,8 @@ describe('TaskManager', () => {
1991
2500
  expect(taskManager.getAllTasks()).toHaveProperty(task2Payload.data.interactionId);
1992
2501
  expect(taskManager.getAllTasks()).toHaveProperty(task3Payload.data.interactionId);
1993
2502
 
1994
- // Create spies for all tasks
1995
- const task1EmitSpy = jest.spyOn(taskManager.getTask(task1Payload.data.interactionId), 'emit');
1996
- const task2EmitSpy = jest.spyOn(taskManager.getTask(task2Payload.data.interactionId), 'emit');
1997
- const task3EmitSpy = jest.spyOn(taskManager.getTask(task3Payload.data.interactionId), 'emit');
1998
-
1999
- // Store reference to task2 before it gets removed
2000
2503
  const task2 = taskManager.getTask(task2Payload.data.interactionId);
2504
+ const task2SendStateMachineEventSpy = task2.sendStateMachineEvent as jest.Mock;
2001
2505
 
2002
2506
  // End only the second task (chat task)
2003
2507
  const chatEndedPayload = {
@@ -2005,15 +2509,18 @@ describe('TaskManager', () => {
2005
2509
  ...task2Payload.data,
2006
2510
  type: CC_EVENTS.CONTACT_ENDED,
2007
2511
  interaction: {mediaType: 'chat', state: 'new'}, // Using 'new' to trigger cleanup
2512
+ wrapUpRequired: false,
2008
2513
  },
2009
2514
  };
2010
2515
 
2516
+ task2.data.interaction.state = 'new';
2011
2517
  webSocketManagerMock.emit('message', JSON.stringify(chatEndedPayload));
2012
2518
 
2013
- // Verify only task2 emitted TASK_END
2014
- expect(task1EmitSpy).not.toHaveBeenCalledWith(TASK_EVENTS.TASK_END);
2015
- expect(task2EmitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_END, task2);
2016
- expect(task3EmitSpy).not.toHaveBeenCalledWith(TASK_EVENTS.TASK_END);
2519
+ const firstEndEvent = expectLastStateMachineEvent(
2520
+ task2SendStateMachineEventSpy,
2521
+ TaskEvent.CONTACT_ENDED
2522
+ );
2523
+ expect(firstEndEvent?.taskData).toEqual(chatEndedPayload.data);
2017
2524
 
2018
2525
  // Verify task2 was removed from collection (since state was 'new')
2019
2526
  expect(taskManager.getTask(task2Payload.data.interactionId)).toBeUndefined();
@@ -2024,6 +2531,7 @@ describe('TaskManager', () => {
2024
2531
 
2025
2532
  // Store reference to task3 before we end it
2026
2533
  const task3 = taskManager.getTask(task3Payload.data.interactionId);
2534
+ const task3SendStateMachineEventSpy = task3.sendStateMachineEvent as jest.Mock;
2027
2535
 
2028
2536
  // Now end task3 with a state that doesn't trigger cleanup
2029
2537
  const emailEndedPayload = {
@@ -2031,31 +2539,32 @@ describe('TaskManager', () => {
2031
2539
  ...task3Payload.data,
2032
2540
  type: CC_EVENTS.CONTACT_ENDED,
2033
2541
  interaction: {mediaType: 'email', state: 'connected'}, // Using 'connected' to NOT trigger cleanup
2542
+ wrapUpRequired: true,
2543
+ agentsPendingWrapUp: ['test-agent-id'],
2034
2544
  },
2035
2545
  };
2036
2546
 
2547
+ task3.data.interaction.state = 'connected';
2037
2548
  webSocketManagerMock.emit('message', JSON.stringify(emailEndedPayload));
2038
2549
 
2039
- // Verify task3 emitted TASK_END
2040
- expect(task3EmitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_END, task3);
2550
+ const secondEndEvent = expectLastStateMachineEvent(
2551
+ task3SendStateMachineEventSpy,
2552
+ TaskEvent.CONTACT_ENDED
2553
+ );
2554
+ expect(secondEndEvent?.taskData).toEqual(emailEndedPayload.data);
2041
2555
 
2042
2556
  // Verify task3 is still in collection (since state was 'connected')
2043
2557
  expect(taskManager.getTask(task3Payload.data.interactionId)).toBeDefined();
2044
2558
 
2045
2559
  // Verify task1 remains unaffected
2046
- expect(task1EmitSpy).not.toHaveBeenCalledWith(TASK_EVENTS.TASK_END);
2047
2560
  expect(taskManager.getTask(task1Payload.data.interactionId)).toBeDefined();
2048
2561
  });
2049
2562
 
2050
- it('should emit TASK_END event on AGENT_VTEAM_TRANSFERRED event', () => {
2563
+ it('should emit TRANSFER_SUCCESS event on AGENT_VTEAM_TRANSFERRED event', () => {
2051
2564
  // First create a task by emitting the initial payload
2052
2565
  webSocketManagerMock.emit('message', JSON.stringify(initalPayload));
2053
-
2054
- // Get a reference to the task from taskCollection
2055
2566
  const task = taskManager.getTask(taskId);
2056
-
2057
- // Now spy on the task's emit method
2058
- const taskEmitSpy = jest.spyOn(task, 'emit');
2567
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
2059
2568
 
2060
2569
  const vteamTransferredPayload = {
2061
2570
  data: {
@@ -2079,8 +2588,9 @@ describe('TaskManager', () => {
2079
2588
 
2080
2589
  webSocketManagerMock.emit('message', JSON.stringify(vteamTransferredPayload));
2081
2590
 
2082
- // Check that task.emit was called with TASK_END event
2083
- expect(taskEmitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_END, task);
2591
+ // Check that the state machine received the END event
2592
+ expectLastStateMachineEvent(sendStateMachineEventSpy, TaskEvent.TRANSFER_SUCCESS);
2593
+ sendStateMachineEventSpy.mockRestore();
2084
2594
 
2085
2595
  // The task should still exist in the collection based on current implementation
2086
2596
  expect(taskManager.getTask(taskId)).toBeDefined();
@@ -2095,12 +2605,16 @@ describe('TaskManager', () => {
2095
2605
  },
2096
2606
  };
2097
2607
  const task = taskManager.getTask(taskId);
2098
- const updateSpy = jest.spyOn(task, 'updateTaskData').mockImplementation((data) => {
2099
- task.data = {...(task.data || {}), ...(data || {})};
2100
- return task;
2101
- });
2608
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
2102
2609
  webSocketManagerMock.emit('message', JSON.stringify(payload));
2103
- expect(updateSpy).toHaveBeenCalledWith(payload.data);
2610
+ expect(sendStateMachineEventSpy).toHaveBeenCalled();
2611
+ const stateMachineEvent = sendStateMachineEventSpy.mock.calls.at(-1)?.[0];
2612
+ expect(stateMachineEvent?.type).toBe(TaskEvent.TASK_WRAPUP);
2613
+ expect(stateMachineEvent?.taskData).toEqual({
2614
+ ...payload.data,
2615
+ wrapUpRequired: true,
2616
+ });
2617
+ sendStateMachineEventSpy.mockRestore();
2104
2618
  });
2105
2619
 
2106
2620
  it('should not attempt cleanup twice when AGENT_CONTACT_UNASSIGNED is followed by AGENT_WRAPUP', () => {
@@ -2176,1176 +2690,1085 @@ describe('TaskManager', () => {
2176
2690
  });
2177
2691
 
2178
2692
  describe('should emit appropriate task events for recording events', () => {
2179
- ['PAUSED', 'PAUSE_FAILED', 'RESUMED', 'RESUME_FAILED'].forEach((suffix) => {
2693
+ const eventMap: Record<string, TaskEvent | null> = {
2694
+ STARTED: TaskEvent.RECORDING_STARTED,
2695
+ PAUSED: TaskEvent.PAUSE_RECORDING,
2696
+ PAUSE_FAILED: null,
2697
+ RESUMED: TaskEvent.RESUME_RECORDING,
2698
+ RESUME_FAILED: null,
2699
+ };
2700
+
2701
+ ['STARTED', 'PAUSED', 'PAUSE_FAILED', 'RESUMED', 'RESUME_FAILED'].forEach((suffix) => {
2180
2702
  const ccEvent = CC_EVENTS[`CONTACT_RECORDING_${suffix}`];
2181
- const taskEvent = TASK_EVENTS[`TASK_RECORDING_${suffix}`];
2182
- it(`should emit ${taskEvent} on ${ccEvent} event`, () => {
2703
+ const expectedTaskEvent = eventMap[suffix];
2704
+ it(`should ${expectedTaskEvent ? 'send' : 'not send'} ${
2705
+ expectedTaskEvent ?? 'a'
2706
+ } state machine event on ${ccEvent} event`, () => {
2183
2707
  const payload = {data: {...initalPayload.data, type: ccEvent}};
2184
2708
  webSocketManagerMock.emit('message', JSON.stringify(initalPayload));
2185
2709
  const task = taskManager.getTask(taskId);
2186
- const spy = jest.spyOn(task, 'emit');
2710
+ const sendStateMachineEventSpy = task.sendStateMachineEvent as jest.Mock;
2711
+ sendStateMachineEventSpy.mockClear();
2187
2712
 
2188
2713
  webSocketManagerMock.emit('message', JSON.stringify(payload));
2189
- expect(spy).toHaveBeenCalledWith(taskEvent, task);
2714
+ if (expectedTaskEvent) {
2715
+ const stateMachineEvent = expectLastStateMachineEvent(
2716
+ sendStateMachineEventSpy,
2717
+ expectedTaskEvent
2718
+ );
2719
+ expect(stateMachineEvent?.taskData).toEqual(payload.data);
2720
+ } else {
2721
+ expect(sendStateMachineEventSpy).not.toHaveBeenCalled();
2722
+ }
2190
2723
  });
2191
2724
  });
2192
2725
  });
2193
2726
 
2194
- describe('Conference event handling', () => {
2195
- let task;
2196
- const agentId = '723a8ffb-a26e-496d-b14a-ff44fb83b64f';
2727
+ describe('Contact owner propagation', () => {
2728
+ const currentAgentId = 'test-agent-id';
2729
+ const previousOwnerId = 'previous-owner-id';
2730
+ const promotedOwnerId = 'promoted-owner-id';
2731
+
2732
+ const createConferenceTaskData = (
2733
+ interactionId: string,
2734
+ owner: string,
2735
+ mainInteractionId = taskId
2736
+ ) => ({
2737
+ ...taskDataMock,
2738
+ agentId: currentAgentId,
2739
+ interactionId,
2740
+ owner,
2741
+ interaction: {
2742
+ mediaType: 'telephony',
2743
+ interactionId,
2744
+ mainInteractionId,
2745
+ owner,
2746
+ participants: {
2747
+ [currentAgentId]: {
2748
+ id: currentAgentId,
2749
+ pType: 'Agent',
2750
+ hasJoined: true,
2751
+ hasLeft: false,
2752
+ },
2753
+ [previousOwnerId]: {
2754
+ id: previousOwnerId,
2755
+ pType: 'Agent',
2756
+ hasJoined: true,
2757
+ hasLeft: false,
2758
+ },
2759
+ [promotedOwnerId]: {
2760
+ id: promotedOwnerId,
2761
+ pType: 'Agent',
2762
+ hasJoined: true,
2763
+ hasLeft: false,
2764
+ },
2765
+ },
2766
+ media: {
2767
+ [mainInteractionId]: {
2768
+ mediaResourceId: mainInteractionId,
2769
+ mediaType: 'telephony',
2770
+ mType: 'mainCall',
2771
+ participants: [currentAgentId, previousOwnerId, promotedOwnerId],
2772
+ },
2773
+ },
2774
+ },
2775
+ });
2197
2776
 
2198
- beforeEach(() => {
2199
- // Set the agentId on taskManager before tests run
2200
- taskManager.setAgentId(agentId);
2777
+ const installTask = (data) => {
2778
+ const task = createMockTask(data);
2779
+ taskManager.taskCollection = {[data.interactionId]: task};
2780
+ (taskManager as any).setupTaskListeners(task);
2201
2781
 
2202
- task = {
2203
- data: {interactionId: taskId},
2204
- emit: jest.fn(),
2205
- updateTaskData: jest.fn().mockImplementation((updatedData) => {
2206
- // Mock the updateTaskData method to actually update task.data
2207
- task.data = {...task.data, ...updatedData};
2208
- return task;
2209
- }),
2210
- };
2211
- taskManager.taskCollection[taskId] = task;
2782
+ return task;
2783
+ };
2784
+
2785
+ const createPromotedAgentOwnerChangeData = (
2786
+ interactionId = 'promoted-child-interaction-id',
2787
+ mainInteractionId = taskId
2788
+ ) => {
2789
+ const data = createConferenceTaskData(interactionId, currentAgentId, mainInteractionId);
2790
+
2791
+ data.interaction.state = 'conference';
2792
+
2793
+ return {...data, type: CC_EVENTS.CONTACT_OWNER_CHANGED};
2794
+ };
2795
+
2796
+ const clearTasksAndFactoryHistory = () => {
2797
+ taskManager.taskCollection = {};
2798
+ (TaskFactory.createTask as jest.Mock).mockClear();
2799
+ };
2800
+
2801
+ it('emits one hydrate when ContactUpdated changes interaction.owner', () => {
2802
+ const task = installTask(createConferenceTaskData(taskId, previousOwnerId));
2803
+ const hydrateHandler = jest.fn();
2804
+ taskManager.on(TASK_EVENTS.TASK_HYDRATE, hydrateHandler);
2805
+
2806
+ webSocketManagerMock.emit(
2807
+ 'message',
2808
+ JSON.stringify({
2809
+ data: {
2810
+ ...createConferenceTaskData(taskId, promotedOwnerId),
2811
+ type: CC_EVENTS.CONTACT_UPDATED,
2812
+ },
2813
+ })
2814
+ );
2815
+
2816
+ expectLastStateMachineEvent(task.sendStateMachineEvent, TaskEvent.CONTACT_OWNER_CHANGED);
2817
+ expect(task.data.interaction.owner).toBe(promotedOwnerId);
2818
+ expect(hydrateHandler).toHaveBeenCalledTimes(1);
2819
+ expect(hydrateHandler).toHaveBeenCalledWith(task);
2212
2820
  });
2213
2821
 
2214
- it('should handle AGENT_CONSULT_CONFERENCED event', () => {
2215
- const payload = {
2216
- data: {
2217
- type: CC_EVENTS.AGENT_CONSULT_CONFERENCED,
2218
- interactionId: taskId,
2219
- isConferencing: true,
2220
- },
2221
- };
2822
+ it.each([
2823
+ ['the same owner', previousOwnerId],
2824
+ ['no owner', undefined],
2825
+ ['a blank owner', ' '],
2826
+ ])('keeps ContactUpdated data-only when it carries %s', (_description, owner) => {
2827
+ const task = installTask(createConferenceTaskData(taskId, previousOwnerId));
2828
+ const hydrateHandler = jest.fn();
2829
+ taskManager.on(TASK_EVENTS.TASK_HYDRATE, hydrateHandler);
2830
+ const interaction = createConferenceTaskData(taskId, previousOwnerId).interaction;
2831
+ if (owner === undefined) {
2832
+ delete interaction.owner;
2833
+ } else {
2834
+ interaction.owner = owner;
2835
+ }
2836
+
2837
+ webSocketManagerMock.emit(
2838
+ 'message',
2839
+ JSON.stringify({
2840
+ data: {
2841
+ ...createConferenceTaskData(taskId, previousOwnerId),
2842
+ type: CC_EVENTS.CONTACT_UPDATED,
2843
+ interaction,
2844
+ },
2845
+ })
2846
+ );
2222
2847
 
2223
- webSocketManagerMock.emit('message', JSON.stringify(payload));
2848
+ expectLastStateMachineEvent(task.sendStateMachineEvent, TaskEvent.CONTACT_UPDATED);
2849
+ expect(hydrateHandler).not.toHaveBeenCalled();
2850
+ });
2851
+
2852
+ it('correlates child-keyed ContactOwnerChanged and keeps the main task identity', () => {
2853
+ const childTaskId = 'surviving-child-id';
2854
+ const promotedChildId = 'promoted-child-id';
2855
+ const task = installTask(
2856
+ createConferenceTaskData(childTaskId, previousOwnerId, taskId)
2857
+ );
2858
+ const hydrateHandler = jest.fn();
2859
+ taskManager.on(TASK_EVENTS.TASK_HYDRATE, hydrateHandler);
2860
+
2861
+ const ownerChangeData = createConferenceTaskData(
2862
+ promotedChildId,
2863
+ promotedOwnerId,
2864
+ taskId
2865
+ );
2866
+ ownerChangeData.interaction.interactionId = taskId;
2867
+ webSocketManagerMock.emit(
2868
+ 'message',
2869
+ JSON.stringify({
2870
+ data: {...ownerChangeData, type: CC_EVENTS.CONTACT_OWNER_CHANGED},
2871
+ })
2872
+ );
2224
2873
 
2225
- expect(task.data.isConferencing).toBe(true);
2226
- expect(task.emit).toHaveBeenCalledWith(TASK_EVENTS.TASK_CONFERENCE_STARTED, task);
2874
+ expectLastStateMachineEvent(task.sendStateMachineEvent, TaskEvent.CONTACT_OWNER_CHANGED);
2875
+ expect(task.data.interactionId).toBe(taskId);
2876
+ expect(task.data.interaction.owner).toBe(promotedOwnerId);
2877
+ expect(taskManager.taskCollection[childTaskId]).toBeUndefined();
2878
+ expect(taskManager.taskCollection[promotedChildId]).toBeUndefined();
2879
+ expect(taskManager.taskCollection[taskId]).toBe(task);
2880
+ expect(Object.values(taskManager.taskCollection).filter((entry) => entry === task)).toHaveLength(
2881
+ 1
2882
+ );
2883
+ expect(hydrateHandler).toHaveBeenCalledTimes(1);
2227
2884
  });
2228
2885
 
2229
- it('should handle AGENT_CONSULT_CONFERENCING event', () => {
2230
- const payload = {
2231
- data: {
2232
- type: CC_EVENTS.AGENT_CONSULT_CONFERENCING,
2233
- interactionId: taskId,
2234
- isConferencing: true,
2886
+ it('uses the incoming promotion snapshot to correlate a stale child-keyed task', () => {
2887
+ const childTaskId = 'stale-child-interaction-id';
2888
+ const staleTaskData = createConferenceTaskData(childTaskId, previousOwnerId, taskId);
2889
+ staleTaskData.interaction.media = {
2890
+ [childTaskId]: {
2891
+ mediaResourceId: childTaskId,
2892
+ mediaType: 'telephony',
2893
+ mType: 'consult',
2894
+ participants: [currentAgentId, promotedOwnerId],
2235
2895
  },
2236
2896
  };
2897
+ const task = installTask(staleTaskData);
2898
+ const hydrateHandler = jest.fn();
2899
+ taskManager.on(TASK_EVENTS.TASK_HYDRATE, hydrateHandler);
2237
2900
 
2238
- webSocketManagerMock.emit('message', JSON.stringify(payload));
2901
+ webSocketManagerMock.emit(
2902
+ 'message',
2903
+ JSON.stringify({data: createPromotedAgentOwnerChangeData()})
2904
+ );
2239
2905
 
2240
- expect(task.data.isConferencing).toBe(true);
2241
- // No task event emission for conferencing - only for conferenced (completed)
2242
- expect(task.emit).not.toHaveBeenCalledWith(TASK_EVENTS.TASK_CONFERENCE_STARTED, task);
2906
+ expectLastStateMachineEvent(task.sendStateMachineEvent, TaskEvent.CONTACT_OWNER_CHANGED);
2907
+ expect(task.data.interaction.owner).toBe(currentAgentId);
2908
+ expect(taskManager.taskCollection[childTaskId]).toBeUndefined();
2909
+ expect(taskManager.taskCollection[taskId]).toBe(task);
2910
+ expect(TaskFactory.createTask).not.toHaveBeenCalled();
2911
+ expect(hydrateHandler).toHaveBeenCalledTimes(1);
2243
2912
  });
2244
2913
 
2245
- it('should handle AGENT_CONSULT_CONFERENCE_FAILED event', () => {
2246
- const payload = {
2247
- data: {
2248
- type: CC_EVENTS.AGENT_CONSULT_CONFERENCE_FAILED,
2249
- interactionId: taskId,
2250
- reason: 'Network error',
2251
- },
2252
- };
2914
+ it('reuses a task stored under the incoming main-call media key', () => {
2915
+ const mainMediaInteractionId = 'main-media-interaction-id';
2916
+ const promotedChildId = 'promoted-child-without-main-id';
2917
+ const task = installTask(
2918
+ createConferenceTaskData(
2919
+ mainMediaInteractionId,
2920
+ previousOwnerId,
2921
+ mainMediaInteractionId
2922
+ )
2923
+ );
2924
+ const hydrateHandler = jest.fn();
2925
+ taskManager.on(TASK_EVENTS.TASK_HYDRATE, hydrateHandler);
2926
+ const ownerChangeData = createPromotedAgentOwnerChangeData(
2927
+ promotedChildId,
2928
+ mainMediaInteractionId
2929
+ );
2930
+ delete ownerChangeData.interaction.mainInteractionId;
2931
+
2932
+ webSocketManagerMock.emit('message', JSON.stringify({data: ownerChangeData}));
2933
+
2934
+ expect(task.sendStateMachineEvent).toHaveBeenCalledTimes(1);
2935
+ expectLastStateMachineEvent(task.sendStateMachineEvent, TaskEvent.CONTACT_OWNER_CHANGED);
2936
+ expect(TaskFactory.createTask).not.toHaveBeenCalled();
2937
+ expect(taskManager.taskCollection[mainMediaInteractionId]).toBe(task);
2938
+ expect(taskManager.taskCollection[promotedChildId]).toBeUndefined();
2939
+ expect(Object.values(taskManager.taskCollection)).toEqual([task]);
2940
+ expect(task.listenerCount(TASK_EVENTS.TASK_HYDRATE)).toBe(1);
2941
+ expect(hydrateHandler).toHaveBeenCalledTimes(1);
2942
+ expect(hydrateHandler).toHaveBeenCalledWith(task);
2943
+ });
2253
2944
 
2254
- webSocketManagerMock.emit('message', JSON.stringify(payload));
2945
+ it('prefers the exact task for ContactOwnerChanged over related child tasks', () => {
2946
+ const exactTask = installTask(createConferenceTaskData(taskId, previousOwnerId));
2947
+ const childTaskId = 'related-child-id';
2948
+ const childTask = createMockTask(
2949
+ createConferenceTaskData(childTaskId, previousOwnerId, taskId)
2950
+ );
2951
+ taskManager.taskCollection[childTaskId] = childTask;
2952
+
2953
+ webSocketManagerMock.emit(
2954
+ 'message',
2955
+ JSON.stringify({
2956
+ data: {
2957
+ ...createConferenceTaskData(taskId, promotedOwnerId),
2958
+ type: CC_EVENTS.CONTACT_OWNER_CHANGED,
2959
+ },
2960
+ })
2961
+ );
2255
2962
 
2256
- expect(task.data.reason).toBe('Network error');
2257
- // No event emission expected for failure - handled by contact method promise rejection
2963
+ expectLastStateMachineEvent(exactTask.sendStateMachineEvent, TaskEvent.CONTACT_OWNER_CHANGED);
2964
+ expect(childTask.sendStateMachineEvent).not.toHaveBeenCalled();
2258
2965
  });
2259
2966
 
2260
- it('should handle PARTICIPANT_JOINED_CONFERENCE event', () => {
2261
- const payload = {
2262
- data: {
2263
- type: CC_EVENTS.PARTICIPANT_JOINED_CONFERENCE,
2264
- interactionId: taskId,
2265
- participantId: 'new-participant-123',
2266
- participantType: 'agent',
2267
- interaction: {
2268
- participants: {
2269
- [agentId]: {pType: 'Agent', hasLeft: false},
2270
- 'new-participant-123': {pType: 'Agent', hasLeft: false},
2271
- },
2272
- media: {
2273
- [taskId]: {
2274
- mType: 'mainCall',
2275
- participants: [agentId, 'new-participant-123'],
2276
- },
2277
- },
2967
+ it('ignores a related ContactOwnerChanged task whose current agent is consult-only', () => {
2968
+ const childTaskId = 'consult-only-child-id';
2969
+ const data = createConferenceTaskData(childTaskId, previousOwnerId, taskId);
2970
+ data.interaction.media[taskId].participants = [previousOwnerId, promotedOwnerId];
2971
+ data.interaction.media[childTaskId] = {
2972
+ mediaResourceId: childTaskId,
2973
+ mediaType: 'telephony',
2974
+ mType: 'consult',
2975
+ participants: [currentAgentId, promotedOwnerId],
2976
+ };
2977
+ const task = installTask(data);
2978
+
2979
+ webSocketManagerMock.emit(
2980
+ 'message',
2981
+ JSON.stringify({
2982
+ data: {
2983
+ ...createConferenceTaskData('unmatched-child-id', promotedOwnerId, taskId),
2984
+ type: CC_EVENTS.CONTACT_OWNER_CHANGED,
2278
2985
  },
2986
+ })
2987
+ );
2988
+
2989
+ expect(task.sendStateMachineEvent).not.toHaveBeenCalled();
2990
+ expect(taskManager.taskCollection[childTaskId]).toBe(task);
2991
+ expect(TaskFactory.createTask).not.toHaveBeenCalled();
2992
+ });
2993
+
2994
+ it.each([
2995
+ [
2996
+ 'the current agent is marked departed',
2997
+ (data) => {
2998
+ data.interaction.participants[currentAgentId].hasLeft = true;
2999
+ },
3000
+ ],
3001
+ [
3002
+ 'the current agent participant is missing',
3003
+ (data) => {
3004
+ delete data.interaction.participants[currentAgentId];
2279
3005
  },
3006
+ ],
3007
+ [
3008
+ 'the current agent is present only on a consult leg',
3009
+ (data) => {
3010
+ data.interaction.media[taskId].mType = 'consult';
3011
+ },
3012
+ ],
3013
+ ])('does not recover a promoted task when %s', (_description, mutatePayload) => {
3014
+ clearTasksAndFactoryHistory();
3015
+ const ownerChangeData = createPromotedAgentOwnerChangeData();
3016
+ mutatePayload(ownerChangeData);
3017
+
3018
+ webSocketManagerMock.emit('message', JSON.stringify({data: ownerChangeData}));
3019
+
3020
+ expect(TaskFactory.createTask).not.toHaveBeenCalled();
3021
+ expect(taskManager.getAllTasks()).toEqual({});
3022
+ });
3023
+
3024
+ it('ignores ambiguous active main-call matches for ContactOwnerChanged', () => {
3025
+ const firstTask = createMockTask(
3026
+ createConferenceTaskData('first-child-id', previousOwnerId, taskId)
3027
+ );
3028
+ const secondTask = createMockTask(
3029
+ createConferenceTaskData('second-child-id', previousOwnerId, taskId)
3030
+ );
3031
+ taskManager.taskCollection = {
3032
+ 'first-child-id': firstTask,
3033
+ 'second-child-id': secondTask,
2280
3034
  };
2281
3035
 
2282
- webSocketManagerMock.emit('message', JSON.stringify(payload));
3036
+ const ownerChangeData = createConferenceTaskData(
3037
+ 'unmatched-child-id',
3038
+ promotedOwnerId,
3039
+ taskId
3040
+ );
3041
+ ownerChangeData.interaction.interactionId = 'unmatched-child-id';
3042
+ webSocketManagerMock.emit(
3043
+ 'message',
3044
+ JSON.stringify({
3045
+ data: {...ownerChangeData, type: CC_EVENTS.CONTACT_OWNER_CHANGED},
3046
+ })
3047
+ );
2283
3048
 
2284
- expect(task.data.participantId).toBe('new-participant-123');
2285
- expect(task.data.participantType).toBe('agent');
2286
- // No specific task event emission for participant joined - just data update
3049
+ expect(firstTask.sendStateMachineEvent).not.toHaveBeenCalled();
3050
+ expect(secondTask.sendStateMachineEvent).not.toHaveBeenCalled();
2287
3051
  });
2288
3052
 
2289
- it('should call updateTaskData only once for PARTICIPANT_JOINED_CONFERENCE with pre-calculated isConferenceInProgress', () => {
2290
- const payload = {
2291
- data: {
2292
- type: CC_EVENTS.PARTICIPANT_JOINED_CONFERENCE,
2293
- interactionId: taskId,
2294
- participantId: 'new-agent-789',
2295
- interaction: {
2296
- participants: {
2297
- [agentId]: {pType: 'Agent', hasLeft: false},
2298
- 'agent-2': {pType: 'Agent', hasLeft: false},
2299
- 'new-agent-789': {pType: 'Agent', hasLeft: false},
2300
- 'customer-1': {pType: 'Customer', hasLeft: false},
2301
- },
2302
- media: {
2303
- [taskId]: {
2304
- mType: 'mainCall',
2305
- participants: [agentId, 'agent-2', 'new-agent-789', 'customer-1'],
2306
- },
2307
- },
2308
- },
2309
- },
3053
+ it('does not recover a new task when multiple stale related tasks become eligible from the payload', () => {
3054
+ const createStaleRelatedTask = (interactionId: string) => {
3055
+ const data = createConferenceTaskData(interactionId, previousOwnerId, taskId);
3056
+ data.interaction.media[taskId].participants = [previousOwnerId, promotedOwnerId];
3057
+
3058
+ return createMockTask(data);
3059
+ };
3060
+ const firstTask = createStaleRelatedTask('first-stale-child-id');
3061
+ const secondTask = createStaleRelatedTask('second-stale-child-id');
3062
+ taskManager.taskCollection = {
3063
+ 'first-stale-child-id': firstTask,
3064
+ 'second-stale-child-id': secondTask,
2310
3065
  };
3066
+ (TaskFactory.createTask as jest.Mock).mockClear();
2311
3067
 
2312
- const updateTaskDataSpy = jest.spyOn(task, 'updateTaskData');
3068
+ webSocketManagerMock.emit(
3069
+ 'message',
3070
+ JSON.stringify({data: createPromotedAgentOwnerChangeData()})
3071
+ );
2313
3072
 
2314
- webSocketManagerMock.emit('message', JSON.stringify(payload));
3073
+ expect(firstTask.sendStateMachineEvent).not.toHaveBeenCalled();
3074
+ expect(secondTask.sendStateMachineEvent).not.toHaveBeenCalled();
3075
+ expect(TaskFactory.createTask).not.toHaveBeenCalled();
3076
+ expect(Object.keys(taskManager.taskCollection)).toEqual([
3077
+ 'first-stale-child-id',
3078
+ 'second-stale-child-id',
3079
+ ]);
3080
+ });
2315
3081
 
2316
- // Verify updateTaskData was called exactly once
2317
- expect(updateTaskDataSpy).toHaveBeenCalledTimes(1);
3082
+ it('ignores ContactOwnerChanged when different direct nested IDs match active tasks', () => {
3083
+ const firstTaskId = 'direct-main-id';
3084
+ const secondTaskId = 'direct-parent-id';
3085
+ const firstTask = createMockTask(
3086
+ createConferenceTaskData(firstTaskId, previousOwnerId, firstTaskId)
3087
+ );
3088
+ const secondTask = createMockTask(
3089
+ createConferenceTaskData(secondTaskId, previousOwnerId, secondTaskId)
3090
+ );
3091
+ taskManager.taskCollection = {
3092
+ [firstTaskId]: firstTask,
3093
+ [secondTaskId]: secondTask,
3094
+ };
2318
3095
 
2319
- // Verify it was called with isConferenceInProgress already calculated
2320
- expect(updateTaskDataSpy).toHaveBeenCalledWith(
2321
- expect.objectContaining({
2322
- participantId: 'new-agent-789',
2323
- isConferenceInProgress: true, // 3 active agents
3096
+ const ownerChangeData = createConferenceTaskData(
3097
+ 'unmatched-child-id',
3098
+ promotedOwnerId,
3099
+ firstTaskId
3100
+ );
3101
+ ownerChangeData.interaction.interactionId = secondTaskId;
3102
+ webSocketManagerMock.emit(
3103
+ 'message',
3104
+ JSON.stringify({
3105
+ data: {...ownerChangeData, type: CC_EVENTS.CONTACT_OWNER_CHANGED},
2324
3106
  })
2325
3107
  );
2326
3108
 
2327
- expect(task.emit).toHaveBeenCalledWith(TASK_EVENTS.TASK_PARTICIPANT_JOINED, task);
3109
+ expect(firstTask.sendStateMachineEvent).not.toHaveBeenCalled();
3110
+ expect(secondTask.sendStateMachineEvent).not.toHaveBeenCalled();
2328
3111
  });
2329
3112
 
2330
- describe('PARTICIPANT_LEFT_CONFERENCE event handling', () => {
2331
- it('should call updateTaskData only once for PARTICIPANT_LEFT_CONFERENCE with pre-calculated isConferenceInProgress', () => {
2332
- const payload = {
3113
+ it('ignores ContactOwnerChanged without an interaction correlation identifier', () => {
3114
+ const task = installTask(createConferenceTaskData(taskId, previousOwnerId));
3115
+
3116
+ webSocketManagerMock.emit(
3117
+ 'message',
3118
+ JSON.stringify({
2333
3119
  data: {
2334
- type: CC_EVENTS.PARTICIPANT_LEFT_CONFERENCE,
2335
- interactionId: taskId,
2336
- interaction: {
2337
- participants: {
2338
- [agentId]: {pType: 'Agent', hasLeft: false},
2339
- 'agent-2': {pType: 'Agent', hasLeft: true}, // This agent left
2340
- 'customer-1': {pType: 'Customer', hasLeft: false},
2341
- },
2342
- media: {
2343
- [taskId]: {
2344
- mType: 'mainCall',
2345
- participants: [agentId, 'customer-1'], // agent-2 removed from participants
2346
- },
2347
- },
2348
- },
3120
+ type: CC_EVENTS.CONTACT_OWNER_CHANGED,
3121
+ interaction: {owner: promotedOwnerId},
2349
3122
  },
2350
- };
3123
+ })
3124
+ );
2351
3125
 
2352
- const updateTaskDataSpy = jest.spyOn(task, 'updateTaskData');
3126
+ expect(task.sendStateMachineEvent).not.toHaveBeenCalled();
3127
+ });
2353
3128
 
2354
- webSocketManagerMock.emit('message', JSON.stringify(payload));
3129
+ it('recovers a missing promoted-agent task under the main interaction and emits one hydrate', () => {
3130
+ clearTasksAndFactoryHistory();
3131
+ const hydrateHandler = jest.fn();
3132
+ const incomingHandler = jest.fn();
3133
+ taskManager.on(TASK_EVENTS.TASK_HYDRATE, hydrateHandler);
3134
+ taskManager.on(TASK_EVENTS.TASK_INCOMING, incomingHandler);
2355
3135
 
2356
- // Verify updateTaskData was called exactly once
2357
- expect(updateTaskDataSpy).toHaveBeenCalledTimes(1);
3136
+ webSocketManagerMock.emit(
3137
+ 'message',
3138
+ JSON.stringify({data: createPromotedAgentOwnerChangeData()})
3139
+ );
2358
3140
 
2359
- // Verify it was called with isConferenceInProgress already calculated
2360
- expect(updateTaskDataSpy).toHaveBeenCalledWith(
2361
- expect.objectContaining({
2362
- isConferenceInProgress: false, // Only 1 active agent remains
2363
- })
2364
- );
3141
+ expect(TaskFactory.createTask).toHaveBeenCalledTimes(1);
3142
+ expect(TaskFactory.createTask).toHaveBeenCalledWith(
3143
+ contactMock,
3144
+ webCallingService,
3145
+ expect.objectContaining({
3146
+ interactionId: taskId,
3147
+ isAutoAnswering: false,
3148
+ isConsulted: false,
3149
+ isConferenceInProgress: true,
3150
+ wrapUpRequired: false,
3151
+ }),
3152
+ undefined,
3153
+ undefined,
3154
+ currentAgentId,
3155
+ undefined
3156
+ );
2365
3157
 
2366
- expect(task.emit).toHaveBeenCalledWith(TASK_EVENTS.TASK_PARTICIPANT_LEFT, task);
2367
- });
3158
+ const recoveredTask = (TaskFactory.createTask as jest.Mock).mock.results[0].value;
3159
+ expect(recoveredTask.sendStateMachineEvent).toHaveBeenCalledTimes(2);
3160
+ expect(recoveredTask.sendStateMachineEvent).toHaveBeenNthCalledWith(
3161
+ 1,
3162
+ expect.objectContaining({
3163
+ type: TaskEvent.HYDRATE,
3164
+ agentId: currentAgentId,
3165
+ taskData: expect.objectContaining({interactionId: taskId}),
3166
+ })
3167
+ );
3168
+ expect(recoveredTask.sendStateMachineEvent).toHaveBeenNthCalledWith(
3169
+ 2,
3170
+ expect.objectContaining({
3171
+ type: TaskEvent.CONTACT_OWNER_CHANGED,
3172
+ taskData: expect.objectContaining({interactionId: taskId}),
3173
+ })
3174
+ );
3175
+ expect(taskManager.taskCollection[taskId]).toBe(recoveredTask);
3176
+ expect(taskManager.taskCollection['promoted-child-interaction-id']).toBeUndefined();
3177
+ expect(Object.values(taskManager.taskCollection)).toEqual([recoveredTask]);
3178
+ expect(recoveredTask.data.interaction.owner).toBe(currentAgentId);
3179
+ expect(hydrateHandler).toHaveBeenCalledTimes(1);
3180
+ expect(hydrateHandler).toHaveBeenCalledWith(recoveredTask);
3181
+ expect(incomingHandler).not.toHaveBeenCalled();
3182
+ });
3183
+
3184
+ it.each([
3185
+ [
3186
+ 'another agent owns the interaction',
3187
+ (data) => {
3188
+ data.interaction.owner = promotedOwnerId;
3189
+ data.owner = promotedOwnerId;
3190
+ },
3191
+ ],
3192
+ [
3193
+ 'the payload has no main-call media',
3194
+ (data) => {
3195
+ data.interaction.media = {};
3196
+ },
3197
+ ],
3198
+ [
3199
+ 'the interaction is explicitly terminated',
3200
+ (data) => {
3201
+ data.interaction.isTerminated = true;
3202
+ },
3203
+ ],
3204
+ ])('does not create a missing task when %s', (_description, mutatePayload) => {
3205
+ clearTasksAndFactoryHistory();
3206
+ const ownerChangeData = createPromotedAgentOwnerChangeData();
3207
+ mutatePayload(ownerChangeData);
3208
+
3209
+ webSocketManagerMock.emit('message', JSON.stringify({data: ownerChangeData}));
3210
+
3211
+ expect(TaskFactory.createTask).not.toHaveBeenCalled();
3212
+ expect(taskManager.getAllTasks()).toEqual({});
3213
+ });
3214
+
3215
+ it('does not create a missing task for an owner-changing ContactUpdated event', () => {
3216
+ clearTasksAndFactoryHistory();
3217
+ const contactUpdatedData = {
3218
+ ...createPromotedAgentOwnerChangeData(),
3219
+ type: CC_EVENTS.CONTACT_UPDATED,
3220
+ };
3221
+
3222
+ webSocketManagerMock.emit('message', JSON.stringify({data: contactUpdatedData}));
3223
+
3224
+ expect(TaskFactory.createTask).not.toHaveBeenCalled();
3225
+ expect(taskManager.getAllTasks()).toEqual({});
3226
+ });
3227
+
3228
+ it('reuses a recovered task for later AgentContact and ContactMerged events', () => {
3229
+ clearTasksAndFactoryHistory();
3230
+ const hydrateHandler = jest.fn();
3231
+ const mergedHandler = jest.fn();
3232
+ taskManager.on(TASK_EVENTS.TASK_HYDRATE, hydrateHandler);
3233
+ taskManager.on(TASK_EVENTS.TASK_MERGED, mergedHandler);
3234
+
3235
+ webSocketManagerMock.emit(
3236
+ 'message',
3237
+ JSON.stringify({data: createPromotedAgentOwnerChangeData()})
3238
+ );
3239
+
3240
+ const recoveredTask = taskManager.taskCollection[taskId];
3241
+ expect(recoveredTask).toBeDefined();
3242
+ expect(recoveredTask.listenerCount(TASK_EVENTS.TASK_HYDRATE)).toBe(1);
2368
3243
 
2369
- it('should emit TASK_PARTICIPANT_LEFT event when participant leaves conference', () => {
2370
- const payload = {
3244
+ webSocketManagerMock.emit(
3245
+ 'message',
3246
+ JSON.stringify({
2371
3247
  data: {
2372
- type: CC_EVENTS.PARTICIPANT_LEFT_CONFERENCE,
2373
- interactionId: taskId,
2374
- interaction: {
2375
- participants: {
2376
- [agentId]: {
2377
- hasLeft: false,
2378
- },
2379
- },
2380
- },
3248
+ ...createConferenceTaskData(taskId, currentAgentId),
3249
+ type: CC_EVENTS.AGENT_CONTACT,
3250
+ },
3251
+ })
3252
+ );
3253
+ webSocketManagerMock.emit(
3254
+ 'message',
3255
+ JSON.stringify({
3256
+ data: {
3257
+ ...createConferenceTaskData(taskId, currentAgentId),
3258
+ type: CC_EVENTS.CONTACT_MERGED,
3259
+ childInteractionId: 'promoted-child-interaction-id',
2381
3260
  },
2382
- };
3261
+ })
3262
+ );
2383
3263
 
2384
- webSocketManagerMock.emit('message', JSON.stringify(payload));
3264
+ expect(TaskFactory.createTask).toHaveBeenCalledTimes(1);
3265
+ expect(taskManager.taskCollection[taskId]).toBe(recoveredTask);
3266
+ expect(taskManager.taskCollection['promoted-child-interaction-id']).toBeUndefined();
3267
+ expect(Object.values(taskManager.taskCollection)).toEqual([recoveredTask]);
3268
+ expect(recoveredTask.listenerCount(TASK_EVENTS.TASK_HYDRATE)).toBe(1);
3269
+ expect(hydrateHandler).toHaveBeenCalledTimes(2);
3270
+ expect(mergedHandler).toHaveBeenCalledTimes(1);
3271
+ expect(mergedHandler).toHaveBeenCalledWith(recoveredTask);
3272
+ });
2385
3273
 
2386
- expect(task.emit).toHaveBeenCalledWith(TASK_EVENTS.TASK_PARTICIPANT_LEFT, task);
2387
- });
3274
+ it('does not let a late ParticipantLeftConference restore a departed owner', () => {
3275
+ const task = installTask(createConferenceTaskData(taskId, previousOwnerId));
2388
3276
 
2389
- it('should NOT remove task when agent is still in interaction', () => {
2390
- const payload = {
3277
+ webSocketManagerMock.emit(
3278
+ 'message',
3279
+ JSON.stringify({
2391
3280
  data: {
2392
- type: CC_EVENTS.PARTICIPANT_LEFT_CONFERENCE,
2393
- interactionId: taskId,
2394
- interaction: {
2395
- participants: {
2396
- [agentId]: {
2397
- hasLeft: false,
2398
- },
2399
- },
2400
- },
3281
+ ...createConferenceTaskData(taskId, promotedOwnerId),
3282
+ type: CC_EVENTS.CONTACT_UPDATED,
2401
3283
  },
2402
- };
3284
+ })
3285
+ );
2403
3286
 
2404
- webSocketManagerMock.emit('message', JSON.stringify(payload));
3287
+ const participantLeftData = createConferenceTaskData(taskId, previousOwnerId);
3288
+ participantLeftData.participantId = previousOwnerId;
3289
+ participantLeftData.interaction.participants[previousOwnerId].hasLeft = true;
3290
+ participantLeftData.interaction.media[taskId].participants = [
3291
+ currentAgentId,
3292
+ promotedOwnerId,
3293
+ ];
3294
+ webSocketManagerMock.emit(
3295
+ 'message',
3296
+ JSON.stringify({
3297
+ data: {...participantLeftData, type: CC_EVENTS.PARTICIPANT_LEFT_CONFERENCE},
3298
+ })
3299
+ );
2405
3300
 
2406
- // Task should still exist in collection
2407
- expect(taskManager.getTask(taskId)).toBeDefined();
2408
- expect(task.emit).toHaveBeenCalledWith(TASK_EVENTS.TASK_PARTICIPANT_LEFT, task);
2409
- });
3301
+ const participantLeaveEvent = expectLastStateMachineEvent(
3302
+ task.sendStateMachineEvent,
3303
+ TaskEvent.PARTICIPANT_LEAVE
3304
+ );
3305
+ expect(participantLeaveEvent.taskData.interaction.owner).toBe(promotedOwnerId);
3306
+ expect(task.data.interaction.owner).toBe(promotedOwnerId);
3307
+ });
2410
3308
 
2411
- it('should NOT remove task when agent left but is in main interaction', () => {
2412
- const payload = {
3309
+ it('does not infer that an incoming owner departed from a partial main-call roster', () => {
3310
+ const task = installTask(createConferenceTaskData(taskId, promotedOwnerId));
3311
+ const partialParticipantLeftData = createConferenceTaskData(taskId, previousOwnerId);
3312
+ partialParticipantLeftData.participantId = 'another-agent-id';
3313
+ partialParticipantLeftData.interaction.media[taskId].participants = [
3314
+ currentAgentId,
3315
+ promotedOwnerId,
3316
+ ];
3317
+
3318
+ webSocketManagerMock.emit(
3319
+ 'message',
3320
+ JSON.stringify({
2413
3321
  data: {
3322
+ ...partialParticipantLeftData,
2414
3323
  type: CC_EVENTS.PARTICIPANT_LEFT_CONFERENCE,
2415
- interactionId: taskId,
2416
- interaction: {
2417
- participants: {
2418
- [agentId]: {
2419
- hasLeft: true,
2420
- },
2421
- },
2422
- media: {
2423
- [taskId]: {
2424
- mType: 'mainCall',
2425
- participants: [agentId],
2426
- },
2427
- },
2428
- },
2429
- },
2430
- };
2431
-
2432
- const removeTaskSpy = jest.spyOn(taskManager, 'removeTaskFromCollection');
2433
-
2434
- webSocketManagerMock.emit('message', JSON.stringify(payload));
2435
-
2436
- // Task should still exist - not removed
2437
- expect(removeTaskSpy).not.toHaveBeenCalled();
2438
- expect(taskManager.getTask(taskId)).toBeDefined();
2439
- expect(task.emit).toHaveBeenCalledWith(TASK_EVENTS.TASK_PARTICIPANT_LEFT, task);
2440
- });
2441
-
2442
- it('should NOT remove task when agent left but is primary (owner)', () => {
2443
- const payload = {
2444
- data: {
2445
- type: CC_EVENTS.PARTICIPANT_LEFT_CONFERENCE,
2446
- interactionId: taskId,
2447
- interaction: {
2448
- participants: {
2449
- [agentId]: {
2450
- hasLeft: true,
2451
- },
2452
- },
2453
- owner: agentId,
2454
- media: {
2455
- [taskId]: {
2456
- mType: 'consultCall',
2457
- participants: ['other-agent'],
2458
- },
2459
- },
2460
- },
2461
- },
2462
- };
2463
-
2464
- const removeTaskSpy = jest.spyOn(taskManager, 'removeTaskFromCollection');
2465
-
2466
- webSocketManagerMock.emit('message', JSON.stringify(payload));
2467
-
2468
- // Task should still exist - not removed because agent is primary
2469
- expect(removeTaskSpy).not.toHaveBeenCalled();
2470
- expect(taskManager.getTask(taskId)).toBeDefined();
2471
- expect(task.emit).toHaveBeenCalledWith(TASK_EVENTS.TASK_PARTICIPANT_LEFT, task);
2472
- });
2473
-
2474
- it('should remove task when agent left and is NOT in main interaction and is NOT primary', () => {
2475
- const payload = {
2476
- data: {
2477
- type: CC_EVENTS.PARTICIPANT_LEFT_CONFERENCE,
2478
- interactionId: taskId,
2479
- interaction: {
2480
- participants: {
2481
- [agentId]: {
2482
- hasLeft: true,
2483
- },
2484
- },
2485
- owner: 'another-agent-id',
2486
- media: {
2487
- [taskId]: {
2488
- mType: 'mainCall',
2489
- participants: ['another-agent-id'],
2490
- },
2491
- },
2492
- },
2493
- },
2494
- };
2495
-
2496
- const removeTaskSpy = jest.spyOn(taskManager, 'removeTaskFromCollection');
2497
-
2498
- webSocketManagerMock.emit('message', JSON.stringify(payload));
2499
-
2500
- // Task should be removed
2501
- expect(removeTaskSpy).toHaveBeenCalled();
2502
- expect(task.emit).toHaveBeenCalledWith(TASK_EVENTS.TASK_PARTICIPANT_LEFT, task);
2503
- });
2504
-
2505
- it('should remove task when agent is not in participants list', () => {
2506
- const payload = {
2507
- data: {
2508
- type: CC_EVENTS.PARTICIPANT_LEFT_CONFERENCE,
2509
- interactionId: taskId,
2510
- interaction: {
2511
- participants: {
2512
- 'other-agent-id': {
2513
- hasLeft: false,
2514
- },
2515
- },
2516
- owner: 'another-agent-id',
2517
- },
2518
- },
2519
- };
2520
-
2521
- const removeTaskSpy = jest.spyOn(taskManager, 'removeTaskFromCollection');
2522
-
2523
- webSocketManagerMock.emit('message', JSON.stringify(payload));
2524
-
2525
- // Task should be removed because agent is not in participants
2526
- expect(removeTaskSpy).toHaveBeenCalled();
2527
- expect(task.emit).toHaveBeenCalledWith(TASK_EVENTS.TASK_PARTICIPANT_LEFT, task);
2528
- });
2529
-
2530
- it('should update isConferenceInProgress based on remaining active agents', () => {
2531
- const payload = {
2532
- data: {
2533
- type: CC_EVENTS.PARTICIPANT_LEFT_CONFERENCE,
2534
- interactionId: taskId,
2535
- interaction: {
2536
- participants: {
2537
- [agentId]: {
2538
- hasLeft: false,
2539
- pType: 'Agent',
2540
- },
2541
- 'agent-2': {
2542
- hasLeft: false,
2543
- pType: 'Agent',
2544
- },
2545
- 'customer-1': {
2546
- hasLeft: false,
2547
- pType: 'Customer',
2548
- },
2549
- },
2550
- media: {
2551
- [taskId]: {
2552
- mType: 'mainCall',
2553
- participants: [agentId, 'agent-2', 'customer-1'],
2554
- },
2555
- },
2556
- },
2557
- },
2558
- };
2559
-
2560
- webSocketManagerMock.emit('message', JSON.stringify(payload));
2561
-
2562
- // isConferenceInProgress should be true (2 active agents)
2563
- expect(task.data.isConferenceInProgress).toBe(true);
2564
- expect(task.emit).toHaveBeenCalledWith(TASK_EVENTS.TASK_PARTICIPANT_LEFT, task);
2565
- });
2566
-
2567
- it('should set isConferenceInProgress to false when only one agent remains', () => {
2568
- const payload = {
2569
- data: {
2570
- type: CC_EVENTS.PARTICIPANT_LEFT_CONFERENCE,
2571
- interactionId: taskId,
2572
- interaction: {
2573
- participants: {
2574
- [agentId]: {
2575
- hasLeft: false,
2576
- pType: 'Agent',
2577
- },
2578
- 'agent-2': {
2579
- hasLeft: true,
2580
- pType: 'Agent',
2581
- },
2582
- 'customer-1': {
2583
- hasLeft: false,
2584
- pType: 'Customer',
2585
- },
2586
- },
2587
- media: {
2588
- [taskId]: {
2589
- mType: 'mainCall',
2590
- participants: [agentId, 'customer-1'],
2591
- },
2592
- },
2593
- },
2594
3324
  },
2595
- };
2596
-
2597
- webSocketManagerMock.emit('message', JSON.stringify(payload));
3325
+ })
3326
+ );
2598
3327
 
2599
- // isConferenceInProgress should be false (only 1 active agent)
2600
- expect(task.data.isConferenceInProgress).toBe(false);
2601
- expect(task.emit).toHaveBeenCalledWith(TASK_EVENTS.TASK_PARTICIPANT_LEFT, task);
2602
- });
3328
+ const participantLeaveEvent = expectLastStateMachineEvent(
3329
+ task.sendStateMachineEvent,
3330
+ TaskEvent.PARTICIPANT_LEAVE
3331
+ );
3332
+ expect(participantLeaveEvent.taskData.interaction.owner).toBe(previousOwnerId);
3333
+ expect(task.data.interaction.owner).toBe(previousOwnerId);
3334
+ });
2603
3335
 
2604
- it('should handle participant left when no participants data exists', () => {
2605
- const payload = {
3336
+ it('applies the promoted owner when ParticipantLeftConference arrives first', () => {
3337
+ const task = installTask(createConferenceTaskData(taskId, previousOwnerId));
3338
+ const participantLeftData = createConferenceTaskData(taskId, previousOwnerId);
3339
+ participantLeftData.participantId = previousOwnerId;
3340
+ participantLeftData.interaction.participants[previousOwnerId].hasLeft = true;
3341
+ participantLeftData.interaction.media[taskId].participants = [
3342
+ currentAgentId,
3343
+ promotedOwnerId,
3344
+ ];
3345
+
3346
+ webSocketManagerMock.emit(
3347
+ 'message',
3348
+ JSON.stringify({
3349
+ data: {...participantLeftData, type: CC_EVENTS.PARTICIPANT_LEFT_CONFERENCE},
3350
+ })
3351
+ );
3352
+ webSocketManagerMock.emit(
3353
+ 'message',
3354
+ JSON.stringify({
2606
3355
  data: {
2607
- type: CC_EVENTS.PARTICIPANT_LEFT_CONFERENCE,
2608
- interactionId: taskId,
2609
- interaction: {},
3356
+ ...createConferenceTaskData(taskId, promotedOwnerId),
3357
+ type: CC_EVENTS.CONTACT_UPDATED,
2610
3358
  },
2611
- };
2612
-
2613
- const removeTaskSpy = jest.spyOn(taskManager, 'removeTaskFromCollection');
2614
-
2615
- webSocketManagerMock.emit('message', JSON.stringify(payload));
3359
+ })
3360
+ );
2616
3361
 
2617
- // When no participants data exists, checkParticipantNotInInteraction returns true
2618
- // Since agent won't be in main interaction either, task should be removed
2619
- expect(removeTaskSpy).toHaveBeenCalled();
2620
- expect(task.emit).toHaveBeenCalledWith(TASK_EVENTS.TASK_PARTICIPANT_LEFT, task);
2621
- });
3362
+ expect(task.data.interaction.owner).toBe(promotedOwnerId);
3363
+ expectLastStateMachineEvent(task.sendStateMachineEvent, TaskEvent.CONTACT_OWNER_CHANGED);
2622
3364
  });
3365
+ });
2623
3366
 
2624
- it('should handle PARTICIPANT_LEFT_CONFERENCE_FAILED event', () => {
2625
- const payload = {
2626
- data: {
2627
- type: CC_EVENTS.PARTICIPANT_LEFT_CONFERENCE_FAILED,
2628
- interactionId: taskId,
2629
- reason: 'Exit failed',
2630
- },
2631
- };
2632
-
2633
- webSocketManagerMock.emit('message', JSON.stringify(payload));
2634
-
2635
- expect(task.data.reason).toBe('Exit failed');
2636
- // No event emission expected for failure - handled by contact method promise rejection
2637
- });
3367
+ describe('Conference event handling', () => {
3368
+ let task;
2638
3369
 
2639
- it('should only update task for matching interactionId', () => {
2640
- const otherTaskId = 'other-task-id';
2641
- const otherTask = {
2642
- data: {interactionId: otherTaskId},
3370
+ beforeEach(() => {
3371
+ task = {
3372
+ data: {interactionId: taskId},
2643
3373
  emit: jest.fn(),
3374
+ updateTaskData: jest.fn(),
3375
+ sendStateMachineEvent: jest.fn(),
2644
3376
  };
2645
- taskManager.taskCollection[otherTaskId] = otherTask;
3377
+ taskManager.taskCollection[taskId] = task as any;
3378
+ });
2646
3379
 
3380
+ it('sends AGENT_CONSULT_CONFERENCED to state machine as CONFERENCE_START', () => {
2647
3381
  const payload = {
2648
- data: {
2649
- type: CC_EVENTS.AGENT_CONSULT_CONFERENCED,
2650
- interactionId: taskId,
2651
- isConferencing: true,
2652
- },
3382
+ data: {type: CC_EVENTS.AGENT_CONSULT_CONFERENCED, interactionId: taskId},
2653
3383
  };
2654
-
2655
3384
  webSocketManagerMock.emit('message', JSON.stringify(payload));
2656
-
2657
- // Only the matching task should be updated
2658
- expect(task.data.isConferencing).toBe(true);
2659
- expect(task.emit).toHaveBeenCalledWith(TASK_EVENTS.TASK_CONFERENCE_STARTED, task);
2660
-
2661
- // Other task should not be affected
2662
- expect(otherTask.data.isConferencing).toBeUndefined();
2663
- expect(otherTask.emit).not.toHaveBeenCalled();
2664
- });
2665
- });
2666
-
2667
- describe('handleTaskCleanup - stage changes', () => {
2668
- const agentId = '723a8ffb-a26e-496d-b14a-ff44fb83b64f';
2669
-
2670
- beforeEach(() => {
2671
- taskManager.setAgentId(agentId);
3385
+ expect(task.sendStateMachineEvent).toHaveBeenCalled();
3386
+ const call = task.sendStateMachineEvent.mock.calls[0][0];
3387
+ expect(call.type).toBe(TaskEvent.CONFERENCE_START);
2672
3388
  });
2673
3389
 
2674
- it('should remove OUTDIAL task on CONTACT_ENDED when current agent is NOT in agentsPendingWrapUp', () => {
2675
- const task = taskManager.getTask(taskId);
2676
- task.updateTaskData = jest.fn().mockImplementation((newData) => {
2677
- task.data = {
2678
- ...task.data,
2679
- ...newData,
2680
- interaction: {
2681
- ...task.data.interaction,
2682
- outboundType: 'OUTDIAL',
2683
- state: 'new',
2684
- mediaType: 'telephony',
2685
- },
2686
- agentsPendingWrapUp: ['different-agent-123'], // Current agent not in the list
2687
- };
2688
- return task;
2689
- });
2690
- task.unregisterWebCallListeners = jest.fn();
2691
- const removeTaskSpy = jest.spyOn(taskManager, 'removeTaskFromCollection');
2692
-
3390
+ it('sends PARTICIPANT_JOINED_CONFERENCE to state machine as CONFERENCE_START', () => {
2693
3391
  const payload = {
2694
- data: {
2695
- type: CC_EVENTS.CONTACT_ENDED,
2696
- interactionId: taskId,
2697
- interaction: {
2698
- outboundType: 'OUTDIAL',
2699
- state: 'new',
2700
- mediaType: 'telephony',
2701
- },
2702
- agentsPendingWrapUp: ['different-agent-123'], // Current agent not in the list
2703
- },
3392
+ data: {type: CC_EVENTS.PARTICIPANT_JOINED_CONFERENCE, interactionId: taskId},
2704
3393
  };
2705
-
2706
3394
  webSocketManagerMock.emit('message', JSON.stringify(payload));
2707
-
2708
- expect(removeTaskSpy).toHaveBeenCalled();
2709
- expect(taskManager.getTask(taskId)).toBeUndefined();
3395
+ expect(task.sendStateMachineEvent).toHaveBeenCalled();
3396
+ const call = task.sendStateMachineEvent.mock.calls[0][0];
3397
+ expect(call.type).toBe(TaskEvent.CONFERENCE_START);
2710
3398
  });
2711
3399
 
2712
- it('should NOT remove OUTDIAL task on CONTACT_ENDED when current agent IS in agentsPendingWrapUp', () => {
2713
- const task = taskManager.getTask(taskId);
2714
- task.updateTaskData = jest.fn().mockImplementation((newData) => {
2715
- task.data = {
2716
- ...task.data,
2717
- ...newData,
2718
- interaction: {
2719
- ...task.data.interaction,
2720
- outboundType: 'OUTDIAL',
2721
- state: 'new',
2722
- mediaType: 'telephony',
2723
- },
2724
- agentsPendingWrapUp: [agentId, 'other-agent-456'], // Current agent IS in the list
2725
- };
2726
- return task;
2727
- });
2728
- task.unregisterWebCallListeners = jest.fn();
2729
- const removeTaskSpy = jest.spyOn(taskManager, 'removeTaskFromCollection');
2730
-
3400
+ it('sends AGENT_CONSULT_CONFERENCE_FAILED to state machine as CONFERENCE_FAILED', () => {
2731
3401
  const payload = {
2732
- data: {
2733
- type: CC_EVENTS.CONTACT_ENDED,
2734
- interactionId: taskId,
2735
- interaction: {
2736
- outboundType: 'OUTDIAL',
2737
- state: 'new',
2738
- mediaType: 'telephony',
2739
- },
2740
- agentsPendingWrapUp: [agentId, 'other-agent-456'], // Current agent IS in the list
2741
- },
3402
+ data: {type: CC_EVENTS.AGENT_CONSULT_CONFERENCE_FAILED, interactionId: taskId},
2742
3403
  };
2743
-
2744
3404
  webSocketManagerMock.emit('message', JSON.stringify(payload));
2745
-
2746
- expect(removeTaskSpy).not.toHaveBeenCalled();
2747
- expect(taskManager.getTask(taskId)).toBeDefined();
3405
+ expect(task.sendStateMachineEvent).toHaveBeenCalled();
3406
+ const call = task.sendStateMachineEvent.mock.calls[0][0];
3407
+ expect(call.type).toBe(TaskEvent.CONFERENCE_FAILED);
2748
3408
  });
2749
3409
 
2750
- it('should remove OUTDIAL task when needsWrapUp is false and task is outdial', () => {
2751
- const task = taskManager.getTask(taskId);
2752
- task.updateTaskData = jest.fn().mockImplementation((newData) => {
2753
- task.data = {
2754
- ...task.data,
2755
- ...newData,
2756
- interaction: {
2757
- ...task.data.interaction,
2758
- outboundType: 'OUTDIAL',
2759
- state: 'WRAPUP', // Not 'new' state
2760
- mediaType: 'telephony',
2761
- },
2762
- agentsPendingWrapUp: [], // No agents pending wrap-up
2763
- };
2764
- return task;
2765
- });
2766
- task.unregisterWebCallListeners = jest.fn();
2767
- const removeTaskSpy = jest.spyOn(taskManager, 'removeTaskFromCollection');
2768
-
3410
+ it('sends PARTICIPANT_LEFT_CONFERENCE to state machine as PARTICIPANT_LEAVE', () => {
2769
3411
  const payload = {
2770
- data: {
2771
- type: CC_EVENTS.CONTACT_ENDED,
2772
- interactionId: taskId,
2773
- interaction: {
2774
- outboundType: 'OUTDIAL',
2775
- state: 'WRAPUP', // Not 'new' state
2776
- mediaType: 'telephony',
2777
- },
2778
- agentsPendingWrapUp: [], // No agents pending wrap-up
2779
- },
3412
+ data: {type: CC_EVENTS.PARTICIPANT_LEFT_CONFERENCE, interactionId: taskId},
2780
3413
  };
2781
-
2782
3414
  webSocketManagerMock.emit('message', JSON.stringify(payload));
2783
-
2784
- expect(removeTaskSpy).toHaveBeenCalled();
2785
- expect(taskManager.getTask(taskId)).toBeUndefined();
3415
+ expect(task.sendStateMachineEvent).toHaveBeenCalled();
3416
+ const call = task.sendStateMachineEvent.mock.calls[0][0];
3417
+ expect(call.type).toBe(TaskEvent.PARTICIPANT_LEAVE);
2786
3418
  });
2787
3419
 
2788
- it('should remove OUTDIAL task when needsWrapUp is false (agentsPendingWrapUp is undefined)', () => {
2789
- const task = taskManager.getTask(taskId);
2790
- task.updateTaskData = jest.fn().mockImplementation((newData) => {
2791
- task.data = {
2792
- ...task.data,
2793
- ...newData,
2794
- interaction: {
2795
- ...task.data.interaction,
2796
- outboundType: 'OUTDIAL',
2797
- state: 'WRAPUP',
2798
- mediaType: 'telephony',
2799
- },
2800
- agentsPendingWrapUp: undefined, // No agentsPendingWrapUp field
2801
- };
2802
- return task;
3420
+ it('routes participant-left from a main interaction to a child-keyed task', () => {
3421
+ const childTaskId = 'child-interaction-id';
3422
+ const childTask = createMockTask({
3423
+ ...taskDataMock,
3424
+ interactionId: childTaskId,
3425
+ isConsulted: true,
3426
+ interaction: {
3427
+ mediaType: 'telephony',
3428
+ interactionId: childTaskId,
3429
+ parentInteractionId: taskId,
3430
+ },
2803
3431
  });
2804
- task.unregisterWebCallListeners = jest.fn();
2805
- const removeTaskSpy = jest.spyOn(taskManager, 'removeTaskFromCollection');
3432
+ delete taskManager.taskCollection[taskId];
3433
+ taskManager.taskCollection[childTaskId] = childTask;
2806
3434
 
2807
- const payload = {
2808
- data: {
2809
- type: CC_EVENTS.CONTACT_ENDED,
2810
- interactionId: taskId,
2811
- interaction: {
2812
- outboundType: 'OUTDIAL',
2813
- state: 'WRAPUP',
2814
- mediaType: 'telephony',
3435
+ webSocketManagerMock.emit(
3436
+ 'message',
3437
+ JSON.stringify({
3438
+ data: {
3439
+ type: CC_EVENTS.PARTICIPANT_LEFT_CONFERENCE,
3440
+ interactionId: taskId,
3441
+ participantId: 'test-agent-id',
3442
+ interaction: {
3443
+ mediaType: 'telephony',
3444
+ interactionId: taskId,
3445
+ mainInteractionId: taskId,
3446
+ },
2815
3447
  },
2816
- // agentsPendingWrapUp not included
2817
- },
2818
- };
2819
-
2820
- webSocketManagerMock.emit('message', JSON.stringify(payload));
3448
+ })
3449
+ );
2821
3450
 
2822
- expect(removeTaskSpy).toHaveBeenCalled();
2823
- expect(taskManager.getTask(taskId)).toBeUndefined();
3451
+ expect(childTask.sendStateMachineEvent).toHaveBeenCalledWith(
3452
+ expect.objectContaining({
3453
+ type: TaskEvent.PARTICIPANT_LEAVE,
3454
+ participantId: 'test-agent-id',
3455
+ })
3456
+ );
3457
+ expect(taskManager.taskCollection[childTaskId]).toBeUndefined();
3458
+ expect(taskManager.taskCollection[taskId]).toBe(childTask);
3459
+ expect(
3460
+ Object.values(taskManager.taskCollection).filter((entry) => entry === childTask)
3461
+ ).toHaveLength(1);
2824
3462
  });
2825
3463
 
2826
- it('should NOT remove OUTDIAL task when needsWrapUp is true (current agent in agentsPendingWrapUp) even if state is WRAPUP', () => {
2827
- const task = taskManager.getTask(taskId);
2828
- task.updateTaskData = jest.fn().mockImplementation((newData) => {
2829
- task.data = {
2830
- ...task.data,
2831
- ...newData,
2832
- interaction: {
2833
- ...task.data.interaction,
2834
- outboundType: 'OUTDIAL',
2835
- state: 'WRAPUP',
2836
- mediaType: 'telephony',
2837
- },
2838
- agentsPendingWrapUp: [agentId], // Current agent needs wrap-up
2839
- };
2840
- return task;
3464
+ it('routes consult-end from a main interaction to a child-keyed consulted task', () => {
3465
+ const childTaskId = 'consult-child-interaction-id';
3466
+ const childTask = createMockTask({
3467
+ ...taskDataMock,
3468
+ interactionId: childTaskId,
3469
+ isConsulted: true,
3470
+ interaction: {
3471
+ mediaType: 'telephony',
3472
+ interactionId: childTaskId,
3473
+ callProcessingDetails: {parentInteractionId: taskId},
3474
+ },
2841
3475
  });
2842
- task.unregisterWebCallListeners = jest.fn();
2843
- const removeTaskSpy = jest.spyOn(taskManager, 'removeTaskFromCollection');
3476
+ delete taskManager.taskCollection[taskId];
3477
+ taskManager.taskCollection[childTaskId] = childTask;
2844
3478
 
2845
- const payload = {
2846
- data: {
2847
- type: CC_EVENTS.CONTACT_ENDED,
2848
- interactionId: taskId,
2849
- interaction: {
2850
- outboundType: 'OUTDIAL',
2851
- state: 'WRAPUP',
2852
- mediaType: 'telephony',
3479
+ webSocketManagerMock.emit(
3480
+ 'message',
3481
+ JSON.stringify({
3482
+ data: {
3483
+ type: CC_EVENTS.AGENT_CONSULT_ENDED,
3484
+ interactionId: taskId,
3485
+ interaction: {
3486
+ mediaType: 'telephony',
3487
+ interactionId: taskId,
3488
+ mainInteractionId: taskId,
3489
+ },
2853
3490
  },
2854
- agentsPendingWrapUp: [agentId], // Current agent needs wrap-up
2855
- },
2856
- };
2857
-
2858
- webSocketManagerMock.emit('message', JSON.stringify(payload));
3491
+ })
3492
+ );
2859
3493
 
2860
- expect(removeTaskSpy).not.toHaveBeenCalled();
2861
- expect(taskManager.getTask(taskId)).toBeDefined();
3494
+ expect(childTask.sendStateMachineEvent).toHaveBeenCalledWith(
3495
+ expect.objectContaining({type: TaskEvent.CONSULT_END})
3496
+ );
2862
3497
  });
2863
3498
 
2864
- it('should remove non-OUTDIAL task when state is new regardless of agentsPendingWrapUp', () => {
2865
- const task = taskManager.getTask(taskId);
2866
- task.updateTaskData = jest.fn().mockImplementation((newData) => {
2867
- task.data = {
2868
- ...task.data,
2869
- ...newData,
2870
- interaction: {
2871
- ...task.data.interaction,
2872
- outboundType: 'PREVIEW', // Not OUTDIAL
2873
- state: 'new',
2874
- mediaType: 'telephony',
2875
- },
2876
- agentsPendingWrapUp: [agentId],
2877
- };
2878
- return task;
3499
+ it('deduplicates aliases of the same child task during related-interaction lookup', () => {
3500
+ const childTaskId = 'aliased-child-interaction-id';
3501
+ const childTask = createMockTask({
3502
+ ...taskDataMock,
3503
+ interactionId: childTaskId,
3504
+ interaction: {
3505
+ mediaType: 'telephony',
3506
+ interactionId: childTaskId,
3507
+ mainInteractionId: taskId,
3508
+ },
2879
3509
  });
2880
- task.unregisterWebCallListeners = jest.fn();
2881
- const removeTaskSpy = jest.spyOn(taskManager, 'removeTaskFromCollection');
3510
+ delete taskManager.taskCollection[taskId];
3511
+ taskManager.taskCollection[childTaskId] = childTask;
3512
+ taskManager.taskCollection['child-task-alias'] = childTask;
2882
3513
 
2883
- const payload = {
2884
- data: {
2885
- type: CC_EVENTS.CONTACT_ENDED,
2886
- interactionId: taskId,
2887
- interaction: {
2888
- outboundType: 'PREVIEW',
2889
- state: 'new',
2890
- mediaType: 'telephony',
3514
+ webSocketManagerMock.emit(
3515
+ 'message',
3516
+ JSON.stringify({
3517
+ data: {
3518
+ type: CC_EVENTS.PARTICIPANT_LEFT_CONFERENCE,
3519
+ interactionId: taskId,
3520
+ participantId: 'test-agent-id',
2891
3521
  },
2892
- agentsPendingWrapUp: [agentId],
2893
- },
2894
- };
2895
-
2896
- webSocketManagerMock.emit('message', JSON.stringify(payload));
3522
+ })
3523
+ );
2897
3524
 
2898
- expect(removeTaskSpy).toHaveBeenCalled();
2899
- expect(taskManager.getTask(taskId)).toBeUndefined();
3525
+ expect(childTask.sendStateMachineEvent).toHaveBeenCalledTimes(1);
3526
+ expect(
3527
+ Object.values(taskManager.taskCollection).filter((entry) => entry === childTask)
3528
+ ).toHaveLength(1);
2900
3529
  });
2901
3530
 
2902
- it('should handle agentsPendingWrapUp with multiple agents correctly - remove if current agent not in list', () => {
2903
- const task = taskManager.getTask(taskId);
2904
- task.updateTaskData = jest.fn().mockImplementation((newData) => {
2905
- task.data = {
2906
- ...task.data,
2907
- ...newData,
2908
- interaction: {
2909
- ...task.data.interaction,
2910
- outboundType: 'OUTDIAL',
2911
- state: 'new',
2912
- mediaType: 'telephony',
2913
- },
2914
- agentsPendingWrapUp: ['agent-1', 'agent-2', 'agent-3'], // Current agent not in the list
2915
- };
2916
- return task;
3531
+ it('prefers an exact task match over a child task with the same main interaction', () => {
3532
+ const childTaskId = 'child-interaction-id';
3533
+ const childTask = createMockTask({
3534
+ ...taskDataMock,
3535
+ interactionId: childTaskId,
3536
+ interaction: {
3537
+ mediaType: 'telephony',
3538
+ interactionId: childTaskId,
3539
+ mainInteractionId: taskId,
3540
+ },
2917
3541
  });
2918
- task.unregisterWebCallListeners = jest.fn();
2919
- const removeTaskSpy = jest.spyOn(taskManager, 'removeTaskFromCollection');
3542
+ taskManager.taskCollection[childTaskId] = childTask;
2920
3543
 
2921
- const payload = {
2922
- data: {
2923
- type: CC_EVENTS.CONTACT_ENDED,
2924
- interactionId: taskId,
2925
- interaction: {
2926
- outboundType: 'OUTDIAL',
2927
- state: 'new',
2928
- mediaType: 'telephony',
3544
+ webSocketManagerMock.emit(
3545
+ 'message',
3546
+ JSON.stringify({
3547
+ data: {
3548
+ type: CC_EVENTS.PARTICIPANT_LEFT_CONFERENCE,
3549
+ interactionId: taskId,
3550
+ participantId: 'another-agent',
2929
3551
  },
2930
- agentsPendingWrapUp: ['agent-1', 'agent-2', 'agent-3'],
2931
- },
2932
- };
2933
-
2934
- webSocketManagerMock.emit('message', JSON.stringify(payload));
3552
+ })
3553
+ );
2935
3554
 
2936
- expect(removeTaskSpy).toHaveBeenCalled();
2937
- expect(taskManager.getTask(taskId)).toBeUndefined();
3555
+ expect(task.sendStateMachineEvent).toHaveBeenCalled();
3556
+ expect(childTask.sendStateMachineEvent).not.toHaveBeenCalled();
2938
3557
  });
2939
3558
 
2940
- it('should handle agentsPendingWrapUp with multiple agents correctly - keep if current agent is in list', () => {
2941
- const task = taskManager.getTask(taskId);
2942
- task.updateTaskData = jest.fn().mockImplementation((newData) => {
2943
- task.data = {
2944
- ...task.data,
2945
- ...newData,
3559
+ it('does not route a main-interaction event when multiple unique child tasks match', () => {
3560
+ delete taskManager.taskCollection[taskId];
3561
+ const createChildTask = (interactionId: string) =>
3562
+ createMockTask({
3563
+ ...taskDataMock,
3564
+ interactionId,
2946
3565
  interaction: {
2947
- ...task.data.interaction,
2948
- outboundType: 'OUTDIAL',
2949
- state: 'new',
2950
3566
  mediaType: 'telephony',
3567
+ interactionId,
3568
+ mainInteractionId: taskId,
2951
3569
  },
2952
- agentsPendingWrapUp: ['agent-1', agentId, 'agent-3'], // Current agent IS in the list
2953
- };
2954
- return task;
2955
- });
2956
- task.unregisterWebCallListeners = jest.fn();
2957
- const removeTaskSpy = jest.spyOn(taskManager, 'removeTaskFromCollection');
2958
-
2959
- const payload = {
2960
- data: {
2961
- type: CC_EVENTS.CONTACT_ENDED,
2962
- interactionId: taskId,
2963
- interaction: {
2964
- outboundType: 'OUTDIAL',
2965
- state: 'new',
2966
- mediaType: 'telephony',
3570
+ });
3571
+ const firstChildTask = createChildTask('child-1');
3572
+ const secondChildTask = createChildTask('child-2');
3573
+ taskManager.taskCollection['child-1'] = firstChildTask;
3574
+ taskManager.taskCollection['child-2'] = secondChildTask;
3575
+
3576
+ webSocketManagerMock.emit(
3577
+ 'message',
3578
+ JSON.stringify({
3579
+ data: {
3580
+ type: CC_EVENTS.PARTICIPANT_LEFT_CONFERENCE,
3581
+ interactionId: taskId,
2967
3582
  },
2968
- agentsPendingWrapUp: ['agent-1', agentId, 'agent-3'],
2969
- },
2970
- };
2971
-
2972
- webSocketManagerMock.emit('message', JSON.stringify(payload));
2973
-
2974
- expect(removeTaskSpy).not.toHaveBeenCalled();
2975
- expect(taskManager.getTask(taskId)).toBeDefined();
2976
- });
2977
- });
2978
-
2979
- describe('CONTACT_MERGED event handling', () => {
2980
- let task;
2981
- let taskEmitSpy;
2982
- let managerEmitSpy;
3583
+ })
3584
+ );
2983
3585
 
2984
- beforeEach(() => {
2985
- // Create initial task
2986
- webSocketManagerMock.emit('message', JSON.stringify(initalPayload));
2987
- task = taskManager.getTask(taskId);
2988
- taskEmitSpy = jest.spyOn(task, 'emit');
2989
- managerEmitSpy = jest.spyOn(taskManager, 'emit');
3586
+ expect(firstChildTask.sendStateMachineEvent).not.toHaveBeenCalled();
3587
+ expect(secondChildTask.sendStateMachineEvent).not.toHaveBeenCalled();
2990
3588
  });
2991
3589
 
2992
- it('should update existing task data and emit TASK_MERGED event when CONTACT_MERGED is received', () => {
2993
- const mergedPayload = {
2994
- data: {
2995
- type: CC_EVENTS.CONTACT_MERGED,
2996
- interactionId: taskId,
2997
- agentId: taskDataMock.agentId,
2998
- interaction: {
2999
- ...taskDataMock.interaction,
3000
- state: 'merged',
3001
- customField: 'updated-value',
3590
+ it('does not route a lifecycle event without a correlation identifier', () => {
3591
+ webSocketManagerMock.emit(
3592
+ 'message',
3593
+ JSON.stringify({
3594
+ data: {
3595
+ type: CC_EVENTS.PARTICIPANT_LEFT_CONFERENCE,
3596
+ participantId: 'another-agent',
3002
3597
  },
3003
- },
3004
- };
3005
-
3006
- webSocketManagerMock.emit('message', JSON.stringify(mergedPayload));
3598
+ })
3599
+ );
3007
3600
 
3008
- const updatedTask = taskManager.getTask(taskId);
3009
- expect(updatedTask).toBeDefined();
3010
- expect(updatedTask.data.interaction.customField).toBe('updated-value');
3011
- expect(updatedTask.data.interaction.state).toBe('merged');
3012
- expect(managerEmitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_MERGED, updatedTask);
3601
+ expect(task.sendStateMachineEvent).not.toHaveBeenCalled();
3013
3602
  });
3014
3603
 
3015
- it('should create new task when CONTACT_MERGED is received for non-existing task', () => {
3016
- const newMergedTaskId = 'new-merged-task-id';
3017
- const mergedPayload = {
3018
- data: {
3019
- type: CC_EVENTS.CONTACT_MERGED,
3020
- interactionId: newMergedTaskId,
3021
- agentId: taskDataMock.agentId,
3022
- interaction: {
3023
- mediaType: 'telephony',
3024
- state: 'merged',
3025
- participants: {
3026
- [taskDataMock.agentId]: {
3027
- isWrapUp: false,
3028
- hasJoined: true,
3029
- },
3030
- },
3031
- },
3032
- },
3033
- };
3034
-
3035
- // Verify task doesn't exist before
3036
- expect(taskManager.getTask(newMergedTaskId)).toBeUndefined();
3604
+ it('removes every collection alias for a task during terminal cleanup', () => {
3605
+ taskManager.taskCollection['task-alias'] = task;
3037
3606
 
3038
- webSocketManagerMock.emit('message', JSON.stringify(mergedPayload));
3607
+ (taskManager as any).removeTaskFromCollection(task);
3039
3608
 
3040
- // Verify task was created
3041
- const newTask = taskManager.getTask(newMergedTaskId);
3042
- expect(newTask).toBeDefined();
3043
- expect(newTask.data.interactionId).toBe(newMergedTaskId);
3044
- expect(managerEmitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_MERGED, newTask);
3609
+ expect(taskManager.taskCollection[taskId]).toBeUndefined();
3610
+ expect(taskManager.taskCollection['task-alias']).toBeUndefined();
3045
3611
  });
3046
3612
 
3047
- it('should remove child task when childInteractionId is present in CONTACT_MERGED', () => {
3048
- const childTaskId = 'child-task-id';
3049
- const parentTaskId = 'parent-task-id';
3050
-
3051
- // Create child task
3052
- const childPayload = {
3053
- data: {
3054
- type: CC_EVENTS.AGENT_CONTACT_RESERVED,
3613
+ it('replaces an EP-DN child task with a hydrated main task on CONTACT_MERGED', () => {
3614
+ const childTaskId = 'ep-dn-child-interaction-id';
3615
+ const childTask = createMockTask({
3616
+ ...taskDataMock,
3617
+ interactionId: childTaskId,
3618
+ interaction: {
3619
+ mediaType: 'telephony',
3055
3620
  interactionId: childTaskId,
3056
- agentId: taskDataMock.agentId,
3057
- interaction: {mediaType: 'telephony'},
3058
- },
3059
- };
3060
- webSocketManagerMock.emit('message', JSON.stringify(childPayload));
3061
-
3062
- // Verify child task exists
3063
- expect(taskManager.getTask(childTaskId)).toBeDefined();
3064
-
3065
- // Create parent task
3066
- const parentPayload = {
3067
- data: {
3068
- type: CC_EVENTS.AGENT_CONTACT_RESERVED,
3069
- interactionId: parentTaskId,
3070
- agentId: taskDataMock.agentId,
3071
- interaction: {mediaType: 'telephony'},
3072
- },
3073
- };
3074
- webSocketManagerMock.emit('message', JSON.stringify(parentPayload));
3075
-
3076
- // Send CONTACT_MERGED with childInteractionId
3077
- const mergedPayload = {
3078
- data: {
3079
- type: CC_EVENTS.CONTACT_MERGED,
3080
- interactionId: parentTaskId,
3081
- childInteractionId: childTaskId,
3082
- agentId: taskDataMock.agentId,
3083
- interaction: {
3084
- mediaType: 'telephony',
3085
- state: 'merged',
3086
- },
3621
+ parentInteractionId: taskId,
3087
3622
  },
3088
- };
3089
-
3090
- webSocketManagerMock.emit('message', JSON.stringify(mergedPayload));
3091
-
3092
- // Verify child task was removed
3093
- expect(taskManager.getTask(childTaskId)).toBeUndefined();
3094
-
3095
- // Verify parent task still exists
3096
- expect(taskManager.getTask(parentTaskId)).toBeDefined();
3097
-
3098
- // Verify TASK_MERGED event was emitted
3099
- expect(managerEmitSpy).toHaveBeenCalledWith(
3100
- TASK_EVENTS.TASK_MERGED,
3101
- expect.objectContaining({
3102
- data: expect.objectContaining({
3103
- interactionId: parentTaskId,
3104
- }),
3105
- })
3106
- );
3107
- });
3108
-
3109
- it('should handle CONTACT_MERGED with EP-DN participant correctly', () => {
3110
- const epdnTaskId = 'epdn-merged-task';
3111
- const mergedPayload = {
3112
- data: {
3113
- type: CC_EVENTS.CONTACT_MERGED,
3114
- interactionId: epdnTaskId,
3115
- agentId: taskDataMock.agentId,
3116
- interaction: {
3117
- mediaType: 'telephony',
3118
- state: 'merged',
3119
- participants: {
3120
- [taskDataMock.agentId]: {
3121
- type: 'Agent',
3122
- isWrapUp: false,
3123
- hasJoined: true,
3623
+ });
3624
+ const mergedHandler = jest.fn();
3625
+ delete taskManager.taskCollection[taskId];
3626
+ taskManager.taskCollection[childTaskId] = childTask;
3627
+ taskManager.on(TASK_EVENTS.TASK_MERGED, mergedHandler);
3628
+
3629
+ webSocketManagerMock.emit(
3630
+ 'message',
3631
+ JSON.stringify({
3632
+ data: {
3633
+ type: CC_EVENTS.CONTACT_MERGED,
3634
+ interactionId: taskId,
3635
+ childInteractionId: childTaskId,
3636
+ interaction: {
3637
+ mediaType: 'telephony',
3638
+ interactionId: taskId,
3639
+ mainInteractionId: taskId,
3640
+ state: 'conference',
3641
+ owner: 'test-agent-id',
3642
+ participants: {
3643
+ 'test-agent-id': {id: 'test-agent-id', pType: 'Agent', hasLeft: false},
3124
3644
  },
3125
- 'epdn-participant': {
3126
- type: 'EpDn',
3127
- epId: 'entry-point-123',
3128
- isWrapUp: false,
3645
+ media: {
3646
+ [taskId]: {
3647
+ mediaResourceId: taskId,
3648
+ mediaType: 'telephony',
3649
+ mType: 'mainCall',
3650
+ participants: ['test-agent-id'],
3651
+ },
3129
3652
  },
3130
3653
  },
3131
3654
  },
3132
- },
3133
- };
3134
-
3135
- webSocketManagerMock.emit('message', JSON.stringify(mergedPayload));
3655
+ })
3656
+ );
3136
3657
 
3137
- const mergedTask = taskManager.getTask(epdnTaskId);
3138
- expect(mergedTask).toBeDefined();
3139
- expect(mergedTask.data.interaction.participants['epdn-participant']).toBeDefined();
3140
- expect(mergedTask.data.interaction.participants['epdn-participant'].type).toBe('EpDn');
3141
- expect(managerEmitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_MERGED, mergedTask);
3658
+ const mainTask = taskManager.taskCollection[taskId];
3659
+ expect(taskManager.taskCollection[childTaskId]).toBeUndefined();
3660
+ expect(mainTask).toBeDefined();
3661
+ expect(mainTask).not.toBe(childTask);
3662
+ expect(mainTask.sendStateMachineEvent).toHaveBeenCalledWith(
3663
+ expect.objectContaining({type: TaskEvent.HYDRATE})
3664
+ );
3665
+ expect(mergedHandler).toHaveBeenCalledWith(mainTask);
3142
3666
  });
3143
3667
 
3144
- it('should not affect other tasks when CONTACT_MERGED is received', () => {
3145
- const otherTaskId = 'other-unrelated-task';
3146
- const otherPayload = {
3147
- data: {
3148
- type: CC_EVENTS.AGENT_CONTACT_RESERVED,
3149
- interactionId: otherTaskId,
3150
- agentId: taskDataMock.agentId,
3151
- interaction: {mediaType: 'chat'},
3152
- },
3153
- };
3154
- webSocketManagerMock.emit('message', JSON.stringify(otherPayload));
3155
-
3156
- const otherTask = taskManager.getTask(otherTaskId);
3157
- const otherTaskEmitSpy = jest.spyOn(otherTask, 'emit');
3158
-
3159
- // Send CONTACT_MERGED for the original task
3160
- const mergedPayload = {
3161
- data: {
3162
- type: CC_EVENTS.CONTACT_MERGED,
3163
- interactionId: taskId,
3164
- agentId: taskDataMock.agentId,
3165
- interaction: {
3166
- mediaType: 'telephony',
3167
- state: 'merged',
3168
- },
3169
- },
3668
+ it('handles AGENT_CONSULT_CONFERENCING event without errors', () => {
3669
+ const payload = {
3670
+ data: {type: CC_EVENTS.AGENT_CONSULT_CONFERENCING, interactionId: taskId},
3170
3671
  };
3171
-
3172
- webSocketManagerMock.emit('message', JSON.stringify(mergedPayload));
3173
-
3174
- // Verify other task was not affected
3175
- expect(otherTaskEmitSpy).not.toHaveBeenCalled();
3176
- expect(otherTask.data.interaction.mediaType).toBe('chat');
3177
-
3178
- // Verify original task was updated
3179
- expect(managerEmitSpy).toHaveBeenCalledWith(
3180
- TASK_EVENTS.TASK_MERGED,
3181
- expect.objectContaining({
3182
- data: expect.objectContaining({
3183
- interactionId: taskId,
3184
- }),
3185
- })
3186
- );
3672
+ expect(() => {
3673
+ webSocketManagerMock.emit('message', JSON.stringify(payload));
3674
+ }).not.toThrow();
3187
3675
  });
3188
- });
3189
3676
 
3190
- describe('Campaign Preview Reservation', () => {
3191
- it('should create a task and emit TASK_CAMPAIGN_PREVIEW_RESERVATION when AgentOfferCampaignReservation is received', () => {
3192
- const campaignPayload = {
3193
- data: {
3194
- type: CC_EVENTS.AGENT_OFFER_CAMPAIGN_RESERVATION,
3195
- interactionId: 'campaign-interaction-123',
3196
- agentId: taskDataMock.agentId,
3197
- orgId: taskDataMock.orgId,
3198
- trackingId: 'campaign-tracking-456',
3199
- interaction: {
3200
- mediaType: 'telephony',
3201
- callProcessingDetails: {
3202
- campaignId: 'campaign-789',
3203
- },
3204
- },
3205
- },
3677
+ it('handles PARTICIPANT_LEFT_CONFERENCE_FAILED event without errors', () => {
3678
+ const payload = {
3679
+ data: {type: CC_EVENTS.PARTICIPANT_LEFT_CONFERENCE_FAILED, interactionId: taskId},
3206
3680
  };
3207
-
3208
- const managerEmitSpy = jest.spyOn(taskManager, 'emit');
3209
-
3210
- webSocketManagerMock.emit('message', JSON.stringify(campaignPayload));
3211
-
3212
- // Should emit with a task object (not raw data)
3213
- expect(managerEmitSpy).toHaveBeenCalledWith(
3214
- TASK_EVENTS.TASK_CAMPAIGN_PREVIEW_RESERVATION,
3215
- expect.objectContaining({
3216
- data: expect.objectContaining({
3217
- interactionId: 'campaign-interaction-123',
3218
- type: CC_EVENTS.AGENT_OFFER_CAMPAIGN_RESERVATION,
3219
- wrapUpRequired: false,
3220
- isAutoAnswering: false,
3221
- }),
3222
- })
3223
- );
3224
-
3225
- // Task should be in the collection so subsequent events (e.g. AGENT_CONTACT_ASSIGNED) can find it
3226
- expect(taskManager['taskCollection']['campaign-interaction-123']).toBeDefined();
3681
+ expect(() => {
3682
+ webSocketManagerMock.emit('message', JSON.stringify(payload));
3683
+ }).not.toThrow();
3227
3684
  });
3228
3685
 
3229
- it('should not emit TASK_INCOMING for campaign preview reservation when incoming WebRTC call arrives', () => {
3230
- const campaignPayload = {
3231
- data: {
3232
- type: CC_EVENTS.AGENT_OFFER_CAMPAIGN_RESERVATION,
3233
- interactionId: 'campaign-interaction-123',
3234
- agentId: taskDataMock.agentId,
3235
- orgId: taskDataMock.orgId,
3236
- trackingId: 'campaign-tracking-456',
3237
- interaction: {
3238
- mediaType: 'telephony',
3239
- callProcessingDetails: {
3240
- campaignId: 'campaign-789',
3241
- },
3242
- },
3243
- },
3686
+ it('only routes conference events to matching tasks', () => {
3687
+ const otherTaskId = 'other-task-id';
3688
+ const otherTask: any = {
3689
+ data: {interactionId: otherTaskId},
3690
+ emit: jest.fn(),
3691
+ updateTaskData: jest.fn(),
3692
+ sendStateMachineEvent: jest.fn(),
3244
3693
  };
3694
+ taskManager.taskCollection[otherTaskId] = otherTask;
3245
3695
 
3246
- // Remove the default task so only the campaign preview task is in the collection
3247
- delete taskManager['taskCollection'][taskId];
3248
-
3249
- // Create campaign preview task via the reservation event
3250
- webSocketManagerMock.emit('message', JSON.stringify(campaignPayload));
3696
+ const payload = {
3697
+ data: {type: CC_EVENTS.AGENT_CONSULT_CONFERENCED, interactionId: taskId},
3698
+ };
3699
+ webSocketManagerMock.emit('message', JSON.stringify(payload));
3251
3700
 
3252
- const managerEmitSpy = jest.spyOn(taskManager, 'emit');
3701
+ expect(task.sendStateMachineEvent).toHaveBeenCalled();
3702
+ expect(otherTask.sendStateMachineEvent).not.toHaveBeenCalled();
3703
+ });
3704
+ });
3253
3705
 
3254
- // Simulate an incoming WebRTC call
3255
- const incomingCallCb = onSpy.mock.calls[0][1];
3256
- incomingCallCb(mockCall);
3706
+ describe('state machine integration', () => {
3707
+ it('maps CC events to task state machine events using normalized payload', () => {
3708
+ const mapped = (TaskManager as any).mapEventToTaskStateMachineEvent(
3709
+ CC_EVENTS.AGENT_CONTACT_ASSIGNED,
3710
+ {...taskDataMock, type: CC_EVENTS.AGENT_CONTACT_ASSIGNED}
3711
+ );
3257
3712
 
3258
- // TASK_INCOMING should NOT be emitted because the only telephony task is a campaign preview
3259
- expect(managerEmitSpy).not.toHaveBeenCalledWith(TASK_EVENTS.TASK_INCOMING, expect.anything());
3713
+ expect(mapped).toEqual({
3714
+ type: TaskEvent.ASSIGN,
3715
+ taskData: {...taskDataMock, type: CC_EVENTS.AGENT_CONTACT_ASSIGNED},
3716
+ });
3260
3717
  });
3261
3718
 
3262
- it('should update existing task when AgentOfferCampaignReservation is received for known interactionId', () => {
3263
- const campaignPayload = {
3264
- data: {
3265
- type: CC_EVENTS.AGENT_OFFER_CAMPAIGN_RESERVATION,
3266
- interactionId: 'campaign-interaction-123',
3267
- agentId: taskDataMock.agentId,
3268
- orgId: taskDataMock.orgId,
3269
- trackingId: 'campaign-tracking-456',
3270
- interaction: {
3271
- mediaType: 'telephony',
3272
- callProcessingDetails: {
3273
- campaignId: 'campaign-789',
3274
- },
3275
- },
3276
- },
3277
- };
3278
-
3279
- // Send the first reservation to create the task
3280
- webSocketManagerMock.emit('message', JSON.stringify(campaignPayload));
3719
+ it('sends mapped events to the task state machine service', () => {
3720
+ const payload = {...taskDataMock, type: CC_EVENTS.AGENT_CONTACT_ASSIGNED};
3721
+ const task = taskManager.getTask(taskId);
3722
+ const sendStateMachineEventSpy = jest.spyOn(task, 'sendStateMachineEvent');
3281
3723
 
3282
- const managerEmitSpy = jest.spyOn(taskManager, 'emit');
3724
+ webSocketManagerMock.emit('message', JSON.stringify({data: payload}));
3283
3725
 
3284
- // Send a second reservation for the same interactionId
3285
- webSocketManagerMock.emit('message', JSON.stringify(campaignPayload));
3726
+ expect(sendStateMachineEventSpy).toHaveBeenCalledWith({
3727
+ type: TaskEvent.ASSIGN,
3728
+ taskData: payload,
3729
+ });
3286
3730
 
3287
- expect(managerEmitSpy).toHaveBeenCalledWith(
3288
- TASK_EVENTS.TASK_CAMPAIGN_PREVIEW_RESERVATION,
3289
- expect.objectContaining({
3290
- data: expect.objectContaining({
3291
- interactionId: 'campaign-interaction-123',
3292
- }),
3293
- })
3294
- );
3731
+ sendStateMachineEventSpy.mockRestore();
3295
3732
  });
3733
+ });
3296
3734
 
3297
- it('should update task data but NOT remove task when CampaignContactUpdated is received', () => {
3298
- const campaignInteractionId = 'campaign-interaction-123';
3735
+ describe('applyEnableWxBetterTogether', () => {
3736
+ it('updates config flags and propagates to active tasks', () => {
3737
+ const taskOne = {setEnableWxBetterTogether: jest.fn()};
3738
+ const taskTwo = {setEnableWxBetterTogether: jest.fn()};
3299
3739
 
3300
- // First create a campaign preview task
3301
- const reservationPayload = {
3302
- data: {
3303
- type: CC_EVENTS.AGENT_OFFER_CAMPAIGN_RESERVATION,
3304
- interactionId: campaignInteractionId,
3305
- agentId: taskDataMock.agentId,
3306
- orgId: taskDataMock.orgId,
3307
- trackingId: 'campaign-tracking-456',
3308
- interaction: {
3309
- mediaType: 'telephony',
3310
- callProcessingDetails: {
3311
- campaignId: 'campaign-789',
3312
- },
3313
- },
3314
- },
3740
+ taskManager.setConfigFlags({
3741
+ isEndTaskEnabled: true,
3742
+ isEndConsultEnabled: true,
3743
+ enableWxBetterTogether: true,
3744
+ });
3745
+ taskManager['taskCollection'] = {
3746
+ [taskId]: taskOne,
3747
+ 'task-2': taskTwo,
3315
3748
  };
3316
3749
 
3317
- webSocketManagerMock.emit('message', JSON.stringify(reservationPayload));
3750
+ taskManager.applyEnableWxBetterTogether(false);
3318
3751
 
3319
- // Verify task exists in collection
3320
- const task = taskManager['taskCollection'][campaignInteractionId];
3321
- expect(task).toBeDefined();
3752
+ expect(taskManager['configFlags']?.enableWxBetterTogether).toBe(false);
3753
+ expect(taskOne.setEnableWxBetterTogether).toHaveBeenCalledWith(false);
3754
+ expect(taskTwo.setEnableWxBetterTogether).toHaveBeenCalledWith(false);
3755
+ });
3756
+ });
3322
3757
 
3323
- const taskEmitSpy = jest.spyOn(task, 'emit');
3758
+ describe('applyWxAppMuteStateFromSync', () => {
3759
+ it('propagates mute state to all tasks', () => {
3760
+ const taskOne = {applyWxAppMuteStateFromSync: jest.fn()};
3761
+ const taskTwo = {applyWxAppMuteStateFromSync: jest.fn()};
3324
3762
 
3325
- // Now send CampaignContactUpdated
3326
- const campaignContactUpdatedPayload = {
3327
- data: {
3328
- type: CC_EVENTS.CAMPAIGN_CONTACT_UPDATED,
3329
- interactionId: campaignInteractionId,
3330
- agentId: taskDataMock.agentId,
3331
- orgId: taskDataMock.orgId,
3332
- interaction: {
3333
- mediaType: 'telephony',
3334
- state: 'new',
3335
- callProcessingDetails: {
3336
- campaignId: 'campaign-789',
3337
- },
3338
- },
3339
- },
3763
+ taskManager['taskCollection'] = {
3764
+ [taskId]: taskOne,
3765
+ 'task-2': taskTwo,
3340
3766
  };
3341
3767
 
3342
- webSocketManagerMock.emit('message', JSON.stringify(campaignContactUpdatedPayload));
3343
-
3344
- // Task should still exist in collection (not removed — non-terminal event)
3345
- expect(taskManager['taskCollection'][campaignInteractionId]).toBeDefined();
3768
+ taskManager.applyWxAppMuteStateFromSync('call-1', true);
3346
3769
 
3347
- // TASK_END should NOT have been emitted
3348
- expect(taskEmitSpy).not.toHaveBeenCalledWith(TASK_EVENTS.TASK_END, expect.anything());
3770
+ expect(taskOne.applyWxAppMuteStateFromSync).toHaveBeenCalledWith('call-1', true);
3771
+ expect(taskTwo.applyWxAppMuteStateFromSync).toHaveBeenCalledWith('call-1', true);
3349
3772
  });
3350
3773
  });
3351
3774
  });