@webex/contact-center 3.12.0 → 3.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (337) hide show
  1. package/.sdd/manifest.json +887 -0
  2. package/AGENTS.md +94 -0
  3. package/ai-docs/ARCHITECTURE.md +168 -0
  4. package/ai-docs/CONTRACTS.md +62 -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 +52 -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 +385 -0
  17. package/ai-docs/features/consult-transfer-list-policy/spec/feature-spec.md +362 -0
  18. package/ai-docs/features/contact-owner-change-refactor.md +78 -0
  19. package/ai-docs/features/generated-spec-conformance-fidelity-remediation/spec/feature-spec.md +117 -0
  20. package/ai-docs/features/residual-warning-coverage-completion/spec/feature-spec.md +203 -0
  21. package/ai-docs/features/validator-code-fidelity-drift-fix/spec/feature-spec.md +315 -0
  22. package/ai-docs/patterns/event-driven-patterns.md +485 -0
  23. package/ai-docs/patterns/testing-patterns.md +480 -0
  24. package/ai-docs/patterns/typescript-patterns.md +365 -0
  25. package/ai-docs/templates/README.md +102 -0
  26. package/ai-docs/templates/documentation/create-agents-md.md +240 -0
  27. package/ai-docs/templates/documentation/create-architecture-md.md +295 -0
  28. package/ai-docs/templates/existing-service/bug-fix.md +254 -0
  29. package/ai-docs/templates/existing-service/feature-enhancement.md +450 -0
  30. package/ai-docs/templates/new-method/00-master.md +80 -0
  31. package/ai-docs/templates/new-method/01-requirements.md +232 -0
  32. package/ai-docs/templates/new-method/02-implementation.md +295 -0
  33. package/ai-docs/templates/new-method/03-tests.md +201 -0
  34. package/ai-docs/templates/new-method/04-validation.md +141 -0
  35. package/ai-docs/templates/new-service/00-master.md +109 -0
  36. package/ai-docs/templates/new-service/01-pre-questions.md +159 -0
  37. package/ai-docs/templates/new-service/02-code-generation.md +346 -0
  38. package/ai-docs/templates/new-service/03-integration.md +178 -0
  39. package/ai-docs/templates/new-service/04-test-generation.md +205 -0
  40. package/ai-docs/templates/new-service/05-validation.md +145 -0
  41. package/dist/cc.js +1045 -45
  42. package/dist/cc.js.map +1 -1
  43. package/dist/config.js +13 -0
  44. package/dist/config.js.map +1 -1
  45. package/dist/constants.js +40 -3
  46. package/dist/constants.js.map +1 -1
  47. package/dist/index.js +54 -17
  48. package/dist/index.js.map +1 -1
  49. package/dist/metrics/MetricsManager.js +16 -0
  50. package/dist/metrics/MetricsManager.js.map +1 -1
  51. package/dist/metrics/behavioral-events.js +211 -0
  52. package/dist/metrics/behavioral-events.js.map +1 -1
  53. package/dist/metrics/constants.js +58 -4
  54. package/dist/metrics/constants.js.map +1 -1
  55. package/dist/services/AddressBook.js +18 -15
  56. package/dist/services/AddressBook.js.map +1 -1
  57. package/dist/services/AnswerCallOnWebexService.js +202 -0
  58. package/dist/services/AnswerCallOnWebexService.js.map +1 -0
  59. package/dist/services/ApiAiAssistant.js +369 -14
  60. package/dist/services/ApiAiAssistant.js.map +1 -1
  61. package/dist/services/EntryPoint.js +46 -68
  62. package/dist/services/EntryPoint.js.map +1 -1
  63. package/dist/services/Queue.js +27 -22
  64. package/dist/services/Queue.js.map +1 -1
  65. package/dist/services/UserPreference.js +427 -0
  66. package/dist/services/UserPreference.js.map +1 -0
  67. package/dist/services/WebCallingService.js +10 -2
  68. package/dist/services/WebCallingService.js.map +1 -1
  69. package/dist/services/WebexCrossClientService.js +225 -0
  70. package/dist/services/WebexCrossClientService.js.map +1 -0
  71. package/dist/services/WxAppTelephonyMercurySync.js +111 -0
  72. package/dist/services/WxAppTelephonyMercurySync.js.map +1 -0
  73. package/dist/services/config/Util.js +48 -48
  74. package/dist/services/config/Util.js.map +1 -1
  75. package/dist/services/config/constants.js +57 -79
  76. package/dist/services/config/constants.js.map +1 -1
  77. package/dist/services/config/index.js +100 -226
  78. package/dist/services/config/index.js.map +1 -1
  79. package/dist/services/config/types.js +97 -24
  80. package/dist/services/config/types.js.map +1 -1
  81. package/dist/services/constants.js +19 -1
  82. package/dist/services/constants.js.map +1 -1
  83. package/dist/services/core/Err.js.map +1 -1
  84. package/dist/services/core/Utils.js +131 -32
  85. package/dist/services/core/Utils.js.map +1 -1
  86. package/dist/services/core/WebexRequest.js +6 -2
  87. package/dist/services/core/WebexRequest.js.map +1 -1
  88. package/dist/services/core/aqm-reqs.js +17 -11
  89. package/dist/services/core/aqm-reqs.js.map +1 -1
  90. package/dist/services/core/constants.js +9 -1
  91. package/dist/services/core/constants.js.map +1 -1
  92. package/dist/services/core/types.js.map +1 -1
  93. package/dist/services/core/websocket/WebSocketManager.js +26 -6
  94. package/dist/services/core/websocket/WebSocketManager.js.map +1 -1
  95. package/dist/services/core/websocket/connection-service.js +3 -1
  96. package/dist/services/core/websocket/connection-service.js.map +1 -1
  97. package/dist/services/core/websocket/types.js.map +1 -1
  98. package/dist/services/index.js +6 -0
  99. package/dist/services/index.js.map +1 -1
  100. package/dist/services/task/Task.js +955 -0
  101. package/dist/services/task/Task.js.map +1 -0
  102. package/dist/services/task/TaskFactory.js +50 -0
  103. package/dist/services/task/TaskFactory.js.map +1 -0
  104. package/dist/services/task/TaskManager.js +1275 -504
  105. package/dist/services/task/TaskManager.js.map +1 -1
  106. package/dist/services/task/TaskUtils.js +221 -27
  107. package/dist/services/task/TaskUtils.js.map +1 -1
  108. package/dist/services/task/WebexCallingUtils.js +70 -0
  109. package/dist/services/task/WebexCallingUtils.js.map +1 -0
  110. package/dist/services/task/constants.js +22 -2
  111. package/dist/services/task/constants.js.map +1 -1
  112. package/dist/services/task/contact.js +29 -0
  113. package/dist/services/task/contact.js.map +1 -1
  114. package/dist/services/task/dialer.js +78 -0
  115. package/dist/services/task/dialer.js.map +1 -1
  116. package/dist/services/task/digital/Digital.js +78 -0
  117. package/dist/services/task/digital/Digital.js.map +1 -0
  118. package/dist/services/task/state-machine/TaskStateMachine.js +982 -0
  119. package/dist/services/task/state-machine/TaskStateMachine.js.map +1 -0
  120. package/dist/services/task/state-machine/actions.js +572 -0
  121. package/dist/services/task/state-machine/actions.js.map +1 -0
  122. package/dist/services/task/state-machine/constants.js +161 -0
  123. package/dist/services/task/state-machine/constants.js.map +1 -0
  124. package/dist/services/task/state-machine/guards.js +379 -0
  125. package/dist/services/task/state-machine/guards.js.map +1 -0
  126. package/dist/services/task/state-machine/index.js +53 -0
  127. package/dist/services/task/state-machine/index.js.map +1 -0
  128. package/dist/services/task/state-machine/types.js +54 -0
  129. package/dist/services/task/state-machine/types.js.map +1 -0
  130. package/dist/services/task/state-machine/uiControlsComputer.js +703 -0
  131. package/dist/services/task/state-machine/uiControlsComputer.js.map +1 -0
  132. package/dist/services/task/taskDataNormalizer.js +99 -0
  133. package/dist/services/task/taskDataNormalizer.js.map +1 -0
  134. package/dist/services/task/types.js +259 -5
  135. package/dist/services/task/types.js.map +1 -1
  136. package/dist/services/task/voice/Voice.js +1504 -0
  137. package/dist/services/task/voice/Voice.js.map +1 -0
  138. package/dist/services/task/voice/WebRTC.js +152 -0
  139. package/dist/services/task/voice/WebRTC.js.map +1 -0
  140. package/dist/services/task/voice/wxAppOfferObservability.js +145 -0
  141. package/dist/services/task/voice/wxAppOfferObservability.js.map +1 -0
  142. package/dist/services/task/voice/wxAppVoiceMethods.js +395 -0
  143. package/dist/services/task/voice/wxAppVoiceMethods.js.map +1 -0
  144. package/dist/services/wxAppDiagnosticLogging.js +159 -0
  145. package/dist/services/wxAppDiagnosticLogging.js.map +1 -0
  146. package/dist/services/wxAppTelephonyUtils.js +19 -0
  147. package/dist/services/wxAppTelephonyUtils.js.map +1 -0
  148. package/dist/types/cc.d.ts +197 -9
  149. package/dist/types/config.d.ts +13 -0
  150. package/dist/types/constants.d.ts +38 -1
  151. package/dist/types/index.d.ts +54 -20
  152. package/dist/types/metrics/MetricsManager.d.ts +6 -0
  153. package/dist/types/metrics/constants.d.ts +52 -1
  154. package/dist/types/services/AddressBook.d.ts +2 -1
  155. package/dist/types/services/AnswerCallOnWebexService.d.ts +38 -0
  156. package/dist/types/services/ApiAiAssistant.d.ts +67 -5
  157. package/dist/types/services/EntryPoint.d.ts +7 -5
  158. package/dist/types/services/Queue.d.ts +5 -3
  159. package/dist/types/services/UserPreference.d.ts +118 -0
  160. package/dist/types/services/WebexCrossClientService.d.ts +32 -0
  161. package/dist/types/services/WxAppTelephonyMercurySync.d.ts +28 -0
  162. package/dist/types/services/config/Util.d.ts +4 -8
  163. package/dist/types/services/config/constants.d.ts +49 -76
  164. package/dist/types/services/config/index.d.ts +16 -64
  165. package/dist/types/services/config/types.d.ts +248 -114
  166. package/dist/types/services/constants.d.ts +16 -0
  167. package/dist/types/services/core/Err.d.ts +6 -0
  168. package/dist/types/services/core/Utils.d.ts +43 -13
  169. package/dist/types/services/core/WebexRequest.d.ts +1 -0
  170. package/dist/types/services/core/constants.d.ts +7 -0
  171. package/dist/types/services/core/types.d.ts +2 -0
  172. package/dist/types/services/core/websocket/WebSocketManager.d.ts +2 -0
  173. package/dist/types/services/core/websocket/types.d.ts +1 -1
  174. package/dist/types/services/index.d.ts +2 -0
  175. package/dist/types/services/task/Task.d.ts +186 -0
  176. package/dist/types/services/task/TaskFactory.d.ts +14 -0
  177. package/dist/types/services/task/TaskUtils.d.ts +54 -2
  178. package/dist/types/services/task/WebexCallingUtils.d.ts +11 -0
  179. package/dist/types/services/task/constants.d.ts +20 -0
  180. package/dist/types/services/task/contact.d.ts +4 -0
  181. package/dist/types/services/task/dialer.d.ts +30 -0
  182. package/dist/types/services/task/digital/Digital.d.ts +23 -0
  183. package/dist/types/services/task/state-machine/TaskStateMachine.d.ts +1442 -0
  184. package/dist/types/services/task/state-machine/actions.d.ts +10 -0
  185. package/dist/types/services/task/state-machine/constants.d.ts +107 -0
  186. package/dist/types/services/task/state-machine/guards.d.ts +103 -0
  187. package/dist/types/services/task/state-machine/index.d.ts +13 -0
  188. package/dist/types/services/task/state-machine/types.d.ts +277 -0
  189. package/dist/types/services/task/state-machine/uiControlsComputer.d.ts +9 -0
  190. package/dist/types/services/task/taskDataNormalizer.d.ts +10 -0
  191. package/dist/types/services/task/types.d.ts +790 -66
  192. package/dist/types/services/task/voice/Voice.d.ts +241 -0
  193. package/dist/types/services/task/voice/WebRTC.d.ts +54 -0
  194. package/dist/types/services/task/voice/wxAppOfferObservability.d.ts +39 -0
  195. package/dist/types/services/task/voice/wxAppVoiceMethods.d.ts +68 -0
  196. package/dist/types/services/wxAppDiagnosticLogging.d.ts +63 -0
  197. package/dist/types/services/wxAppTelephonyUtils.d.ts +5 -0
  198. package/dist/types/types.d.ts +213 -11
  199. package/dist/types/utils/PageCache.d.ts +20 -3
  200. package/dist/types/webex.d.ts +1 -0
  201. package/dist/types.js +168 -6
  202. package/dist/types.js.map +1 -1
  203. package/dist/utils/PageCache.js +19 -5
  204. package/dist/utils/PageCache.js.map +1 -1
  205. package/dist/webex.js +22 -2
  206. package/dist/webex.js.map +1 -1
  207. package/package.json +16 -12
  208. package/src/cc.ts +1367 -101
  209. package/src/config.ts +13 -0
  210. package/src/constants.ts +41 -1
  211. package/src/index.ts +62 -15
  212. package/src/metrics/MetricsManager.ts +16 -0
  213. package/src/metrics/ai-docs/AGENTS.md +350 -0
  214. package/src/metrics/ai-docs/ARCHITECTURE.md +338 -0
  215. package/src/metrics/ai-docs/metrics-spec.md +971 -0
  216. package/src/metrics/behavioral-events.ts +218 -0
  217. package/src/metrics/constants.ts +63 -4
  218. package/src/services/AddressBook.ts +17 -6
  219. package/src/services/AnswerCallOnWebexService.ts +239 -0
  220. package/src/services/ApiAiAssistant.ts +494 -15
  221. package/src/services/EntryPoint.ts +59 -60
  222. package/src/services/Queue.ts +29 -12
  223. package/src/services/UserPreference.ts +509 -0
  224. package/src/services/WebCallingService.ts +16 -2
  225. package/src/services/WebexCrossClientService.ts +298 -0
  226. package/src/services/WxAppTelephonyMercurySync.ts +142 -0
  227. package/src/services/agent/ai-docs/AGENTS.md +240 -0
  228. package/src/services/agent/ai-docs/ARCHITECTURE.md +304 -0
  229. package/src/services/agent/ai-docs/agent-spec.md +505 -0
  230. package/src/services/ai-docs/AGENTS.md +386 -0
  231. package/src/services/ai-docs/services-spec.md +512 -0
  232. package/src/services/config/Util.ts +54 -84
  233. package/src/services/config/ai-docs/AGENTS.md +250 -0
  234. package/src/services/config/ai-docs/ARCHITECTURE.md +413 -0
  235. package/src/services/config/ai-docs/config-spec.md +669 -0
  236. package/src/services/config/constants.ts +64 -86
  237. package/src/services/config/index.ts +116 -277
  238. package/src/services/config/types.ts +233 -125
  239. package/src/services/constants.ts +18 -0
  240. package/src/services/core/Err.ts +3 -0
  241. package/src/services/core/Utils.ts +151 -37
  242. package/src/services/core/WebexRequest.ts +3 -1
  243. package/src/services/core/ai-docs/AGENTS.md +381 -0
  244. package/src/services/core/ai-docs/ARCHITECTURE.md +698 -0
  245. package/src/services/core/ai-docs/core-spec.md +797 -0
  246. package/src/services/core/aqm-reqs.ts +18 -12
  247. package/src/services/core/constants.ts +8 -0
  248. package/src/services/core/types.ts +33 -1
  249. package/src/services/core/websocket/WebSocketManager.ts +37 -8
  250. package/src/services/core/websocket/connection-service.ts +5 -1
  251. package/src/services/core/websocket/types.ts +1 -1
  252. package/src/services/index.ts +4 -0
  253. package/src/services/task/Task.ts +1211 -0
  254. package/src/services/task/TaskFactory.ts +82 -0
  255. package/src/services/task/TaskManager.ts +1551 -584
  256. package/src/services/task/TaskUtils.ts +316 -25
  257. package/src/services/task/WebexCallingUtils.ts +136 -0
  258. package/src/services/task/ai-docs/AGENTS.md +457 -0
  259. package/src/services/task/ai-docs/ARCHITECTURE.md +595 -0
  260. package/src/services/task/ai-docs/task-spec.md +1501 -0
  261. package/src/services/task/constants.ts +21 -0
  262. package/src/services/task/contact.ts +30 -0
  263. package/src/services/task/dialer.ts +80 -0
  264. package/src/services/task/digital/Digital.ts +102 -0
  265. package/src/services/task/state-machine/TaskStateMachine.ts +1320 -0
  266. package/src/services/task/state-machine/actions.ts +741 -0
  267. package/src/services/task/state-machine/ai-docs/AGENTS.md +460 -0
  268. package/src/services/task/state-machine/ai-docs/ARCHITECTURE.md +1156 -0
  269. package/src/services/task/state-machine/ai-docs/task-state-machine-spec.md +2247 -0
  270. package/src/services/task/state-machine/constants.ts +172 -0
  271. package/src/services/task/state-machine/guards.ts +442 -0
  272. package/src/services/task/state-machine/index.ts +28 -0
  273. package/src/services/task/state-machine/types.ts +258 -0
  274. package/src/services/task/state-machine/uiControlsComputer.ts +1135 -0
  275. package/src/services/task/taskDataNormalizer.ts +137 -0
  276. package/src/services/task/types.ts +974 -70
  277. package/src/services/task/voice/Voice.ts +1878 -0
  278. package/src/services/task/voice/WebRTC.ts +194 -0
  279. package/src/services/task/voice/wxAppOfferObservability.ts +204 -0
  280. package/src/services/task/voice/wxAppVoiceMethods.ts +575 -0
  281. package/src/services/wxAppDiagnosticLogging.ts +286 -0
  282. package/src/services/wxAppTelephonyUtils.ts +14 -0
  283. package/src/types.ts +272 -13
  284. package/src/utils/AGENTS.md +289 -0
  285. package/src/utils/PageCache.ts +38 -5
  286. package/src/utils/ai-docs/utils-spec.md +391 -0
  287. package/src/webex.js +10 -0
  288. package/test/unit/fixtures/aiSummaryTestUtils.ts +40 -0
  289. package/test/unit/spec/cc.ts +3764 -118
  290. package/test/unit/spec/index.ts +885 -0
  291. package/test/unit/spec/logger-proxy.ts +70 -0
  292. package/test/unit/spec/metrics/MetricsManager.ts +25 -0
  293. package/test/unit/spec/metrics/behavioral-events.ts +60 -0
  294. package/test/unit/spec/services/AddressBook.ts +37 -6
  295. package/test/unit/spec/services/AnswerCallOnWebexService.ts +264 -0
  296. package/test/unit/spec/services/ApiAiAssistant.ts +442 -23
  297. package/test/unit/spec/services/EntryPoint.ts +87 -40
  298. package/test/unit/spec/services/Queue.ts +123 -12
  299. package/test/unit/spec/services/UserPreference.ts +401 -0
  300. package/test/unit/spec/services/WebCallingService.ts +45 -1
  301. package/test/unit/spec/services/WebexCrossClientService.ts +509 -0
  302. package/test/unit/spec/services/WxAppTelephonyMercurySync.ts +136 -0
  303. package/test/unit/spec/services/config/Util.ts +501 -0
  304. package/test/unit/spec/services/config/index.ts +318 -548
  305. package/test/unit/spec/services/core/Utils.ts +447 -8
  306. package/test/unit/spec/services/core/WebexRequest.ts +8 -7
  307. package/test/unit/spec/services/core/aqm-reqs.ts +142 -1
  308. package/test/unit/spec/services/core/websocket/WebSocketManager.ts +132 -56
  309. package/test/unit/spec/services/core/websocket/connection-service.ts +3 -1
  310. package/test/unit/spec/services/task/AutoWrapup.ts +63 -0
  311. package/test/unit/spec/services/task/Task.ts +2723 -0
  312. package/test/unit/spec/services/task/TaskFactory.ts +116 -0
  313. package/test/unit/spec/services/task/TaskManager.ts +4800 -1586
  314. package/test/unit/spec/services/task/TaskUtils.ts +307 -0
  315. package/test/unit/spec/services/task/WebexCallingUtils.ts +153 -0
  316. package/test/unit/spec/services/task/contact.ts +33 -0
  317. package/test/unit/spec/services/task/dialer.ts +190 -0
  318. package/test/unit/spec/services/task/digital/Digital.ts +105 -0
  319. package/test/unit/spec/services/task/state-machine/TaskStateMachine.ts +4060 -0
  320. package/test/unit/spec/services/task/state-machine/guards.ts +839 -0
  321. package/test/unit/spec/services/task/state-machine/types.ts +18 -0
  322. package/test/unit/spec/services/task/state-machine/uiControlsComputer.ts +3101 -0
  323. package/test/unit/spec/services/task/taskTestUtils.ts +87 -0
  324. package/test/unit/spec/services/task/voice/Voice.ts +2355 -0
  325. package/test/unit/spec/services/task/voice/WebRTC.ts +235 -0
  326. package/test/unit/spec/services/task/voice/wxAppOfferObservability.ts +361 -0
  327. package/test/unit/spec/services/task/voice/wxAppVoiceMethods.ts +719 -0
  328. package/test/unit/spec/services/wxAppDiagnosticLogging.ts +179 -0
  329. package/test/unit/spec/wellnessSampleUtils.ts +288 -0
  330. package/typedoc.md +1 -1
  331. package/umd/contact-center.min.js +2 -2
  332. package/umd/contact-center.min.js.map +1 -1
  333. package/dist/services/task/index.js +0 -1525
  334. package/dist/services/task/index.js.map +0 -1
  335. package/dist/types/services/task/index.d.ts +0 -650
  336. package/src/services/task/index.ts +0 -1801
  337. package/test/unit/spec/services/task/index.ts +0 -2184
@@ -1,5 +1,8 @@
1
1
  import 'jsdom-global/register';
