@webex/contact-center 3.12.0-webex-services-ready.4 → 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 (250) hide show
  1. package/.sdd/manifest.json +24 -13
  2. package/ai-docs/ARCHITECTURE.md +1 -1
  3. package/ai-docs/CONTRACTS.md +19 -3
  4. package/ai-docs/SECURITY.md +1 -1
  5. package/ai-docs/SERVICE_STATE.md +4 -0
  6. package/ai-docs/contact-center-spec.md +50 -6
  7. package/ai-docs/features/consult-transfer-list-policy/spec/feature-spec.md +362 -0
  8. package/ai-docs/features/contact-owner-change-refactor.md +78 -0
  9. package/dist/cc.js +757 -22
  10. package/dist/cc.js.map +1 -1
  11. package/dist/config.js +7 -0
  12. package/dist/config.js.map +1 -1
  13. package/dist/constants.js +23 -2
  14. package/dist/constants.js.map +1 -1
  15. package/dist/index.js +34 -12
  16. package/dist/index.js.map +1 -1
  17. package/dist/metrics/MetricsManager.js +16 -0
  18. package/dist/metrics/MetricsManager.js.map +1 -1
  19. package/dist/metrics/behavioral-events.js +110 -0
  20. package/dist/metrics/behavioral-events.js.map +1 -1
  21. package/dist/metrics/constants.js +33 -0
  22. package/dist/metrics/constants.js.map +1 -1
  23. package/dist/services/AddressBook.js +18 -15
  24. package/dist/services/AddressBook.js.map +1 -1
  25. package/dist/services/AnswerCallOnWebexService.js +202 -0
  26. package/dist/services/AnswerCallOnWebexService.js.map +1 -0
  27. package/dist/services/ApiAiAssistant.js +221 -11
  28. package/dist/services/ApiAiAssistant.js.map +1 -1
  29. package/dist/services/EntryPoint.js +46 -68
  30. package/dist/services/EntryPoint.js.map +1 -1
  31. package/dist/services/Queue.js +27 -22
  32. package/dist/services/Queue.js.map +1 -1
  33. package/dist/services/WebCallingService.js +10 -2
  34. package/dist/services/WebCallingService.js.map +1 -1
  35. package/dist/services/WebexCrossClientService.js +225 -0
  36. package/dist/services/WebexCrossClientService.js.map +1 -0
  37. package/dist/services/WxAppTelephonyMercurySync.js +111 -0
  38. package/dist/services/WxAppTelephonyMercurySync.js.map +1 -0
  39. package/dist/services/config/Util.js +46 -46
  40. package/dist/services/config/Util.js.map +1 -1
  41. package/dist/services/config/constants.js +34 -77
  42. package/dist/services/config/constants.js.map +1 -1
  43. package/dist/services/config/index.js +100 -226
  44. package/dist/services/config/index.js.map +1 -1
  45. package/dist/services/config/types.js +51 -18
  46. package/dist/services/config/types.js.map +1 -1
  47. package/dist/services/constants.js +11 -1
  48. package/dist/services/constants.js.map +1 -1
  49. package/dist/services/core/Err.js.map +1 -1
  50. package/dist/services/core/Utils.js +25 -1
  51. package/dist/services/core/Utils.js.map +1 -1
  52. package/dist/services/core/WebexRequest.js +6 -2
  53. package/dist/services/core/WebexRequest.js.map +1 -1
  54. package/dist/services/core/aqm-reqs.js +17 -11
  55. package/dist/services/core/aqm-reqs.js.map +1 -1
  56. package/dist/services/core/constants.js +9 -1
  57. package/dist/services/core/constants.js.map +1 -1
  58. package/dist/services/core/types.js.map +1 -1
  59. package/dist/services/core/websocket/WebSocketManager.js +17 -1
  60. package/dist/services/core/websocket/WebSocketManager.js.map +1 -1
  61. package/dist/services/task/Task.js +275 -8
  62. package/dist/services/task/Task.js.map +1 -1
  63. package/dist/services/task/TaskFactory.js +11 -6
  64. package/dist/services/task/TaskFactory.js.map +1 -1
  65. package/dist/services/task/TaskManager.js +590 -42
  66. package/dist/services/task/TaskManager.js.map +1 -1
  67. package/dist/services/task/TaskUtils.js +11 -1
  68. package/dist/services/task/TaskUtils.js.map +1 -1
  69. package/dist/services/task/WebexCallingUtils.js +70 -0
  70. package/dist/services/task/WebexCallingUtils.js.map +1 -0
  71. package/dist/services/task/constants.js +14 -2
  72. package/dist/services/task/constants.js.map +1 -1
  73. package/dist/services/task/contact.js +29 -0
  74. package/dist/services/task/contact.js.map +1 -1
  75. package/dist/services/task/digital/Digital.js +4 -3
  76. package/dist/services/task/digital/Digital.js.map +1 -1
  77. package/dist/services/task/state-machine/TaskStateMachine.js +162 -53
  78. package/dist/services/task/state-machine/TaskStateMachine.js.map +1 -1
  79. package/dist/services/task/state-machine/actions.js +6 -1
  80. package/dist/services/task/state-machine/actions.js.map +1 -1
  81. package/dist/services/task/state-machine/guards.js +7 -10
  82. package/dist/services/task/state-machine/guards.js.map +1 -1
  83. package/dist/services/task/state-machine/types.js.map +1 -1
  84. package/dist/services/task/state-machine/uiControlsComputer.js +118 -18
  85. package/dist/services/task/state-machine/uiControlsComputer.js.map +1 -1
  86. package/dist/services/task/types.js +47 -1
  87. package/dist/services/task/types.js.map +1 -1
  88. package/dist/services/task/voice/Voice.js +477 -17
  89. package/dist/services/task/voice/Voice.js.map +1 -1
  90. package/dist/services/task/voice/WebRTC.js +6 -3
  91. package/dist/services/task/voice/WebRTC.js.map +1 -1
  92. package/dist/services/task/voice/wxAppOfferObservability.js +145 -0
  93. package/dist/services/task/voice/wxAppOfferObservability.js.map +1 -0
  94. package/dist/services/task/voice/wxAppVoiceMethods.js +395 -0
  95. package/dist/services/task/voice/wxAppVoiceMethods.js.map +1 -0
  96. package/dist/services/wxAppDiagnosticLogging.js +159 -0
  97. package/dist/services/wxAppDiagnosticLogging.js.map +1 -0
  98. package/dist/services/wxAppTelephonyUtils.js +19 -0
  99. package/dist/services/wxAppTelephonyUtils.js.map +1 -0
  100. package/dist/types/cc.d.ts +102 -8
  101. package/dist/types/config.d.ts +7 -0
  102. package/dist/types/constants.d.ts +21 -0
  103. package/dist/types/index.d.ts +34 -15
  104. package/dist/types/metrics/MetricsManager.d.ts +6 -0
  105. package/dist/types/metrics/constants.d.ts +31 -0
  106. package/dist/types/services/AddressBook.d.ts +2 -1
  107. package/dist/types/services/AnswerCallOnWebexService.d.ts +38 -0
  108. package/dist/types/services/ApiAiAssistant.d.ts +48 -4
  109. package/dist/types/services/EntryPoint.d.ts +7 -5
  110. package/dist/types/services/Queue.d.ts +5 -3
  111. package/dist/types/services/WebexCrossClientService.d.ts +32 -0
  112. package/dist/types/services/WxAppTelephonyMercurySync.d.ts +28 -0
  113. package/dist/types/services/config/Util.d.ts +4 -8
  114. package/dist/types/services/config/constants.d.ts +28 -76
  115. package/dist/types/services/config/index.d.ts +16 -64
  116. package/dist/types/services/config/types.d.ts +146 -173
  117. package/dist/types/services/constants.d.ts +9 -0
  118. package/dist/types/services/core/Err.d.ts +2 -0
  119. package/dist/types/services/core/Utils.d.ts +10 -0
  120. package/dist/types/services/core/WebexRequest.d.ts +1 -0
  121. package/dist/types/services/core/constants.d.ts +7 -0
  122. package/dist/types/services/core/types.d.ts +2 -0
  123. package/dist/types/services/task/Task.d.ts +34 -5
  124. package/dist/types/services/task/TaskFactory.d.ts +4 -2
  125. package/dist/types/services/task/TaskUtils.d.ts +6 -0
  126. package/dist/types/services/task/WebexCallingUtils.d.ts +11 -0
  127. package/dist/types/services/task/constants.d.ts +12 -0
  128. package/dist/types/services/task/contact.d.ts +4 -0
  129. package/dist/types/services/task/digital/Digital.d.ts +4 -3
  130. package/dist/types/services/task/state-machine/TaskStateMachine.d.ts +304 -56
  131. package/dist/types/services/task/state-machine/guards.d.ts +6 -5
  132. package/dist/types/services/task/state-machine/types.d.ts +9 -1
  133. package/dist/types/services/task/types.d.ts +192 -5
  134. package/dist/types/services/task/voice/Voice.d.ts +68 -11
  135. package/dist/types/services/task/voice/WebRTC.d.ts +5 -4
  136. package/dist/types/services/task/voice/wxAppOfferObservability.d.ts +39 -0
  137. package/dist/types/services/task/voice/wxAppVoiceMethods.d.ts +68 -0
  138. package/dist/types/services/wxAppDiagnosticLogging.d.ts +63 -0
  139. package/dist/types/services/wxAppTelephonyUtils.d.ts +5 -0
  140. package/dist/types/types.d.ts +80 -13
  141. package/dist/types/utils/PageCache.d.ts +20 -3
  142. package/dist/types.js +54 -8
  143. package/dist/types.js.map +1 -1
  144. package/dist/utils/PageCache.js +19 -5
  145. package/dist/utils/PageCache.js.map +1 -1
  146. package/dist/webex.js +9 -1
  147. package/dist/webex.js.map +1 -1
  148. package/package.json +10 -9
  149. package/src/cc.ts +969 -38
  150. package/src/config.ts +7 -0
  151. package/src/constants.ts +24 -0
  152. package/src/index.ts +39 -10
  153. package/src/metrics/MetricsManager.ts +16 -0
  154. package/src/metrics/ai-docs/metrics-spec.md +138 -21
  155. package/src/metrics/behavioral-events.ts +112 -0
  156. package/src/metrics/constants.ts +36 -0
  157. package/src/services/AddressBook.ts +17 -6
  158. package/src/services/AnswerCallOnWebexService.ts +239 -0
  159. package/src/services/ApiAiAssistant.ts +297 -13
  160. package/src/services/EntryPoint.ts +59 -60
  161. package/src/services/Queue.ts +29 -12
  162. package/src/services/WebCallingService.ts +16 -2
  163. package/src/services/WebexCrossClientService.ts +298 -0
  164. package/src/services/WxAppTelephonyMercurySync.ts +142 -0
  165. package/src/services/agent/ai-docs/AGENTS.md +1 -1
  166. package/src/services/agent/ai-docs/agent-spec.md +1 -0
  167. package/src/services/ai-docs/AGENTS.md +10 -10
  168. package/src/services/ai-docs/services-spec.md +25 -5
  169. package/src/services/config/Util.ts +52 -82
  170. package/src/services/config/ai-docs/AGENTS.md +35 -40
  171. package/src/services/config/ai-docs/ARCHITECTURE.md +90 -103
  172. package/src/services/config/ai-docs/config-spec.md +132 -132
  173. package/src/services/config/constants.ts +39 -85
  174. package/src/services/config/index.ts +116 -277
  175. package/src/services/config/types.ts +140 -195
  176. package/src/services/constants.ts +10 -0
  177. package/src/services/core/Err.ts +1 -0
  178. package/src/services/core/Utils.ts +28 -0
  179. package/src/services/core/WebexRequest.ts +3 -1
  180. package/src/services/core/ai-docs/core-spec.md +25 -11
  181. package/src/services/core/aqm-reqs.ts +18 -12
  182. package/src/services/core/constants.ts +8 -0
  183. package/src/services/core/types.ts +33 -1
  184. package/src/services/core/websocket/WebSocketManager.ts +26 -2
  185. package/src/services/task/Task.ts +386 -12
  186. package/src/services/task/TaskFactory.ts +33 -6
  187. package/src/services/task/TaskManager.ts +857 -41
  188. package/src/services/task/TaskUtils.ts +13 -0
  189. package/src/services/task/WebexCallingUtils.ts +136 -0
  190. package/src/services/task/ai-docs/ARCHITECTURE.md +1 -0
  191. package/src/services/task/ai-docs/task-spec.md +190 -8
  192. package/src/services/task/constants.ts +13 -0
  193. package/src/services/task/contact.ts +30 -0
  194. package/src/services/task/digital/Digital.ts +11 -4
  195. package/src/services/task/state-machine/TaskStateMachine.ts +235 -81
  196. package/src/services/task/state-machine/actions.ts +5 -2
  197. package/src/services/task/state-machine/ai-docs/AGENTS.md +6 -4
  198. package/src/services/task/state-machine/ai-docs/ARCHITECTURE.md +35 -16
  199. package/src/services/task/state-machine/ai-docs/task-state-machine-spec.md +103 -33
  200. package/src/services/task/state-machine/guards.ts +7 -10
  201. package/src/services/task/state-machine/types.ts +16 -1
  202. package/src/services/task/state-machine/uiControlsComputer.ts +206 -32
  203. package/src/services/task/types.ts +269 -4
  204. package/src/services/task/voice/Voice.ts +625 -17
  205. package/src/services/task/voice/WebRTC.ts +11 -4
  206. package/src/services/task/voice/wxAppOfferObservability.ts +204 -0
  207. package/src/services/task/voice/wxAppVoiceMethods.ts +575 -0
  208. package/src/services/wxAppDiagnosticLogging.ts +286 -0
  209. package/src/services/wxAppTelephonyUtils.ts +14 -0
  210. package/src/types.ts +108 -13
  211. package/src/utils/AGENTS.md +21 -10
  212. package/src/utils/PageCache.ts +38 -5
  213. package/src/utils/ai-docs/utils-spec.md +21 -11
  214. package/src/webex.js +8 -0
  215. package/test/unit/fixtures/aiSummaryTestUtils.ts +40 -0
  216. package/test/unit/spec/cc.ts +3408 -152
  217. package/test/unit/spec/index.ts +885 -0
  218. package/test/unit/spec/metrics/MetricsManager.ts +25 -0
  219. package/test/unit/spec/metrics/behavioral-events.ts +60 -0
  220. package/test/unit/spec/services/AddressBook.ts +37 -6
  221. package/test/unit/spec/services/AnswerCallOnWebexService.ts +264 -0
  222. package/test/unit/spec/services/ApiAiAssistant.ts +269 -8
  223. package/test/unit/spec/services/EntryPoint.ts +87 -40
  224. package/test/unit/spec/services/Queue.ts +123 -12
  225. package/test/unit/spec/services/WebCallingService.ts +38 -0
  226. package/test/unit/spec/services/WebexCrossClientService.ts +509 -0
  227. package/test/unit/spec/services/WxAppTelephonyMercurySync.ts +136 -0
  228. package/test/unit/spec/services/config/Util.ts +501 -0
  229. package/test/unit/spec/services/config/index.ts +313 -543
  230. package/test/unit/spec/services/core/Utils.ts +22 -0
  231. package/test/unit/spec/services/core/WebexRequest.ts +8 -7
  232. package/test/unit/spec/services/core/aqm-reqs.ts +142 -1
  233. package/test/unit/spec/services/core/websocket/WebSocketManager.ts +64 -14
  234. package/test/unit/spec/services/task/Task.ts +2257 -11
  235. package/test/unit/spec/services/task/TaskFactory.ts +56 -2
  236. package/test/unit/spec/services/task/TaskManager.ts +5559 -1493
  237. package/test/unit/spec/services/task/TaskUtils.ts +72 -0
  238. package/test/unit/spec/services/task/WebexCallingUtils.ts +153 -0
  239. package/test/unit/spec/services/task/contact.ts +33 -0
  240. package/test/unit/spec/services/task/state-machine/TaskStateMachine.ts +1501 -92
  241. package/test/unit/spec/services/task/state-machine/guards.ts +210 -8
  242. package/test/unit/spec/services/task/state-machine/uiControlsComputer.ts +445 -7
  243. package/test/unit/spec/services/task/voice/Voice.ts +1710 -4
  244. package/test/unit/spec/services/task/voice/wxAppOfferObservability.ts +361 -0
  245. package/test/unit/spec/services/task/voice/wxAppVoiceMethods.ts +719 -0
  246. package/test/unit/spec/services/wxAppDiagnosticLogging.ts +179 -0
  247. package/test/unit/spec/wellnessSampleUtils.ts +288 -0
  248. package/typedoc.md +1 -1
  249. package/umd/contact-center.min.js +2 -2
  250. package/umd/contact-center.min.js.map +1 -1