2
+ import EventEmitter from 'events';
2
3
  import {
4
+ AIAssistantEventName,
5
+ AIAssistantEventType,
3
6
  BuddyAgents,
4
7
  BuddyAgentsResponse,
5
8
  LoginOption,
@@ -15,10 +18,14 @@ import type {ContactServiceQueuesResponse} from '../../../src/types';
15
18
  import MockWebex from '@webex/test-helper-mock-webex';
16
19
  import {StationLoginSuccess, AGENT_EVENTS} from '../../../src/services/agent/types';
17
20
  import {SetStateResponse} from '../../../src/types';
18
- import {AGENT, WEB_RTC_PREFIX} from '../../../src/services/constants';
21
+ import {
22
+ AGENT,
23
+ SUBSCRIBE_API,
24
+ WEB_RTC_PREFIX,
25
+ } from '../../../src/services/constants';
19
26
  import Services from '../../../src/services';
20
27
  import config from '../../../src/config';
21
- import {CC_EVENTS} from '../../../src/services/config/types';
28
+ import {CC_TASK_EVENTS, CC_EVENTS} from '../../../src/services/config/types';
22
29
  import LoggerProxy from '../../../src/logger-proxy';
23
30
  import * as Utils from '../../../src/services/core/Utils';
24
31
  import {
@@ -33,11 +40,26 @@ import {
33
40
  import '../../../__mocks__/workerMock';
34
41
  import {Profile} from '../../../src/services/config/types';
35
42
  import TaskManager from '../../../src/services/task/TaskManager';
36
- import {AgentContact, TASK_EVENTS} from '../../../src/services/task/types';
43
+ import Task from '../../../src/services/task/Task';
44
+ import {
45
+ AgentContact,
46
+ AISummaryResponse,
47
+ TASK_CHANNEL_TYPE,
48
+ TASK_EVENTS,
49
+ TaskData,
50
+ } from '../../../src/services/task/types';
51
+ import {AI_SUMMARY_REQUEST_CANCELLED} from '../../../src/services/task/constants';
52
+ import type {ApiAIAssistant} from '../../../src/services/ApiAiAssistant';
53
+ import type {AIFeatureFlags} from '../../../src/types';
37
54
  import MetricsManager from '../../../src/metrics/MetricsManager';
38
55
  import {METRIC_EVENT_NAMES} from '../../../src/metrics/constants';
39
56
  import Mercury from '@webex/internal-plugin-mercury';
40
57
  import WebexRequest from '../../../src/services/core/WebexRequest';
58
+ import {
59
+ createDeferred,
60
+ flushEventLoopTurn,
61
+ flushMicrotasks,
62
+ } from '../fixtures/aiSummaryTestUtils';
41
63
 
42
64
  jest.mock('../../../src/logger-proxy', () => ({
43
65
  __esModule: true,
@@ -45,20 +67,309 @@ jest.mock('../../../src/logger-proxy', () => ({
45
67
  log: jest.fn(),
46
68
  error: jest.fn(),
47
69
  info: jest.fn(),
70
+ warn: jest.fn(),
48
71
  initialize: jest.fn(),
49
72
  },
50
73
  }));
51
74
 
75
+ jest.mock('../../../src/services', () => ({
76
+ __esModule: true,
77
+ default: {
78
+ getInstance: jest.fn(() => ({
79
+ agent: {
80
+ stationLogin: jest.fn(),
81
+ logout: jest.fn(),
82
+ reload: jest.fn(),
83
+ stateChange: jest.fn(),
84
+ buddyAgents: jest.fn(),
85
+ },
86
+ config: {
87
+ getAgentConfig: jest.fn(),
88
+ getOutdialAniEntries: jest.fn(),
89
+ },
90
+ webSocketManager: {
91
+ initWebSocket: jest.fn(),
92
+ on: jest.fn(),
93
+ off: jest.fn(),
94
+ close: jest.fn(),
95
+ isSocketClosed: false,
96
+ },
97
+ rtdWebSocketManager: {
98
+ initWebSocket: jest.fn(),
99
+ on: jest.fn(),
100
+ off: jest.fn(),
101
+ close: jest.fn(),
102
+ isSocketClosed: false,
103
+ },
104
+ connectionService: {
105
+ on: jest.fn(),
106
+ off: jest.fn(),
107
+ },
108
+ contact: {},
109
+ dialer: {
110
+ startOutdial: jest.fn(),
111
+ acceptPreviewContact: jest.fn(),
112
+ skipPreviewContact: jest.fn(),
113
+ removePreviewContact: jest.fn(),
114
+ },
115
+ })),
116
+ },
117
+ }));
118
+
119
+ jest.mock('../../../src/services/task/TaskManager', () => ({
120
+ __esModule: true,
121
+ default: {
122
+ getTaskManager: jest.fn(() => ({
123
+ on: jest.fn(),
124
+ off: jest.fn(),
125
+ emit: jest.fn(),
126
+ setConfigFlags: jest.fn(),
127
+ setWrapupData: jest.fn(),
128
+ setAgentId: jest.fn(),
129
+ setAgentName: jest.fn(),
130
+ setWebRtcEnabled: jest.fn(),
131
+ setAnswerCallOnWebexService: jest.fn(),
132
+ registerIncomingCallEvent: jest.fn(),
133
+ registerTaskListeners: jest.fn(),
134
+ unregisterIncomingCallEvent: jest.fn(),
135
+ getTask: jest.fn(),
136
+ getActiveTasks: jest.fn(),
137
+ handleRealtimeWebsocketEvent: jest.fn(),
138
+ clearAISummaryState: jest.fn(),
139
+ })),
140
+ },
141
+ }));
142
+
143
+ jest.mock('../../../src/metrics/MetricsManager', () => ({
144
+ __esModule: true,
145
+ default: {
146
+ getInstance: jest.fn(),
147
+ getCommonTrackingFieldForAQMResponse: jest.fn(() => ({})),
148
+ getCommonTrackingFieldForAQMResponseFailed: jest.fn(() => ({})),
149
+ },
150
+ }));
151
+
152
+ jest.mock('../../../src/services/core/WebexRequest', () => ({
153
+ __esModule: true,
154
+ default: {
155
+ getInstance: jest.fn(() => ({
156
+ request: jest.fn(),
157
+ uploadLogs: jest.fn(),
158
+ })),
159
+ },
160
+ }));
161
+
162
+ jest.mock('../../../src/services/ApiAiAssistant', () => {
163
+ class MockApiAIAssistant {
164
+ public sendEvent = jest.fn();
165
+ public requestAndWaitForRtd = jest.fn();
166
+ public resolveFromRtdEvent = jest.fn();
167
+ public clearAllRtdRequests = jest.fn();
168
+ public getSuggestedResponse = jest.fn();
169
+ public fetchHistoricTranscripts = jest.fn();
170
+ public requestWellnessBreak = jest.fn();
171
+ public respondToWellnessBreak = jest.fn();
172
+ public setAIFeatureFlags = jest.fn();
173
+ public setAgentId = jest.fn();
174
+ }
175
+
176
+ return {
177
+ __esModule: true,
178
+ default: MockApiAIAssistant,
179
+ ApiAIAssistant: MockApiAIAssistant,
180
+ };
181
+ });
182
+
183
+ jest.mock('../../../src/services/WebCallingService', () => {
184
+ class MockWebCallingService {
185
+ public loginOption = 'AGENT_DN';
186
+ public registerWebCallingLine = jest.fn().mockResolvedValue(undefined);
187
+ public deregisterWebCallingLine = jest.fn().mockResolvedValue(undefined);
188
+ public setLoginOption = jest.fn((loginOption: string) => {
189
+ this.loginOption = loginOption;
190
+ });
191
+ }
192
+
193
+ return {
194
+ __esModule: true,
195
+ default: MockWebCallingService,
196
+ };
197
+ });
198
+
199
+ jest.mock('../../../src/services/task/TaskFactory', () => ({
200
+ __esModule: true,
201
+ default: {
202
+ createTask: jest.fn(),
203
+ },
204
+ }));
205
+
206
+ jest.mock('../../../src/services/task/voice/WebRTC', () => ({
207
+ __esModule: true,
208
+ default: class MockWebRTC {},
209
+ }));
210
+
211
+ jest.mock('../../../src/services/task/taskDataNormalizer', () => ({
212
+ normalizeTaskData: jest.fn((data) => data),
213
+ }));
214
+
215
+ jest.mock('../../../src/services/task/state-machine', () => ({
216
+ ...jest.requireActual('../../../src/services/task/state-machine'),
217
+ createTaskStateMachine: jest.fn(
218
+ jest.requireActual('../../../src/services/task/state-machine').createTaskStateMachine
219
+ ),
220
+ }));
221
+
222
+ jest.mock('../../../src/services/task/state-machine/uiControlsComputer', () => ({
223
+ computeUIControls: jest.fn(() => ({})),
224
+ getDefaultUIControls: jest.fn(() => ({})),
225
+ haveUIControlsChanged: jest.fn(() => false),
226
+ }));
227
+
228
+ jest.mock('../../../src/services/task/AutoWrapup', () => ({
229
+ __esModule: true,
230
+ default: class MockAutoWrapup {},
231
+ }));
232
+
233
+ jest.mock('../../../src/services/EntryPoint', () => {
234
+ class MockEntryPoint {
235
+ public getEntryPoints() {
236
+ return Promise.resolve({});
237
+ }
238
+ }
239
+
240
+ return {
241
+ __esModule: true,
242
+ default: MockEntryPoint,
243
+ EntryPoint: MockEntryPoint,
244
+ };
245
+ });
246
+
247
+ jest.mock('../../../src/services/AddressBook', () => {
248
+ class MockAddressBook {
249
+ public getEntries() {
250
+ return Promise.resolve({});
251
+ }
252
+ }
253
+
254
+ return {
255
+ __esModule: true,
256
+ default: MockAddressBook,
257
+ AddressBook: MockAddressBook,
258
+ };
259
+ });
260
+
261
+ jest.mock('../../../src/services/Queue', () => {
262
+ class MockQueue {
263
+ public getQueues() {
264
+ return Promise.resolve({});
265
+ }
266
+ }
267
+
268
+ return {
269
+ __esModule: true,
270
+ default: MockQueue,
271
+ Queue: MockQueue,
272
+ };
273
+ });
274
+
52
275
  jest.mock('../../../src/services/config');
53
276
  jest.mock('../../../src/services/core/websocket/WebSocketManager');
54
277
  jest.mock('../../../src/services/core/websocket/connection-service');
55
- jest.mock('../../../src/services/WebCallingService');
56
278
  jest.mock('uuid', () => ({v4: () => 'mock-tracking-uuid'}));
57
279
 
58
280
  global.URL.createObjectURL = jest.fn(() => 'blob:http://localhost:3000/12345');
59
281
 
282
+ class EventEmitterDouble extends EventEmitter {
283
+ public isSocketClosed = false;
284
+ public initWebSocket = jest.fn().mockResolvedValue({});
285
+ public close = jest.fn(() => {
286
+ this.isSocketClosed = true;
287
+ });
288
+ public mapCallToTask = jest.fn();
289
+
290
+ public on = jest.fn((eventName: string | symbol, listener: (...args: unknown[]) => void) => {
291
+ super.on(eventName, listener);
292
+
293
+ return this;
294
+ });
295
+
296
+ public off = jest.fn((eventName: string | symbol, listener: (...args: unknown[]) => void) => {
297
+ super.off(eventName, listener);
298
+
299
+ return this;
300
+ });
301
+ }
302
+
303
+ class AISummaryLifecycleTask extends Task {
304
+ public constructor(data: TaskData, apiAIAssistant?: ApiAIAssistant, agentId = 'agent-1') {
305
+ super(
306
+ {} as any,
307
+ data,
308
+ {
309
+ channelType: TASK_CHANNEL_TYPE.VOICE,
310
+ isEndTaskEnabled: true,
311
+ isEndConsultEnabled: true,
312
+ },
313
+ undefined,
314
+ agentId,
315
+ undefined,
316
+ apiAIAssistant
317
+ );
318
+ }
319
+
320
+ public accept() {
321
+ return Promise.resolve({} as any);
322
+ }
323
+ }
324
+
325
+ const createAISummaryLifecycleTask = (
326
+ data: TaskData = createAISummaryLifecycleTaskData(),
327
+ apiAIAssistant?: ApiAIAssistant
328
+ ): AISummaryLifecycleTask => new AISummaryLifecycleTask(data, apiAIAssistant);
329
+
330
+ const createAISummaryLifecycleTaskData = (
331
+ overrides: Partial<TaskData> & {conversationId?: string} = {}
332
+ ): TaskData => {
333
+ const {
334
+ conversationId = 'conversation-1',
335
+ interaction: interactionOverrides,
336
+ ...taskOverrides
337
+ } = overrides;
338
+ const interactionId = taskOverrides.interactionId ?? 'interaction-1';
339
+
340
+ return {
341
+ mediaResourceId: 'media-resource-1',
342
+ eventType: CC_EVENTS.AGENT_CONTACT_ASSIGNED,
343
+ agentId: 'agent-1',
344
+ destAgentId: '',
345
+ trackingId: 'tracking-1',
346
+ consultMediaResourceId: '',
347
+ interactionId,
348
+ orgId: 'org-1',
349
+ owner: 'agent-1',
350
+ queueMgr: 'queue-manager-1',
351
+ type: 'telephony',
352
+ isConferencing: false,
353
+ taskId: 'task-owner-1',
354
+ ...taskOverrides,
355
+ interaction: {
356
+ interactionId,
357
+ mainInteractionId: conversationId,
358
+ mediaType: 'telephony',
359
+ media: {
360
+ [interactionId]: {
361
+ mediaResourceId: 'media-resource-1',
362
+ },
363
+ },
364
+ callProcessingDetails: {},
365
+ ...(interactionOverrides as Record<string, unknown> | undefined),
366
+ },
367
+ } as TaskData;
368
+ };
369
+
60
370
  describe('webex.cc', () => {
61
371
  let webex;
372
+ let mockApiAIAssistant;
62
373
  let mockContact;
63
374
  let mockTaskManager;
64
375
  let mockMetricsManager;
@@ -88,6 +399,8 @@ describe('webex.cc', () => {
88
399
  initWebSocket: jest.fn(),
89
400
  on: jest.fn(),
90
401
  off: jest.fn(),
402
+ close: jest.fn(),
403
+ isSocketClosed: false,
91
404
  };
92
405
 
93
406
  mockContact = {
@@ -107,6 +420,14 @@ describe('webex.cc', () => {
107
420
  cancelCtq: jest.fn(),
108
421
  };
109
422
 
423
+ mockApiAIAssistant = {
424
+ sendEvent: jest.fn(),
425
+ getRealTimeAssistance: jest.fn(),
426
+ fetchHistoricTranscripts: jest.fn(),
427
+ setAIFeatureFlags: jest.fn(),
428
+ setAgentId: jest.fn(),
429
+ };
430
+
110
431
  // Mock Services instance
111
432
  const mockServicesInstance = {
112
433
  agent: {
@@ -119,8 +440,16 @@ describe('webex.cc', () => {
119
440
  config: {
120
441
  getAgentConfig: jest.fn(),
121
442
  getOutdialAniEntries: jest.fn(),
443
+ getWellbeingBreakIdleCode: jest.fn(),
122
444
  },
123
445
  webSocketManager: mockWebSocketManager,
446
+ rtdWebSocketManager: {
447
+ initWebSocket: jest.fn().mockResolvedValue({}),
448
+ on: jest.fn(),
449
+ off: jest.fn(),
450
+ close: jest.fn(),
451
+ isSocketClosed: false,
452
+ },
124
453
  connectionService: {
125
454
  on: jest.fn(),
126
455
  off: jest.fn(),
@@ -130,6 +459,8 @@ describe('webex.cc', () => {
130
459
  dialer: {
131
460
  startOutdial: jest.fn(),
132
461
  acceptPreviewContact: jest.fn(),
462
+ skipPreviewContact: jest.fn(),
463
+ removePreviewContact: jest.fn(),
133
464
  },
134
465
  apiAIAssistant: {
135
466
  sendEvent: jest.fn(),
@@ -138,24 +469,33 @@ describe('webex.cc', () => {
138
469
  };
139
470
 
140
471
  mockTaskManager = {
472
+ apiAIAssistant: mockApiAIAssistant,
141
473
  contact: mockContact,
142
474
  call: undefined,
143
475
  taskCollection: {},
144
476
  webCallingService: undefined,
145
477
  webSocketManager: mockWebSocketManager,
146
478
  task: undefined,
479
+ setConfigFlags: jest.fn(),
147
480
  setWrapupData: jest.fn(),
148
481
  setAgentId: jest.fn(),
482
+ setAgentName: jest.fn(),
149
483
  setWebRtcEnabled: jest.fn(),
150
- setApiAIAssistant: jest.fn(),
484
+ setAnswerCallOnWebexService: jest.fn(),
485
+ handleRealtimeWebsocketEvent: jest.fn(),
151
486
  registerIncomingCallEvent: jest.fn(),
152
487
  registerTaskListeners: jest.fn(),
153
488
  getTask: jest.fn(),
154
489
  getActiveTasks: jest.fn(),
490
+ applyEnableWxBetterTogether: jest.fn(),
491
+ syncWxAppMuteFromCallDetailsForAllTasks: jest.fn(),
492
+ refreshWxAppOfferObservabilityForAllTasks: jest.fn(),
155
493
  on: jest.fn(),
156
494
  off: jest.fn(),
157
495
  emit: jest.fn(),
158
496
  unregisterIncomingCallEvent: jest.fn(),
497
+ handleRealtimeWebsocketEvent: jest.fn(),
498
+ clearAISummaryState: jest.fn(),
159
499
  };
160
500
 
161
501
  mockMetricsManager = {
@@ -179,6 +519,7 @@ describe('webex.cc', () => {
179
519
 
180
520
  afterEach(() => {
181
521
  jest.clearAllMocks();
522
+ jest.restoreAllMocks();
182
523
  });
183
524
 
184
525
  it('should initialize services and logger proxy on ready event', () => {
@@ -190,6 +531,35 @@ describe('webex.cc', () => {
190
531
  webex.emit('ready');
191
532
  });
192
533
 
534
+ it('should throw when WebRTC registration is disabled without multi-login', () => {
535
+ const invalidWebex = MockWebex({
536
+ children: {
537
+ mercury: Mercury,
538
+ },
539
+ logger: {
540
+ log: jest.fn(),
541
+ error: jest.fn(),
542
+ info: jest.fn(),
543
+ },
544
+ credentials: {
545
+ getOrgId: jest.fn(() => 'mockOrgId'),
546
+ },
547
+ config: {
548
+ ...config,
549
+ cc: {
550
+ ...config.cc,
551
+ allowMultiLogin: false,
552
+ disableWebRTCRegistration: true,
553
+ },
554
+ },
555
+ once: jest.fn((event, callback) => callback()),
556
+ }) as unknown as WebexSDK;
557
+
558
+ expect(() => new ContactCenter({parent: invalidWebex})).toThrow(
559
+ 'Invalid Contact Center configuration: disableWebRTCRegistration cannot be true when allowMultiLogin is false. Enable allowMultiLogin or allow WebRTC registration so an SDK instance can receive Mobius/WebRTC task events.'
560
+ );
561
+ });
562
+
193
563
  describe('cc.getDeviceId', () => {
194
564
  it('should return dialNumber when loginOption is EXTENSION', () => {
195
565
  const loginOption = LoginOption.EXTENSION;
@@ -216,7 +586,7 @@ describe('webex.cc', () => {
216
586
  });
217
587
 
218
588
  describe('register', () => {
219
- const mockAgentProfile: Profile = {
589
+ const createFreshAgentProfile = (overrides: Partial<Profile> = {}): Profile => ({
220
590
  agentId: 'agent123',
221
591
  agentMailId: '',
222
592
  agentName: 'John',
@@ -257,17 +627,25 @@ describe('webex.cc', () => {
257
627
  isAgentAvailableAfterOutdial: false,
258
628
  isCampaignManagementEnabled: false,
259
629
  outDialEp: '',
260
- isEndCallEnabled: false,
630
+ isEndTaskEnabled: false,
261
631
  isEndConsultEnabled: false,
262
632
  agentDbId: '',
263
633
  allowConsultToQueue: false,
634
+ accessQueue: 'SPECIFIC',
635
+ accessEntryPoint: 'ALL',
636
+ accessBuddyTeam: 'ALL',
264
637
  agentPersonalStatsEnabled: false,
265
638
  isTimeoutDesktopInactivityEnabled: false,
266
639
  webRtcEnabled: true,
267
640
  lostConnectionRecoveryTimeout: 0,
268
- };
641
+ isWellnessBreakEnabled: false,
642
+ ...overrides,
643
+ });
644
+
645
+ const mockAgentProfile: Profile = createFreshAgentProfile();
269
646
 
270
647
  it('should register successfully and return agent profile', async () => {
648
+ mockAgentProfile.aiFeature = {realtimeTranscripts: {enable: true}} as any;
271
649
  const mercuryConnect = jest.spyOn(webex.internal.mercury, 'connect').mockResolvedValue(true);
272
650
  const connectWebsocketSpy = jest.spyOn(webex.cc, 'connectWebsocket');
273
651
  const setupEventListenersSpy = jest.spyOn(webex.cc, 'setupEventListeners');
@@ -275,6 +653,7 @@ describe('webex.cc', () => {
275
653
  data: {
276
654
  auxCodeId: 'auxCodeId',
277
655
  agentId: 'agentId',
656
+ agentSessionId: 'session-after-refresh',
278
657
  deviceType: LoginOption.EXTENSION,
279
658
  dn: '12345',
280
659
  },
@@ -289,7 +668,7 @@ describe('webex.cc', () => {
289
668
  const result = await webex.cc.register();
290
669
 
291
670
  // Verify logging calls
292
- expect(LoggerProxy.info).toHaveBeenCalledWith('Starting CC SDK registration', {
671
+ expect(LoggerProxy.log).toHaveBeenCalledWith('Starting CC SDK registration', {
293
672
  module: CC_FILE,
294
673
  method: 'register',
295
674
  });
@@ -311,9 +690,10 @@ describe('webex.cc', () => {
311
690
  clientType: 'WebexCCSDK',
312
691
  allowMultiLogin: false,
313
692
  },
693
+ resource: SUBSCRIBE_API,
314
694
  });
315
695
 
316
- // TODO: https://jira-eng-gpk2.cisco.com/jira/browse/SPARK-626777 Implement the de-register method and close the listener there
696
+ // SPARK-626777 tracks moving listener cleanup into the future de-register API.
317
697
  expect(mockTaskManager.on).toHaveBeenCalledWith(
318
698
  TASK_EVENTS.TASK_INCOMING,
319
699
  expect.any(Function)
@@ -322,15 +702,50 @@ describe('webex.cc', () => {
322
702
  TASK_EVENTS.TASK_HYDRATE,
323
703
  expect.any(Function)
324
704
  );
705
+ expect(mockTaskManager.on).toHaveBeenCalledWith(
706
+ TASK_EVENTS.TASK_MULTI_LOGIN_HYDRATE,
707
+ expect.any(Function)
708
+ );
325
709
  expect(mockWebSocketManager.on).toHaveBeenCalledWith('message', expect.any(Function));
710
+ expect(webex.cc.services.rtdWebSocketManager.initWebSocket).toHaveBeenCalledWith({
711
+ body: {
712
+ force: true,
713
+ isKeepAliveEnabled: false,
714
+ clientType: 'WebexCCSDK',
715
+ allowMultiLogin: false,
716
+ },
717
+ resource: 'v1/realtime/subscribe',
718
+ });
719
+ expect(webex.cc.services.rtdWebSocketManager.on).toHaveBeenCalledWith(
720
+ 'message',
721
+ expect.any(Function)
722
+ );
326
723
 
327
724
  expect(configSpy).toHaveBeenCalled();
328
725
  expect(LoggerProxy.log).toHaveBeenCalledWith('Agent config is fetched successfully', {
329
726
  module: CC_FILE,
330
727
  method: 'connectWebsocket',
331
728
  });
729
+ expect(mockTaskManager.setConfigFlags).toHaveBeenCalledWith(
730
+ expect.objectContaining({
731
+ isEndTaskEnabled: mockAgentProfile.isEndTaskEnabled,
732
+ isEndConsultEnabled: mockAgentProfile.isEndConsultEnabled,
733
+ webRtcEnabled: mockAgentProfile.webRtcEnabled,
734
+ autoWrapup: mockAgentProfile.wrapUpData.wrapUpProps.autoWrapup ?? false,
735
+ aiFeature: mockAgentProfile.aiFeature,
736
+ consultTransfer: {
737
+ allowConsultToQueue: mockAgentProfile.allowConsultToQueue,
738
+ accessQueue: mockAgentProfile.accessQueue,
739
+ accessEntryPoint: mockAgentProfile.accessEntryPoint,
740
+ accessBuddyTeam: mockAgentProfile.accessBuddyTeam,
741
+ },
742
+ enableWxBetterTogether: false,
743
+ getWxAppUsersubPublished: expect.any(Function),
744
+ })
745
+ );
746
+ expect(mockTaskManager.clearAISummaryState).not.toHaveBeenCalled();
332
747
  expect(reloadSpy).toHaveBeenCalled();
333
- expect(result).toEqual(mockAgentProfile);
748
+ expect(result).toEqual({...mockAgentProfile, agentSessionId: 'session-after-refresh'});
334
749
  expect(mockMetricsManager.timeEvent).toHaveBeenCalledWith([
335
750
  METRIC_EVENT_NAMES.WEBSOCKET_REGISTER_SUCCESS,
336
751
  METRIC_EVENT_NAMES.WEBSOCKET_REGISTER_FAILED,
@@ -366,6 +781,7 @@ describe('webex.cc', () => {
366
781
  clientType: 'WebexCCSDK',
367
782
  allowMultiLogin: true,
368
783
  },
784
+ resource: SUBSCRIBE_API,
369
785
  });
370
786
  expect(configSpy).toHaveBeenCalled();
371
787
  expect(LoggerProxy.log).toHaveBeenCalledWith('Agent config is fetched successfully', {
@@ -387,7 +803,7 @@ describe('webex.cc', () => {
387
803
 
388
804
  await expect(webex.cc.register()).rejects.toThrow('Error while performing register');
389
805
 
390
- expect(LoggerProxy.info).toHaveBeenCalledWith('Starting CC SDK registration', {
806
+ expect(LoggerProxy.log).toHaveBeenCalledWith('Starting CC SDK registration', {
391
807
  module: CC_FILE,
392
808
  method: 'register',
393
809
  });
@@ -406,6 +822,25 @@ describe('webex.cc', () => {
406
822
  );
407
823
  });
408
824
 
825
+ it('clears wellness session context when registration fails after relogin', async () => {
826
+ const mockError = new Error('Error after silent relogin');
827
+ webex.cc.$config = {...webex.cc.$config, allowAutomatedRelogin: true};
828
+ jest.spyOn(webex.cc.services.config, 'getAgentConfig').mockResolvedValue({
829
+ ...mockAgentProfile,
830
+ webRtcEnabled: false,
831
+ aiFeature: undefined,
832
+ } as Profile);
833
+ mockWebSocketManager.initWebSocket.mockResolvedValue({agentId: 'agent123'});
834
+ jest.spyOn(webex.cc as any, 'silentRelogin').mockImplementation(async () => {
835
+ webex.cc['updateWellnessSession']('partial-session');
836
+ throw mockError;
837
+ });
838
+
839
+ await expect(webex.cc.register()).rejects.toThrow(mockError);
840
+
841
+ expect(webex.cc['currentAgentSessionId']).toBeUndefined();
842
+ });
843
+
409
844
  it('should log error if mercury connect fails but cc.register() should not fail', async () => {
410
845
  const mockError = new Error('Error while performing mercury connect');
411
846
  jest.spyOn(webex.internal.mercury, 'connect').mockRejectedValue(mockError);
@@ -445,6 +880,7 @@ describe('webex.cc', () => {
445
880
  clientType: 'WebexCCSDK',
446
881
  allowMultiLogin: false,
447
882
  },
883
+ resource: SUBSCRIBE_API,
448
884
  });
449
885
 
450
886
  expect(mockTaskManager.on).toHaveBeenCalledWith(
@@ -455,6 +891,10 @@ describe('webex.cc', () => {
455
891
  TASK_EVENTS.TASK_HYDRATE,
456
892
  expect.any(Function)
457
893
  );
894
+ expect(mockTaskManager.on).toHaveBeenCalledWith(
895
+ TASK_EVENTS.TASK_MULTI_LOGIN_HYDRATE,
896
+ expect.any(Function)
897
+ );
458
898
  expect(mockWebSocketManager.on).toHaveBeenCalledWith('message', expect.any(Function));
459
899
 
460
900
  expect(configSpy).toHaveBeenCalled();
@@ -466,8 +906,39 @@ describe('webex.cc', () => {
466
906
  expect(result).toEqual(mockAgentProfile);
467
907
  });
468
908
 
909
+ it('should skip mercury connection when disableWebRTCRegistration is enabled', async () => {
910
+ webex.cc.$config = {
911
+ ...webex.cc.$config,
912
+ allowAutomatedRelogin: false,
913
+ disableWebRTCRegistration: true,
914
+ };
915
+ mockAgentProfile.webRtcEnabled = true;
916
+ const mercurySpy = jest.spyOn(webex.internal.mercury, 'connect');
917
+ const connectWebsocketSpy = jest.spyOn(webex.cc, 'connectWebsocket');
918
+ const setupEventListenersSpy = jest.spyOn(webex.cc, 'setupEventListeners');
919
+ jest.spyOn(webex.cc.services.config, 'getAgentConfig').mockResolvedValue(mockAgentProfile);
920
+ mockWebSocketManager.initWebSocket.mockResolvedValue({
921
+ agentId: 'agent123',
922
+ });
923
+
924
+ const result = await webex.cc.register();
925
+
926
+ expect(connectWebsocketSpy).toHaveBeenCalled();
927
+ expect(setupEventListenersSpy).toHaveBeenCalled();
928
+ expect(mercurySpy).not.toHaveBeenCalled();
929
+ expect(LoggerProxy.info).toHaveBeenCalledWith(
930
+ 'Skipping Mobius registration because disableWebRTCRegistration is enabled',
931
+ {
932
+ module: CC_FILE,
933
+ method: 'connectWebsocket',
934
+ }
935
+ );
936
+ expect(result).toEqual(mockAgentProfile);
937
+ });
938
+
469
939
  it('should not attempt for mercury connection when webrtc is disabled', async () => {
470
940
  mockAgentProfile.webRtcEnabled = false;
941
+ mockAgentProfile.aiFeature = {realtimeTranscripts: {enable: false}} as any;
471
942
  const mercurySpy = jest.spyOn(webex.internal.mercury, 'connect');
472
943
  const connectWebsocketSpy = jest.spyOn(webex.cc, 'connectWebsocket');
473
944
  const setupEventListenersSpy = jest.spyOn(webex.cc, 'setupEventListeners');
@@ -497,66 +968,1035 @@ describe('webex.cc', () => {
497
968
  clientType: 'WebexCCSDK',
498
969
  allowMultiLogin: false,
499
970
  },
971
+ resource: SUBSCRIBE_API,
500
972
  });
501
973
 
502
974
  expect(configSpy).toHaveBeenCalled();
503
975
  expect(mercurySpy).not.toHaveBeenCalled();
976
+ expect(webex.cc.services.rtdWebSocketManager.initWebSocket).not.toHaveBeenCalled();
504
977
  expect(result).toEqual(mockAgentProfile);
505
978
  });
506
- });
507
979
 
508
- describe('stationLogin', () => {
509
- it('should login successfully with LoginOption.BROWSER and webrtc enabled', async () => {
510
- const mockTask = {};
511
- const options = {
512
- teamId: 'teamId',
513
- loginOption: LoginOption.BROWSER,
514
- };
980
+ it('should connect RTD websocket when only wellness breaks are enabled', async () => {
981
+ mockAgentProfile.aiFeature = {
982
+ realtimeTranscripts: {enable: false},
983
+ suggestedResponses: {enable: false},
984
+ } as any;
985
+ mockAgentProfile.isWellnessBreakEnabled = true;
986
+ jest.spyOn(webex.internal.mercury, 'connect').mockResolvedValue(true);
987
+ jest.spyOn(webex.cc.services.agent, 'reload').mockResolvedValue({
988
+ data: {
989
+ auxCodeId: 'auxCodeId',
990
+ agentId: 'agentId',
991
+ deviceType: LoginOption.EXTENSION,
992
+ dn: '12345',
993
+ },
994
+ });
995
+ jest.spyOn(webex.cc.services.config, 'getAgentConfig').mockResolvedValue(mockAgentProfile);
996
+ mockWebSocketManager.initWebSocket.mockResolvedValue({agentId: 'agent123'});
515
997
 
516
- webex.cc.agentConfig = {
517
- agentId: 'agentId',
518
- webRtcEnabled: true,
519
- loginVoiceOptions: ['BROWSER', 'EXTENSION', 'AGENT_DN'],
520
- };
998
+ await webex.cc.register();
521
999
 
522
- const registerWebCallingLineSpy = jest.spyOn(
523
- webex.cc.webCallingService,
524
- 'registerWebCallingLine'
1000
+ expect(webex.cc.services.rtdWebSocketManager.initWebSocket).toHaveBeenCalledWith({
1001
+ body: {
1002
+ force: true,
1003
+ isKeepAliveEnabled: false,
1004
+ clientType: 'WebexCCSDK',
1005
+ allowMultiLogin: false,
1006
+ },
1007
+ resource: 'v1/realtime/subscribe',
1008
+ });
1009
+ expect(webex.cc.services.rtdWebSocketManager.on).toHaveBeenCalledWith(
1010
+ 'message',
1011
+ expect.any(Function)
525
1012
  );
1013
+ });
526
1014
 
527
- const mockData = {
1015
+ it('should not connect RTD websocket when transcripts, suggestions, and wellness are disabled', async () => {
1016
+ mockAgentProfile.aiFeature = {
1017
+ realtimeTranscripts: {enable: false},
1018
+ suggestedResponses: {enable: false},
1019
+ } as any;
1020
+ mockAgentProfile.isWellnessBreakEnabled = false;
1021
+ jest.spyOn(webex.internal.mercury, 'connect').mockResolvedValue(true);
1022
+ jest.spyOn(webex.cc.services.agent, 'reload').mockResolvedValue({
528
1023
  data: {
529
- loginOption: LoginOption.BROWSER,
1024
+ auxCodeId: 'auxCodeId',
530
1025
  agentId: 'agentId',
531
- teamId: 'teamId',
532
- siteId: 'siteId',
533
- roles: [AGENT],
534
- trackingId: '1234',
535
- eventType: 'DESKTOP_MESSAGE',
536
- channelsMap: {
537
- chat: ['25d8ggg7-4821-7de7-b626-36437adec509', '14e7fff7-7de7-4821-a919-36437adec509'],
538
- email: [
539
- '14e7fff7-7de7-4821-a919-36437adec509',
540
- '14e7fff7-7de7-4821-a919-36437adec509',
541
- '14e7fff7-7de7-4821-a919-36437adec509',
542
- ],
543
- social: [],
544
- telephony: ['14e7fff7-7de7-4821-a919-36437adec509'],
545
- },
1026
+ deviceType: LoginOption.EXTENSION,
1027
+ dn: '12345',
546
1028
  },
547
- trackingId: 'notifs_52628',
548
- orgId: 'orgId',
549
- type: 'StationLoginSuccess',
550
- eventType: 'STATION_LOGIN',
551
- };
1029
+ });
1030
+ jest.spyOn(webex.cc.services.config, 'getAgentConfig').mockResolvedValue(mockAgentProfile);
1031
+ mockWebSocketManager.initWebSocket.mockResolvedValue({
1032
+ agentId: 'agent123',
1033
+ });
552
1034
 
553
- const responseMock = {
554
- loginOption: LoginOption.BROWSER,
555
- agentId: 'agentId',
556
- teamId: 'teamId',
557
- siteId: 'siteId',
558
- roles: [AGENT],
559
- trackingId: '1234',
1035
+ await webex.cc.register();
1036
+
1037
+ expect(webex.cc.services.rtdWebSocketManager.initWebSocket).not.toHaveBeenCalled();
1038
+ expect(webex.cc.services.rtdWebSocketManager.on).not.toHaveBeenCalledWith(
1039
+ 'message',
1040
+ expect.any(Function)
1041
+ );
1042
+ });
1043
+
1044
+ it('should connect RTD websocket when either generated summary organization flag is enabled', async () => {
1045
+ jest.spyOn(webex.internal.mercury, 'connect').mockResolvedValue(true);
1046
+ jest.spyOn(webex.cc.services.agent, 'reload').mockResolvedValue({
1047
+ data: {
1048
+ auxCodeId: 'auxCodeId',
1049
+ agentId: 'agentId',
1050
+ deviceType: LoginOption.EXTENSION,
1051
+ dn: '12345',
1052
+ },
1053
+ });
1054
+ mockWebSocketManager.initWebSocket.mockResolvedValue({agentId: 'agent123'});
1055
+
1056
+ for (const generatedSummaries of [
1057
+ {wrapUpSummariesEnabled: true, consultTransferSummariesEnabled: false},
1058
+ {wrapUpSummariesEnabled: false, consultTransferSummariesEnabled: true},
1059
+ ]) {
1060
+ jest.clearAllMocks();
1061
+ jest.spyOn(webex.cc.services.config, 'getAgentConfig').mockResolvedValue({
1062
+ ...mockAgentProfile,
1063
+ aiFeature: {generatedSummaries} as any,
1064
+ });
1065
+
1066
+ await webex.cc.register();
1067
+
1068
+ expect(webex.cc.services.rtdWebSocketManager.initWebSocket).toHaveBeenCalledWith({
1069
+ body: {
1070
+ force: true,
1071
+ isKeepAliveEnabled: false,
1072
+ clientType: 'WebexCCSDK',
1073
+ allowMultiLogin: false,
1074
+ },
1075
+ resource: 'v1/realtime/subscribe',
1076
+ });
1077
+ }
1078
+ });
1079
+
1080
+ it.each([
1081
+ {
1082
+ title: 'aiFeature is absent',
1083
+ profileAgentId: 'profile-agent-without-ai-feature',
1084
+ defaultDn: 'normalized-dn-without-ai-feature',
1085
+ aiFeature: undefined,
1086
+ },
1087
+ {
1088
+ title: 'aiFeature has no optional feature objects',
1089
+ profileAgentId: 'profile-agent-with-empty-ai-feature',
1090
+ defaultDn: 'normalized-dn-with-empty-ai-feature',
1091
+ aiFeature: {} as any,
1092
+ },
1093
+ ])(
1094
+ 'should tolerate absent AI feature shapes without summary-driven RTD setup when $title',
1095
+ async ({profileAgentId, defaultDn, aiFeature}) => {
1096
+ const welcomeAgentId = 'welcome-agent-for-absent-ai-feature';
1097
+ const configuredProfile = createFreshAgentProfile({
1098
+ agentId: profileAgentId,
1099
+ defaultDn,
1100
+ dn: 'pre-register-dn',
1101
+ webRtcEnabled: true,
1102
+ aiFeature,
1103
+ });
1104
+ const expectedProfile = {...configuredProfile, dn: defaultDn};
1105
+ webex.cc.$config = {...webex.cc.$config, allowAutomatedRelogin: false};
1106
+ jest.spyOn(webex.internal.mercury, 'connect').mockResolvedValue(true);
1107
+ const configSpy = jest
1108
+ .spyOn(webex.cc.services.config, 'getAgentConfig')
1109
+ .mockResolvedValue(configuredProfile);
1110
+ mockWebSocketManager.initWebSocket.mockResolvedValue({agentId: welcomeAgentId});
1111
+
1112
+ await expect(webex.cc.register()).resolves.toEqual(expectedProfile);
1113
+
1114
+ expect(configSpy).toHaveBeenCalledWith('mockOrgId', welcomeAgentId);
1115
+ expect(webex.cc.services.rtdWebSocketManager.initWebSocket).not.toHaveBeenCalled();
1116
+ }
1117
+ );
1118
+
1119
+ it.each([
1120
+ {
1121
+ title: 'all generated summary organization flags are disabled',
1122
+ aiFeature: {
1123
+ realtimeTranscripts: {enable: false},
1124
+ suggestedResponses: {enable: false},
1125
+ generatedSummaries: {
1126
+ wrapUpSummariesEnabled: false,
1127
+ consultTransferSummariesEnabled: false,
1128
+ },
1129
+ } as any,
1130
+ },
1131
+ ])(
1132
+ 'should keep registration operational without summary-driven RTD setup when $title',
1133
+ async ({aiFeature}) => {
1134
+ const welcomeAgentId = 'welcome-agent-with-disabled-summaries';
1135
+ const configuredProfile = createFreshAgentProfile({
1136
+ agentId: 'profile-agent-with-disabled-summaries',
1137
+ defaultDn: 'normalized-dn-with-disabled-summaries',
1138
+ dn: 'pre-register-dn',
1139
+ webRtcEnabled: true,
1140
+ aiFeature,
1141
+ });
1142
+ const expectedProfile = {...configuredProfile, dn: configuredProfile.defaultDn};
1143
+ webex.cc.$config = {...webex.cc.$config, allowAutomatedRelogin: false};
1144
+ const mercuryConnect = jest
1145
+ .spyOn(webex.internal.mercury, 'connect')
1146
+ .mockResolvedValue(true);
1147
+ const setupEventListenersSpy = jest.spyOn(webex.cc, 'setupEventListeners');
1148
+ const configSpy = jest
1149
+ .spyOn(webex.cc.services.config, 'getAgentConfig')
1150
+ .mockResolvedValue(configuredProfile);
1151
+ mockWebSocketManager.initWebSocket.mockResolvedValue({agentId: welcomeAgentId});
1152
+
1153
+ const result = await webex.cc.register();
1154
+
1155
+ expect(mockWebSocketManager.initWebSocket).toHaveBeenCalledWith({
1156
+ body: {
1157
+ force: true,
1158
+ isKeepAliveEnabled: false,
1159
+ clientType: 'WebexCCSDK',
1160
+ allowMultiLogin: false,
1161
+ },
1162
+ resource: SUBSCRIBE_API,
1163
+ });
1164
+ expect(configSpy).toHaveBeenCalledWith('mockOrgId', welcomeAgentId);
1165
+ expect(setupEventListenersSpy).toHaveBeenCalled();
1166
+ expect(mockTaskManager.on).toHaveBeenCalledWith(
1167
+ TASK_EVENTS.TASK_INCOMING,
1168
+ expect.any(Function)
1169
+ );
1170
+ expect(mockTaskManager.on).toHaveBeenCalledWith(
1171
+ TASK_EVENTS.TASK_HYDRATE,
1172
+ expect.any(Function)
1173
+ );
1174
+ expect(mockTaskManager.on).toHaveBeenCalledWith(
1175
+ TASK_EVENTS.TASK_MULTI_LOGIN_HYDRATE,
1176
+ expect.any(Function)
1177
+ );
1178
+ expect(mockWebSocketManager.on).toHaveBeenCalledWith('message', expect.any(Function));
1179
+ expect(mockTaskManager.setConfigFlags).toHaveBeenCalledWith({
1180
+ isEndTaskEnabled: configuredProfile.isEndTaskEnabled,
1181
+ isEndConsultEnabled: configuredProfile.isEndConsultEnabled,
1182
+ webRtcEnabled: configuredProfile.webRtcEnabled,
1183
+ autoWrapup: configuredProfile.wrapUpData.wrapUpProps.autoWrapup ?? false,
1184
+ aiFeature,
1185
+ getWxAppUsersubPublished: expect.any(Function),
1186
+ consultTransfer: {
1187
+ allowConsultToQueue: configuredProfile.allowConsultToQueue,
1188
+ accessQueue: configuredProfile.accessQueue,
1189
+ accessEntryPoint: configuredProfile.accessEntryPoint,
1190
+ accessBuddyTeam: configuredProfile.accessBuddyTeam,
1191
+ },
1192
+ enableWxBetterTogether: false,
1193
+ });
1194
+ expect(webex.cc.services.rtdWebSocketManager.initWebSocket).not.toHaveBeenCalled();
1195
+ expect(webex.cc.services.rtdWebSocketManager.on).not.toHaveBeenCalledWith(
1196
+ 'message',
1197
+ expect.any(Function)
1198
+ );
1199
+ expect(mercuryConnect).toHaveBeenCalled();
1200
+ expect(result).toEqual(expectedProfile);
1201
+ }
1202
+ );
1203
+ });
1204
+
1205
+ describe('AI summary lifecycle wiring', () => {
1206
+ const sentinels = [
1207
+ 'summary-sentinel-cc-lifecycle',
1208
+ 'section-key-sentinel-cc-lifecycle',
1209
+ 'section-value-sentinel-cc-lifecycle',
1210
+ 'adaptive-card-sentinel-cc-lifecycle',
1211
+ 'agent-name-sentinel-cc-lifecycle',
1212
+ ];
1213
+
1214
+ const createSummaryHarness = () => {
1215
+ const ActualTaskManager = jest.requireActual('../../../src/services/task/TaskManager')
1216
+ .default as typeof TaskManager;
1217
+ const webSocketManager = new EventEmitterDouble();
1218
+ const rtdWebSocketManager = new EventEmitterDouble();
1219
+ const connectionService = new EventEmitterDouble();
1220
+ const webCallingService = new EventEmitterDouble();
1221
+ const transportDeferreds: Deferred<void>[] = [];
1222
+ const pendingRequests = new Map<string, any>();
1223
+ const apiAIAssistant: any = {
1224
+ aiFeature: {
1225
+ id: 'test-ai-feature',
1226
+ generatedSummaries: {
1227
+ wrapUpSummariesEnabled: true,
1228
+ consultTransferSummariesEnabled: true,
1229
+ },
1230
+ },
1231
+ getSuggestedResponse: jest.fn(),
1232
+ fetchHistoricTranscripts: jest.fn(),
1233
+ setAIFeatureFlags: jest.fn((flags: AIFeatureFlags) => {
1234
+ apiAIAssistant.aiFeature = flags;
1235
+ }),
1236
+ setAgentId: jest.fn(),
1237
+ pendingRequests,
1238
+ sendEvent: jest.fn((_agentId: string, _interactionId: string, _eventType: string, eventName: string) => {
1239
+ if (eventName.includes('SUMMARY_RESPONSE')) {
1240
+ return Promise.resolve(undefined);
1241
+ }
1242
+
1243
+ const deferred = createDeferred<void>();
1244
+
1245
+ transportDeferreds.push(deferred);
1246
+
1247
+ return deferred.promise;
1248
+ }),
1249
+ };
1250
+ apiAIAssistant.requestAndWaitForRtd = jest.fn(async (options: any) => {
1251
+ const publishTimestamp = Date.now();
1252
+ let resolveResult: (payload: any) => void = () => undefined;
1253
+ let rejectResult: (error: Error) => void = () => undefined;
1254
+ const result = new Promise((resolve, reject) => {
1255
+ resolveResult = resolve;
1256
+ rejectResult = reject;
1257
+ });
1258
+ const key = JSON.stringify([options.rtdEventType, options.correlationId]);
1259
+ pendingRequests.set(key, {
1260
+ eventType: options.rtdEventType,
1261
+ correlationId: options.correlationId,
1262
+ resolve: resolveResult,
1263
+ reject: rejectResult,
1264
+ result,
1265
+ });
1266
+ try {
1267
+ const acknowledgement = apiAIAssistant.sendEvent(
1268
+ options.agentId,
1269
+ options.interactionId,
1270
+ options.eventType,
1271
+ options.eventName,
1272
+ options.eventMetaData,
1273
+ undefined,
1274
+ undefined,
1275
+ publishTimestamp,
1276
+ options.timeout
1277
+ );
1278
+ const [payload] = await Promise.all([result, acknowledgement]);
1279
+ pendingRequests.delete(key);
1280
+ return payload;
1281
+ } catch (error) {
1282
+ pendingRequests.delete(key);
1283
+ throw error;
1284
+ }
1285
+ });
1286
+ apiAIAssistant.resolveFromRtdEvent = jest.fn(
1287
+ (eventType: string, correlationId: string, payload: any) => {
1288
+ const key = JSON.stringify([eventType, correlationId]);
1289
+ const request = pendingRequests.get(key);
1290
+ if (!request) return 'not-found';
1291
+ pendingRequests.delete(key);
1292
+ request.resolve(payload);
1293
+ return 'resolved';
1294
+ }
1295
+ );
1296
+ apiAIAssistant.clearAllRtdRequests = jest.fn(() => {
1297
+ pendingRequests.forEach((request) => {
1298
+ const error = new Error(AI_SUMMARY_REQUEST_CANCELLED) as Error & {
1299
+ data?: Record<string, unknown>;
1300
+ };
1301
+ error.data = {errorCode: AI_SUMMARY_REQUEST_CANCELLED};
1302
+ request.reject(error);
1303
+ });
1304
+ pendingRequests.clear();
1305
+ });
1306
+ const taskManager = new ActualTaskManager(
1307
+ apiAIAssistant as any,
1308
+ mockContact,
1309
+ webCallingService as any,
1310
+ webSocketManager as any,
1311
+ rtdWebSocketManager as any
1312
+ );
1313
+ const taskFactory = jest.requireMock('../../../src/services/task/TaskFactory')
1314
+ .default as {createTask: jest.Mock};
1315
+
1316
+ taskFactory.createTask.mockImplementation(
1317
+ (
1318
+ _contact,
1319
+ _webCallingService,
1320
+ taskData: TaskData,
1321
+ _configFlags,
1322
+ _wrapupData,
1323
+ _agentId,
1324
+ _agentName,
1325
+ _answerCallService,
1326
+ taskApiAIAssistant: ApiAIAssistant
1327
+ ) => createAISummaryLifecycleTask(taskData, taskApiAIAssistant)
1328
+ );
1329
+ const task = createAISummaryLifecycleTask(undefined, apiAIAssistant);
1330
+
1331
+ taskManager.setConfigFlags({
1332
+ isEndTaskEnabled: true,
1333
+ isEndConsultEnabled: true,
1334
+ webRtcEnabled: false,
1335
+ autoWrapup: false,
1336
+ aiFeature: {
1337
+ generatedSummaries: {
1338
+ wrapUpSummariesEnabled: true,
1339
+ consultTransferSummariesEnabled: true,
1340
+ },
1341
+ },
1342
+ } as any);
1343
+ taskManager.setAgentId('agent-1');
1344
+ taskManager.setWebRtcEnabled(false);
1345
+ (taskManager as any).taskCollection[task.data.interactionId] = task;
1346
+
1347
+ (webex.cc as any).taskManager = taskManager;
1348
+ webex.cc.apiAIAssistant = apiAIAssistant as any;
1349
+ webex.cc.services.webSocketManager = webSocketManager as any;
1350
+ webex.cc.services.rtdWebSocketManager = rtdWebSocketManager as any;
1351
+ webex.cc.services.connectionService = connectionService as any;
1352
+
1353
+ const emitRtdFrame = (type: string, data: Record<string, unknown>) => {
1354
+ rtdWebSocketManager.emit('message', JSON.stringify({type, data: {data}}));
1355
+ };
1356
+ const dispatchRtdFrame = (type: string, data: Record<string, unknown>) => {
1357
+ webex.cc['handleRTDWebsocketMessage'](JSON.stringify({type, data: {data}}));
1358
+ };
1359
+ const getApiAIAssistant = () => apiAIAssistant as any;
1360
+ const getSummaryMapCounts = () => {
1361
+ const api = getApiAIAssistant() as any;
1362
+ const manager = taskManager as any;
1363
+ const pendingRequests = Array.from(api.pendingRequests.values());
1364
+
1365
+ return {
1366
+ pendingPostCall: pendingRequests.filter(
1367
+ (request: any) => request.eventType === 'POST_CALL_SUMMARY'
1368
+ ).length,
1369
+ pendingMidCall: pendingRequests.filter(
1370
+ (request: any) => request.eventType === 'MID_CALL_SUMMARY'
1371
+ ).length,
1372
+ receiving: manager.receivingSummaryBuffer.size,
1373
+ featureEnablement: manager.pendingFeatureEnablement.size,
1374
+ };
1375
+ };
1376
+ const expectSummaryStateCleared = () => {
1377
+ expect(getSummaryMapCounts()).toEqual({
1378
+ pendingPostCall: 0,
1379
+ pendingMidCall: 0,
1380
+ receiving: 0,
1381
+ featureEnablement: 0,
1382
+ });
1383
+ };
1384
+
1385
+ return {
1386
+ apiAIAssistant,
1387
+ connectionService,
1388
+ dispatchRtdFrame,
1389
+ emitRtdFrame,
1390
+ expectSummaryStateCleared,
1391
+ getApiAIAssistant,
1392
+ getSummaryMapCounts,
1393
+ rtdWebSocketManager,
1394
+ task,
1395
+ taskManager,
1396
+ transportDeferreds,
1397
+ webSocketManager,
1398
+ };
1399
+ };
1400
+
1401
+ const attachRtdMessageListener = (rtdWebSocketManager: EventEmitterDouble) => {
1402
+ rtdWebSocketManager.on('message', webex.cc['handleRTDWebsocketMessage']);
1403
+ };
1404
+
1405
+ const countAISummaryRequestFinalMetrics = () =>
1406
+ mockMetricsManager.trackEvent.mock.calls.filter(([eventName]) =>
1407
+ [
1408
+ METRIC_EVENT_NAMES.AI_SUMMARY_GET_POST_CALL_SUCCESS,
1409
+ METRIC_EVENT_NAMES.AI_SUMMARY_GET_POST_CALL_FAILED,
1410
+ METRIC_EVENT_NAMES.AI_SUMMARY_GET_MID_CALL_SUCCESS,
1411
+ METRIC_EVENT_NAMES.AI_SUMMARY_GET_MID_CALL_FAILED,
1412
+ ].includes(eventName)
1413
+ ).length;
1414
+
1415
+ const expectSentinelsNotObserved = () => {
1416
+ const observedArguments = JSON.stringify([
1417
+ LoggerProxy.log.mock.calls,
1418
+ LoggerProxy.info.mock.calls,
1419
+ LoggerProxy.warn.mock.calls,
1420
+ LoggerProxy.error.mock.calls,
1421
+ mockMetricsManager.trackEvent.mock.calls,
1422
+ mockMetricsManager.timeEvent.mock.calls,
1423
+ ]);
1424
+
1425
+ sentinels.forEach((sentinel) => {
1426
+ expect(observedArguments).not.toContain(sentinel);
1427
+ });
1428
+ };
1429
+
1430
+ const emitFeatureEnablement = (
1431
+ harness: ReturnType<typeof createSummaryHarness>,
1432
+ payload = {
1433
+ interactionId: 'interaction-1',
1434
+ postCallEnabled: true,
1435
+ midCallEnabled: true,
1436
+ actionTimestamp: 1,
1437
+ }
1438
+ ) => {
1439
+ harness.emitRtdFrame(CC_TASK_EVENTS.FEATURE_ENABLEMENT, payload);
1440
+ };
1441
+
1442
+ const dispatchFeatureEnablement = (
1443
+ harness: ReturnType<typeof createSummaryHarness>,
1444
+ payload = {
1445
+ interactionId: 'interaction-1',
1446
+ postCallEnabled: true,
1447
+ midCallEnabled: true,
1448
+ actionTimestamp: 1,
1449
+ }
1450
+ ) => {
1451
+ harness.dispatchRtdFrame(CC_TASK_EVENTS.FEATURE_ENABLEMENT, payload);
1452
+ };
1453
+
1454
+ const emitTaskLifecycleEvent = (
1455
+ harness: ReturnType<typeof createSummaryHarness>,
1456
+ eventType: CC_EVENTS,
1457
+ overrides: Partial<TaskData> & {conversationId?: string}
1458
+ ) => {
1459
+ const interactionId = overrides.interactionId ?? 'interaction-1';
1460
+
1461
+ harness.webSocketManager.emit(
1462
+ 'message',
1463
+ JSON.stringify({
1464
+ data: {
1465
+ ...createAISummaryLifecycleTaskData({
1466
+ mediaResourceId: interactionId,
1467
+ taskId: `task-owner-${interactionId}`,
1468
+ ...overrides,
1469
+ }),
1470
+ type: eventType,
1471
+ },
1472
+ })
1473
+ );
1474
+ };
1475
+
1476
+ const emitSentinelPostCallSummary = (
1477
+ harness: ReturnType<typeof createSummaryHarness>,
1478
+ conversationId = 'conversation-1'
1479
+ ) => {
1480
+ harness.emitRtdFrame(CC_TASK_EVENTS.POST_CALL_SUMMARY, {
1481
+ conversationId,
1482
+ summaryText: sentinels[0],
1483
+ sections: {
1484
+ [sentinels[1]]: sentinels[2],
1485
+ initialContactReason: sentinels[2],
1486
+ },
1487
+ adaptiveCard: {
1488
+ body: [{text: sentinels[3]}],
1489
+ },
1490
+ });
1491
+ };
1492
+
1493
+ const dispatchSentinelPostCallSummary = (
1494
+ harness: ReturnType<typeof createSummaryHarness>,
1495
+ conversationId = 'conversation-1'
1496
+ ) => {
1497
+ harness.dispatchRtdFrame(CC_TASK_EVENTS.POST_CALL_SUMMARY, {
1498
+ conversationId,
1499
+ summaryText: sentinels[0],
1500
+ sections: {
1501
+ [sentinels[1]]: sentinels[2],
1502
+ initialContactReason: sentinels[2],
1503
+ },
1504
+ adaptiveCard: {
1505
+ body: [{text: sentinels[3]}],
1506
+ },
1507
+ });
1508
+ };
1509
+
1510
+ const emitSentinelMidCallSummary = (
1511
+ harness: ReturnType<typeof createSummaryHarness>,
1512
+ conversationId = 'conversation-1'
1513
+ ) => {
1514
+ harness.emitRtdFrame(CC_TASK_EVENTS.MID_CALL_SUMMARY, {
1515
+ conversationId,
1516
+ summaryText: sentinels[0],
1517
+ agentName: sentinels[4],
1518
+ sections: {
1519
+ [sentinels[1]]: sentinels[2],
1520
+ reasonForTransferOrConsult: sentinels[2],
1521
+ },
1522
+ adaptiveCard: {
1523
+ body: [{text: sentinels[3]}],
1524
+ },
1525
+ });
1526
+ };
1527
+
1528
+ afterEach(() => {
1529
+ jest.useRealTimers();
1530
+ });
1531
+
1532
+ it('forwards task-manager handlers through ContactCenter trigger and delegates RTD messages', () => {
1533
+ const triggerSpy = jest.spyOn(webex.cc, 'trigger');
1534
+ const task = {data: {interactionId: 'interaction-1'}} as any;
1535
+
1536
+ webex.cc['handleTaskHydrate'](task);
1537
+ webex.cc['handleTaskMultiLoginHydrate'](task);
1538
+ webex.cc['handleTaskMerged'](task);
1539
+ webex.cc['handleCampaignPreviewReservation'](task);
1540
+ webex.cc['handleRTDWebsocketMessage']('summary-frame');
1541
+
1542
+ expect(triggerSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_HYDRATE, task);
1543
+ expect(triggerSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_MULTI_LOGIN_HYDRATE, task);
1544
+ expect(triggerSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_MERGED, task);
1545
+ expect(triggerSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_CAMPAIGN_PREVIEW_RESERVATION, task);
1546
+ expect(mockTaskManager.handleRealtimeWebsocketEvent).toHaveBeenCalledWith('summary-frame');
1547
+ });
1548
+
1549
+ it('clears active summary state on deregister', async () => {
1550
+ jest.useFakeTimers();
1551
+
1552
+ const harness = createSummaryHarness();
1553
+ const triggerSpy = jest.spyOn(webex.cc, 'trigger');
1554
+ const profile = {
1555
+ agentId: 'agent-1',
1556
+ webRtcEnabled: false,
1557
+ loginVoiceOptions: [LoginOption.EXTENSION],
1558
+ isEndTaskEnabled: true,
1559
+ isEndConsultEnabled: true,
1560
+ wrapUpData: {wrapUpProps: {autoWrapup: false}},
1561
+ aiFeature: {
1562
+ generatedSummaries: {
1563
+ wrapUpSummariesEnabled: true,
1564
+ consultTransferSummariesEnabled: true,
1565
+ },
1566
+ },
1567
+ } as any;
1568
+
1569
+ webex.cc.$config = {...webex.cc.$config, allowAutomatedRelogin: false};
1570
+ harness.webSocketManager.initWebSocket.mockResolvedValue({agentId: 'agent-1'});
1571
+ jest.spyOn(webex.cc.services.config, 'getAgentConfig').mockResolvedValue(profile);
1572
+
1573
+ await webex.cc.register();
1574
+ await flushMicrotasks();
1575
+
1576
+ expect(harness.rtdWebSocketManager.listenerCount('message')).toBe(1);
1577
+
1578
+ dispatchFeatureEnablement(harness);
1579
+ expect(harness.task.aiSummaryCapabilities).toEqual({
1580
+ midCallEnabled: true,
1581
+ postCallEnabled: true,
1582
+ });
1583
+
1584
+ dispatchFeatureEnablement(harness, {
1585
+ interactionId: 'orphan-before-deregister',
1586
+ postCallEnabled: true,
1587
+ midCallEnabled: true,
1588
+ actionTimestamp: 4,
1589
+ });
1590
+ harness.dispatchRtdFrame(CC_TASK_EVENTS.MID_CALL_SUMMARY_RESPONSE_SUBSEQUENT_AGENT, {
1591
+ conversationId: 'queued-before-deregister',
1592
+ summaryText: sentinels[0],
1593
+ });
1594
+ expect(jest.getTimerCount()).toBe(0);
1595
+ expect(harness.task.aiSummaryCapabilities).toEqual({
1596
+ midCallEnabled: true,
1597
+ postCallEnabled: true,
1598
+ });
1599
+ expect(harness.getSummaryMapCounts()).toEqual({
1600
+ pendingPostCall: 0,
1601
+ pendingMidCall: 0,
1602
+ receiving: 1,
1603
+ featureEnablement: 1,
1604
+ });
1605
+ expect(jest.getTimerCount()).toBe(0);
1606
+
1607
+ await webex.cc.deregister();
1608
+
1609
+ harness.expectSummaryStateCleared();
1610
+ expect(harness.task.aiSummaryCapabilities).toEqual({
1611
+ midCallEnabled: false,
1612
+ postCallEnabled: false,
1613
+ });
1614
+ expect(jest.getTimerCount()).toBe(0);
1615
+ expect(harness.rtdWebSocketManager.listenerCount('message')).toBe(0);
1616
+ triggerSpy.mockClear();
1617
+
1618
+ dispatchSentinelPostCallSummary(harness, 'queued-after-deregister');
1619
+
1620
+ expect(harness.getSummaryMapCounts()).toEqual({
1621
+ pendingPostCall: 0,
1622
+ pendingMidCall: 0,
1623
+ receiving: 0,
1624
+ featureEnablement: 0,
1625
+ });
1626
+ expect(triggerSpy).not.toHaveBeenCalled();
1627
+ expectSentinelsNotObserved();
1628
+ });
1629
+
1630
+ it('flushes a buffered receiving summary through real TaskManager task publication once the task is answered', () => {
1631
+ jest.useFakeTimers();
1632
+
1633
+ const harness = createSummaryHarness();
1634
+ const interactionId = 'receiver-arrival-interaction';
1635
+ const conversationId = interactionId;
1636
+ const receivingPayload = {
1637
+ conversationId,
1638
+ summaryText: sentinels[0],
1639
+ adaptiveCard: {body: [{text: sentinels[3]}]},
1640
+ };
1641
+ const receiverHandler = jest.fn();
1642
+ const observedOrder: string[] = [];
1643
+ let publishedTask: Task | undefined;
1644
+ let receiverEmitSpy: jest.SpyInstance | undefined;
1645
+
1646
+ harness.dispatchRtdFrame(CC_TASK_EVENTS.MID_CALL_SUMMARY_RESPONSE_SUBSEQUENT_AGENT, {
1647
+ ...receivingPayload,
1648
+ });
1649
+
1650
+ expect(harness.getSummaryMapCounts()).toEqual({
1651
+ pendingPostCall: 0,
1652
+ pendingMidCall: 0,
1653
+ receiving: 1,
1654
+ featureEnablement: 0,
1655
+ });
1656
+ expect(jest.getTimerCount()).toBe(0);
1657
+
1658
+ harness.taskManager.on(TASK_EVENTS.TASK_INCOMING, (task: Task) => {
1659
+ publishedTask = task;
1660
+ receiverEmitSpy = jest.spyOn(task, 'emit');
1661
+ task.on(TASK_EVENTS.TASK_ASSIGNED, () => observedOrder.push('answered'));
1662
+ task.on(TASK_EVENTS.TASK_MID_CALL_SUMMARY_RECEIVED, (payload) => {
1663
+ observedOrder.push('receiver-summary');
1664
+ receiverHandler(payload);
1665
+ });
1666
+ });
1667
+
1668
+ emitTaskLifecycleEvent(harness, CC_EVENTS.AGENT_CONTACT_RESERVED, {
1669
+ interactionId,
1670
+ conversationId,
1671
+ });
1672
+
1673
+ expect(publishedTask).toBe(harness.taskManager.getTask(interactionId));
1674
+ expect(publishedTask).toBeInstanceOf(Task);
1675
+ expect(receiverHandler).not.toHaveBeenCalled();
1676
+ expect(harness.getSummaryMapCounts().receiving).toBe(1);
1677
+
1678
+ emitTaskLifecycleEvent(harness, CC_EVENTS.AGENT_CONTACT_ASSIGNED, {
1679
+ interactionId,
1680
+ conversationId,
1681
+ });
1682
+
1683
+ expect(observedOrder).toEqual(['answered', 'receiver-summary']);
1684
+ expect(receiverHandler).toHaveBeenCalledTimes(1);
1685
+ expect(receiverHandler).toHaveBeenCalledWith(receivingPayload);
1686
+ expect(
1687
+ receiverEmitSpy?.mock.calls.filter(
1688
+ ([eventName]) => eventName === TASK_EVENTS.TASK_MID_CALL_SUMMARY_RECEIVED
1689
+ )
1690
+ ).toHaveLength(1);
1691
+ expect(harness.getSummaryMapCounts()).toEqual({
1692
+ pendingPostCall: 0,
1693
+ pendingMidCall: 0,
1694
+ receiving: 0,
1695
+ featureEnablement: 0,
1696
+ });
1697
+ expect(jest.getTimerCount()).toBe(0);
1698
+ expectSentinelsNotObserved();
1699
+ });
1700
+
1701
+ it('resolves a real post-call request through RTD and keeps summary sentinels out of metrics', async () => {
1702
+ jest.useFakeTimers();
1703
+
1704
+ const harness = createSummaryHarness();
1705
+
1706
+ attachRtdMessageListener(harness.rtdWebSocketManager);
1707
+ emitFeatureEnablement(harness);
1708
+ jest.clearAllMocks();
1709
+
1710
+ const postCallRequest = harness.task.requestPostCallSummary();
1711
+
1712
+ await flushMicrotasks();
1713
+ expect(harness.apiAIAssistant.sendEvent).toHaveBeenCalledWith(
1714
+ 'agent-1',
1715
+ 'interaction-1',
1716
+ AIAssistantEventType.CTI_EVENT,
1717
+ AIAssistantEventName.GET_POST_CALL_SUMMARY,
1718
+ expect.objectContaining({conversationId: 'conversation-1'}),
1719
+ undefined,
1720
+ undefined,
1721
+ expect.any(Number),
1722
+ 15000
1723
+ );
1724
+ emitSentinelPostCallSummary(harness);
1725
+ harness.transportDeferreds[0].resolve(undefined);
1726
+
1727
+ await expect(postCallRequest).resolves.toMatchObject({
1728
+ conversationId: 'conversation-1',
1729
+ summaryText: sentinels[0],
1730
+ });
1731
+ expect(harness.getSummaryMapCounts()).toEqual({
1732
+ pendingPostCall: 0,
1733
+ pendingMidCall: 0,
1734
+ receiving: 0,
1735
+ featureEnablement: 0,
1736
+ });
1737
+ expect(jest.getTimerCount()).toBe(0);
1738
+ expect(mockMetricsManager.trackEvent).toHaveBeenCalledWith(
1739
+ METRIC_EVENT_NAMES.AI_SUMMARY_GET_POST_CALL_SUCCESS,
1740
+ expect.objectContaining({
1741
+ conversationId: 'conversation-1',
1742
+ interactionId: 'interaction-1',
1743
+ }),
1744
+ ['operational']
1745
+ );
1746
+ harness.taskManager.clearAISummaryState();
1747
+ harness.expectSummaryStateCleared();
1748
+ expectSentinelsNotObserved();
1749
+ });
1750
+
1751
+ it('sends post-call responses using current task data after manager cleanup', async () => {
1752
+ jest.useFakeTimers();
1753
+
1754
+ const harness = createSummaryHarness();
1755
+ const interactionId = 'post-call-cleanup-interaction';
1756
+ const conversationId = 'post-call-cleanup-conversation';
1757
+ const apiAIAssistant = harness.getApiAIAssistant();
1758
+ let applicationTask: Task | undefined;
1759
+
1760
+ harness.taskManager.on(TASK_EVENTS.TASK_INCOMING, (task: Task) => {
1761
+ if (task.data.interactionId === interactionId) {
1762
+ applicationTask = task;
1763
+ }
1764
+ });
1765
+ emitTaskLifecycleEvent(harness, CC_EVENTS.AGENT_CONTACT_RESERVED, {
1766
+ interactionId,
1767
+ conversationId,
1768
+ });
1769
+ emitTaskLifecycleEvent(harness, CC_EVENTS.AGENT_CONTACT_ASSIGNED, {
1770
+ interactionId,
1771
+ conversationId,
1772
+ });
1773
+
1774
+ expect(applicationTask).toBe(harness.taskManager.getTask(interactionId));
1775
+ const retainedTask = applicationTask as Task;
1776
+
1777
+ dispatchFeatureEnablement(harness, {
1778
+ interactionId,
1779
+ postCallEnabled: true,
1780
+ midCallEnabled: true,
1781
+ actionTimestamp: 9,
1782
+ });
1783
+
1784
+ const postCallRequest = retainedTask.requestPostCallSummary();
1785
+
1786
+ await flushMicrotasks();
1787
+ expect(postCallRequest).toBeDefined();
1788
+ expect(harness.apiAIAssistant.sendEvent).toHaveBeenCalledWith(
1789
+ 'agent-1',
1790
+ interactionId,
1791
+ AIAssistantEventType.CTI_EVENT,
1792
+ AIAssistantEventName.GET_POST_CALL_SUMMARY,
1793
+ expect.objectContaining({conversationId}),
1794
+ undefined,
1795
+ undefined,
1796
+ expect.any(Number),
1797
+ 15000
1798
+ );
1799
+ harness.dispatchRtdFrame(CC_TASK_EVENTS.POST_CALL_SUMMARY, {
1800
+ conversationId,
1801
+ summaryText: sentinels[0],
1802
+ });
1803
+ harness.transportDeferreds[0].resolve(undefined);
1804
+
1805
+ await expect(postCallRequest).resolves.toMatchObject({
1806
+ conversationId,
1807
+ summaryText: sentinels[0],
1808
+ });
1809
+ expect(harness.getSummaryMapCounts()).toEqual({
1810
+ pendingPostCall: 0,
1811
+ pendingMidCall: 0,
1812
+ receiving: 0,
1813
+ featureEnablement: 0,
1814
+ });
1815
+
1816
+ emitTaskLifecycleEvent(harness, CC_EVENTS.AGENT_WRAPUP, {
1817
+ interactionId,
1818
+ conversationId,
1819
+ });
1820
+ emitTaskLifecycleEvent(harness, CC_EVENTS.AGENT_WRAPPEDUP, {
1821
+ interactionId,
1822
+ conversationId,
1823
+ });
1824
+
1825
+ expect(harness.taskManager.getTask(interactionId)).toBeUndefined();
1826
+ expect(harness.getSummaryMapCounts()).toEqual({
1827
+ pendingPostCall: 0,
1828
+ pendingMidCall: 0,
1829
+ receiving: 0,
1830
+ featureEnablement: 0,
1831
+ });
1832
+ expect(jest.getTimerCount()).toBe(0);
1833
+
1834
+ const requestCallsAfterRemoval = (apiAIAssistant as any).pendingRequests.size;
1835
+ const responseInteractionId = 'post-call-response-current-interaction';
1836
+ const responseConversationId = 'post-call-response-current-conversation';
1837
+
1838
+ retainedTask.updateTaskData(
1839
+ createAISummaryLifecycleTaskData({
1840
+ interactionId: responseInteractionId,
1841
+ conversationId: responseConversationId,
1842
+ }),
1843
+ true
1844
+ );
1845
+
1846
+ const responsePayload: AISummaryResponse = {
1847
+ summary: {initialContactReason: 'resolved'},
1848
+ feedback: 'thumbs_up',
1849
+ state: 'DEFAULT',
1850
+ wrapUpCode: 'resolved',
1851
+ numberOfTimesViewed: 1,
1852
+ numberOfTimesEdited: 0,
1853
+ numberOfTimesCopied: 0,
1854
+ };
1855
+
1856
+ await expect(
1857
+ retainedTask.sendPostCallSummaryResponse(responsePayload)
1858
+ ).resolves.toBeUndefined();
1859
+
1860
+ expect((apiAIAssistant as any).pendingRequests.size).toBe(requestCallsAfterRemoval);
1861
+ expect(harness.apiAIAssistant.sendEvent).toHaveBeenCalledTimes(2);
1862
+ expect(harness.apiAIAssistant.sendEvent).toHaveBeenNthCalledWith(
1863
+ 2,
1864
+ 'agent-1',
1865
+ responseInteractionId,
1866
+ AIAssistantEventType.CTI_EVENT,
1867
+ AIAssistantEventName.POST_CALL_SUMMARY_RESPONSE,
1868
+ {
1869
+ conversationId: responseConversationId,
1870
+ clientType: 'WxCC',
1871
+ action: AIAssistantEventName.POST_CALL_SUMMARY_RESPONSE,
1872
+ summary: {initialContactReason: 'resolved'},
1873
+ feedback: 'thumbs_up',
1874
+ wrapUpCode: 'resolved',
1875
+ numberOfTimesViewed: 1,
1876
+ numberOfTimesEdited: 0,
1877
+ numberOfTimesCopied: 0,
1878
+ state: 'DEFAULT',
1879
+ },
1880
+ undefined,
1881
+ undefined,
1882
+ expect.any(Number),
1883
+ 15000
1884
+ );
1885
+ });
1886
+
1887
+ it('cancels pending real public requests on deregister and ignores late HTTP settlement', async () => {
1888
+ const harness = createSummaryHarness();
1889
+ const unhandledRejections: unknown[] = [];
1890
+ const unhandledRejectionListener = jest.fn((reason) => {
1891
+ unhandledRejections.push(reason);
1892
+ });
1893
+
1894
+ attachRtdMessageListener(harness.rtdWebSocketManager);
1895
+ emitFeatureEnablement(harness);
1896
+ jest.clearAllMocks();
1897
+
1898
+ webex.cc.agentConfig = {
1899
+ agentId: 'agent-1',
1900
+ webRtcEnabled: false,
1901
+ loginVoiceOptions: [LoginOption.EXTENSION],
1902
+ };
1903
+
1904
+ process.on('unhandledRejection', unhandledRejectionListener);
1905
+ try {
1906
+ const postCallRequest = harness.task.requestPostCallSummary();
1907
+ const midCallRequest = harness.task.requestMidCallSummary('CONSULT');
1908
+ postCallRequest.catch(() => undefined);
1909
+ midCallRequest.catch(() => undefined);
1910
+
1911
+ await flushMicrotasks();
1912
+ expect(harness.transportDeferreds).toHaveLength(2);
1913
+
1914
+ await webex.cc.deregister();
1915
+ await flushEventLoopTurn();
1916
+
1917
+ expect(unhandledRejectionListener).not.toHaveBeenCalled();
1918
+ expect(unhandledRejections).toHaveLength(0);
1919
+ await expect(postCallRequest).rejects.toMatchObject({
1920
+ message: AI_SUMMARY_REQUEST_CANCELLED,
1921
+ data: {errorCode: AI_SUMMARY_REQUEST_CANCELLED},
1922
+ });
1923
+ await expect(midCallRequest).rejects.toMatchObject({
1924
+ message: AI_SUMMARY_REQUEST_CANCELLED,
1925
+ data: {errorCode: AI_SUMMARY_REQUEST_CANCELLED},
1926
+ });
1927
+ harness.expectSummaryStateCleared();
1928
+
1929
+ const finalMetricCountAfterCancellation = countAISummaryRequestFinalMetrics();
1930
+
1931
+ dispatchSentinelPostCallSummary(harness, 'queued-after-deregister');
1932
+ harness.transportDeferreds[0].resolve(undefined);
1933
+ harness.transportDeferreds[1].reject(new Error('late-http-rejected-after-deregister'));
1934
+ await flushEventLoopTurn();
1935
+
1936
+ expect(unhandledRejectionListener).not.toHaveBeenCalled();
1937
+ expect(unhandledRejections).toHaveLength(0);
1938
+ expect(countAISummaryRequestFinalMetrics()).toBe(finalMetricCountAfterCancellation);
1939
+ harness.expectSummaryStateCleared();
1940
+ expectSentinelsNotObserved();
1941
+ } finally {
1942
+ process.off('unhandledRejection', unhandledRejectionListener);
1943
+ harness.taskManager.clearAISummaryState();
1944
+ }
1945
+ });
1946
+ });
1947
+
1948
+ describe('stationLogin', () => {
1949
+ it('should login successfully with LoginOption.BROWSER and webrtc enabled', async () => {
1950
+ const mockTask = {};
1951
+ const options = {
1952
+ teamId: 'teamId',
1953
+ loginOption: LoginOption.BROWSER,
1954
+ };
1955
+
1956
+ webex.cc.agentConfig = {
1957
+ agentId: 'agentId',
1958
+ webRtcEnabled: true,
1959
+ loginVoiceOptions: ['BROWSER', 'EXTENSION', 'AGENT_DN'],
1960
+ };
1961
+
1962
+ const registerWebCallingLineSpy = jest.spyOn(
1963
+ webex.cc.webCallingService,
1964
+ 'registerWebCallingLine'
1965
+ );
1966
+
1967
+ const mockData = {
1968
+ data: {
1969
+ loginOption: LoginOption.BROWSER,
1970
+ agentId: 'agentId',
1971
+ teamId: 'teamId',
1972
+ siteId: 'siteId',
1973
+ roles: [AGENT],
1974
+ trackingId: '1234',
1975
+ eventType: 'DESKTOP_MESSAGE',
1976
+ channelsMap: {
1977
+ chat: ['25d8ggg7-4821-7de7-b626-36437adec509', '14e7fff7-7de7-4821-a919-36437adec509'],
1978
+ email: [
1979
+ '14e7fff7-7de7-4821-a919-36437adec509',
1980
+ '14e7fff7-7de7-4821-a919-36437adec509',
1981
+ '14e7fff7-7de7-4821-a919-36437adec509',
1982
+ ],
1983
+ social: [],
1984
+ telephony: ['14e7fff7-7de7-4821-a919-36437adec509'],
1985
+ },
1986
+ },
1987
+ trackingId: 'notifs_52628',
1988
+ orgId: 'orgId',
1989
+ type: 'StationLoginSuccess',
1990
+ eventType: 'STATION_LOGIN',
1991
+ };
1992
+
1993
+ const responseMock = {
1994
+ loginOption: LoginOption.BROWSER,
1995
+ agentId: 'agentId',
1996
+ teamId: 'teamId',
1997
+ siteId: 'siteId',
1998
+ roles: [AGENT],
1999
+ trackingId: '1234',
560
2000
  eventType: 'DESKTOP_MESSAGE',
561
2001
  mmProfile: {
562
2002
  chat: 2,
@@ -576,7 +2016,7 @@ describe('webex.cc', () => {
576
2016
  expect(registerWebCallingLineSpy).toHaveBeenCalled();
577
2017
  expect(stationLoginMock).toHaveBeenCalledWith({
578
2018
  data: {
579
- dialNumber: 'agentId',
2019
+ dialNumber: `${WEB_RTC_PREFIX}agentId`,
580
2020
  teamId: 'teamId',
581
2021
  deviceType: LoginOption.BROWSER,
582
2022
  isExtension: false,
@@ -594,6 +2034,7 @@ describe('webex.cc', () => {
594
2034
  METRIC_EVENT_NAMES.STATION_LOGIN_FAILED,
595
2035
  ]);
596
2036
  expect(result).toEqual(responseMock);
2037
+ expect(webex.cc.agentConfig.deviceType).toBe(LoginOption.BROWSER);
597
2038
 
598
2039
  const onSpy = jest.spyOn(mockTaskManager, 'on');
599
2040
  const emitSpy = jest.spyOn(webex.cc, 'trigger');
@@ -606,10 +2047,8 @@ describe('webex.cc', () => {
606
2047
 
607
2048
  expect(emitSpy).toHaveBeenCalledTimes(1);
608
2049
  expect(emitSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_INCOMING, mockTask);
609
- // Verify message event listener
610
- const messageCallback = mockWebSocketManager.on.mock.calls.find(
611
- (call) => call[0] === 'message'
612
- )[1];
2050
+ // Verify websocket message handling
2051
+ const messageCallback = webex.cc['handleWebsocketMessage'];
613
2052
  const agentStateChangeEventData = {
614
2053
  type: CC_EVENTS.AGENT_STATE_CHANGE,
615
2054
  data: {some: 'data'},
@@ -637,43 +2076,96 @@ describe('webex.cc', () => {
637
2076
  );
638
2077
  });
639
2078
 
640
- it('should not attempt mobius registration for LoginOption.BROWSER if webrtc is disabled', async () => {
2079
+ it('should skip web calling line registration when disableWebRTCRegistration is enabled', async () => {
641
2080
  const options = {
642
2081
  teamId: 'teamId',
643
2082
  loginOption: LoginOption.BROWSER,
644
2083
  };
645
2084
 
2085
+ webex.cc.$config = {
2086
+ ...webex.cc.$config,
2087
+ disableWebRTCRegistration: true,
2088
+ };
646
2089
  webex.cc.agentConfig = {
647
2090
  agentId: 'agentId',
648
- webRtcEnabled: false,
2091
+ webRtcEnabled: true,
2092
+ loginVoiceOptions: ['BROWSER', 'EXTENSION', 'AGENT_DN'],
649
2093
  };
650
2094
 
651
- const mockData = {
2095
+ const registerWebCallingLineSpy = jest.spyOn(
2096
+ webex.cc.webCallingService,
2097
+ 'registerWebCallingLine'
2098
+ );
2099
+
2100
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
652
2101
  data: {
653
2102
  loginOption: LoginOption.BROWSER,
654
2103
  agentId: 'agentId',
655
2104
  teamId: 'teamId',
656
2105
  siteId: 'siteId',
657
2106
  roles: [AGENT],
658
- trackingId: '1234',
659
- eventType: 'DESKTOP_MESSAGE',
660
2107
  channelsMap: {
661
- chat: ['25d8ggg7-4821-7de7-b626-36437adec509', '14e7fff7-7de7-4821-a919-36437adec509'],
2108
+ chat: [],
662
2109
  email: [],
663
2110
  social: [],
664
- telephony: ['14e7fff7-7de7-4821-a919-36437adec509'],
2111
+ telephony: [],
665
2112
  },
666
2113
  },
667
- trackingId: '1234',
2114
+ trackingId: 'notifs_52628',
668
2115
  orgId: 'orgId',
669
2116
  type: 'StationLoginSuccess',
670
2117
  eventType: 'STATION_LOGIN',
671
- };
2118
+ } as unknown as StationLoginSuccess);
672
2119
 
673
- const registerWebCallingLineSpy = jest.spyOn(
674
- webex.cc.webCallingService,
675
- 'registerWebCallingLine'
676
- );
2120
+ await webex.cc.stationLogin(options);
2121
+
2122
+ expect(registerWebCallingLineSpy).not.toHaveBeenCalled();
2123
+ expect(LoggerProxy.info).toHaveBeenCalledWith(
2124
+ 'Skipping web calling line registration because disableWebRTCRegistration is enabled',
2125
+ {
2126
+ module: CC_FILE,
2127
+ method: 'stationLogin',
2128
+ }
2129
+ );
2130
+ });
2131
+
2132
+ it('should not attempt mobius registration for LoginOption.BROWSER if webrtc is disabled', async () => {
2133
+ const options = {
2134
+ teamId: 'teamId',
2135
+ loginOption: LoginOption.BROWSER,
2136
+ };
2137
+
2138
+ webex.cc.agentConfig = {
2139
+ agentId: 'agentId',
2140
+ webRtcEnabled: false,
2141
+ };
2142
+
2143
+ const mockData = {
2144
+ data: {
2145
+ loginOption: LoginOption.BROWSER,
2146
+ agentId: 'agentId',
2147
+ teamId: 'teamId',
2148
+ siteId: 'siteId',
2149
+ roles: [AGENT],
2150
+ trackingId: '1234',
2151
+ eventType: 'DESKTOP_MESSAGE',
2152
+ channelsMap: {
2153
+ chat: ['25d8ggg7-4821-7de7-b626-36437adec509', '14e7fff7-7de7-4821-a919-36437adec509'],
2154
+ email: [],
2155
+ social: [],
2156
+ telephony: ['14e7fff7-7de7-4821-a919-36437adec509'],
2157
+ },
2158
+ },
2159
+ trackingId: '1234',
2160
+ orgId: 'orgId',
2161
+ type: 'StationLoginSuccess',
2162
+ eventType: 'STATION_LOGIN',
2163
+ };
2164
+
2165
+ const registerWebCallingLineSpy = jest.spyOn(
2166
+ webex.cc.webCallingService,
2167
+ 'registerWebCallingLine'
2168
+ );
677
2169
 
678
2170
  const stationLoginSpy = jest
679
2171
  .spyOn(webex.cc.services.agent, 'stationLogin')
@@ -684,7 +2176,7 @@ describe('webex.cc', () => {
684
2176
  expect(registerWebCallingLineSpy).not.toHaveBeenCalled();
685
2177
  expect(stationLoginSpy).toHaveBeenCalledWith({
686
2178
  data: {
687
- dialNumber: 'agentId',
2179
+ dialNumber: `${WEB_RTC_PREFIX}agentId`,
688
2180
  teamId: 'teamId',
689
2181
  deviceType: LoginOption.BROWSER,
690
2182
  isExtension: false,
@@ -759,10 +2251,13 @@ describe('webex.cc', () => {
759
2251
  const result = await webex.cc.stationLogin(options);
760
2252
 
761
2253
  // Verify logging calls
762
- expect(LoggerProxy.info).toHaveBeenCalledWith('Starting agent station login', {
763
- module: CC_FILE,
764
- method: 'stationLogin',
765
- });
2254
+ expect(LoggerProxy.log).toHaveBeenCalledWith(
2255
+ `Starting agent station login | loginOption: ${options.loginOption} teamId: ${options.teamId}`,
2256
+ {
2257
+ module: CC_FILE,
2258
+ method: 'stationLogin',
2259
+ }
2260
+ );
766
2261
  expect(LoggerProxy.log).toHaveBeenCalledWith(
767
2262
  `Agent station login completed successfully agentId: ${mockData.data.agentId} loginOption: ${mockData.data.loginOption} teamId: ${mockData.data.teamId}`,
768
2263
  {
@@ -813,15 +2308,756 @@ describe('webex.cc', () => {
813
2308
 
814
2309
  await expect(webex.cc.stationLogin(options)).rejects.toThrow(error.details.data.reason);
815
2310
 
816
- expect(LoggerProxy.info).toHaveBeenCalledWith('Starting agent station login', {
817
- module: CC_FILE,
818
- method: 'stationLogin',
819
- });
2311
+ expect(LoggerProxy.log).toHaveBeenCalledWith(
2312
+ `Starting agent station login | loginOption: ${options.loginOption} teamId: ${options.teamId}`,
2313
+ {
2314
+ module: CC_FILE,
2315
+ method: 'stationLogin',
2316
+ }
2317
+ );
820
2318
  expect(LoggerProxy.error).toHaveBeenCalledWith(
821
2319
  `stationLogin failed with reason: ${error.details.data.reason}`,
822
2320
  {module: CC_FILE, method: 'stationLogin', trackingId: error.details.trackingId}
823
2321
  );
824
2322
  });
2323
+
2324
+ it('should publish usersub and subscribe Mercury on station login when enableWxBetterTogether is true at init', async () => {
2325
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
2326
+ webex.internal.device = {
2327
+ userId: 'user-123',
2328
+ url: 'https://wdm.example.com/devices/dev-1',
2329
+ registered: true,
2330
+ register: jest.fn().mockResolvedValue(undefined),
2331
+ };
2332
+ webex.internal.mercury.connected = true;
2333
+ webex.internal.mercury.connect = jest.fn().mockResolvedValue(undefined);
2334
+ webex.cc.agentConfig = {
2335
+ agentId: 'agentId',
2336
+ webRtcEnabled: false,
2337
+ loginVoiceOptions: ['EXTENSION'],
2338
+ };
2339
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
2340
+
2341
+ const publishSpy = jest
2342
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
2343
+ .mockResolvedValue(undefined);
2344
+ const subscribeSpy = jest
2345
+ .spyOn(webex.cc['wxAppTelephonyMercurySync'], 'subscribe')
2346
+ .mockImplementation(() => {});
2347
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
2348
+
2349
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2350
+ data: {
2351
+ agentId: 'agentId',
2352
+ teamId: 'teamId',
2353
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
2354
+ },
2355
+ trackingId: 'track-1',
2356
+ } as StationLoginSuccess);
2357
+
2358
+ await webex.cc.stationLogin({
2359
+ teamId: 'teamId',
2360
+ loginOption: LoginOption.EXTENSION,
2361
+ dialNumber: '1001',
2362
+ });
2363
+
2364
+ expect(publishSpy).toHaveBeenCalledWith(true, {userId: 'user-123', trackPublishMetrics: true});
2365
+ expect(subscribeSpy).toHaveBeenCalledWith('agentId', expect.any(Function));
2366
+ expect(mockTaskManager.refreshWxAppOfferObservabilityForAllTasks).toHaveBeenCalled();
2367
+ });
2368
+
2369
+ it('should rollback wxApp config when post-station-login init fails', async () => {
2370
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
2371
+ webex.internal.device = {userId: 'user-123', url: 'https://wdm.example.com/devices/dev-1'};
2372
+ webex.cc.agentConfig = {
2373
+ agentId: 'agentId',
2374
+ webRtcEnabled: false,
2375
+ loginVoiceOptions: ['EXTENSION'],
2376
+ };
2377
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
2378
+ mockTaskManager.applyEnableWxBetterTogether(true);
2379
+
2380
+ jest
2381
+ .spyOn(webex.cc as never, 'publishAnswerOnWebexCrossClientState' as never)
2382
+ .mockRejectedValue(new Error('usersub publish failed'));
2383
+ const unsubscribeSpy = jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'unsubscribe');
2384
+
2385
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2386
+ data: {
2387
+ agentId: 'agentId',
2388
+ teamId: 'teamId',
2389
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
2390
+ },
2391
+ trackingId: 'track-1',
2392
+ } as StationLoginSuccess);
2393
+
2394
+ await webex.cc.stationLogin({
2395
+ teamId: 'teamId',
2396
+ loginOption: LoginOption.EXTENSION,
2397
+ dialNumber: '1001',
2398
+ });
2399
+
2400
+ expect(unsubscribeSpy).toHaveBeenCalled();
2401
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(false);
2402
+ expect(mockTaskManager.applyEnableWxBetterTogether).toHaveBeenCalledWith(false);
2403
+ });
2404
+
2405
+ it('should reset wxApp config when Mercury fails before usersub publish on station login', async () => {
2406
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
2407
+ webex.internal.device = {userId: 'user-123', url: 'https://wdm.example.com/devices/dev-1'};
2408
+ webex.cc.agentConfig = {
2409
+ agentId: 'agentId',
2410
+ webRtcEnabled: false,
2411
+ loginVoiceOptions: ['EXTENSION'],
2412
+ };
2413
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
2414
+ mockTaskManager.applyEnableWxBetterTogether(true);
2415
+
2416
+ const publishSpy = jest
2417
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
2418
+ .mockResolvedValue(undefined);
2419
+ jest
2420
+ .spyOn(webex.cc as any, 'ensureWxAppMercuryConnected')
2421
+ .mockRejectedValue(new Error('mercury connect failed'));
2422
+ const teardownSpy = jest.spyOn(webex.cc['webexCrossClientService'], 'teardown');
2423
+ const unsubscribeSpy = jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'unsubscribe');
2424
+ jest
2425
+ .spyOn(webex.cc as any, 'releaseWxAppMercuryResources')
2426
+ .mockResolvedValue(undefined);
2427
+ const metricSpy = jest.spyOn(mockMetricsManager, 'trackEvent');
2428
+
2429
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2430
+ data: {
2431
+ agentId: 'agentId',
2432
+ teamId: 'teamId',
2433
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
2434
+ },
2435
+ trackingId: 'track-1',
2436
+ } as StationLoginSuccess);
2437
+
2438
+ await webex.cc.stationLogin({
2439
+ teamId: 'teamId',
2440
+ loginOption: LoginOption.EXTENSION,
2441
+ dialNumber: '1001',
2442
+ });
2443
+
2444
+ expect(publishSpy).not.toHaveBeenCalled();
2445
+ expect(teardownSpy).not.toHaveBeenCalled();
2446
+ expect(unsubscribeSpy).toHaveBeenCalled();
2447
+ expect(metricSpy).toHaveBeenCalledWith(
2448
+ METRIC_EVENT_NAMES.WXAPP_SESSION_INIT_FAILED,
2449
+ expect.objectContaining({skipReason: 'mercury_subscribe_failed'}),
2450
+ ['operational', 'behavioral']
2451
+ );
2452
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(false);
2453
+ expect(mockTaskManager.applyEnableWxBetterTogether).toHaveBeenCalledWith(false);
2454
+ });
2455
+
2456
+ it('should record publish_failed when usersub publish fails after Mercury init', async () => {
2457
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
2458
+ webex.internal.device = {userId: 'user-123', url: 'https://wdm.example.com/devices/dev-1'};
2459
+ webex.cc.agentConfig = {
2460
+ agentId: 'agentId',
2461
+ webRtcEnabled: false,
2462
+ loginVoiceOptions: ['EXTENSION'],
2463
+ };
2464
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
2465
+ mockTaskManager.applyEnableWxBetterTogether(true);
2466
+
2467
+ jest.spyOn(webex.cc as any, 'ensureWxAppMercuryConnected').mockResolvedValue(undefined);
2468
+ jest
2469
+ .spyOn(webex.cc['wxAppTelephonyMercurySync'], 'subscribe')
2470
+ .mockImplementation(() => {});
2471
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
2472
+ jest
2473
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
2474
+ .mockRejectedValue(new Error('publish failed'));
2475
+ jest
2476
+ .spyOn(webex.cc as any, 'releaseWxAppMercuryResources')
2477
+ .mockResolvedValue(undefined);
2478
+ const metricSpy = jest.spyOn(mockMetricsManager, 'trackEvent');
2479
+
2480
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2481
+ data: {
2482
+ agentId: 'agentId',
2483
+ teamId: 'teamId',
2484
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
2485
+ },
2486
+ trackingId: 'track-1',
2487
+ } as StationLoginSuccess);
2488
+
2489
+ await webex.cc.stationLogin({
2490
+ teamId: 'teamId',
2491
+ loginOption: LoginOption.EXTENSION,
2492
+ dialNumber: '1001',
2493
+ });
2494
+
2495
+ expect(metricSpy).toHaveBeenCalledWith(
2496
+ METRIC_EVENT_NAMES.WXAPP_SESSION_INIT_FAILED,
2497
+ expect.objectContaining({skipReason: 'publish_failed', usersubPublished: false}),
2498
+ ['operational', 'behavioral']
2499
+ );
2500
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(false);
2501
+ });
2502
+
2503
+ it('should report retained usersub state when publish fails during re-init', async () => {
2504
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
2505
+ webex.internal.device = {userId: 'user-123', url: 'https://wdm.example.com/devices/dev-1'};
2506
+ webex.cc.agentConfig = {
2507
+ agentId: 'agentId',
2508
+ webRtcEnabled: false,
2509
+ loginVoiceOptions: ['EXTENSION'],
2510
+ };
2511
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
2512
+ mockTaskManager.applyEnableWxBetterTogether(true);
2513
+
2514
+ jest.spyOn(webex.cc as any, 'ensureWxAppMercuryConnected').mockResolvedValue(undefined);
2515
+ jest
2516
+ .spyOn(webex.cc['wxAppTelephonyMercurySync'], 'subscribe')
2517
+ .mockImplementation(() => {});
2518
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
2519
+ jest
2520
+ .spyOn(webex.cc['webexCrossClientService'], 'isAnswerCallsStateActive')
2521
+ .mockReturnValue(true);
2522
+ jest
2523
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
2524
+ .mockRejectedValue(new Error('publish failed'));
2525
+ jest
2526
+ .spyOn(webex.cc as any, 'releaseWxAppMercuryResources')
2527
+ .mockResolvedValue(undefined);
2528
+ const metricSpy = jest.spyOn(mockMetricsManager, 'trackEvent');
2529
+
2530
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2531
+ data: {
2532
+ agentId: 'agentId',
2533
+ teamId: 'teamId',
2534
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
2535
+ },
2536
+ trackingId: 'track-1',
2537
+ } as StationLoginSuccess);
2538
+
2539
+ await webex.cc.stationLogin({
2540
+ teamId: 'teamId',
2541
+ loginOption: LoginOption.EXTENSION,
2542
+ dialNumber: '1001',
2543
+ });
2544
+
2545
+ expect(metricSpy).toHaveBeenCalledWith(
2546
+ METRIC_EVENT_NAMES.WXAPP_SESSION_INIT_FAILED,
2547
+ expect.objectContaining({skipReason: 'publish_failed', usersubPublished: true}),
2548
+ ['operational', 'behavioral']
2549
+ );
2550
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(false);
2551
+ });
2552
+
2553
+ it('should register device before publishing usersub true on extension station login', async () => {
2554
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
2555
+ webex.internal.device = {
2556
+ userId: 'user-123',
2557
+ registered: false,
2558
+ register: jest.fn().mockImplementation(async function (this: {
2559
+ url?: string;
2560
+ registered?: boolean;
2561
+ }) {
2562
+ this.url = 'https://wdm.example.com/devices/dev-1';
2563
+ this.registered = true;
2564
+ }),
2565
+ };
2566
+ webex.internal.mercury = {
2567
+ connected: false,
2568
+ connect: jest.fn().mockResolvedValue(undefined),
2569
+ };
2570
+ webex.cc.agentConfig = {
2571
+ agentId: 'agentId',
2572
+ webRtcEnabled: false,
2573
+ loginVoiceOptions: ['EXTENSION'],
2574
+ };
2575
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
2576
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'subscribe').mockImplementation(() => {});
2577
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
2578
+
2579
+ const callOrder: string[] = [];
2580
+ jest.spyOn(webex.internal.device, 'register').mockImplementation(async function (this: {
2581
+ url?: string;
2582
+ registered?: boolean;
2583
+ }) {
2584
+ callOrder.push('device.register');
2585
+ this.url = 'https://wdm.example.com/devices/dev-1';
2586
+ this.registered = true;
2587
+ });
2588
+ jest
2589
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
2590
+ .mockImplementation(async (enable: boolean) => {
2591
+ if (enable === true && !webex.internal.device.url) {
2592
+ throw new Error('Device URL is unavailable for cross-client publish');
2593
+ }
2594
+ callOrder.push(enable ? 'publish:true' : 'publish:false');
2595
+ });
2596
+
2597
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2598
+ data: {
2599
+ agentId: 'agentId',
2600
+ teamId: 'teamId',
2601
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
2602
+ },
2603
+ trackingId: 'track-1',
2604
+ } as StationLoginSuccess);
2605
+
2606
+ await webex.cc.stationLogin({
2607
+ teamId: 'teamId',
2608
+ loginOption: LoginOption.EXTENSION,
2609
+ dialNumber: '1001',
2610
+ });
2611
+
2612
+ expect(callOrder).toEqual(['device.register', 'publish:true']);
2613
+ });
2614
+
2615
+ it('should register device before publishing forced usersub false when wxApp is disabled at station login', async () => {
2616
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: false};
2617
+ webex.internal.device = {
2618
+ userId: 'user-123',
2619
+ registered: false,
2620
+ register: jest.fn().mockImplementation(async function (this: {
2621
+ url?: string;
2622
+ registered?: boolean;
2623
+ }) {
2624
+ this.url = 'https://wdm.example.com/devices/dev-1';
2625
+ this.registered = true;
2626
+ }),
2627
+ };
2628
+ webex.internal.mercury = {
2629
+ connected: false,
2630
+ connect: jest.fn().mockResolvedValue(undefined),
2631
+ };
2632
+ webex.cc.agentConfig = {
2633
+ agentId: 'agentId',
2634
+ webRtcEnabled: false,
2635
+ loginVoiceOptions: ['EXTENSION'],
2636
+ };
2637
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
2638
+ jest
2639
+ .spyOn(webex.cc as any, 'releaseWxAppMercuryResources')
2640
+ .mockResolvedValue(undefined);
2641
+
2642
+ const callOrder: string[] = [];
2643
+ jest.spyOn(webex.internal.device, 'register').mockImplementation(async function (this: {
2644
+ url?: string;
2645
+ registered?: boolean;
2646
+ }) {
2647
+ callOrder.push('device.register');
2648
+ this.url = 'https://wdm.example.com/devices/dev-1';
2649
+ this.registered = true;
2650
+ });
2651
+ jest
2652
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
2653
+ .mockImplementation(async (enable: boolean) => {
2654
+ if (!webex.internal.device.url) {
2655
+ throw new Error('Device URL is unavailable for cross-client publish');
2656
+ }
2657
+ callOrder.push(enable ? 'publish:true' : 'publish:false');
2658
+ });
2659
+
2660
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2661
+ data: {
2662
+ agentId: 'agentId',
2663
+ teamId: 'teamId',
2664
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
2665
+ },
2666
+ trackingId: 'track-1',
2667
+ } as StationLoginSuccess);
2668
+
2669
+ await webex.cc.stationLogin({
2670
+ teamId: 'teamId',
2671
+ loginOption: LoginOption.EXTENSION,
2672
+ dialNumber: '1001',
2673
+ });
2674
+
2675
+ expect(callOrder).toEqual(['device.register', 'publish:false']);
2676
+ });
2677
+
2678
+ it('should retry forced false publish when wxApp is disabled at station login', async () => {
2679
+ jest.useFakeTimers();
2680
+ try {
2681
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: false};
2682
+ webex.internal.device = {userId: 'user-123', url: 'https://wdm.example.com/devices/dev-1'};
2683
+ webex.cc.agentConfig = {
2684
+ agentId: 'agentId',
2685
+ webRtcEnabled: false,
2686
+ loginVoiceOptions: ['EXTENSION'],
2687
+ };
2688
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
2689
+
2690
+ const publishSpy = jest
2691
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
2692
+ .mockRejectedValueOnce(new Error('usersub publish failed'))
2693
+ .mockResolvedValue(undefined);
2694
+ const scheduleRetrySpy = jest.spyOn(
2695
+ webex.cc as any,
2696
+ 'scheduleForcedFalsePublishRetry'
2697
+ );
2698
+ const teardownSpy = jest.spyOn(webex.cc['webexCrossClientService'], 'teardown');
2699
+ jest
2700
+ .spyOn(webex.cc as any, 'releaseWxAppMercuryResources')
2701
+ .mockResolvedValue(undefined);
2702
+
2703
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2704
+ data: {
2705
+ agentId: 'agentId',
2706
+ teamId: 'teamId',
2707
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
2708
+ },
2709
+ trackingId: 'track-1',
2710
+ } as StationLoginSuccess);
2711
+
2712
+ await webex.cc.stationLogin({
2713
+ teamId: 'teamId',
2714
+ loginOption: LoginOption.EXTENSION,
2715
+ dialNumber: '1001',
2716
+ });
2717
+
2718
+ expect(publishSpy).toHaveBeenCalledTimes(1);
2719
+ expect(scheduleRetrySpy).toHaveBeenCalled();
2720
+ expect(teardownSpy).not.toHaveBeenCalled();
2721
+
2722
+ jest.advanceTimersByTime(30_000);
2723
+ await publishSpy.mock.results[1]?.value;
2724
+
2725
+ expect(publishSpy).toHaveBeenCalledTimes(2);
2726
+ expect(publishSpy).toHaveBeenLastCalledWith(false, {userId: 'user-123', trackPublishMetrics: true});
2727
+ } finally {
2728
+ jest.useRealTimers();
2729
+ }
2730
+ });
2731
+
2732
+ it('should not publish usersub on BROWSER station login even when enableWxBetterTogether is true at init', async () => {
2733
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
2734
+ webex.internal.device = {userId: 'user-123', url: 'https://wdm.example.com/devices/dev-1'};
2735
+ webex.cc.agentConfig = {
2736
+ agentId: 'agentId',
2737
+ webRtcEnabled: true,
2738
+ loginVoiceOptions: ['BROWSER'],
2739
+ };
2740
+ webex.cc.webCallingService.loginOption = LoginOption.BROWSER;
2741
+
2742
+ const publishSpy = jest.spyOn(
2743
+ webex.cc['webexCrossClientService'],
2744
+ 'setManageWebexCallingInWxcc'
2745
+ );
2746
+
2747
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2748
+ data: {
2749
+ agentId: 'agentId',
2750
+ teamId: 'teamId',
2751
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
2752
+ },
2753
+ trackingId: 'track-1',
2754
+ } as StationLoginSuccess);
2755
+
2756
+ await webex.cc.stationLogin({
2757
+ teamId: 'teamId',
2758
+ loginOption: LoginOption.BROWSER,
2759
+ });
2760
+
2761
+ expect(publishSpy).not.toHaveBeenCalled();
2762
+ });
2763
+
2764
+ it('should force-publish usersub false on station login when enableWxBetterTogether is false at init', async () => {
2765
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: false};
2766
+ webex.internal.device = {userId: 'user-123', url: 'https://wdm.example.com/devices/dev-1'};
2767
+ webex.cc.agentConfig = {
2768
+ agentId: 'agentId',
2769
+ webRtcEnabled: false,
2770
+ loginVoiceOptions: ['EXTENSION'],
2771
+ };
2772
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
2773
+
2774
+ const publishSpy = jest
2775
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
2776
+ .mockResolvedValue(undefined);
2777
+ const teardownSpy = jest.spyOn(webex.cc['webexCrossClientService'], 'teardown');
2778
+ const unsubscribeSpy = jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'unsubscribe');
2779
+
2780
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2781
+ data: {
2782
+ agentId: 'agentId',
2783
+ teamId: 'teamId',
2784
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
2785
+ },
2786
+ trackingId: 'track-1',
2787
+ } as StationLoginSuccess);
2788
+
2789
+ await webex.cc.stationLogin({
2790
+ teamId: 'teamId',
2791
+ loginOption: LoginOption.EXTENSION,
2792
+ dialNumber: '1001',
2793
+ });
2794
+
2795
+ expect(publishSpy).toHaveBeenCalledWith(false, {userId: 'user-123', trackPublishMetrics: true});
2796
+ expect(teardownSpy).toHaveBeenCalled();
2797
+ expect(unsubscribeSpy).toHaveBeenCalled();
2798
+ expect(mockMetricsManager.trackEvent).toHaveBeenCalledWith(
2799
+ METRIC_EVENT_NAMES.WXAPP_SESSION_SKIPPED,
2800
+ expect.objectContaining({
2801
+ enableWxBetterTogether: false,
2802
+ skipReason: 'flag_disabled',
2803
+ }),
2804
+ ['operational', 'behavioral']
2805
+ );
2806
+ });
2807
+
2808
+ it('should not emit WXAPP_SESSION_INIT_FAILED when flag-disabled cleanup fails', async () => {
2809
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: false};
2810
+ webex.internal.device = {userId: 'user-123', url: 'https://wdm.example.com/devices/dev-1'};
2811
+ webex.cc.agentConfig = {
2812
+ agentId: 'agentId',
2813
+ webRtcEnabled: false,
2814
+ loginVoiceOptions: ['EXTENSION'],
2815
+ };
2816
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
2817
+
2818
+ jest
2819
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
2820
+ .mockRejectedValue(new Error('forced false publish failed'));
2821
+ const metricSpy = jest.spyOn(mockMetricsManager, 'trackEvent');
2822
+
2823
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2824
+ data: {
2825
+ agentId: 'agentId',
2826
+ teamId: 'teamId',
2827
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
2828
+ },
2829
+ trackingId: 'track-1',
2830
+ } as StationLoginSuccess);
2831
+
2832
+ await webex.cc.stationLogin({
2833
+ teamId: 'teamId',
2834
+ loginOption: LoginOption.EXTENSION,
2835
+ dialNumber: '1001',
2836
+ });
2837
+
2838
+ expect(metricSpy).not.toHaveBeenCalledWith(
2839
+ METRIC_EVENT_NAMES.WXAPP_SESSION_INIT_FAILED,
2840
+ expect.anything(),
2841
+ expect.anything()
2842
+ );
2843
+ });
2844
+
2845
+ it('should still publish usersub but record session init failed when Mercury is unavailable', async () => {
2846
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
2847
+ webex.internal.device = {
2848
+ userId: 'user-123',
2849
+ url: 'https://wdm.example.com/devices/dev-1',
2850
+ registered: true,
2851
+ register: jest.fn().mockResolvedValue(undefined),
2852
+ };
2853
+ delete webex.internal.mercury;
2854
+ webex.cc.agentConfig = {
2855
+ agentId: 'agentId',
2856
+ webRtcEnabled: false,
2857
+ loginVoiceOptions: ['EXTENSION'],
2858
+ };
2859
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
2860
+ mockTaskManager.applyEnableWxBetterTogether(true);
2861
+
2862
+ const publishSpy = jest
2863
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
2864
+ .mockResolvedValue(undefined);
2865
+ jest
2866
+ .spyOn(webex.cc['webexCrossClientService'], 'isAnswerCallsStateActive')
2867
+ .mockReturnValue(true);
2868
+ const metricSpy = jest.spyOn(mockMetricsManager, 'trackEvent');
2869
+
2870
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2871
+ data: {
2872
+ agentId: 'agentId',
2873
+ teamId: 'teamId',
2874
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
2875
+ },
2876
+ trackingId: 'track-1',
2877
+ } as StationLoginSuccess);
2878
+
2879
+ await webex.cc.stationLogin({
2880
+ teamId: 'teamId',
2881
+ loginOption: LoginOption.EXTENSION,
2882
+ dialNumber: '1001',
2883
+ });
2884
+
2885
+ expect(publishSpy).toHaveBeenCalledWith(true, {userId: 'user-123', trackPublishMetrics: true});
2886
+ expect(metricSpy).toHaveBeenCalledWith(
2887
+ METRIC_EVENT_NAMES.WXAPP_MERCURY_SUBSCRIBE_FAILED,
2888
+ expect.objectContaining({error: 'Mercury is unavailable for wxApp mute sync'}),
2889
+ ['operational', 'behavioral']
2890
+ );
2891
+ expect(metricSpy).not.toHaveBeenCalledWith(
2892
+ METRIC_EVENT_NAMES.WXAPP_SESSION_INIT_SUCCESS,
2893
+ expect.anything(),
2894
+ expect.anything()
2895
+ );
2896
+ expect(metricSpy).toHaveBeenCalledWith(
2897
+ METRIC_EVENT_NAMES.WXAPP_SESSION_INIT_FAILED,
2898
+ expect.objectContaining({skipReason: 'mercury_not_subscribed'}),
2899
+ ['operational', 'behavioral']
2900
+ );
2901
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(true);
2902
+ });
2903
+
2904
+ it('should record session init failed when userId is missing but not emit success', async () => {
2905
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
2906
+ webex.internal.device = {
2907
+ url: 'https://wdm.example.com/devices/dev-1',
2908
+ registered: true,
2909
+ register: jest.fn().mockResolvedValue(undefined),
2910
+ };
2911
+ webex.internal.mercury = {
2912
+ connected: true,
2913
+ connect: jest.fn().mockResolvedValue(undefined),
2914
+ on: jest.fn(),
2915
+ off: jest.fn(),
2916
+ };
2917
+ webex.cc.agentConfig = {
2918
+ agentId: 'agentId',
2919
+ webRtcEnabled: false,
2920
+ loginVoiceOptions: ['EXTENSION'],
2921
+ };
2922
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
2923
+ mockTaskManager.applyEnableWxBetterTogether(true);
2924
+
2925
+ const publishSpy = jest
2926
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
2927
+ .mockResolvedValue(undefined);
2928
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
2929
+ const metricSpy = jest.spyOn(mockMetricsManager, 'trackEvent');
2930
+
2931
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2932
+ data: {
2933
+ agentId: 'agentId',
2934
+ teamId: 'teamId',
2935
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
2936
+ },
2937
+ trackingId: 'track-1',
2938
+ } as StationLoginSuccess);
2939
+
2940
+ await webex.cc.stationLogin({
2941
+ teamId: 'teamId',
2942
+ loginOption: LoginOption.EXTENSION,
2943
+ dialNumber: '1001',
2944
+ });
2945
+
2946
+ expect(publishSpy).not.toHaveBeenCalledWith(true, expect.anything());
2947
+ expect(metricSpy).not.toHaveBeenCalledWith(
2948
+ METRIC_EVENT_NAMES.WXAPP_SESSION_INIT_SUCCESS,
2949
+ expect.anything(),
2950
+ expect.anything()
2951
+ );
2952
+ expect(metricSpy).toHaveBeenCalledWith(
2953
+ METRIC_EVENT_NAMES.WXAPP_SESSION_INIT_FAILED,
2954
+ expect.objectContaining({skipReason: 'usersub_not_published'}),
2955
+ ['operational', 'behavioral']
2956
+ );
2957
+ expect(metricSpy).toHaveBeenCalledWith(
2958
+ METRIC_EVENT_NAMES.WXAPP_USERSUB_PUBLISH_FAILED,
2959
+ expect.objectContaining({skipReason: 'user_id_unavailable', usersubPublished: false}),
2960
+ ['operational', 'behavioral']
2961
+ );
2962
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(true);
2963
+ });
2964
+
2965
+ it('should report retained usersub state when userId is missing during re-init', async () => {
2966
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
2967
+ webex.internal.device = {
2968
+ url: 'https://wdm.example.com/devices/dev-1',
2969
+ registered: true,
2970
+ register: jest.fn().mockResolvedValue(undefined),
2971
+ };
2972
+ webex.internal.mercury = {
2973
+ connected: true,
2974
+ connect: jest.fn().mockResolvedValue(undefined),
2975
+ on: jest.fn(),
2976
+ off: jest.fn(),
2977
+ };
2978
+ webex.cc.agentConfig = {
2979
+ agentId: 'agentId',
2980
+ webRtcEnabled: false,
2981
+ loginVoiceOptions: ['EXTENSION'],
2982
+ };
2983
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
2984
+ mockTaskManager.applyEnableWxBetterTogether(true);
2985
+
2986
+ jest
2987
+ .spyOn(webex.cc['webexCrossClientService'], 'isAnswerCallsStateActive')
2988
+ .mockReturnValue(true);
2989
+ const publishSpy = jest
2990
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
2991
+ .mockResolvedValue(undefined);
2992
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
2993
+ const metricSpy = jest.spyOn(mockMetricsManager, 'trackEvent');
2994
+
2995
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2996
+ data: {
2997
+ agentId: 'agentId',
2998
+ teamId: 'teamId',
2999
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
3000
+ },
3001
+ trackingId: 'track-1',
3002
+ } as StationLoginSuccess);
3003
+
3004
+ await webex.cc.stationLogin({
3005
+ teamId: 'teamId',
3006
+ loginOption: LoginOption.EXTENSION,
3007
+ dialNumber: '1001',
3008
+ });
3009
+
3010
+ expect(publishSpy).not.toHaveBeenCalledWith(true, expect.anything());
3011
+ expect(metricSpy).toHaveBeenCalledWith(
3012
+ METRIC_EVENT_NAMES.WXAPP_USERSUB_PUBLISH_FAILED,
3013
+ expect.objectContaining({skipReason: 'user_id_unavailable', usersubPublished: true}),
3014
+ ['operational', 'behavioral']
3015
+ );
3016
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(true);
3017
+ });
3018
+
3019
+ it('should clear stale usersub on login after prior session enabled wxApp then hard refresh', async () => {
3020
+ webex.internal.device = {userId: 'user-123', url: 'https://wdm.example.com/devices/dev-1'};
3021
+ webex.cc.agentConfig = {
3022
+ agentId: 'agentId',
3023
+ webRtcEnabled: false,
3024
+ loginVoiceOptions: ['EXTENSION'],
3025
+ };
3026
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
3027
+ webex.request = jest.fn().mockResolvedValue({body: {}});
3028
+
3029
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
3030
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
3031
+ data: {
3032
+ agentId: 'agentId',
3033
+ teamId: 'teamId',
3034
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
3035
+ },
3036
+ trackingId: 'track-1',
3037
+ } as StationLoginSuccess);
3038
+
3039
+ await webex.cc.stationLogin({
3040
+ teamId: 'teamId',
3041
+ loginOption: LoginOption.EXTENSION,
3042
+ dialNumber: '1001',
3043
+ });
3044
+
3045
+ webex.cc['webexCrossClientService'].teardown();
3046
+ webex.cc['wxAppTelephonyMercurySync'].unsubscribe();
3047
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: false};
3048
+
3049
+ const publishSpy = jest
3050
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
3051
+ .mockResolvedValue(undefined);
3052
+
3053
+ await webex.cc.stationLogin({
3054
+ teamId: 'teamId',
3055
+ loginOption: LoginOption.EXTENSION,
3056
+ dialNumber: '1001',
3057
+ });
3058
+
3059
+ expect(publishSpy).toHaveBeenCalledWith(false, {userId: 'user-123', trackPublishMetrics: true});
3060
+ });
825
3061
  });
826
3062
 
827
3063
  describe('stationLogout', () => {
@@ -846,7 +3082,7 @@ describe('webex.cc', () => {
846
3082
  });
847
3083
 
848
3084
  expect(stationLogoutMock).toHaveBeenCalledWith({data: data});
849
- // TODO: https://jira-eng-gpk2.cisco.com/jira/browse/SPARK-626777 Implement the de-register method and close the listener there
3085
+ // SPARK-626777 tracks moving listener cleanup into the future de-register API.
850
3086
  // expect(mockTaskManager.unregisterIncomingCallEvent).toHaveBeenCalledWith();
851
3087
  // expect(mockTaskManager.off).toHaveBeenCalledWith(
852
3088
  // TASK_EVENTS.TASK_INCOMING,
@@ -864,6 +3100,216 @@ describe('webex.cc', () => {
864
3100
  ]);
865
3101
  });
866
3102
 
3103
+ it('should not publish usersub false on logout when wxApp was never enabled', async () => {
3104
+ webex.internal.device = {userId: 'user-123'};
3105
+ const publishSpy = jest
3106
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
3107
+ .mockResolvedValue(undefined);
3108
+ const teardownSpy = jest.spyOn(webex.cc['webexCrossClientService'], 'teardown');
3109
+ const unsubscribeSpy = jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'unsubscribe');
3110
+
3111
+ jest.spyOn(webex.cc.services.agent, 'logout').mockResolvedValue({
3112
+ trackingId: 'track-1',
3113
+ } as StationLogoutResponse);
3114
+
3115
+ await webex.cc.stationLogout({logoutReason: 'Logout reason'});
3116
+
3117
+ expect(publishSpy).not.toHaveBeenCalled();
3118
+ expect(teardownSpy).toHaveBeenCalled();
3119
+ expect(unsubscribeSpy).toHaveBeenCalled();
3120
+ });
3121
+
3122
+ it('should publish usersub false and teardown wxApp sync on logout when wxApp was enabled', async () => {
3123
+ webex.internal.device = {
3124
+ userId: 'user-123',
3125
+ url: 'https://wdm.example.com/devices/dev-1',
3126
+ registered: false,
3127
+ register: jest.fn().mockResolvedValue(undefined),
3128
+ unregister: jest.fn().mockResolvedValue(undefined),
3129
+ };
3130
+ webex.internal.mercury = {
3131
+ connected: false,
3132
+ connect: jest.fn().mockResolvedValue(undefined),
3133
+ disconnect: jest.fn().mockResolvedValue(undefined),
3134
+ };
3135
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'subscribe').mockImplementation(() => {});
3136
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
3137
+ webex.request = jest.fn().mockResolvedValue({body: {}});
3138
+ webex.cc['agentConfig'] = {
3139
+ agentId: 'agent-123',
3140
+ deviceType: LoginOption.EXTENSION,
3141
+ } as Profile;
3142
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
3143
+
3144
+ await (webex.cc as any).setManageWebexCallingInWxcc(true);
3145
+
3146
+ const publishSpy = jest
3147
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
3148
+ .mockResolvedValue(undefined);
3149
+ const teardownSpy = jest.spyOn(webex.cc['webexCrossClientService'], 'teardown');
3150
+ const unsubscribeSpy = jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'unsubscribe');
3151
+
3152
+ jest.spyOn(webex.cc.services.agent, 'logout').mockResolvedValue({
3153
+ trackingId: 'track-1',
3154
+ } as StationLogoutResponse);
3155
+
3156
+ await webex.cc.stationLogout({logoutReason: 'Logout reason'});
3157
+
3158
+ expect(publishSpy).toHaveBeenCalledWith(false, {userId: 'user-123', trackPublishMetrics: true});
3159
+ expect(teardownSpy).toHaveBeenCalled();
3160
+ expect(unsubscribeSpy).toHaveBeenCalled();
3161
+ });
3162
+
3163
+ it('should teardown wxApp state on logout even when usersub publish fails', async () => {
3164
+ webex.internal.device = {userId: 'user-123'};
3165
+ webex.cc['agentConfig'] = {
3166
+ agentId: 'agent-123',
3167
+ deviceType: LoginOption.EXTENSION,
3168
+ } as Profile;
3169
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
3170
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
3171
+ mockTaskManager.applyEnableWxBetterTogether(true);
3172
+
3173
+ jest.spyOn(webex.cc.services.agent, 'logout').mockResolvedValue({
3174
+ trackingId: 'track-1',
3175
+ } as StationLogoutResponse);
3176
+ jest
3177
+ .spyOn(webex.cc as never, 'publishAnswerOnWebexCrossClientState' as never)
3178
+ .mockRejectedValue(new Error('usersub publish failed'));
3179
+ const scheduleRetrySpy = jest.spyOn(
3180
+ webex.cc as any,
3181
+ 'scheduleCompensatingFalsePublishRetry'
3182
+ );
3183
+ const teardownSpy = jest.spyOn(webex.cc['webexCrossClientService'], 'teardown');
3184
+ const unsubscribeSpy = jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'unsubscribe');
3185
+
3186
+ const result = await webex.cc.stationLogout({logoutReason: 'Logout reason'});
3187
+
3188
+ expect(result).toEqual({trackingId: 'track-1'});
3189
+ expect(teardownSpy).toHaveBeenCalled();
3190
+ expect(unsubscribeSpy).toHaveBeenCalled();
3191
+ expect(scheduleRetrySpy).toHaveBeenCalled();
3192
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(true);
3193
+ });
3194
+
3195
+ it('should retry compensating false publish when teardown usersub publish fails on logout', async () => {
3196
+ jest.useFakeTimers();
3197
+ try {
3198
+ webex.internal.device = {
3199
+ userId: 'user-123',
3200
+ url: 'https://wdm.example.com/devices/dev-1',
3201
+ };
3202
+ webex.cc['agentConfig'] = {
3203
+ agentId: 'agent-123',
3204
+ deviceType: LoginOption.EXTENSION,
3205
+ } as Profile;
3206
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
3207
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
3208
+ mockTaskManager.applyEnableWxBetterTogether(true);
3209
+ webex.cc['webexCrossClientService'].answerCallsState = true;
3210
+
3211
+ jest.spyOn(webex.cc.services.agent, 'logout').mockResolvedValue({
3212
+ trackingId: 'track-1',
3213
+ } as StationLogoutResponse);
3214
+
3215
+ const publishSpy = jest
3216
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
3217
+ .mockRejectedValueOnce(new Error('usersub publish failed'))
3218
+ .mockResolvedValue(undefined);
3219
+ const teardownSpy = jest.spyOn(webex.cc['webexCrossClientService'], 'teardown');
3220
+ const unsubscribeSpy = jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'unsubscribe');
3221
+ jest
3222
+ .spyOn(webex.cc as any, 'releaseWxAppMercuryResources')
3223
+ .mockResolvedValue(undefined);
3224
+
3225
+ const result = await webex.cc.stationLogout({logoutReason: 'Logout reason'});
3226
+
3227
+ expect(result).toEqual({trackingId: 'track-1'});
3228
+ expect(publishSpy).toHaveBeenCalledTimes(1);
3229
+ expect(publishSpy).toHaveBeenCalledWith(false, {userId: 'user-123', trackPublishMetrics: true});
3230
+ expect(teardownSpy).toHaveBeenCalled();
3231
+ expect(unsubscribeSpy).toHaveBeenCalled();
3232
+
3233
+ jest.advanceTimersByTime(30_000);
3234
+ await publishSpy.mock.results[1]?.value;
3235
+
3236
+ expect(publishSpy).toHaveBeenCalledTimes(2);
3237
+ expect(publishSpy).toHaveBeenLastCalledWith(false, {userId: 'user-123', trackPublishMetrics: true});
3238
+ } finally {
3239
+ jest.useRealTimers();
3240
+ }
3241
+ });
3242
+
3243
+ it('should cancel compensating retry when station login succeeds before retry fires', async () => {
3244
+ jest.useFakeTimers();
3245
+ try {
3246
+ webex.internal.device = {
3247
+ userId: 'user-123',
3248
+ url: 'https://wdm.example.com/devices/dev-1',
3249
+ registered: false,
3250
+ register: jest.fn().mockResolvedValue(undefined),
3251
+ unregister: jest.fn().mockResolvedValue(undefined),
3252
+ };
3253
+ webex.internal.mercury = {
3254
+ connected: false,
3255
+ connect: jest.fn().mockResolvedValue(undefined),
3256
+ disconnect: jest.fn().mockResolvedValue(undefined),
3257
+ };
3258
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'subscribe').mockImplementation(() => {});
3259
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
3260
+ webex.cc['agentConfig'] = {
3261
+ agentId: 'agent-123',
3262
+ deviceType: LoginOption.EXTENSION,
3263
+ webRtcEnabled: false,
3264
+ loginVoiceOptions: ['EXTENSION'],
3265
+ } as Profile;
3266
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
3267
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
3268
+ mockTaskManager.applyEnableWxBetterTogether(true);
3269
+ webex.cc['webexCrossClientService'].answerCallsState = true;
3270
+
3271
+ jest.spyOn(webex.cc.services.agent, 'logout').mockResolvedValue({
3272
+ trackingId: 'track-1',
3273
+ } as StationLogoutResponse);
3274
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
3275
+ data: {
3276
+ agentId: 'agent-123',
3277
+ teamId: 'team-123',
3278
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
3279
+ },
3280
+ trackingId: 'track-2',
3281
+ } as StationLoginSuccess);
3282
+
3283
+ const publishSpy = jest
3284
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
3285
+ .mockRejectedValueOnce(new Error('usersub publish failed'))
3286
+ .mockResolvedValue(undefined);
3287
+ const teardownSpy = jest.spyOn(webex.cc['webexCrossClientService'], 'teardown');
3288
+ jest
3289
+ .spyOn(webex.cc as any, 'releaseWxAppMercuryResources')
3290
+ .mockResolvedValue(undefined);
3291
+
3292
+ await webex.cc.stationLogout({logoutReason: 'Logout reason'});
3293
+ await webex.cc.stationLogin({
3294
+ teamId: 'team-123',
3295
+ loginOption: LoginOption.EXTENSION,
3296
+ dialNumber: '1001',
3297
+ });
3298
+
3299
+ expect(publishSpy).toHaveBeenCalledTimes(2);
3300
+ expect(publishSpy).toHaveBeenNthCalledWith(1, false, {userId: 'user-123', trackPublishMetrics: true});
3301
+ expect(publishSpy).toHaveBeenNthCalledWith(2, true, {userId: 'user-123', trackPublishMetrics: true});
3302
+ expect(teardownSpy).toHaveBeenCalledTimes(1);
3303
+
3304
+ jest.advanceTimersByTime(30_000);
3305
+
3306
+ expect(publishSpy).toHaveBeenCalledTimes(2);
3307
+ expect(teardownSpy).toHaveBeenCalledTimes(1);
3308
+ } finally {
3309
+ jest.useRealTimers();
3310
+ }
3311
+ });
3312
+
867
3313
  it('should handle error during stationLogout', async () => {
868
3314
  const data = {logoutReason: 'Logout reason'};
869
3315
  const error = {
@@ -1016,6 +3462,257 @@ describe('webex.cc', () => {
1016
3462
  });
1017
3463
  });
1018
3464
 
3465
+ describe('Agent Wellness Break SDK contracts', () => {
3466
+ const wellbeingCode = {
3467
+ id: 'wellbeing-code',
3468
+ name: 'WellbeingBreak',
3469
+ isSystem: true,
3470
+ isDefault: false,
3471
+ };
3472
+
3473
+ beforeEach(() => {
3474
+ webex.cc.agentConfig = {
3475
+ agentId: 'agent-1',
3476
+ isWellnessBreakEnabled: true,
3477
+ } as Profile;
3478
+ webex.cc['updateWellnessSession']('session-1');
3479
+ });
3480
+
3481
+ it('fetches the system idle code once per registration', async () => {
3482
+ const lookup = jest
3483
+ .spyOn(webex.cc.services.config, 'getWellbeingBreakIdleCode')
3484
+ .mockResolvedValue(wellbeingCode);
3485
+
3486
+ await expect(webex.cc.getWellbeingBreakIdleCode()).resolves.toEqual(wellbeingCode);
3487
+ await expect(webex.cc.getWellbeingBreakIdleCode()).resolves.toEqual(wellbeingCode);
3488
+
3489
+ expect(lookup).toHaveBeenCalledTimes(1);
3490
+ expect(lookup).toHaveBeenCalledWith('mockOrgId');
3491
+ });
3492
+
3493
+ it('does not cache an idle-code lookup that completes after a new registration starts', async () => {
3494
+ let resolveLookup: (idleCode: typeof wellbeingCode) => void = () => undefined;
3495
+ jest
3496
+ .spyOn(webex.cc.services.config, 'getWellbeingBreakIdleCode')
3497
+ .mockImplementation(
3498
+ () =>
3499
+ new Promise((resolve) => {
3500
+ resolveLookup = resolve;
3501
+ })
3502
+ );
3503
+
3504
+ const lookupPromise = webex.cc.getWellbeingBreakIdleCode();
3505
+ const staleLookup = expect(lookupPromise).rejects.toThrow(
3506
+ 'WELLNESS_BREAK_REGISTRATION_CHANGED'
3507
+ );
3508
+ jest
3509
+ .spyOn(webex.cc, 'connectWebsocket')
3510
+ .mockRejectedValue(new Error('replacement registration failed'));
3511
+
3512
+ await expect(webex.cc.register()).rejects.toThrow('replacement registration failed');
3513
+ resolveLookup(wellbeingCode);
3514
+
3515
+ await staleLookup;
3516
+ expect(webex.cc['wellbeingBreakIdleCode']).toBeUndefined();
3517
+ });
3518
+
3519
+ it('rejects the system idle-code lookup when wellness is disabled', async () => {
3520
+ webex.cc.agentConfig.isWellnessBreakEnabled = false;
3521
+
3522
+ await expect(webex.cc.getWellbeingBreakIdleCode()).rejects.toThrow(
3523
+ 'WELLNESS_BREAK_NOT_ENABLED'
3524
+ );
3525
+ expect(webex.cc.services.config.getWellbeingBreakIdleCode).not.toHaveBeenCalled();
3526
+ });
3527
+
3528
+ it('invalidates the wellness session only for a current-session multi-login close', () => {
3529
+ webex.cc['handleWebsocketMessage'](
3530
+ JSON.stringify({
3531
+ type: CC_EVENTS.AGENT_MULTI_LOGIN,
3532
+ data: {
3533
+ type: 'AgentMultiLoginCloseSession',
3534
+ agentSessionId: 'another-session',
3535
+ },
3536
+ })
3537
+ );
3538
+ expect(webex.cc['currentAgentSessionId']).toBe('session-1');
3539
+
3540
+ webex.cc['handleWebsocketMessage'](
3541
+ JSON.stringify({
3542
+ type: CC_EVENTS.AGENT_MULTI_LOGIN,
3543
+ data: {
3544
+ type: 'AgentMultiLoginCloseSession',
3545
+ agentSessionId: 'session-1',
3546
+ },
3547
+ })
3548
+ );
3549
+ expect(webex.cc['currentAgentSessionId']).toBeUndefined();
3550
+ });
3551
+
3552
+ it('emits primary wellness notifications regardless of notification session metadata', () => {
3553
+ const emitSpy = jest.spyOn(webex.cc, 'emit');
3554
+ const payload = {
3555
+ type: 'Wellness_Break_Handler',
3556
+ orgId: 'mockOrgId',
3557
+ trackingId: 'data-notification-tracking',
3558
+ data: {
3559
+ agentId: 'agent-1',
3560
+ orgId: 'mockOrgId',
3561
+ notifType: 'Wellness_Break_Handler',
3562
+ notifDetails: {
3563
+ actionEvent: 'SUGGEST_WELLNESS_BREAK',
3564
+ actionText: 'How about a break?',
3565
+ },
3566
+ data: {
3567
+ orgId: 'mockOrgId',
3568
+ agentSessionId: 'notification-session',
3569
+ interactionId: 'interaction-1',
3570
+ },
3571
+ },
3572
+ };
3573
+
3574
+ webex.cc['handleWebsocketMessage'](JSON.stringify(payload));
3575
+
3576
+ expect(emitSpy).toHaveBeenCalledWith(CC_EVENTS.WELLNESS_BREAK, {
3577
+ agentId: 'agent-1',
3578
+ orgId: 'mockOrgId',
3579
+ agentSessionId: 'notification-session',
3580
+ actionEvent: 'SUGGEST_WELLNESS_BREAK',
3581
+ actionText: 'How about a break?',
3582
+ interactionId: 'interaction-1',
3583
+ trackingId: 'data-notification-tracking',
3584
+ });
3585
+ });
3586
+
3587
+ it('routes data-socket wellness notifications without sending them to TaskManager', () => {
3588
+ const emitSpy = jest.spyOn(webex.cc, 'emit');
3589
+ const taskEventSpy = mockTaskManager.handleRealtimeWebsocketEvent;
3590
+ const wellnessMessage = JSON.stringify({
3591
+ type: 'Wellness_Break_Handler',
3592
+ orgId: 'mockOrgId',
3593
+ data: {
3594
+ agentId: 'agent-1',
3595
+ orgId: 'mockOrgId',
3596
+ notifType: 'Wellness_Break_Handler',
3597
+ notifDetails: {actionEvent: 'PROVIDE_WELLNESS_BREAK'},
3598
+ data: {orgId: 'mockOrgId', agentSessionId: 'notification-session'},
3599
+ },
3600
+ });
3601
+
3602
+ webex.cc['handleRTDWebsocketMessage'](wellnessMessage);
3603
+
3604
+ expect(emitSpy).toHaveBeenCalledWith(CC_EVENTS.WELLNESS_BREAK, {
3605
+ agentId: 'agent-1',
3606
+ orgId: 'mockOrgId',
3607
+ agentSessionId: 'notification-session',
3608
+ actionEvent: 'PROVIDE_WELLNESS_BREAK',
3609
+ });
3610
+ expect(taskEventSpy).not.toHaveBeenCalled();
3611
+
3612
+ const transcriptMessage = JSON.stringify({type: CC_EVENTS.REAL_TIME_TRANSCRIPTION});
3613
+ webex.cc['handleRTDWebsocketMessage'](transcriptMessage);
3614
+ expect(taskEventSpy).toHaveBeenCalledWith(transcriptMessage);
3615
+ });
3616
+
3617
+ it.each([
3618
+ ['SUGGEST_WELLNESS_BREAK', 'interactionId'],
3619
+ ['WELLNESS_BREAK_NOT_ALLOWED', 'InteractionId'],
3620
+ ])('normalizes the %s action and either interaction-id spelling', (actionEvent, key) => {
3621
+ const emitSpy = jest.spyOn(webex.cc, 'emit');
3622
+ webex.cc['handleWebsocketMessage'](
3623
+ JSON.stringify({
3624
+ type: 'Wellness_Break_Handler',
3625
+ orgId: 'mockOrgId',
3626
+ data: {
3627
+ agentId: 'agent-1',
3628
+ orgId: 'mockOrgId',
3629
+ notifType: 'Wellness_Break_Handler',
3630
+ notifDetails: {actionEvent},
3631
+ data: {
3632
+ orgId: 'mockOrgId',
3633
+ agentSessionId: 'session-1',
3634
+ [key]: 'interaction-2',
3635
+ },
3636
+ },
3637
+ })
3638
+ );
3639
+
3640
+ expect(emitSpy).toHaveBeenCalledWith(
3641
+ CC_EVENTS.WELLNESS_BREAK,
3642
+ expect.objectContaining({actionEvent, interactionId: 'interaction-2'})
3643
+ );
3644
+ });
3645
+
3646
+ it('does not promote uncontracted notification text fields', () => {
3647
+ const emitSpy = jest.spyOn(webex.cc, 'emit');
3648
+ webex.cc['handleWebsocketMessage'](
3649
+ JSON.stringify({
3650
+ type: 'Wellness_Break_Handler',
3651
+ orgId: 'mockOrgId',
3652
+ trackingId: 'notification-tracking',
3653
+ data: {
3654
+ agentId: 'agent-1',
3655
+ orgId: 'mockOrgId',
3656
+ notifType: 'Wellness_Break_Handler',
3657
+ notifDetails: {
3658
+ actionEvent: 'SUGGEST_WELLNESS_BREAK',
3659
+ actionText2: 'Uncontracted text',
3660
+ },
3661
+ data: {
3662
+ orgId: 'mockOrgId',
3663
+ agentSessionId: 'session-1',
3664
+ InteractionId: 'interaction-qa',
3665
+ },
3666
+ },
3667
+ })
3668
+ );
3669
+
3670
+ expect(emitSpy).toHaveBeenCalledWith(CC_EVENTS.WELLNESS_BREAK, {
3671
+ agentId: 'agent-1',
3672
+ orgId: 'mockOrgId',
3673
+ agentSessionId: 'session-1',
3674
+ actionEvent: 'SUGGEST_WELLNESS_BREAK',
3675
+ interactionId: 'interaction-qa',
3676
+ trackingId: 'notification-tracking',
3677
+ });
3678
+ });
3679
+
3680
+ it('ignores wellness events when the effective flag is disabled or identity is missing', () => {
3681
+ const emitSpy = jest.spyOn(webex.cc, 'emit');
3682
+ const payload = {
3683
+ type: 'Wellness_Break_Handler',
3684
+ orgId: 'mockOrgId',
3685
+ data: {
3686
+ agentId: 'agent-1',
3687
+ orgId: 'mockOrgId',
3688
+ notifType: 'Wellness_Break_Handler',
3689
+ notifDetails: {actionEvent: 'SUGGEST_WELLNESS_BREAK'},
3690
+ data: {orgId: 'mockOrgId', agentSessionId: 'session-1'},
3691
+ },
3692
+ };
3693
+
3694
+ webex.cc.agentConfig.isWellnessBreakEnabled = false;
3695
+ webex.cc['handleWebsocketMessage'](JSON.stringify(payload));
3696
+ webex.cc.agentConfig.isWellnessBreakEnabled = true;
3697
+ const {orgId: omittedOrgId, ...payloadWithoutEnvelopeOrg} = payload;
3698
+ expect(omittedOrgId).toBe('mockOrgId');
3699
+ webex.cc['handleWebsocketMessage'](JSON.stringify(payloadWithoutEnvelopeOrg));
3700
+
3701
+ expect(emitSpy).not.toHaveBeenCalledWith(CC_EVENTS.WELLNESS_BREAK, expect.anything());
3702
+ expect(mockMetricsManager.trackEvent).toHaveBeenCalledWith(
3703
+ METRIC_EVENT_NAMES.AI_ASSISTANT_WELLNESS_EVENT_INVALID,
3704
+ {reason: 'wellness_disabled'},
3705
+ ['operational']
3706
+ );
3707
+ expect(mockMetricsManager.trackEvent).toHaveBeenCalledWith(
3708
+ METRIC_EVENT_NAMES.AI_ASSISTANT_WELLNESS_EVENT_INVALID,
3709
+ {reason: 'missing_wellness_identity'},
3710
+ ['operational']
3711
+ );
3712
+ });
3713
+
3714
+ });
3715
+
1019
3716
  describe('getBuddyAgents', () => {
1020
3717
  it('should return buddy agents response when successful', async () => {
1021
3718
  const data: BuddyAgents = {state: 'Available', mediaType: 'telephony'};
@@ -1079,6 +3776,41 @@ describe('webex.cc', () => {
1079
3776
  ]);
1080
3777
  });
1081
3778
 
3779
+ it('should map Transfer action to an Available backend state filter', async () => {
3780
+ webex.cc.agentConfig = {agentProfileID: 'test-agent-profile-id'};
3781
+ const buddyAgentsResponse = {data: {agentList: []}};
3782
+ const buddyAgentsSpy = jest
3783
+ .spyOn(webex.cc.services.agent, 'buddyAgents')
3784
+ .mockResolvedValue(buddyAgentsResponse);
3785
+
3786
+ await webex.cc.getBuddyAgents({action: 'Transfer', mediaType: 'chat'});
3787
+
3788
+ expect(buddyAgentsSpy).toHaveBeenCalledWith({
3789
+ data: {
3790
+ agentProfileId: 'test-agent-profile-id',
3791
+ mediaType: 'chat',
3792
+ state: 'Available',
3793
+ },
3794
+ });
3795
+ });
3796
+
3797
+ it('should omit the backend state filter for Consult and default media type to telephony', async () => {
3798
+ webex.cc.agentConfig = {agentProfileID: 'test-agent-profile-id'};
3799
+ const buddyAgentsResponse = {data: {agentList: []}};
3800
+ const buddyAgentsSpy = jest
3801
+ .spyOn(webex.cc.services.agent, 'buddyAgents')
3802
+ .mockResolvedValue(buddyAgentsResponse);
3803
+
3804
+ await webex.cc.getBuddyAgents({action: 'Consult'});
3805
+
3806
+ expect(buddyAgentsSpy).toHaveBeenCalledWith({
3807
+ data: {
3808
+ agentProfileId: 'test-agent-profile-id',
3809
+ mediaType: 'telephony',
3810
+ },
3811
+ });
3812
+ });
3813
+
1082
3814
  it('should handle error', async () => {
1083
3815
  const data: BuddyAgents = {state: 'Available', mediaType: 'telephony'};
1084
3816
  webex.cc.agentConfig = {
@@ -1151,15 +3883,13 @@ describe('webex.cc', () => {
1151
3883
  );
1152
3884
 
1153
3885
  const setLoginOptionSpy = jest.spyOn(webex.cc.webCallingService, 'setLoginOption');
1154
- const incomingTaskListenerSpy = jest.spyOn(webex.cc, 'incomingTaskListener');
1155
- const webSocketManagerOnSpy = jest.spyOn(webex.cc.services.webSocketManager, 'on');
1156
3886
  await webex.cc['silentRelogin']();
1157
3887
 
1158
- expect(LoggerProxy.info).toHaveBeenCalledWith('Starting silent relogin process', {
3888
+ expect(LoggerProxy.log).toHaveBeenCalledWith('Starting silent relogin process', {
1159
3889
  module: CC_FILE,
1160
3890
  method: 'silentRelogin',
1161
3891
  });
1162
- expect(LoggerProxy.info).toHaveBeenCalledWith(
3892
+ expect(LoggerProxy.log).toHaveBeenCalledWith(
1163
3893
  'event=requestAutoStateChange | Requesting state change to available on socket reconnect',
1164
3894
  {module: CC_FILE, method: 'silentRelogin'}
1165
3895
  );
@@ -1183,8 +3913,8 @@ describe('webex.cc', () => {
1183
3913
  expect(webex.cc.agentConfig.deviceType).toBe(LoginOption.BROWSER);
1184
3914
  expect(registerWebCallingLineSpy).toHaveBeenCalled();
1185
3915
  expect(setLoginOptionSpy).toHaveBeenCalledWith(LoginOption.BROWSER);
1186
- // TODO: https://jira-eng-gpk2.cisco.com/jira/browse/SPARK-626777 Implement the de-register method and close the listener there
1187
- // expect(incomingTaskListenerSpy).toHaveBeenCalled();
3916
+ // SPARK-626777 tracks moving listener cleanup into the future de-register API.
3917
+ // expect(eventForwarderRefreshSpy).toHaveBeenCalled();
1188
3918
  // expect(webSocketManagerOnSpy).toHaveBeenCalledWith('message', expect.any(Function));
1189
3919
  // expect(mockTaskManager.on).toHaveBeenCalledWith(
1190
3920
  // TASK_EVENTS.TASK_HYDRATE,
@@ -1204,7 +3934,7 @@ describe('webex.cc', () => {
1204
3934
 
1205
3935
  jest.spyOn(webex.cc.services.agent, 'reload').mockRejectedValue(error);
1206
3936
  await webex.cc['silentRelogin']();
1207
- expect(LoggerProxy.info).toHaveBeenCalledWith('Starting silent relogin process', {
3937
+ expect(LoggerProxy.log).toHaveBeenCalledWith('Starting silent relogin process', {
1208
3938
  module: CC_FILE,
1209
3939
  method: 'silentRelogin',
1210
3940
  });
@@ -1219,7 +3949,7 @@ describe('webex.cc', () => {
1219
3949
  jest.spyOn(webex.cc.services.agent, 'reload').mockRejectedValue(error);
1220
3950
 
1221
3951
  await expect(webex.cc['silentRelogin']()).rejects.toThrow(error);
1222
- expect(LoggerProxy.info).toHaveBeenCalledWith('Starting silent relogin process', {
3952
+ expect(LoggerProxy.log).toHaveBeenCalledWith('Starting silent relogin process', {
1223
3953
  module: CC_FILE,
1224
3954
  method: 'silentRelogin',
1225
3955
  });
@@ -1261,7 +3991,7 @@ describe('webex.cc', () => {
1261
3991
 
1262
3992
  await webex.cc['silentRelogin']();
1263
3993
 
1264
- expect(LoggerProxy.info).toHaveBeenCalledWith('Starting silent relogin process', {
3994
+ expect(LoggerProxy.log).toHaveBeenCalledWith('Starting silent relogin process', {
1265
3995
  module: CC_FILE,
1266
3996
  method: 'silentRelogin',
1267
3997
  });
@@ -1306,6 +4036,83 @@ describe('webex.cc', () => {
1306
4036
  expect(webex.cc.agentConfig.deviceType).toBe(LoginOption.AGENT_DN);
1307
4037
  expect(webex.cc.agentConfig.dn).toBe('67890');
1308
4038
  });
4039
+
4040
+ it('should publish usersub true on silent relogin when enableWxBetterTogether is true at init', async () => {
4041
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
4042
+ webex.internal.device = {
4043
+ userId: 'user-123',
4044
+ url: 'https://wdm.example.com/devices/dev-1',
4045
+ registered: true,
4046
+ register: jest.fn().mockResolvedValue(undefined),
4047
+ };
4048
+ webex.internal.mercury.connected = true;
4049
+ webex.internal.mercury.connect = jest.fn().mockResolvedValue(undefined);
4050
+ webex.cc.agentConfig = {
4051
+ agentId: 'agentId',
4052
+ agentProfileID: 'test-agent-profile-id',
4053
+ isAgentLoggedIn: false,
4054
+ } as Profile;
4055
+
4056
+ jest.spyOn(webex.cc.services.agent, 'reload').mockResolvedValue({
4057
+ data: {
4058
+ auxCodeId: 'auxCodeId',
4059
+ agentId: 'agentId',
4060
+ deviceType: LoginOption.EXTENSION,
4061
+ dn: '1001',
4062
+ teamId: 'teamId',
4063
+ lastStateChangeTimestamp: 1738575135188,
4064
+ lastIdleCodeChangeTimestamp: 1738575135189,
4065
+ },
4066
+ });
4067
+
4068
+ const publishSpy = jest
4069
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
4070
+ .mockResolvedValue(undefined);
4071
+ const subscribeSpy = jest
4072
+ .spyOn(webex.cc['wxAppTelephonyMercurySync'], 'subscribe')
4073
+ .mockImplementation(() => {});
4074
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
4075
+
4076
+ await webex.cc['silentRelogin']();
4077
+
4078
+ expect(publishSpy).toHaveBeenCalledWith(true, {userId: 'user-123', trackPublishMetrics: true});
4079
+ expect(subscribeSpy).toHaveBeenCalledWith('agentId', expect.any(Function));
4080
+ expect(mockTaskManager.refreshWxAppOfferObservabilityForAllTasks).toHaveBeenCalled();
4081
+ });
4082
+
4083
+ it('should force-publish usersub false on silent relogin when enableWxBetterTogether is false at init', async () => {
4084
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: false};
4085
+ webex.internal.device = {userId: 'user-123', url: 'https://wdm.example.com/devices/dev-1'};
4086
+ webex.cc.agentConfig = {
4087
+ agentId: 'agentId',
4088
+ agentProfileID: 'test-agent-profile-id',
4089
+ isAgentLoggedIn: false,
4090
+ } as Profile;
4091
+
4092
+ jest.spyOn(webex.cc.services.agent, 'reload').mockResolvedValue({
4093
+ data: {
4094
+ auxCodeId: 'auxCodeId',
4095
+ agentId: 'agentId',
4096
+ deviceType: LoginOption.EXTENSION,
4097
+ dn: '1001',
4098
+ teamId: 'teamId',
4099
+ lastStateChangeTimestamp: 1738575135188,
4100
+ lastIdleCodeChangeTimestamp: 1738575135189,
4101
+ },
4102
+ });
4103
+
4104
+ const publishSpy = jest
4105
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
4106
+ .mockResolvedValue(undefined);
4107
+ const teardownSpy = jest.spyOn(webex.cc['webexCrossClientService'], 'teardown');
4108
+ const unsubscribeSpy = jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'unsubscribe');
4109
+
4110
+ await webex.cc['silentRelogin']();
4111
+
4112
+ expect(publishSpy).toHaveBeenCalledWith(false, {userId: 'user-123', trackPublishMetrics: true});
4113
+ expect(teardownSpy).toHaveBeenCalled();
4114
+ expect(unsubscribeSpy).toHaveBeenCalled();
4115
+ });
1309
4116
  });
1310
4117
 
1311
4118
  describe('setupEventListeners()', () => {
@@ -1442,6 +4249,30 @@ describe('webex.cc', () => {
1442
4249
  {module: CC_FILE, method: `startOutdial`, trackingId: error.details.trackingId}
1443
4250
  );
1444
4251
  expect(getErrorDetailsSpy).toHaveBeenCalledWith(error, 'startOutdial', CC_FILE);
4252
+ expect(mockWebexRequest.uploadLogs).toHaveBeenCalledWith({
4253
+ correlationId: error.details.trackingId,
4254
+ });
4255
+ });
4256
+ });
4257
+
4258
+ describe('getQueues', () => {
4259
+ it('delegates to the queue service when successful', async () => {
4260
+ const mockQueuesResponse = [{queueId: 'queue1', queueName: 'Queue 1'}];
4261
+ const queueSpy = jest
4262
+ .spyOn(webex.cc.queue, 'getQueues')
4263
+ .mockResolvedValue(mockQueuesResponse as any);
4264
+
4265
+ const result = await webex.cc.getQueues({page: 1});
4266
+
4267
+ expect(queueSpy).toHaveBeenCalledWith({page: 1});
4268
+ expect(result).toBe(mockQueuesResponse);
4269
+ });
4270
+
4271
+ it('propagates queue service errors', async () => {
4272
+ const error = new Error('Test error.');
4273
+ jest.spyOn(webex.cc.queue, 'getQueues').mockRejectedValue(error);
4274
+
4275
+ await expect(webex.cc.getQueues()).rejects.toThrow('Test error.');
1445
4276
  });
1446
4277
  });
1447
4278
 
@@ -1474,6 +4305,7 @@ describe('webex.cc', () => {
1474
4305
 
1475
4306
  describe('unregister', () => {
1476
4307
  let mockWebSocketManager;
4308
+ let mockRTDWebSocketManager;
1477
4309
  let mercuryDisconnectSpy;
1478
4310
  let deviceUnregisterSpy;
1479
4311
 
@@ -1490,8 +4322,15 @@ describe('webex.cc', () => {
1490
4322
  off: jest.fn(),
1491
4323
  on: jest.fn(),
1492
4324
  };
4325
+ mockRTDWebSocketManager = {
4326
+ isSocketClosed: false,
4327
+ close: jest.fn(),
4328
+ off: jest.fn(),
4329
+ on: jest.fn(),
4330
+ };
1493
4331
 
1494
4332
  webex.cc.services.webSocketManager = mockWebSocketManager;
4333
+ webex.cc.services.rtdWebSocketManager = mockRTDWebSocketManager;
1495
4334
 
1496
4335
  webex.internal = webex.internal || {};
1497
4336
  webex.internal.mercury = {
@@ -1507,7 +4346,62 @@ describe('webex.cc', () => {
1507
4346
  deviceUnregisterSpy = jest.spyOn(webex.internal.device, 'unregister');
1508
4347
  });
1509
4348
 
4349
+ afterEach(() => {
4350
+ mockTaskManager.off.mockImplementation(() => undefined);
4351
+ mockTaskManager.clearAISummaryState.mockImplementation(() => undefined);
4352
+ mockRTDWebSocketManager.off.mockImplementation(() => undefined);
4353
+ mockRTDWebSocketManager.close.mockImplementation(() => undefined);
4354
+ });
4355
+
4356
+ it('invalidates wellness context before deregistration cleanup can fail', async () => {
4357
+ const cleanupError = new Error('cleanup failed');
4358
+ let rejectCleanup: (error: Error) => void = () => undefined;
4359
+ const cleanup = new Promise((resolve, reject) => {
4360
+ rejectCleanup = reject;
4361
+ });
4362
+ webex.cc.agentConfig = {
4363
+ ...webex.cc.agentConfig,
4364
+ isWellnessBreakEnabled: true,
4365
+ };
4366
+ webex.cc['updateWellnessSession']('session-1');
4367
+ jest.spyOn(webex.cc as any, 'teardownWxAppLocalState').mockReturnValue(cleanup);
4368
+ webex.cc.apiAIAssistant.requestWellnessBreak.mockRejectedValue(
4369
+ new Error('WELLNESS_BREAK_AGENT_SESSION_REQUIRED')
4370
+ );
4371
+
4372
+ const deregistration = webex.cc.deregister();
4373
+ const rejection = expect(deregistration).rejects.toThrow(cleanupError);
4374
+
4375
+ expect(webex.cc['currentAgentSessionId']).toBeUndefined();
4376
+ await expect(webex.cc.apiAIAssistant.requestWellnessBreak()).rejects.toThrow(
4377
+ 'WELLNESS_BREAK_AGENT_SESSION_REQUIRED'
4378
+ );
4379
+
4380
+ rejectCleanup(cleanupError);
4381
+ await rejection;
4382
+ expect(webex.cc['currentAgentSessionId']).toBeUndefined();
4383
+ });
4384
+
1510
4385
  it('should unregister successfully and clean up all resources when webrtc is enabled', async () => {
4386
+ webex.cc.services.rtdWebSocketManager = {
4387
+ isSocketClosed: false,
4388
+ close: jest.fn(),
4389
+ off: jest.fn(),
4390
+ on: jest.fn(),
4391
+ } as any;
4392
+
4393
+ webex.internal.device = {
4394
+ ...webex.internal.device,
4395
+ userId: 'user-123',
4396
+ unregister: jest.fn().mockResolvedValue(undefined),
4397
+ };
4398
+ deviceUnregisterSpy = jest.spyOn(webex.internal.device, 'unregister');
4399
+ const publishSpy = jest
4400
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
4401
+ .mockResolvedValue(undefined);
4402
+ const teardownSpy = jest.spyOn(webex.cc['webexCrossClientService'], 'teardown');
4403
+ const unsubscribeSpy = jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'unsubscribe');
4404
+
1511
4405
  await webex.cc.deregister();
1512
4406
 
1513
4407
  expect(mockTaskManager.off).toHaveBeenCalledWith(
@@ -1518,13 +4412,32 @@ describe('webex.cc', () => {
1518
4412
  TASK_EVENTS.TASK_HYDRATE,
1519
4413
  expect.any(Function)
1520
4414
  );
4415
+ expect(mockTaskManager.off).toHaveBeenCalledWith(
4416
+ TASK_EVENTS.TASK_MULTI_LOGIN_HYDRATE,
4417
+ expect.any(Function)
4418
+ );
1521
4419
  expect(mockWebSocketManager.off).toHaveBeenCalledWith('message', expect.any(Function));
4420
+ expect(webex.cc.services.rtdWebSocketManager.off).toHaveBeenCalledWith(
4421
+ 'message',
4422
+ expect.any(Function)
4423
+ );
1522
4424
  expect(webex.cc.services.connectionService.off).toHaveBeenCalledWith(
1523
4425
  'connectionLost',
1524
4426
  expect.any(Function)
1525
4427
  );
1526
4428
 
1527
4429
  expect(mockWebSocketManager.close).toHaveBeenCalledWith(false, 'Unregistering the SDK');
4430
+ expect(webex.cc.services.rtdWebSocketManager.close).toHaveBeenNthCalledWith(
4431
+ 1,
4432
+ false,
4433
+ 'Unregistering the SDK'
4434
+ );
4435
+ expect(webex.cc.services.rtdWebSocketManager.close).toHaveBeenNthCalledWith(
4436
+ 2,
4437
+ false,
4438
+ 'Unregistering the RTD websocket'
4439
+ );
4440
+ expect(webex.cc.services.rtdWebSocketManager.close).toHaveBeenCalledTimes(2);
1528
4441
  expect(webex.cc.agentConfig).toBeNull();
1529
4442
 
1530
4443
  expect(webex.internal.mercury.off).toHaveBeenCalledWith('online');
@@ -1536,6 +4449,7 @@ describe('webex.cc', () => {
1536
4449
  METRIC_EVENT_NAMES.WEBSOCKET_DEREGISTER_SUCCESS,
1537
4450
  METRIC_EVENT_NAMES.WEBSOCKET_DEREGISTER_FAIL,
1538
4451
  ]);
4452
+ expect(mockTaskManager.clearAISummaryState).toHaveBeenCalled();
1539
4453
  expect(mockMetricsManager.trackEvent).toHaveBeenCalledWith(
1540
4454
  METRIC_EVENT_NAMES.WEBSOCKET_DEREGISTER_SUCCESS,
1541
4455
  {},
@@ -1555,17 +4469,25 @@ describe('webex.cc', () => {
1555
4469
  const incomingCalls = mockTaskManager.off.mock.calls.filter(
1556
4470
  ([evt]) => evt === TASK_EVENTS.TASK_INCOMING
1557
4471
  );
1558
- expect(incomingCalls).toHaveLength(1);
1559
- const [, incomingCallback] = incomingCalls[0];
4472
+ expect(incomingCalls.length).toBeGreaterThanOrEqual(1);
4473
+ const [, incomingCallback] = incomingCalls[incomingCalls.length - 1];
1560
4474
  expect(incomingCallback).toBe(webex.cc['handleIncomingTask']);
1561
4475
 
1562
4476
  const hydrateCalls = mockTaskManager.off.mock.calls.filter(
1563
4477
  ([evt]) => evt === TASK_EVENTS.TASK_HYDRATE
1564
4478
  );
1565
- expect(hydrateCalls).toHaveLength(1);
1566
- const [, hydrateCallback] = hydrateCalls[0];
4479
+ expect(hydrateCalls.length).toBeGreaterThanOrEqual(1);
4480
+ const [, hydrateCallback] = hydrateCalls[hydrateCalls.length - 1];
1567
4481
  expect(hydrateCallback).toBe(webex.cc['handleTaskHydrate']);
1568
4482
 
4483
+ const multiLoginHydrateCalls = mockTaskManager.off.mock.calls.filter(
4484
+ ([evt]) => evt === TASK_EVENTS.TASK_MULTI_LOGIN_HYDRATE
4485
+ );
4486
+ expect(multiLoginHydrateCalls.length).toBeGreaterThanOrEqual(1);
4487
+ const [, multiLoginHydrateCallback] =
4488
+ multiLoginHydrateCalls[multiLoginHydrateCalls.length - 1];
4489
+ expect(multiLoginHydrateCallback).toBe(webex.cc['handleTaskMultiLoginHydrate']);
4490
+
1569
4491
  const messageCalls = mockWebSocketManager.off.mock.calls.filter(([evt]) => evt === 'message');
1570
4492
  expect(messageCalls).toHaveLength(1);
1571
4493
  const [, messageCallback] = messageCalls[0];
@@ -1577,6 +4499,39 @@ describe('webex.cc', () => {
1577
4499
  expect(connectionCalls).toHaveLength(1);
1578
4500
  const [, connectionCallback] = connectionCalls[0];
1579
4501
  expect(connectionCallback).toBe(webex.cc['handleConnectionLost']);
4502
+
4503
+ expect(publishSpy).not.toHaveBeenCalled();
4504
+ expect(teardownSpy).toHaveBeenCalled();
4505
+ expect(unsubscribeSpy).toHaveBeenCalled();
4506
+ });
4507
+
4508
+ it('should publish usersub false before device unregister when wxApp is active on deregister', async () => {
4509
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
4510
+ webex.cc['webexCrossClientService'].answerCallsState = true;
4511
+ webex.internal.device = {
4512
+ userId: 'user-123',
4513
+ url: 'https://wdm.example.com/devices/dev-1',
4514
+ unregister: jest.fn().mockResolvedValue(undefined),
4515
+ };
4516
+ deviceUnregisterSpy = jest.spyOn(webex.internal.device, 'unregister');
4517
+
4518
+ const callOrder: string[] = [];
4519
+ jest
4520
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
4521
+ .mockImplementation(async (enable: boolean) => {
4522
+ if (enable === false && !webex.internal.device.url) {
4523
+ throw new Error('Device URL is unavailable for cross-client publish');
4524
+ }
4525
+ callOrder.push(enable ? 'publish:true' : 'publish:false');
4526
+ });
4527
+ deviceUnregisterSpy.mockImplementation(async () => {
4528
+ callOrder.push('device.unregister');
4529
+ webex.internal.device.url = undefined;
4530
+ });
4531
+
4532
+ await webex.cc.deregister();
4533
+
4534
+ expect(callOrder).toEqual(['publish:false', 'device.unregister']);
1580
4535
  });
1581
4536
 
1582
4537
  it('should skip webCallingService and internal cleanup when webrtc is disabled', async () => {
@@ -1591,33 +4546,188 @@ describe('webex.cc', () => {
1591
4546
  TASK_EVENTS.TASK_HYDRATE,
1592
4547
  expect.any(Function)
1593
4548
  );
4549
+ expect(mockTaskManager.off).toHaveBeenCalledWith(
4550
+ TASK_EVENTS.TASK_MULTI_LOGIN_HYDRATE,
4551
+ expect.any(Function)
4552
+ );
1594
4553
  expect(mockWebSocketManager.off).toHaveBeenCalledWith('message', expect.any(Function));
1595
4554
  expect(webex.cc.services.connectionService.off).toHaveBeenCalledWith(
1596
4555
  'connectionLost',
1597
4556
  expect.any(Function)
1598
4557
  );
1599
4558
 
1600
- expect(webex.internal.mercury.off).not.toHaveBeenCalled();
1601
- expect(mercuryDisconnectSpy).not.toHaveBeenCalled();
1602
- expect(deviceUnregisterSpy).not.toHaveBeenCalled();
4559
+ expect(webex.internal.mercury.off).not.toHaveBeenCalled();
4560
+ expect(mercuryDisconnectSpy).not.toHaveBeenCalled();
4561
+ expect(deviceUnregisterSpy).not.toHaveBeenCalled();
4562
+ expect(mockRTDWebSocketManager.close).toHaveBeenNthCalledWith(
4563
+ 1,
4564
+ false,
4565
+ 'Unregistering the SDK'
4566
+ );
4567
+ expect(mockRTDWebSocketManager.close).toHaveBeenNthCalledWith(
4568
+ 2,
4569
+ false,
4570
+ 'Unregistering the RTD websocket'
4571
+ );
4572
+ expect(mockRTDWebSocketManager.close).toHaveBeenCalledTimes(2);
4573
+ });
4574
+
4575
+ it('should skip internal mercury cleanup when loginVoiceOptions does not include BROWSER', async () => {
4576
+ webex.cc.agentConfig = {
4577
+ agentId: 'agentId',
4578
+ webRtcEnabled: true,
4579
+ loginVoiceOptions: ['EXTENSION'],
4580
+ };
4581
+
4582
+ await webex.cc.deregister();
4583
+
4584
+ // mercury listeners & disconnect should not run
4585
+ expect(webex.internal.mercury.off).not.toHaveBeenCalled();
4586
+ expect(mercuryDisconnectSpy).not.toHaveBeenCalled();
4587
+ expect(deviceUnregisterSpy).not.toHaveBeenCalled();
4588
+
4589
+ expect(mockWebSocketManager.close).toHaveBeenCalledWith(false, 'Unregistering the SDK');
4590
+ expect(mockRTDWebSocketManager.close).toHaveBeenNthCalledWith(
4591
+ 1,
4592
+ false,
4593
+ 'Unregistering the SDK'
4594
+ );
4595
+ expect(mockRTDWebSocketManager.close).toHaveBeenNthCalledWith(
4596
+ 2,
4597
+ false,
4598
+ 'Unregistering the RTD websocket'
4599
+ );
4600
+ expect(mockRTDWebSocketManager.close).toHaveBeenCalledTimes(2);
4601
+ expect(webex.cc.agentConfig).toBeNull();
4602
+ });
4603
+
4604
+ it('should teardown wxApp state on deregister even when usersub publish fails', async () => {
4605
+ webex.cc.agentConfig = {
4606
+ agentId: 'agentId',
4607
+ webRtcEnabled: false,
4608
+ loginVoiceOptions: [LoginOption.EXTENSION],
4609
+ };
4610
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
4611
+ webex.cc['webexCrossClientService'].answerCallsState = true;
4612
+ webex.internal.device = {
4613
+ userId: 'user-123',
4614
+ unregister: jest.fn().mockResolvedValue(undefined),
4615
+ };
4616
+
4617
+ jest
4618
+ .spyOn(webex.cc as never, 'publishAnswerOnWebexCrossClientState' as never)
4619
+ .mockRejectedValue(new Error('usersub publish failed'));
4620
+ const teardownSpy = jest.spyOn(webex.cc['webexCrossClientService'], 'teardown');
4621
+ const unsubscribeSpy = jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'unsubscribe');
4622
+
4623
+ await expect(webex.cc.deregister()).rejects.toThrow('usersub publish failed');
4624
+
4625
+ expect(teardownSpy).toHaveBeenCalled();
4626
+ expect(unsubscribeSpy).toHaveBeenCalled();
4627
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(false);
4628
+ expect(mockWebSocketManager.close).toHaveBeenCalledWith(false, 'Unregistering the SDK');
4629
+ expect(webex.cc.agentConfig).toBeNull();
4630
+ });
4631
+
4632
+ it('should publish forced false during teardown when enable publish is still in flight', async () => {
4633
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
4634
+ webex.internal.device = {
4635
+ userId: 'user-123',
4636
+ url: 'https://wdm.example.com/devices/dev-1',
4637
+ };
4638
+
4639
+ let resolveEnable: () => void = () => {};
4640
+ const enableGate = new Promise<void>((resolve) => {
4641
+ resolveEnable = resolve;
4642
+ });
4643
+
4644
+ const publishSpy = jest
4645
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
4646
+ .mockImplementation(async (enable: boolean) => {
4647
+ if (enable) {
4648
+ await enableGate;
4649
+ }
4650
+ });
4651
+ jest
4652
+ .spyOn(webex.cc as any, 'releaseWxAppMercuryResources')
4653
+ .mockResolvedValue(undefined);
4654
+
4655
+ expect(webex.cc['webexCrossClientService'].answerCallsState).toBe(false);
4656
+
4657
+ const enableInFlight = (webex.cc as any).publishAnswerOnWebexCrossClientState(true);
4658
+
4659
+ await (webex.cc as any).teardownWxAppLocalState();
4660
+
4661
+ expect(publishSpy).toHaveBeenCalledWith(false, {userId: 'user-123', trackPublishMetrics: true});
4662
+
4663
+ resolveEnable();
4664
+ await enableInFlight;
1603
4665
  });
1604
4666
 
1605
- it('should skip internal mercury cleanup when loginVoiceOptions does not include BROWSER', async () => {
4667
+ it('should release wxApp-owned Mercury and device on deregister', async () => {
1606
4668
  webex.cc.agentConfig = {
1607
4669
  agentId: 'agentId',
1608
- webRtcEnabled: true,
1609
- loginVoiceOptions: ['EXTENSION'],
4670
+ webRtcEnabled: false,
4671
+ loginVoiceOptions: [LoginOption.EXTENSION],
1610
4672
  };
4673
+ webex.cc['wxAppMercuryConnectedByCc'] = true;
4674
+ webex.cc['wxAppDeviceRegisteredByCc'] = true;
4675
+ webex.internal.mercury.connected = true;
4676
+ webex.internal.device.registered = true;
4677
+
4678
+ const mercuryDisconnectSpy = jest
4679
+ .spyOn(webex.internal.mercury, 'disconnect')
4680
+ .mockResolvedValue(undefined);
4681
+ const deviceUnregisterSpy = jest
4682
+ .spyOn(webex.internal.device, 'unregister')
4683
+ .mockResolvedValue(undefined);
1611
4684
 
1612
4685
  await webex.cc.deregister();
1613
4686
 
1614
- // mercury listeners & disconnect should not run
1615
- expect(webex.internal.mercury.off).not.toHaveBeenCalled();
1616
- expect(mercuryDisconnectSpy).not.toHaveBeenCalled();
1617
- expect(deviceUnregisterSpy).not.toHaveBeenCalled();
4687
+ expect(mercuryDisconnectSpy).toHaveBeenCalled();
4688
+ expect(deviceUnregisterSpy).toHaveBeenCalled();
4689
+ expect(webex.cc['wxAppMercuryConnectedByCc']).toBe(false);
4690
+ expect(webex.cc['wxAppDeviceRegisteredByCc']).toBe(false);
4691
+ });
1618
4692
 
1619
- expect(mockWebSocketManager.close).toHaveBeenCalledWith(false, 'Unregistering the SDK');
1620
- expect(webex.cc.agentConfig).toBeNull();
4693
+ it('should retain wxApp Mercury ownership when disconnect fails and retry cleanup', async () => {
4694
+ webex.cc['wxAppMercuryConnectedByCc'] = true;
4695
+ webex.internal.mercury.connected = true;
4696
+
4697
+ const mercuryDisconnectSpy = jest
4698
+ .spyOn(webex.internal.mercury, 'disconnect')
4699
+ .mockRejectedValueOnce(new Error('disconnect failed'))
4700
+ .mockResolvedValueOnce(undefined);
4701
+
4702
+ await webex.cc['releaseWxAppMercuryResources']();
4703
+
4704
+ expect(mercuryDisconnectSpy).toHaveBeenCalledTimes(1);
4705
+ expect(webex.cc['wxAppMercuryConnectedByCc']).toBe(true);
4706
+
4707
+ await webex.cc['releaseWxAppMercuryResources']();
4708
+
4709
+ expect(mercuryDisconnectSpy).toHaveBeenCalledTimes(2);
4710
+ expect(webex.cc['wxAppMercuryConnectedByCc']).toBe(false);
4711
+ });
4712
+
4713
+ it('should retain wxApp device ownership when unregister fails and retry cleanup', async () => {
4714
+ webex.cc['wxAppDeviceRegisteredByCc'] = true;
4715
+ webex.internal.device.registered = true;
4716
+
4717
+ const deviceUnregisterSpy = jest
4718
+ .spyOn(webex.internal.device, 'unregister')
4719
+ .mockRejectedValueOnce(new Error('unregister failed'))
4720
+ .mockResolvedValueOnce(undefined);
4721
+
4722
+ await webex.cc['releaseWxAppMercuryResources']();
4723
+
4724
+ expect(deviceUnregisterSpy).toHaveBeenCalledTimes(1);
4725
+ expect(webex.cc['wxAppDeviceRegisteredByCc']).toBe(true);
4726
+
4727
+ await webex.cc['releaseWxAppMercuryResources']();
4728
+
4729
+ expect(deviceUnregisterSpy).toHaveBeenCalledTimes(2);
4730
+ expect(webex.cc['wxAppDeviceRegisteredByCc']).toBe(false);
1621
4731
  });
1622
4732
 
1623
4733
  it('should handle errors during unregister and track metrics', async () => {
@@ -1634,11 +4744,20 @@ describe('webex.cc', () => {
1634
4744
  TASK_EVENTS.TASK_HYDRATE,
1635
4745
  expect.any(Function)
1636
4746
  );
4747
+ expect(mockTaskManager.off).toHaveBeenCalledWith(
4748
+ TASK_EVENTS.TASK_MULTI_LOGIN_HYDRATE,
4749
+ expect.any(Function)
4750
+ );
1637
4751
 
1638
4752
  expect(LoggerProxy.error).toHaveBeenCalledWith(`Error during deregister: ${mockError}`, {
1639
4753
  module: CC_FILE,
1640
4754
  method: 'deregister',
1641
4755
  });
4756
+ expect(mockTaskManager.clearAISummaryState).toHaveBeenCalled();
4757
+ expect(webex.cc.services.rtdWebSocketManager.off).toHaveBeenCalledWith(
4758
+ 'message',
4759
+ webex.cc['handleRTDWebsocketMessage']
4760
+ );
1642
4761
 
1643
4762
  expect(mockMetricsManager.trackEvent).toHaveBeenCalledWith(
1644
4763
  METRIC_EVENT_NAMES.WEBSOCKET_DEREGISTER_FAIL,
@@ -1656,7 +4775,7 @@ describe('webex.cc', () => {
1656
4775
 
1657
4776
  beforeEach(() => {
1658
4777
  emitSpy = jest.spyOn(webex.cc, 'emit');
1659
- messageCallback = mockWebSocketManager.on.mock.calls.find((c) => c[0] === 'message')[1];
4778
+ messageCallback = webex.cc['handleWebsocketMessage'];
1660
4779
  });
1661
4780
 
1662
4781
  it('should emit AGENT_STATION_LOGIN_SUCCESS on CC_EVENTS.AGENT_STATION_LOGIN_SUCCESS with mapped payload', () => {
@@ -1749,6 +4868,27 @@ describe('webex.cc', () => {
1749
4868
  });
1750
4869
  });
1751
4870
 
4871
+ it('does not emit an unknown server-controlled event type', () => {
4872
+ const payload = {
4873
+ type: 'UnhandledMessage',
4874
+ data: {foo: 'bar', type: 'MaliciousInjectedType'},
4875
+ };
4876
+
4877
+ messageCallback(JSON.stringify(payload));
4878
+
4879
+ expect(emitSpy).not.toHaveBeenCalledWith('MaliciousInjectedType', expect.anything());
4880
+ });
4881
+
4882
+ it('emits a known agent event type verbatim from data.type', () => {
4883
+ const sample = {foo: 'bar', type: CC_EVENTS.AGENT_STATE_CHANGE_SUCCESS};
4884
+
4885
+ messageCallback(
4886
+ JSON.stringify({type: CC_EVENTS.AGENT_STATE_CHANGE_SUCCESS, data: sample})
4887
+ );
4888
+
4889
+ expect(emitSpy).toHaveBeenCalledWith(CC_EVENTS.AGENT_STATE_CHANGE_SUCCESS, sample);
4890
+ });
4891
+
1752
4892
  it('should call webCallingService.setLoginOption with correct deviceType on AGENT_STATION_LOGIN_SUCCESS', () => {
1753
4893
  const setLoginOptionSpy = jest.spyOn(webex.cc.webCallingService, 'setLoginOption');
1754
4894
  const deviceType = LoginOption.EXTENSION;
@@ -1866,6 +5006,55 @@ describe('webex.cc', () => {
1866
5006
  expect(result).toEqual(mockResp);
1867
5007
  });
1868
5008
 
5009
+ it('should preserve enableWxBetterTogether init flag across profile update logout/login', async () => {
5010
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
5011
+ webex.internal.device = {userId: 'user-123', url: 'https://wdm.example.com/devices/dev-1'};
5012
+ webex.cc.agentConfig = {
5013
+ ...webex.cc.agentConfig,
5014
+ agentId: 'agentId',
5015
+ webRtcEnabled: false,
5016
+ loginVoiceOptions: ['BROWSER', 'EXTENSION'],
5017
+ } as Profile;
5018
+ webex.cc.webCallingService.loginOption = LoginOption.BROWSER;
5019
+ webex.cc.webCallingService.setLoginOption = jest.fn((loginOption: LoginOption) => {
5020
+ webex.cc.webCallingService.loginOption = loginOption;
5021
+ });
5022
+ webex.cc['webexCrossClientService'].answerCallsState = true;
5023
+
5024
+ const publishSpy = jest
5025
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
5026
+ .mockResolvedValue(undefined);
5027
+ jest
5028
+ .spyOn(webex.cc['wxAppTelephonyMercurySync'], 'subscribe')
5029
+ .mockImplementation(() => {});
5030
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
5031
+ jest.spyOn(webex.cc as any, 'releaseWxAppMercuryResources').mockResolvedValue(undefined);
5032
+
5033
+ jest.spyOn(webex.cc.services.agent, 'logout').mockResolvedValue({
5034
+ trackingId: 'track-logout',
5035
+ } as StationLogoutResponse);
5036
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
5037
+ data: {
5038
+ agentId: 'agentId',
5039
+ teamId: 'teamId',
5040
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
5041
+ },
5042
+ trackingId: 'track-login',
5043
+ } as StationLoginSuccess);
5044
+
5045
+ webex.internal.mercury.connected = true;
5046
+
5047
+ await webex.cc.updateAgentProfile({
5048
+ teamId: 'teamId',
5049
+ loginOption: LoginOption.EXTENSION,
5050
+ dialNumber: '1001',
5051
+ });
5052
+
5053
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(true);
5054
+ expect(publishSpy).toHaveBeenCalledWith(false, {userId: 'user-123', trackPublishMetrics: true});
5055
+ expect(publishSpy).toHaveBeenCalledWith(true, {userId: 'user-123', trackPublishMetrics: true});
5056
+ });
5057
+
1869
5058
  it('should use provided teamId if passed in payload', async () => {
1870
5059
  const dataWithTeam = {
1871
5060
  teamId: 'newTeam',
@@ -2102,16 +5291,15 @@ describe('webex.cc', () => {
2102
5291
  mockError.details = {
2103
5292
  trackingId: 'test-tracking-id',
2104
5293
  orgId: 'mockOrgId',
2105
- error: 'Service error',
5294
+ type: 'OutdialAniEntriesFailed',
5295
+ data: {
5296
+ reason: 'Detailed service error',
5297
+ },
2106
5298
  };
2107
5299
 
2108
5300
  // Mock the service call to throw an error
2109
5301
  webex.cc.services.config.getOutdialAniEntries.mockRejectedValue(mockError);
2110
5302
 
2111
- // Mock getErrorDetails to return a detailed error
2112
- const detailedError = new Error('Detailed service error');
2113
- getErrorDetailsSpy.mockReturnValue({error: detailedError});
2114
-
2115
5303
  await expect(webex.cc.getOutdialAniEntries(mockParams)).rejects.toThrow(
2116
5304
  'Detailed service error'
2117
5305
  );
@@ -2136,9 +5324,20 @@ describe('webex.cc', () => {
2136
5324
  trackingId: 'test-tracking-id',
2137
5325
  }
2138
5326
  );
5327
+ expect(LoggerProxy.error).toHaveBeenCalledWith(
5328
+ 'getOutdialAniEntries failed with reason: Detailed service error',
5329
+ {
5330
+ module: CC_FILE,
5331
+ method: 'getOutdialAniEntries',
5332
+ trackingId: 'test-tracking-id',
5333
+ }
5334
+ );
2139
5335
 
2140
5336
  // Verify getErrorDetails was called
2141
5337
  expect(getErrorDetailsSpy).toHaveBeenCalledWith(mockError, 'getOutdialAniEntries', CC_FILE);
5338
+ expect(mockWebexRequest.uploadLogs).toHaveBeenCalledWith({
5339
+ correlationId: 'test-tracking-id',
5340
+ });
2142
5341
  });
2143
5342
 
2144
5343
  it('should throw error when orgId is not found', async () => {
@@ -2221,8 +5420,7 @@ describe('webex.cc', () => {
2221
5420
  });
2222
5421
 
2223
5422
  it('should handle error during acceptPreviewContact', async () => {
2224
- getErrorDetailsSpy.mockRestore();
2225
- getErrorDetailsSpy = jest.spyOn(Utils, 'getErrorDetails');
5423
+ getErrorDetailsSpy.mockClear();
2226
5424
 
2227
5425
  const error = {
2228
5426
  details: {
@@ -2248,6 +5446,454 @@ describe('webex.cc', () => {
2248
5446
  {module: CC_FILE, method: 'acceptPreviewContact', trackingId: error.details.trackingId}
2249
5447
  );
2250
5448
  expect(getErrorDetailsSpy).toHaveBeenCalledWith(error, 'acceptPreviewContact', CC_FILE);
5449
+ expect(mockWebexRequest.uploadLogs).toHaveBeenCalledWith({
5450
+ correlationId: error.details.trackingId,
5451
+ });
5452
+ });
5453
+ });
5454
+
5455
+ describe('skipPreviewContact', () => {
5456
+ const previewPayload = {
5457
+ interactionId: 'interaction-123',
5458
+ campaignId: 'campaign-456',
5459
+ };
5460
+
5461
+ it('should skip preview contact successfully', async () => {
5462
+ const mockResponse = {trackingId: 'track-123'} as AgentContact;
5463
+
5464
+ const skipPreviewContactMock = jest
5465
+ .spyOn(webex.cc.services.dialer, 'skipPreviewContact')
5466
+ .mockResolvedValue(mockResponse);
5467
+
5468
+ const result = await webex.cc.skipPreviewContact(previewPayload);
5469
+
5470
+ expect(LoggerProxy.info).toHaveBeenCalledWith('Skipping campaign preview contact', {
5471
+ module: CC_FILE,
5472
+ method: 'skipPreviewContact',
5473
+ });
5474
+ expect(LoggerProxy.log).toHaveBeenCalledWith(
5475
+ 'Campaign preview contact skipped successfully',
5476
+ {
5477
+ module: CC_FILE,
5478
+ method: 'skipPreviewContact',
5479
+ trackingId: 'track-123',
5480
+ interactionId: previewPayload.interactionId,
5481
+ }
5482
+ );
5483
+
5484
+ expect(skipPreviewContactMock).toHaveBeenCalledWith({data: previewPayload});
5485
+ expect(result).toEqual(mockResponse);
5486
+ });
5487
+
5488
+ it('should handle error during skipPreviewContact', async () => {
5489
+ getErrorDetailsSpy.mockClear();
5490
+
5491
+ const error = {
5492
+ details: {
5493
+ trackingId: '1234',
5494
+ data: {
5495
+ reason: 'Error while performing skipPreviewContact',
5496
+ },
5497
+ },
5498
+ };
5499
+
5500
+ jest.spyOn(webex.cc.services.dialer, 'skipPreviewContact').mockRejectedValue(error);
5501
+
5502
+ await expect(webex.cc.skipPreviewContact(previewPayload)).rejects.toThrow(
5503
+ error.details.data.reason
5504
+ );
5505
+
5506
+ expect(LoggerProxy.info).toHaveBeenCalledWith('Skipping campaign preview contact', {
5507
+ module: CC_FILE,
5508
+ method: 'skipPreviewContact',
5509
+ });
5510
+ expect(LoggerProxy.error).toHaveBeenCalledWith(
5511
+ `skipPreviewContact failed with reason: ${error.details.data.reason}`,
5512
+ {module: CC_FILE, method: 'skipPreviewContact', trackingId: error.details.trackingId}
5513
+ );
5514
+ expect(getErrorDetailsSpy).toHaveBeenCalledWith(error, 'skipPreviewContact', CC_FILE);
5515
+ expect(mockWebexRequest.uploadLogs).toHaveBeenCalledWith({
5516
+ correlationId: error.details.trackingId,
5517
+ });
5518
+ });
5519
+ });
5520
+
5521
+ describe('removePreviewContact', () => {
5522
+ const previewPayload = {
5523
+ interactionId: 'interaction-123',
5524
+ campaignId: 'campaign-456',
5525
+ };
5526
+
5527
+ it('should remove preview contact successfully', async () => {
5528
+ const mockResponse = {trackingId: 'track-123'} as AgentContact;
5529
+
5530
+ const removePreviewContactMock = jest
5531
+ .spyOn(webex.cc.services.dialer, 'removePreviewContact')
5532
+ .mockResolvedValue(mockResponse);
5533
+
5534
+ const result = await webex.cc.removePreviewContact(previewPayload);
5535
+
5536
+ expect(LoggerProxy.info).toHaveBeenCalledWith('Removing campaign preview contact', {
5537
+ module: CC_FILE,
5538
+ method: 'removePreviewContact',
5539
+ });
5540
+ expect(LoggerProxy.log).toHaveBeenCalledWith(
5541
+ 'Campaign preview contact removed successfully',
5542
+ {
5543
+ module: CC_FILE,
5544
+ method: 'removePreviewContact',
5545
+ trackingId: 'track-123',
5546
+ interactionId: previewPayload.interactionId,
5547
+ }
5548
+ );
5549
+
5550
+ expect(removePreviewContactMock).toHaveBeenCalledWith({data: previewPayload});
5551
+ expect(result).toEqual(mockResponse);
5552
+ });
5553
+
5554
+ it('should handle error during removePreviewContact', async () => {
5555
+ getErrorDetailsSpy.mockClear();
5556
+
5557
+ const error = {
5558
+ details: {
5559
+ trackingId: '1234',
5560
+ data: {
5561
+ reason: 'Error while performing removePreviewContact',
5562
+ },
5563
+ },
5564
+ };
5565
+
5566
+ jest.spyOn(webex.cc.services.dialer, 'removePreviewContact').mockRejectedValue(error);
5567
+
5568
+ await expect(webex.cc.removePreviewContact(previewPayload)).rejects.toThrow(
5569
+ error.details.data.reason
5570
+ );
5571
+
5572
+ expect(LoggerProxy.info).toHaveBeenCalledWith('Removing campaign preview contact', {
5573
+ module: CC_FILE,
5574
+ method: 'removePreviewContact',
5575
+ });
5576
+ expect(LoggerProxy.error).toHaveBeenCalledWith(
5577
+ `removePreviewContact failed with reason: ${error.details.data.reason}`,
5578
+ {module: CC_FILE, method: 'removePreviewContact', trackingId: error.details.trackingId}
5579
+ );
5580
+ expect(getErrorDetailsSpy).toHaveBeenCalledWith(error, 'removePreviewContact', CC_FILE);
5581
+ expect(mockWebexRequest.uploadLogs).toHaveBeenCalledWith({
5582
+ correlationId: error.details.trackingId,
5583
+ });
5584
+ });
5585
+ });
5586
+
5587
+ describe('private setManageWebexCallingInWxcc (runtime toggle impl)', () => {
5588
+ beforeEach(() => {
5589
+ webex.internal.device = {
5590
+ userId: 'user-123',
5591
+ registered: false,
5592
+ register: jest.fn().mockResolvedValue(undefined),
5593
+ unregister: jest.fn().mockResolvedValue(undefined),
5594
+ };
5595
+ webex.internal.mercury = {
5596
+ connected: false,
5597
+ connect: jest.fn().mockResolvedValue(undefined),
5598
+ disconnect: jest.fn().mockResolvedValue(undefined),
5599
+ };
5600
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'subscribe').mockImplementation(() => {});
5601
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
5602
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: false};
5603
+ webex.cc['agentConfig'] = {
5604
+ agentId: 'agent-123',
5605
+ deviceType: LoginOption.EXTENSION,
5606
+ } as Profile;
5607
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
5608
+ webex.cc.webCallingService.setLoginOption = jest.fn((loginOption: LoginOption) => {
5609
+ webex.cc.webCallingService.loginOption = loginOption;
5610
+ });
5611
+ });
5612
+
5613
+ afterEach(() => {
5614
+ jest.restoreAllMocks();
5615
+ });
5616
+
5617
+ it('should update config, task manager, and publish usersub when enabled', async () => {
5618
+ const publishSpy = jest
5619
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
5620
+ .mockResolvedValue(undefined);
5621
+
5622
+ await (webex.cc as any).setManageWebexCallingInWxcc(true);
5623
+
5624
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(true);
5625
+ expect(mockTaskManager.applyEnableWxBetterTogether).toHaveBeenCalledWith(true);
5626
+ expect(publishSpy).toHaveBeenCalledWith(true, {userId: 'user-123', trackPublishMetrics: true});
5627
+ expect(mockTaskManager.refreshWxAppOfferObservabilityForAllTasks).toHaveBeenCalled();
5628
+ });
5629
+
5630
+ it('should publish false and update config when disabled after wxApp was enabled', async () => {
5631
+ webex.internal.device = {
5632
+ userId: 'user-123',
5633
+ url: 'https://wdm.example.com/devices/dev-1',
5634
+ };
5635
+ webex.request = jest.fn().mockResolvedValue({body: {}});
5636
+
5637
+ await (webex.cc as any).setManageWebexCallingInWxcc(true);
5638
+
5639
+ const publishSpy = jest
5640
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
5641
+ .mockResolvedValue(undefined);
5642
+
5643
+ await (webex.cc as any).setManageWebexCallingInWxcc(false);
5644
+
5645
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(false);
5646
+ expect(mockTaskManager.applyEnableWxBetterTogether).toHaveBeenCalledWith(false);
5647
+ expect(publishSpy).toHaveBeenCalledWith(false, {userId: 'user-123', trackPublishMetrics: true});
5648
+ });
5649
+
5650
+ it('should skip usersub publish when disabling without prior wxApp publish', async () => {
5651
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
5652
+ const publishSpy = jest
5653
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
5654
+ .mockResolvedValue(undefined);
5655
+
5656
+ await (webex.cc as any).setManageWebexCallingInWxcc(false);
5657
+
5658
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(false);
5659
+ expect(mockTaskManager.applyEnableWxBetterTogether).toHaveBeenCalledWith(false);
5660
+ expect(publishSpy).not.toHaveBeenCalled();
5661
+ });
5662
+
5663
+ it('should throw when enabling before login', async () => {
5664
+ webex.internal.device = undefined;
5665
+
5666
+ await expect((webex.cc as any).setManageWebexCallingInWxcc(true)).rejects.toThrow(
5667
+ 'Cannot publish answer-calls-on-wxcc: user is not logged in'
5668
+ );
5669
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(false);
5670
+ expect(mockTaskManager.applyEnableWxBetterTogether).not.toHaveBeenCalled();
5671
+ });
5672
+
5673
+ it('should throw when enabling on BROWSER (Desktop) login', async () => {
5674
+ webex.cc['agentConfig'] = {deviceType: LoginOption.BROWSER} as Profile;
5675
+ webex.cc.webCallingService.loginOption = LoginOption.BROWSER;
5676
+ const publishSpy = jest
5677
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
5678
+ .mockResolvedValue(undefined);
5679
+
5680
+ await expect((webex.cc as any).setManageWebexCallingInWxcc(true)).rejects.toThrow(
5681
+ 'setManageWebexCallingInWxcc requires EXTENSION or AGENT_DN station login'
5682
+ );
5683
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(false);
5684
+ expect(mockTaskManager.applyEnableWxBetterTogether).not.toHaveBeenCalled();
5685
+ expect(publishSpy).not.toHaveBeenCalled();
5686
+ });
5687
+
5688
+ it('should throw when enabling before station login', async () => {
5689
+ webex.cc['agentConfig'] = undefined as unknown as Profile;
5690
+ webex.cc.webCallingService.loginOption = undefined as unknown as LoginOption;
5691
+ const publishSpy = jest
5692
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
5693
+ .mockResolvedValue(undefined);
5694
+
5695
+ await expect((webex.cc as any).setManageWebexCallingInWxcc(true)).rejects.toThrow(
5696
+ 'setManageWebexCallingInWxcc requires EXTENSION or AGENT_DN station login'
5697
+ );
5698
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(false);
5699
+ expect(mockTaskManager.applyEnableWxBetterTogether).not.toHaveBeenCalled();
5700
+ expect(publishSpy).not.toHaveBeenCalled();
5701
+ });
5702
+
5703
+ it('should throw when webCallingService is BROWSER even if agentConfig deviceType is stale', async () => {
5704
+ webex.cc['agentConfig'] = {deviceType: LoginOption.EXTENSION} as Profile;
5705
+ webex.cc.webCallingService.loginOption = LoginOption.BROWSER;
5706
+ const publishSpy = jest
5707
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
5708
+ .mockResolvedValue(undefined);
5709
+
5710
+ await expect((webex.cc as any).setManageWebexCallingInWxcc(true)).rejects.toThrow(
5711
+ 'setManageWebexCallingInWxcc requires EXTENSION or AGENT_DN station login'
5712
+ );
5713
+ expect(publishSpy).not.toHaveBeenCalled();
5714
+ });
5715
+
5716
+ it('should publish usersub when enabling on AGENT_DN login', async () => {
5717
+ webex.cc['agentConfig'] = {
5718
+ agentId: 'agent-123',
5719
+ deviceType: LoginOption.AGENT_DN,
5720
+ } as Profile;
5721
+ const publishSpy = jest
5722
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
5723
+ .mockResolvedValue(undefined);
5724
+
5725
+ await (webex.cc as any).setManageWebexCallingInWxcc(true);
5726
+
5727
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(true);
5728
+ expect(publishSpy).toHaveBeenCalledWith(true, {userId: 'user-123', trackPublishMetrics: true});
5729
+ });
5730
+
5731
+ it('should no-op usersub publish when disabling before login', async () => {
5732
+ webex.internal.device = undefined;
5733
+ const publishSpy = jest
5734
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
5735
+ .mockResolvedValue(undefined);
5736
+
5737
+ await (webex.cc as any).setManageWebexCallingInWxcc(false);
5738
+
5739
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(false);
5740
+ expect(mockTaskManager.applyEnableWxBetterTogether).toHaveBeenCalledWith(false);
5741
+ expect(publishSpy).not.toHaveBeenCalled();
5742
+ });
5743
+
5744
+ it('should subscribe to wxApp Mercury mute sync when enabled', async () => {
5745
+ webex.cc['agentConfig'] = {agentId: 'agent-123'} as Profile;
5746
+ webex.internal.device = {
5747
+ ...webex.internal.device,
5748
+ registered: true,
5749
+ register: jest.fn().mockResolvedValue(undefined),
5750
+ };
5751
+ webex.internal.mercury.connected = true;
5752
+ webex.internal.mercury.connect = jest.fn().mockResolvedValue(undefined);
5753
+ jest
5754
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
5755
+ .mockResolvedValue(undefined);
5756
+ const subscribeSpy = jest
5757
+ .spyOn(webex.cc['wxAppTelephonyMercurySync'], 'subscribe')
5758
+ .mockImplementation(() => {});
5759
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
5760
+
5761
+ await (webex.cc as any).setManageWebexCallingInWxcc(true);
5762
+
5763
+ expect(subscribeSpy).toHaveBeenCalledWith('agent-123', expect.any(Function));
5764
+ });
5765
+
5766
+ it('should unsubscribe from wxApp Mercury mute sync when disabled', async () => {
5767
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
5768
+ jest
5769
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
5770
+ .mockResolvedValue(undefined);
5771
+ const unsubscribeSpy = jest
5772
+ .spyOn(webex.cc['wxAppTelephonyMercurySync'], 'unsubscribe')
5773
+ .mockImplementation(() => {});
5774
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
5775
+
5776
+ await (webex.cc as any).setManageWebexCallingInWxcc(false);
5777
+
5778
+ expect(unsubscribeSpy).toHaveBeenCalled();
5779
+ });
5780
+
5781
+ it('should register device and connect mercury when enabling wxApp sync', async () => {
5782
+ webex.cc['agentConfig'] = {agentId: 'agent-123'} as Profile;
5783
+ webex.internal.device = {
5784
+ userId: 'user-123',
5785
+ registered: false,
5786
+ register: jest.fn().mockResolvedValue(undefined),
5787
+ };
5788
+ webex.internal.mercury = {
5789
+ connected: false,
5790
+ connect: jest.fn().mockResolvedValue(undefined),
5791
+ };
5792
+ jest
5793
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
5794
+ .mockResolvedValue(undefined);
5795
+ const subscribeSpy = jest
5796
+ .spyOn(webex.cc['wxAppTelephonyMercurySync'], 'subscribe')
5797
+ .mockImplementation(() => {});
5798
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
5799
+
5800
+ await (webex.cc as any).setManageWebexCallingInWxcc(true);
5801
+
5802
+ expect(webex.internal.device.register).toHaveBeenCalled();
5803
+ expect(webex.internal.mercury.connect).toHaveBeenCalled();
5804
+ expect(subscribeSpy).toHaveBeenCalledWith('agent-123', expect.any(Function));
5805
+ });
5806
+
5807
+ it('should rollback config and task manager when usersub publish fails', async () => {
5808
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: false};
5809
+ jest
5810
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
5811
+ .mockRejectedValue(new Error('usersub failed'));
5812
+
5813
+ await expect((webex.cc as any).setManageWebexCallingInWxcc(true)).rejects.toThrow('usersub failed');
5814
+
5815
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(false);
5816
+ expect(mockTaskManager.applyEnableWxBetterTogether).toHaveBeenCalledWith(true);
5817
+ expect(mockTaskManager.applyEnableWxBetterTogether).toHaveBeenLastCalledWith(false);
5818
+ });
5819
+
5820
+ it('should rollback config and release Mercury resources when Mercury connect fails', async () => {
5821
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: false};
5822
+ const publishSpy = jest
5823
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
5824
+ .mockResolvedValue(undefined);
5825
+ jest
5826
+ .spyOn(webex.cc as any, 'ensureWxAppMercuryConnected')
5827
+ .mockRejectedValue(new Error('mercury connect failed'));
5828
+ const releaseSpy = jest
5829
+ .spyOn(webex.cc as any, 'releaseWxAppMercuryResources')
5830
+ .mockResolvedValue(undefined);
5831
+ const unsubscribeSpy = jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'unsubscribe');
5832
+ const teardownSpy = jest.spyOn(webex.cc['webexCrossClientService'], 'teardown');
5833
+
5834
+ await expect((webex.cc as any).setManageWebexCallingInWxcc(true)).rejects.toThrow(
5835
+ 'mercury connect failed'
5836
+ );
5837
+
5838
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(false);
5839
+ expect(mockTaskManager.applyEnableWxBetterTogether).toHaveBeenLastCalledWith(false);
5840
+ expect(publishSpy).not.toHaveBeenCalled();
5841
+ expect(teardownSpy).not.toHaveBeenCalled();
5842
+ expect(unsubscribeSpy).toHaveBeenCalled();
5843
+ expect(releaseSpy).toHaveBeenCalled();
5844
+ });
5845
+
5846
+ it('should schedule compensating false retry when rollback publish fails after enable error', async () => {
5847
+ jest.useFakeTimers();
5848
+ try {
5849
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
5850
+ webex.internal.device = {userId: 'user-123', url: 'https://wdm.example.com/devices/dev-1'};
5851
+ webex.cc.agentConfig = {
5852
+ agentId: 'agent-123',
5853
+ deviceType: LoginOption.EXTENSION,
5854
+ };
5855
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
5856
+
5857
+ const publishSpy = jest
5858
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
5859
+ .mockResolvedValueOnce(undefined)
5860
+ .mockRejectedValueOnce(new Error('compensating false failed'))
5861
+ .mockResolvedValue(undefined);
5862
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'subscribe').mockImplementation(() => {});
5863
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
5864
+ jest
5865
+ .spyOn(webex.cc as any, 'ensureWxAppMercuryConnected')
5866
+ .mockResolvedValue(undefined);
5867
+ jest
5868
+ .spyOn(webex.cc as any, 'releaseWxAppMercuryResources')
5869
+ .mockResolvedValue(undefined);
5870
+ jest
5871
+ .spyOn(mockTaskManager, 'syncWxAppMuteFromCallDetailsForAllTasks')
5872
+ .mockImplementation(() => {
5873
+ throw new Error('sync failed');
5874
+ });
5875
+ const scheduleRetrySpy = jest.spyOn(
5876
+ webex.cc as any,
5877
+ 'scheduleCompensatingFalsePublishRetry'
5878
+ );
5879
+
5880
+ await expect((webex.cc as any).setManageWebexCallingInWxcc(true)).rejects.toThrow(
5881
+ 'sync failed'
5882
+ );
5883
+
5884
+ expect(scheduleRetrySpy).toHaveBeenCalled();
5885
+ expect(publishSpy).toHaveBeenCalledTimes(2);
5886
+ expect(publishSpy).toHaveBeenNthCalledWith(1, true, {userId: 'user-123', trackPublishMetrics: true});
5887
+ expect(publishSpy).toHaveBeenNthCalledWith(2, false, {userId: 'user-123', trackPublishMetrics: true});
5888
+
5889
+ jest.advanceTimersByTime(30_000);
5890
+ await publishSpy.mock.results[2]?.value;
5891
+
5892
+ expect(publishSpy).toHaveBeenCalledTimes(3);
5893
+ expect(publishSpy).toHaveBeenLastCalledWith(false, {userId: 'user-123', trackPublishMetrics: true});
5894
+ } finally {
5895
+ jest.useRealTimers();
5896
+ }
2251
5897
  });
2252
5898
  });
2253
5899
  });