@@ -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, SUBSCRIBE_API, 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,18 +67,306 @@ 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;
62
372
  let mockApiAIAssistant;
@@ -130,6 +440,7 @@ describe('webex.cc', () => {
130
440
  config: {
131
441
  getAgentConfig: jest.fn(),
132
442
  getOutdialAniEntries: jest.fn(),
443
+ getWellbeingBreakIdleCode: jest.fn(),
133
444
  },
134
445
  webSocketManager: mockWebSocketManager,
135
446
  rtdWebSocketManager: {
@@ -168,15 +479,23 @@ describe('webex.cc', () => {
168
479
  setConfigFlags: jest.fn(),
169
480
  setWrapupData: jest.fn(),
170
481
  setAgentId: jest.fn(),
482
+ setAgentName: jest.fn(),
171
483
  setWebRtcEnabled: jest.fn(),
484
+ setAnswerCallOnWebexService: jest.fn(),
485
+ handleRealtimeWebsocketEvent: jest.fn(),
172
486
  registerIncomingCallEvent: jest.fn(),
173
487
  registerTaskListeners: jest.fn(),
174
488
  getTask: jest.fn(),
175
489
  getActiveTasks: jest.fn(),
490
+ applyEnableWxBetterTogether: jest.fn(),
491
+ syncWxAppMuteFromCallDetailsForAllTasks: jest.fn(),
492
+ refreshWxAppOfferObservabilityForAllTasks: jest.fn(),
176
493
  on: jest.fn(),
177
494
  off: jest.fn(),
178
495
  emit: jest.fn(),
179
496
  unregisterIncomingCallEvent: jest.fn(),
497
+ handleRealtimeWebsocketEvent: jest.fn(),
498
+ clearAISummaryState: jest.fn(),
180
499
  };
181
500
 
182
501
  mockMetricsManager = {
@@ -200,6 +519,7 @@ describe('webex.cc', () => {
200
519
 
201
520
  afterEach(() => {
202
521
  jest.clearAllMocks();
522
+ jest.restoreAllMocks();
203
523
  });
204
524
 
205
525
  it('should initialize services and logger proxy on ready event', () => {
@@ -266,7 +586,7 @@ describe('webex.cc', () => {
266
586
  });
267
587
 
268
588
  describe('register', () => {
269
- const mockAgentProfile: Profile = {
589
+ const createFreshAgentProfile = (overrides: Partial<Profile> = {}): Profile => ({
270
590
  agentId: 'agent123',
271
591
  agentMailId: '',
272
592
  agentName: 'John',
@@ -311,11 +631,18 @@ describe('webex.cc', () => {
311
631
  isEndConsultEnabled: false,
312
632
  agentDbId: '',
313
633
  allowConsultToQueue: false,
634
+ accessQueue: 'SPECIFIC',
635
+ accessEntryPoint: 'ALL',
636
+ accessBuddyTeam: 'ALL',
314
637
  agentPersonalStatsEnabled: false,
315
638
  isTimeoutDesktopInactivityEnabled: false,
316
639
  webRtcEnabled: true,
317
640
  lostConnectionRecoveryTimeout: 0,
318
- };
641
+ isWellnessBreakEnabled: false,
642
+ ...overrides,
643
+ });
644
+
645
+ const mockAgentProfile: Profile = createFreshAgentProfile();
319
646
 
320
647
  it('should register successfully and return agent profile', async () => {
321
648
  mockAgentProfile.aiFeature = {realtimeTranscripts: {enable: true}} as any;
@@ -326,6 +653,7 @@ describe('webex.cc', () => {
326
653
  data: {
327
654
  auxCodeId: 'auxCodeId',
328
655
  agentId: 'agentId',
656
+ agentSessionId: 'session-after-refresh',
329
657
  deviceType: LoginOption.EXTENSION,
330
658
  dn: '12345',
331
659
  },
@@ -365,7 +693,7 @@ describe('webex.cc', () => {
365
693
  resource: SUBSCRIBE_API,
366
694
  });
367
695
 
368
- // 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.
369
697
  expect(mockTaskManager.on).toHaveBeenCalledWith(
370
698
  TASK_EVENTS.TASK_INCOMING,
371
699
  expect.any(Function)
@@ -398,15 +726,26 @@ describe('webex.cc', () => {
398
726
  module: CC_FILE,
399
727
  method: 'connectWebsocket',
400
728
  });
401
- expect(mockTaskManager.setConfigFlags).toHaveBeenCalledWith({
402
- isEndTaskEnabled: mockAgentProfile.isEndTaskEnabled,
403
- isEndConsultEnabled: mockAgentProfile.isEndConsultEnabled,
404
- webRtcEnabled: mockAgentProfile.webRtcEnabled,
405
- autoWrapup: mockAgentProfile.wrapUpData.wrapUpProps.autoWrapup ?? false,
406
- aiFeature: mockAgentProfile.aiFeature,
407
- });
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();
408
747
  expect(reloadSpy).toHaveBeenCalled();
409
- expect(result).toEqual(mockAgentProfile);
748
+ expect(result).toEqual({...mockAgentProfile, agentSessionId: 'session-after-refresh'});
410
749
  expect(mockMetricsManager.timeEvent).toHaveBeenCalledWith([
411
750
  METRIC_EVENT_NAMES.WEBSOCKET_REGISTER_SUCCESS,
412
751
  METRIC_EVENT_NAMES.WEBSOCKET_REGISTER_FAILED,
@@ -483,6 +822,25 @@ describe('webex.cc', () => {
483
822
  );
484
823
  });
485
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
+
486
844
  it('should log error if mercury connect fails but cc.register() should not fail', async () => {
487
845
  const mockError = new Error('Error while performing mercury connect');
488
846
  jest.spyOn(webex.internal.mercury, 'connect').mockRejectedValue(mockError);
@@ -619,8 +977,47 @@ describe('webex.cc', () => {
619
977
  expect(result).toEqual(mockAgentProfile);
620
978
  });
621
979
 
622
- it('should not connect RTD websocket when realtime transcripts feature is disabled', async () => {
623
- mockAgentProfile.aiFeature = {realtimeTranscripts: {enable: false}} as any;
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'});
997
+
998
+ await webex.cc.register();
999
+
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)
1012
+ );
1013
+ });
1014
+
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;
624
1021
  jest.spyOn(webex.internal.mercury, 'connect').mockResolvedValue(true);
625
1022
  jest.spyOn(webex.cc.services.agent, 'reload').mockResolvedValue({
626
1023
  data: {
@@ -643,80 +1040,983 @@ describe('webex.cc', () => {
643
1040
  expect.any(Function)
644
1041
  );
645
1042
  });
646
- });
647
1043
 
648
- describe('stationLogin', () => {
649
- it('should login successfully with LoginOption.BROWSER and webrtc enabled', async () => {
650
- const mockTask = {};
651
- const options = {
652
- teamId: 'teamId',
653
- loginOption: LoginOption.BROWSER,
654
- };
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
+ });
655
1079
 
656
- webex.cc.agentConfig = {
657
- agentId: 'agentId',
658
- webRtcEnabled: true,
659
- loginVoiceOptions: ['BROWSER', 'EXTENSION', 'AGENT_DN'],
660
- };
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
+ );
661
1118
 
662
- const registerWebCallingLineSpy = jest.spyOn(
663
- webex.cc.webCallingService,
664
- 'registerWebCallingLine'
665
- );
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
+ });
666
1204
 
667
- const mockData = {
668
- data: {
669
- loginOption: LoginOption.BROWSER,
670
- agentId: 'agentId',
671
- teamId: 'teamId',
672
- siteId: 'siteId',
673
- roles: [AGENT],
674
- trackingId: '1234',
675
- eventType: 'DESKTOP_MESSAGE',
676
- channelsMap: {
677
- chat: ['25d8ggg7-4821-7de7-b626-36437adec509', '14e7fff7-7de7-4821-a919-36437adec509'],
678
- email: [
679
- '14e7fff7-7de7-4821-a919-36437adec509',
680
- '14e7fff7-7de7-4821-a919-36437adec509',
681
- '14e7fff7-7de7-4821-a919-36437adec509',
682
- ],
683
- social: [],
684
- telephony: ['14e7fff7-7de7-4821-a919-36437adec509'],
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,
685
1229
  },
686
1230
  },
687
- trackingId: 'notifs_52628',
688
- orgId: 'orgId',
689
- type: 'StationLoginSuccess',
690
- eventType: 'STATION_LOGIN',
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
+ }),
691
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);
692
1330
 
693
- const responseMock = {
694
- loginOption: LoginOption.BROWSER,
695
- agentId: 'agentId',
696
- teamId: 'teamId',
697
- siteId: 'siteId',
698
- roles: [AGENT],
699
- trackingId: '1234',
700
- eventType: 'DESKTOP_MESSAGE',
701
- mmProfile: {
702
- chat: 2,
703
- email: 3,
704
- social: 0,
705
- telephony: 1,
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
+ },
706
1341
  },
707
- notifsTrackingId: 'notifs_52628',
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
+ });
708
1383
  };
709
1384
 
710
- const stationLoginMock = jest
711
- .spyOn(webex.cc.services.agent, 'stationLogin')
712
- .mockResolvedValue(mockData as unknown as StationLoginSuccess);
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
+ };
713
1400
 
714
- const result = await webex.cc.stationLogin(options);
1401
+ const attachRtdMessageListener = (rtdWebSocketManager: EventEmitterDouble) => {
1402
+ rtdWebSocketManager.on('message', webex.cc['handleRTDWebsocketMessage']);
1403
+ };
715
1404
 
716
- expect(registerWebCallingLineSpy).toHaveBeenCalled();
717
- expect(stationLoginMock).toHaveBeenCalledWith({
718
- data: {
719
- dialNumber: 'agentId',
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',
2000
+ eventType: 'DESKTOP_MESSAGE',
2001
+ mmProfile: {
2002
+ chat: 2,
2003
+ email: 3,
2004
+ social: 0,
2005
+ telephony: 1,
2006
+ },
2007
+ notifsTrackingId: 'notifs_52628',
2008
+ };
2009
+
2010
+ const stationLoginMock = jest
2011
+ .spyOn(webex.cc.services.agent, 'stationLogin')
2012
+ .mockResolvedValue(mockData as unknown as StationLoginSuccess);
2013
+
2014
+ const result = await webex.cc.stationLogin(options);
2015
+
2016
+ expect(registerWebCallingLineSpy).toHaveBeenCalled();
2017
+ expect(stationLoginMock).toHaveBeenCalledWith({
2018
+ data: {
2019
+ dialNumber: `${WEB_RTC_PREFIX}agentId`,
720
2020
  teamId: 'teamId',
721
2021
  deviceType: LoginOption.BROWSER,
722
2022
  isExtension: false,
@@ -734,6 +2034,7 @@ describe('webex.cc', () => {
734
2034
  METRIC_EVENT_NAMES.STATION_LOGIN_FAILED,
735
2035
  ]);
736
2036
  expect(result).toEqual(responseMock);
2037
+ expect(webex.cc.agentConfig.deviceType).toBe(LoginOption.BROWSER);
737
2038
 
738
2039
  const onSpy = jest.spyOn(mockTaskManager, 'on');
739
2040
  const emitSpy = jest.spyOn(webex.cc, 'trigger');
@@ -875,7 +2176,7 @@ describe('webex.cc', () => {
875
2176
  expect(registerWebCallingLineSpy).not.toHaveBeenCalled();
876
2177
  expect(stationLoginSpy).toHaveBeenCalledWith({
877
2178
  data: {
878
- dialNumber: 'agentId',
2179
+ dialNumber: `${WEB_RTC_PREFIX}agentId`,
879
2180
  teamId: 'teamId',
880
2181
  deviceType: LoginOption.BROWSER,
881
2182
  isExtension: false,
@@ -966,58 +2267,796 @@ describe('webex.cc', () => {
966
2267
  }
967
2268
  );
968
2269
 
969
- expect(stationLoginMock).toHaveBeenCalledWith({
2270
+ expect(stationLoginMock).toHaveBeenCalledWith({
2271
+ data: {
2272
+ dialNumber: '12345678901',
2273
+ teamId: 'teamId',
2274
+ deviceType: LoginOption.AGENT_DN,
2275
+ isExtension: false,
2276
+ deviceId: '12345678901',
2277
+ roles: [AGENT],
2278
+ teamName: '',
2279
+ siteId: '',
2280
+ usesOtherDN: false,
2281
+ auxCodeId: '',
2282
+ },
2283
+ });
2284
+ expect(result).toEqual(responseMock);
2285
+ });
2286
+
2287
+ it('should handle error during stationLogin', async () => {
2288
+ webex.cc.agentConfig = {
2289
+ webRtcEnabled: true,
2290
+ };
2291
+
2292
+ const options = {
2293
+ teamId: 'teamId',
2294
+ loginOption: LoginOption.EXTENSION,
2295
+ dialNumber: '1234567890',
2296
+ };
2297
+
2298
+ const error = {
2299
+ details: {
2300
+ trackingId: '1234',
2301
+ data: {
2302
+ reason: 'Error while performing stationLogin',
2303
+ },
2304
+ },
2305
+ };
2306
+
2307
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockRejectedValue(error);
2308
+
2309
+ await expect(webex.cc.stationLogin(options)).rejects.toThrow(error.details.data.reason);
2310
+
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
+ );
2318
+ expect(LoggerProxy.error).toHaveBeenCalledWith(
2319
+ `stationLogin failed with reason: ${error.details.data.reason}`,
2320
+ {module: CC_FILE, method: 'stationLogin', trackingId: error.details.trackingId}
2321
+ );
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({
970
2996
  data: {
971
- dialNumber: '12345678901',
2997
+ agentId: 'agentId',
972
2998
  teamId: 'teamId',
973
- deviceType: LoginOption.AGENT_DN,
974
- isExtension: false,
975
- deviceId: '12345678901',
976
- roles: [AGENT],
977
- teamName: '',
978
- siteId: '',
979
- usesOtherDN: false,
980
- auxCodeId: '',
2999
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
981
3000
  },
3001
+ trackingId: 'track-1',
3002
+ } as StationLoginSuccess);
3003
+
3004
+ await webex.cc.stationLogin({
3005
+ teamId: 'teamId',
3006
+ loginOption: LoginOption.EXTENSION,
3007
+ dialNumber: '1001',
982
3008
  });
983
- expect(result).toEqual(responseMock);
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);
984
3017
  });
985
3018
 
986
- it('should handle error during stationLogin', async () => {
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'};
987
3021
  webex.cc.agentConfig = {
988
- webRtcEnabled: true,
3022
+ agentId: 'agentId',
3023
+ webRtcEnabled: false,
3024
+ loginVoiceOptions: ['EXTENSION'],
989
3025
  };
3026
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
3027
+ webex.request = jest.fn().mockResolvedValue({body: {}});
990
3028
 
991
- const options = {
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({
992
3040
  teamId: 'teamId',
993
3041
  loginOption: LoginOption.EXTENSION,
994
- dialNumber: '1234567890',
995
- };
3042
+ dialNumber: '1001',
3043
+ });
996
3044
 
997
- const error = {
998
- details: {
999
- trackingId: '1234',
1000
- data: {
1001
- reason: 'Error while performing stationLogin',
1002
- },
1003
- },
1004
- };
3045
+ webex.cc['webexCrossClientService'].teardown();
3046
+ webex.cc['wxAppTelephonyMercurySync'].unsubscribe();
3047
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: false};
1005
3048
 
1006
- jest.spyOn(webex.cc.services.agent, 'stationLogin').mockRejectedValue(error);
3049
+ const publishSpy = jest
3050
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
3051
+ .mockResolvedValue(undefined);
1007
3052
 
1008
- await expect(webex.cc.stationLogin(options)).rejects.toThrow(error.details.data.reason);
3053
+ await webex.cc.stationLogin({
3054
+ teamId: 'teamId',
3055
+ loginOption: LoginOption.EXTENSION,
3056
+ dialNumber: '1001',
3057
+ });
1009
3058
 
1010
- expect(LoggerProxy.log).toHaveBeenCalledWith(
1011
- `Starting agent station login | loginOption: ${options.loginOption} teamId: ${options.teamId}`,
1012
- {
1013
- module: CC_FILE,
1014
- method: 'stationLogin',
1015
- }
1016
- );
1017
- expect(LoggerProxy.error).toHaveBeenCalledWith(
1018
- `stationLogin failed with reason: ${error.details.data.reason}`,
1019
- {module: CC_FILE, method: 'stationLogin', trackingId: error.details.trackingId}
1020
- );
3059
+ expect(publishSpy).toHaveBeenCalledWith(false, {userId: 'user-123', trackPublishMetrics: true});
1021
3060
  });
1022
3061
  });
1023
3062
 
@@ -1043,7 +3082,7 @@ describe('webex.cc', () => {
1043
3082
  });
1044
3083
 
1045
3084
  expect(stationLogoutMock).toHaveBeenCalledWith({data: data});
1046
- // 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.
1047
3086
  // expect(mockTaskManager.unregisterIncomingCallEvent).toHaveBeenCalledWith();
1048
3087
  // expect(mockTaskManager.off).toHaveBeenCalledWith(
1049
3088
  // TASK_EVENTS.TASK_INCOMING,
@@ -1061,6 +3100,216 @@ describe('webex.cc', () => {
1061
3100
  ]);
1062
3101
  });
1063
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
+
1064
3313
  it('should handle error during stationLogout', async () => {
1065
3314
  const data = {logoutReason: 'Logout reason'};
1066
3315
  const error = {
@@ -1213,6 +3462,257 @@ describe('webex.cc', () => {
1213
3462
  });
1214
3463
  });
1215
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
+
1216
3716
  describe('getBuddyAgents', () => {
1217
3717
  it('should return buddy agents response when successful', async () => {
1218
3718
  const data: BuddyAgents = {state: 'Available', mediaType: 'telephony'};
@@ -1276,6 +3776,41 @@ describe('webex.cc', () => {
1276
3776
  ]);
1277
3777
  });
1278
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
+
1279
3814
  it('should handle error', async () => {
1280
3815
  const data: BuddyAgents = {state: 'Available', mediaType: 'telephony'};
1281
3816
  webex.cc.agentConfig = {
@@ -1348,8 +3883,6 @@ describe('webex.cc', () => {
1348
3883
  );
1349
3884
 
1350
3885
  const setLoginOptionSpy = jest.spyOn(webex.cc.webCallingService, 'setLoginOption');
1351
- const incomingTaskListenerSpy = jest.spyOn(webex.cc, 'incomingTaskListener');
1352
- const webSocketManagerOnSpy = jest.spyOn(webex.cc.services.webSocketManager, 'on');
1353
3886
  await webex.cc['silentRelogin']();
1354
3887
 
1355
3888
  expect(LoggerProxy.log).toHaveBeenCalledWith('Starting silent relogin process', {
@@ -1380,8 +3913,8 @@ describe('webex.cc', () => {
1380
3913
  expect(webex.cc.agentConfig.deviceType).toBe(LoginOption.BROWSER);
1381
3914
  expect(registerWebCallingLineSpy).toHaveBeenCalled();
1382
3915
  expect(setLoginOptionSpy).toHaveBeenCalledWith(LoginOption.BROWSER);
1383
- // TODO: https://jira-eng-gpk2.cisco.com/jira/browse/SPARK-626777 Implement the de-register method and close the listener there
1384
- // expect(incomingTaskListenerSpy).toHaveBeenCalled();
3916
+ // SPARK-626777 tracks moving listener cleanup into the future de-register API.
3917
+ // expect(eventForwarderRefreshSpy).toHaveBeenCalled();
1385
3918
  // expect(webSocketManagerOnSpy).toHaveBeenCalledWith('message', expect.any(Function));
1386
3919
  // expect(mockTaskManager.on).toHaveBeenCalledWith(
1387
3920
  // TASK_EVENTS.TASK_HYDRATE,
@@ -1477,31 +4010,108 @@ describe('webex.cc', () => {
1477
4010
  expect(webex.cc.agentConfig.lastIdleCodeChangeTimestamp).toStrictEqual(1738575135189);
1478
4011
  });
1479
4012
 
1480
- it('should update agentConfig with deviceType during silent relogin for AGENT_DN', async () => {
1481
- const mockReLoginResponse = {
4013
+ it('should update agentConfig with deviceType during silent relogin for AGENT_DN', async () => {
4014
+ const mockReLoginResponse = {
4015
+ data: {
4016
+ auxCodeId: 'auxCodeId',
4017
+ agentId: 'agentId',
4018
+ lastStateChangeReason: 'agent-wss-disconnect',
4019
+ deviceType: LoginOption.AGENT_DN,
4020
+ dn: '67890',
4021
+ subStatus: 'subStatusValue',
4022
+ },
4023
+ };
4024
+
4025
+ // Mock the agentConfig
4026
+ webex.cc.agentConfig = {
4027
+ agentId: 'agentId',
4028
+ agentProfileID: 'test-agent-profile-id',
4029
+ isAgentLoggedIn: false,
4030
+ } as Profile;
4031
+
4032
+ jest.spyOn(webex.cc.services.agent, 'reload').mockResolvedValue(mockReLoginResponse);
4033
+
4034
+ await webex.cc['silentRelogin']();
4035
+
4036
+ expect(webex.cc.agentConfig.deviceType).toBe(LoginOption.AGENT_DN);
4037
+ expect(webex.cc.agentConfig.dn).toBe('67890');
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({
1482
4057
  data: {
1483
4058
  auxCodeId: 'auxCodeId',
1484
4059
  agentId: 'agentId',
1485
- lastStateChangeReason: 'agent-wss-disconnect',
1486
- deviceType: LoginOption.AGENT_DN,
1487
- dn: '67890',
1488
- subStatus: 'subStatusValue',
4060
+ deviceType: LoginOption.EXTENSION,
4061
+ dn: '1001',
4062
+ teamId: 'teamId',
4063
+ lastStateChangeTimestamp: 1738575135188,
4064
+ lastIdleCodeChangeTimestamp: 1738575135189,
1489
4065
  },
1490
- };
4066
+ });
1491
4067
 
1492
- // Mock the agentConfig
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'};
1493
4086
  webex.cc.agentConfig = {
1494
4087
  agentId: 'agentId',
1495
4088
  agentProfileID: 'test-agent-profile-id',
1496
4089
  isAgentLoggedIn: false,
1497
4090
  } as Profile;
1498
4091
 
1499
- jest.spyOn(webex.cc.services.agent, 'reload').mockResolvedValue(mockReLoginResponse);
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');
1500
4109
 
1501
4110
  await webex.cc['silentRelogin']();
1502
4111
 
1503
- expect(webex.cc.agentConfig.deviceType).toBe(LoginOption.AGENT_DN);
1504
- expect(webex.cc.agentConfig.dn).toBe('67890');
4112
+ expect(publishSpy).toHaveBeenCalledWith(false, {userId: 'user-123', trackPublishMetrics: true});
4113
+ expect(teardownSpy).toHaveBeenCalled();
4114
+ expect(unsubscribeSpy).toHaveBeenCalled();
1505
4115
  });
1506
4116
  });
1507
4117
 
@@ -1639,6 +4249,9 @@ describe('webex.cc', () => {
1639
4249
  {module: CC_FILE, method: `startOutdial`, trackingId: error.details.trackingId}
1640
4250
  );
1641
4251
  expect(getErrorDetailsSpy).toHaveBeenCalledWith(error, 'startOutdial', CC_FILE);
4252
+ expect(mockWebexRequest.uploadLogs).toHaveBeenCalledWith({
4253
+ correlationId: error.details.trackingId,
4254
+ });
1642
4255
  });
1643
4256
  });
1644
4257
 
@@ -1733,6 +4346,42 @@ describe('webex.cc', () => {
1733
4346
  deviceUnregisterSpy = jest.spyOn(webex.internal.device, 'unregister');
1734
4347
  });
1735
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
+
1736
4385
  it('should unregister successfully and clean up all resources when webrtc is enabled', async () => {
1737
4386
  webex.cc.services.rtdWebSocketManager = {
1738
4387
  isSocketClosed: false,
@@ -1741,6 +4390,18 @@ describe('webex.cc', () => {
1741
4390
  on: jest.fn(),
1742
4391
  } as any;
1743
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
+
1744
4405
  await webex.cc.deregister();
1745
4406
 
1746
4407
  expect(mockTaskManager.off).toHaveBeenCalledWith(
@@ -1766,10 +4427,17 @@ describe('webex.cc', () => {
1766
4427
  );
1767
4428
 
1768
4429
  expect(mockWebSocketManager.close).toHaveBeenCalledWith(false, 'Unregistering the SDK');
1769
- expect(webex.cc.services.rtdWebSocketManager.close).toHaveBeenCalledWith(
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,
1770
4437
  false,
1771
4438
  'Unregistering the RTD websocket'
1772
4439
  );
4440
+ expect(webex.cc.services.rtdWebSocketManager.close).toHaveBeenCalledTimes(2);
1773
4441
  expect(webex.cc.agentConfig).toBeNull();
1774
4442
 
1775
4443
  expect(webex.internal.mercury.off).toHaveBeenCalledWith('online');
@@ -1781,6 +4449,7 @@ describe('webex.cc', () => {
1781
4449
  METRIC_EVENT_NAMES.WEBSOCKET_DEREGISTER_SUCCESS,
1782
4450
  METRIC_EVENT_NAMES.WEBSOCKET_DEREGISTER_FAIL,
1783
4451
  ]);
4452
+ expect(mockTaskManager.clearAISummaryState).toHaveBeenCalled();
1784
4453
  expect(mockMetricsManager.trackEvent).toHaveBeenCalledWith(
1785
4454
  METRIC_EVENT_NAMES.WEBSOCKET_DEREGISTER_SUCCESS,
1786
4455
  {},
@@ -1800,22 +4469,23 @@ describe('webex.cc', () => {
1800
4469
  const incomingCalls = mockTaskManager.off.mock.calls.filter(
1801
4470
  ([evt]) => evt === TASK_EVENTS.TASK_INCOMING
1802
4471
  );
1803
- expect(incomingCalls).toHaveLength(1);
1804
- const [, incomingCallback] = incomingCalls[0];
4472
+ expect(incomingCalls.length).toBeGreaterThanOrEqual(1);
4473
+ const [, incomingCallback] = incomingCalls[incomingCalls.length - 1];
1805
4474
  expect(incomingCallback).toBe(webex.cc['handleIncomingTask']);
1806
4475
 
1807
4476
  const hydrateCalls = mockTaskManager.off.mock.calls.filter(
1808
4477
  ([evt]) => evt === TASK_EVENTS.TASK_HYDRATE
1809
4478
  );
1810
- expect(hydrateCalls).toHaveLength(1);
1811
- const [, hydrateCallback] = hydrateCalls[0];
4479
+ expect(hydrateCalls.length).toBeGreaterThanOrEqual(1);
4480
+ const [, hydrateCallback] = hydrateCalls[hydrateCalls.length - 1];
1812
4481
  expect(hydrateCallback).toBe(webex.cc['handleTaskHydrate']);
1813
4482
 
1814
4483
  const multiLoginHydrateCalls = mockTaskManager.off.mock.calls.filter(
1815
4484
  ([evt]) => evt === TASK_EVENTS.TASK_MULTI_LOGIN_HYDRATE
1816
4485
  );
1817
- expect(multiLoginHydrateCalls).toHaveLength(1);
1818
- const [, multiLoginHydrateCallback] = multiLoginHydrateCalls[0];
4486
+ expect(multiLoginHydrateCalls.length).toBeGreaterThanOrEqual(1);
4487
+ const [, multiLoginHydrateCallback] =
4488
+ multiLoginHydrateCalls[multiLoginHydrateCalls.length - 1];
1819
4489
  expect(multiLoginHydrateCallback).toBe(webex.cc['handleTaskMultiLoginHydrate']);
1820
4490
 
1821
4491
  const messageCalls = mockWebSocketManager.off.mock.calls.filter(([evt]) => evt === 'message');
@@ -1829,6 +4499,39 @@ describe('webex.cc', () => {
1829
4499
  expect(connectionCalls).toHaveLength(1);
1830
4500
  const [, connectionCallback] = connectionCalls[0];
1831
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']);
1832
4535
  });
1833
4536
 
1834
4537
  it('should skip webCallingService and internal cleanup when webrtc is disabled', async () => {
@@ -1856,7 +4559,17 @@ describe('webex.cc', () => {
1856
4559
  expect(webex.internal.mercury.off).not.toHaveBeenCalled();
1857
4560
  expect(mercuryDisconnectSpy).not.toHaveBeenCalled();
1858
4561
  expect(deviceUnregisterSpy).not.toHaveBeenCalled();
1859
- expect(mockRTDWebSocketManager.close).toHaveBeenCalledWith(false, 'Unregistering the SDK');
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);
1860
4573
  });
1861
4574
 
1862
4575
  it('should skip internal mercury cleanup when loginVoiceOptions does not include BROWSER', async () => {
@@ -1874,10 +4587,149 @@ describe('webex.cc', () => {
1874
4587
  expect(deviceUnregisterSpy).not.toHaveBeenCalled();
1875
4588
 
1876
4589
  expect(mockWebSocketManager.close).toHaveBeenCalledWith(false, 'Unregistering the SDK');
1877
- expect(mockRTDWebSocketManager.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');
1878
4629
  expect(webex.cc.agentConfig).toBeNull();
1879
4630
  });
1880
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;
4665
+ });
4666
+
4667
+ it('should release wxApp-owned Mercury and device on deregister', async () => {
4668
+ webex.cc.agentConfig = {
4669
+ agentId: 'agentId',
4670
+ webRtcEnabled: false,
4671
+ loginVoiceOptions: [LoginOption.EXTENSION],
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);
4684
+
4685
+ await webex.cc.deregister();
4686
+
4687
+ expect(mercuryDisconnectSpy).toHaveBeenCalled();
4688
+ expect(deviceUnregisterSpy).toHaveBeenCalled();
4689
+ expect(webex.cc['wxAppMercuryConnectedByCc']).toBe(false);
4690
+ expect(webex.cc['wxAppDeviceRegisteredByCc']).toBe(false);
4691
+ });
4692
+
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);
4731
+ });
4732
+
1881
4733
  it('should handle errors during unregister and track metrics', async () => {
1882
4734
  const mockError = new Error('Failed to deregister device');
1883
4735
  webex.internal.device.unregister.mockRejectedValue(mockError);
@@ -1901,6 +4753,11 @@ describe('webex.cc', () => {
1901
4753
  module: CC_FILE,
1902
4754
  method: 'deregister',
1903
4755
  });
4756
+ expect(mockTaskManager.clearAISummaryState).toHaveBeenCalled();
4757
+ expect(webex.cc.services.rtdWebSocketManager.off).toHaveBeenCalledWith(
4758
+ 'message',
4759
+ webex.cc['handleRTDWebsocketMessage']
4760
+ );
1904
4761
 
1905
4762
  expect(mockMetricsManager.trackEvent).toHaveBeenCalledWith(
1906
4763
  METRIC_EVENT_NAMES.WEBSOCKET_DEREGISTER_FAIL,
@@ -2011,6 +4868,27 @@ describe('webex.cc', () => {
2011
4868
  });
2012
4869
  });
2013
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
+
2014
4892
  it('should call webCallingService.setLoginOption with correct deviceType on AGENT_STATION_LOGIN_SUCCESS', () => {
2015
4893
  const setLoginOptionSpy = jest.spyOn(webex.cc.webCallingService, 'setLoginOption');
2016
4894
  const deviceType = LoginOption.EXTENSION;
@@ -2128,6 +5006,55 @@ describe('webex.cc', () => {
2128
5006
  expect(result).toEqual(mockResp);
2129
5007
  });
2130
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
+
2131
5058
  it('should use provided teamId if passed in payload', async () => {
2132
5059
  const dataWithTeam = {
2133
5060
  teamId: 'newTeam',
@@ -2364,16 +5291,15 @@ describe('webex.cc', () => {
2364
5291
  mockError.details = {
2365
5292
  trackingId: 'test-tracking-id',
2366
5293
  orgId: 'mockOrgId',
2367
- error: 'Service error',
5294
+ type: 'OutdialAniEntriesFailed',
5295
+ data: {
5296
+ reason: 'Detailed service error',
5297
+ },
2368
5298
  };
2369
5299
 
2370
5300
  // Mock the service call to throw an error
2371
5301
  webex.cc.services.config.getOutdialAniEntries.mockRejectedValue(mockError);
2372
5302
 
2373
- // Mock getErrorDetails to return a detailed error
2374
- const detailedError = new Error('Detailed service error');
2375
- getErrorDetailsSpy.mockReturnValue({error: detailedError});
2376
-
2377
5303
  await expect(webex.cc.getOutdialAniEntries(mockParams)).rejects.toThrow(
2378
5304
  'Detailed service error'
2379
5305
  );
@@ -2398,9 +5324,20 @@ describe('webex.cc', () => {
2398
5324
  trackingId: 'test-tracking-id',
2399
5325
  }
2400
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
+ );
2401
5335
 
2402
5336
  // Verify getErrorDetails was called
2403
5337
  expect(getErrorDetailsSpy).toHaveBeenCalledWith(mockError, 'getOutdialAniEntries', CC_FILE);
5338
+ expect(mockWebexRequest.uploadLogs).toHaveBeenCalledWith({
5339
+ correlationId: 'test-tracking-id',
5340
+ });
2404
5341
  });
2405
5342
 
2406
5343
  it('should throw error when orgId is not found', async () => {
@@ -2483,8 +5420,7 @@ describe('webex.cc', () => {
2483
5420
  });
2484
5421
 
2485
5422
  it('should handle error during acceptPreviewContact', async () => {
2486
- getErrorDetailsSpy.mockRestore();
2487
- getErrorDetailsSpy = jest.spyOn(Utils, 'getErrorDetails');
5423
+ getErrorDetailsSpy.mockClear();
2488
5424
 
2489
5425
  const error = {
2490
5426
  details: {
@@ -2510,6 +5446,9 @@ describe('webex.cc', () => {
2510
5446
  {module: CC_FILE, method: 'acceptPreviewContact', trackingId: error.details.trackingId}
2511
5447
  );
2512
5448
  expect(getErrorDetailsSpy).toHaveBeenCalledWith(error, 'acceptPreviewContact', CC_FILE);
5449
+ expect(mockWebexRequest.uploadLogs).toHaveBeenCalledWith({
5450
+ correlationId: error.details.trackingId,
5451
+ });
2513
5452
  });
2514
5453
  });
2515
5454
 
@@ -2547,8 +5486,7 @@ describe('webex.cc', () => {
2547
5486
  });
2548
5487
 
2549
5488
  it('should handle error during skipPreviewContact', async () => {
2550
- getErrorDetailsSpy.mockRestore();
2551
- getErrorDetailsSpy = jest.spyOn(Utils, 'getErrorDetails');
5489
+ getErrorDetailsSpy.mockClear();
2552
5490
 
2553
5491
  const error = {
2554
5492
  details: {
@@ -2574,6 +5512,9 @@ describe('webex.cc', () => {
2574
5512
  {module: CC_FILE, method: 'skipPreviewContact', trackingId: error.details.trackingId}
2575
5513
  );
2576
5514
  expect(getErrorDetailsSpy).toHaveBeenCalledWith(error, 'skipPreviewContact', CC_FILE);
5515
+ expect(mockWebexRequest.uploadLogs).toHaveBeenCalledWith({
5516
+ correlationId: error.details.trackingId,
5517
+ });
2577
5518
  });
2578
5519
  });
2579
5520
 
@@ -2611,8 +5552,7 @@ describe('webex.cc', () => {
2611
5552
  });
2612
5553
 
2613
5554
  it('should handle error during removePreviewContact', async () => {
2614
- getErrorDetailsSpy.mockRestore();
2615
- getErrorDetailsSpy = jest.spyOn(Utils, 'getErrorDetails');
5555
+ getErrorDetailsSpy.mockClear();
2616
5556
 
2617
5557
  const error = {
2618
5558
  details: {
@@ -2638,6 +5578,322 @@ describe('webex.cc', () => {
2638
5578
  {module: CC_FILE, method: 'removePreviewContact', trackingId: error.details.trackingId}
2639
5579
  );
2640
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
+ }
2641
5897
  });
2642
5898
  });
2643
5899
  });