@webex/contact-center 3.12.0-webex-services-ready.4 → 3.13.0-next.1

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 +21 -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 +53 -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 +816 -26
  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 +29 -2
  14. package/dist/constants.js.map +1 -1
  15. package/dist/index.js +66 -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 +287 -37
  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 +55 -35
  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 +127 -9
  101. package/dist/types/config.d.ts +7 -0
  102. package/dist/types/constants.d.ts +23 -0
  103. package/dist/types/index.d.ts +38 -17
  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 +150 -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 +125 -13
  141. package/dist/types/utils/PageCache.d.ts +20 -3
  142. package/dist/types.js +90 -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 +1047 -48
  150. package/src/config.ts +7 -0
  151. package/src/constants.ts +36 -0
  152. package/src/index.ts +49 -11
  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 +362 -40
  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 +11 -11
  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 +145 -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 +159 -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 +3595 -120
  217. package/test/unit/spec/index.ts +891 -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 +483 -54
  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,11 +1,17 @@
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,
6
9
  StationLogoutResponse,
7
10
  WebexSDK,
11
+ VOICE_CONNECTION_STATUS,
12
+ VOICE_CONNECTION_ERROR,
8
13
  } from '../../../src/types';
14
+ import {VOICE_CONNECTION_EVENTS} from '../../../src/services/config/types';
9
15
  import ContactCenter from '../../../src/cc';
10
16
  import EntryPoint from '../../../src/services/EntryPoint';
11
17
  import type {EntryPointListResponse} from '../../../src/types';
@@ -15,10 +21,14 @@ import type {ContactServiceQueuesResponse} from '../../../src/types';
15
21
  import MockWebex from '@webex/test-helper-mock-webex';
16
22
  import {StationLoginSuccess, AGENT_EVENTS} from '../../../src/services/agent/types';
17
23
  import {SetStateResponse} from '../../../src/types';
18
- import {AGENT, SUBSCRIBE_API, WEB_RTC_PREFIX} from '../../../src/services/constants';
24
+ import {
25
+ AGENT,
26
+ SUBSCRIBE_API,
27
+ WEB_RTC_PREFIX,
28
+ } from '../../../src/services/constants';
19
29
  import Services from '../../../src/services';
20
30
  import config from '../../../src/config';
21
- import {CC_EVENTS} from '../../../src/services/config/types';
31
+ import {CC_TASK_EVENTS, CC_EVENTS} from '../../../src/services/config/types';
22
32
  import LoggerProxy from '../../../src/logger-proxy';
23
33
  import * as Utils from '../../../src/services/core/Utils';
24
34
  import {
@@ -33,11 +43,26 @@ import {
33
43
  import '../../../__mocks__/workerMock';
34
44
  import {Profile} from '../../../src/services/config/types';
35
45
  import TaskManager from '../../../src/services/task/TaskManager';
36
- import {AgentContact, TASK_EVENTS} from '../../../src/services/task/types';
46
+ import Task from '../../../src/services/task/Task';
47
+ import {
48
+ AgentContact,
49
+ AISummaryResponse,
50
+ TASK_CHANNEL_TYPE,
51
+ TASK_EVENTS,
52
+ TaskData,
53
+ } from '../../../src/services/task/types';
54
+ import {AI_SUMMARY_REQUEST_CANCELLED} from '../../../src/services/task/constants';
55
+ import type {ApiAIAssistant} from '../../../src/services/ApiAiAssistant';
56
+ import type {AIFeatureFlags} from '../../../src/types';
37
57
  import MetricsManager from '../../../src/metrics/MetricsManager';
38
58
  import {METRIC_EVENT_NAMES} from '../../../src/metrics/constants';
39
59
  import Mercury from '@webex/internal-plugin-mercury';
40
60
  import WebexRequest from '../../../src/services/core/WebexRequest';
61
+ import {
62
+ createDeferred,
63
+ flushEventLoopTurn,
64
+ flushMicrotasks,
65
+ } from '../fixtures/aiSummaryTestUtils';
41
66
 
42
67
  jest.mock('../../../src/logger-proxy', () => ({
43
68
  __esModule: true,
@@ -45,18 +70,315 @@ jest.mock('../../../src/logger-proxy', () => ({
45
70
  log: jest.fn(),
46
71
  error: jest.fn(),
47
72
  info: jest.fn(),
73
+ warn: jest.fn(),
48
74
  initialize: jest.fn(),
49
75
  },
50
76
  }));
51
77
 
78
+ jest.mock('../../../src/services', () => ({
79
+ __esModule: true,
80
+ default: {
81
+ getInstance: jest.fn(() => ({
82
+ agent: {
83
+ stationLogin: jest.fn(),
84
+ logout: jest.fn(),
85
+ reload: jest.fn(),
86
+ stateChange: jest.fn(),
87
+ buddyAgents: jest.fn(),
88
+ },
89
+ config: {
90
+ getAgentConfig: jest.fn(),
91
+ getOutdialAniEntries: jest.fn(),
92
+ },
93
+ webSocketManager: {
94
+ initWebSocket: jest.fn(),
95
+ on: jest.fn(),
96
+ off: jest.fn(),
97
+ close: jest.fn(),
98
+ isSocketClosed: false,
99
+ },
100
+ rtdWebSocketManager: {
101
+ initWebSocket: jest.fn(),
102
+ on: jest.fn(),
103
+ off: jest.fn(),
104
+ close: jest.fn(),
105
+ isSocketClosed: false,
106
+ },
107
+ connectionService: {
108
+ on: jest.fn(),
109
+ off: jest.fn(),
110
+ },
111
+ contact: {},
112
+ dialer: {
113
+ startOutdial: jest.fn(),
114
+ acceptPreviewContact: jest.fn(),
115
+ skipPreviewContact: jest.fn(),
116
+ removePreviewContact: jest.fn(),
117
+ },
118
+ })),
119
+ },
120
+ }));
121
+
122
+ jest.mock('../../../src/services/task/TaskManager', () => ({
123
+ __esModule: true,
124
+ default: {
125
+ getTaskManager: jest.fn(() => ({
126
+ on: jest.fn(),
127
+ off: jest.fn(),
128
+ emit: jest.fn(),
129
+ setConfigFlags: jest.fn(),
130
+ setWrapupData: jest.fn(),
131
+ setAgentId: jest.fn(),
132
+ setAgentName: jest.fn(),
133
+ setWebRtcEnabled: jest.fn(),
134
+ setAnswerCallOnWebexService: jest.fn(),
135
+ registerIncomingCallEvent: jest.fn(),
136
+ registerTaskListeners: jest.fn(),
137
+ unregisterIncomingCallEvent: jest.fn(),
138
+ getTask: jest.fn(),
139
+ getActiveTasks: jest.fn(),
140
+ handleRealtimeWebsocketEvent: jest.fn(),
141
+ clearAISummaryState: jest.fn(),
142
+ })),
143
+ },
144
+ }));
145
+
146
+ jest.mock('../../../src/metrics/MetricsManager', () => ({
147
+ __esModule: true,
148
+ default: {
149
+ getInstance: jest.fn(),
150
+ getCommonTrackingFieldForAQMResponse: jest.fn(() => ({})),
151
+ getCommonTrackingFieldForAQMResponseFailed: jest.fn(() => ({})),
152
+ },
153
+ }));
154
+
155
+ jest.mock('../../../src/services/core/WebexRequest', () => ({
156
+ __esModule: true,
157
+ default: {
158
+ getInstance: jest.fn(() => ({
159
+ request: jest.fn(),
160
+ uploadLogs: jest.fn(),
161
+ })),
162
+ },
163
+ }));
164
+
165
+ jest.mock('../../../src/services/ApiAiAssistant', () => {
166
+ class MockApiAIAssistant {
167
+ public sendEvent = jest.fn();
168
+ public requestAndWaitForRtd = jest.fn();
169
+ public resolveFromRtdEvent = jest.fn();
170
+ public clearAllRtdRequests = jest.fn();
171
+ public getSuggestedResponse = jest.fn();
172
+ public fetchHistoricTranscripts = jest.fn();
173
+ public requestWellnessBreak = jest.fn();
174
+ public respondToWellnessBreak = jest.fn();
175
+ public setAIFeatureFlags = jest.fn();
176
+ public setAgentId = jest.fn();
177
+ }
178
+
179
+ return {
180
+ __esModule: true,
181
+ default: MockApiAIAssistant,
182
+ ApiAIAssistant: MockApiAIAssistant,
183
+ };
184
+ });
185
+
186
+ jest.mock('../../../src/services/WebCallingService', () => {
187
+ class MockWebCallingService {
188
+ public loginOption = 'AGENT_DN';
189
+ public on = jest.fn();
190
+ public getVoiceConnectionState = jest.fn(() => ({
191
+ status: 'unavailable',
192
+ lineStatus: 'unregistered',
193
+ mobiusSocketStatus: 'disconnected',
194
+ }));
195
+ public isBrowserVoiceRequired = jest.fn(() => false);
196
+ public isVoiceReady = jest.fn(() => false);
197
+ public registerWebCallingLine = jest.fn().mockResolvedValue(undefined);
198
+ public deregisterWebCallingLine = jest.fn().mockResolvedValue(undefined);
199
+ public setLoginOption = jest.fn((loginOption: string) => {
200
+ this.loginOption = loginOption;
201
+ });
202
+ public setBrowserVoiceRequired = jest.fn();
203
+ }
204
+
205
+ return {
206
+ __esModule: true,
207
+ default: MockWebCallingService,
208
+ };
209
+ });
210
+
211
+ jest.mock('../../../src/services/task/TaskFactory', () => ({
212
+ __esModule: true,
213
+ default: {
214
+ createTask: jest.fn(),
215
+ },
216
+ }));
217
+
218
+ jest.mock('../../../src/services/task/voice/WebRTC', () => ({
219
+ __esModule: true,
220
+ default: class MockWebRTC {},
221
+ }));
222
+
223
+ jest.mock('../../../src/services/task/taskDataNormalizer', () => ({
224
+ normalizeTaskData: jest.fn((data) => data),
225
+ }));
226
+
227
+ jest.mock('../../../src/services/task/state-machine', () => ({
228
+ ...jest.requireActual('../../../src/services/task/state-machine'),
229
+ createTaskStateMachine: jest.fn(
230
+ jest.requireActual('../../../src/services/task/state-machine').createTaskStateMachine
231
+ ),
232
+ }));
233
+
234
+ jest.mock('../../../src/services/task/state-machine/uiControlsComputer', () => ({
235
+ computeUIControls: jest.fn(() => ({})),
236
+ getDefaultUIControls: jest.fn(() => ({})),
237
+ haveUIControlsChanged: jest.fn(() => false),
238
+ }));
239
+
240
+ jest.mock('../../../src/services/task/AutoWrapup', () => ({
241
+ __esModule: true,
242
+ default: class MockAutoWrapup {},
243
+ }));
244
+
245
+ jest.mock('../../../src/services/EntryPoint', () => {
246
+ class MockEntryPoint {
247
+ public getEntryPoints() {
248
+ return Promise.resolve({});
249
+ }
250
+ }
251
+
252
+ return {
253
+ __esModule: true,
254
+ default: MockEntryPoint,
255
+ EntryPoint: MockEntryPoint,
256
+ };
257
+ });
258
+
259
+ jest.mock('../../../src/services/AddressBook', () => {
260
+ class MockAddressBook {
261
+ public getEntries() {
262
+ return Promise.resolve({});
263
+ }
264
+ }
265
+
266
+ return {
267
+ __esModule: true,
268
+ default: MockAddressBook,
269
+ AddressBook: MockAddressBook,
270
+ };
271
+ });
272
+
273
+ jest.mock('../../../src/services/Queue', () => {
274
+ class MockQueue {
275
+ public getQueues() {
276
+ return Promise.resolve({});
277
+ }
278
+ }
279
+
280
+ return {
281
+ __esModule: true,
282
+ default: MockQueue,
283
+ Queue: MockQueue,
284
+ };
285
+ });
286
+
52
287
  jest.mock('../../../src/services/config');
53
288
  jest.mock('../../../src/services/core/websocket/WebSocketManager');
54
289
  jest.mock('../../../src/services/core/websocket/connection-service');
55
- jest.mock('../../../src/services/WebCallingService');
56
290
  jest.mock('uuid', () => ({v4: () => 'mock-tracking-uuid'}));
57
291
 
58
292
  global.URL.createObjectURL = jest.fn(() => 'blob:http://localhost:3000/12345');
59
293
 
294
+ class EventEmitterDouble extends EventEmitter {
295
+ public isSocketClosed = false;
296
+ public initWebSocket = jest.fn().mockResolvedValue({});
297
+ public close = jest.fn(() => {
298
+ this.isSocketClosed = true;
299
+ });
300
+ public mapCallToTask = jest.fn();
301
+
302
+ public on = jest.fn((eventName: string | symbol, listener: (...args: unknown[]) => void) => {
303
+ super.on(eventName, listener);
304
+
305
+ return this;
306
+ });
307
+
308
+ public off = jest.fn((eventName: string | symbol, listener: (...args: unknown[]) => void) => {
309
+ super.off(eventName, listener);
310
+
311
+ return this;
312
+ });
313
+ }
314
+
315
+ class AISummaryLifecycleTask extends Task {
316
+ public constructor(data: TaskData, apiAIAssistant?: ApiAIAssistant, agentId = 'agent-1') {
317
+ super(
318
+ {} as any,
319
+ data,
320
+ {
321
+ channelType: TASK_CHANNEL_TYPE.VOICE,
322
+ isEndTaskEnabled: true,
323
+ isEndConsultEnabled: true,
324
+ },
325
+ undefined,
326
+ agentId,
327
+ undefined,
328
+ apiAIAssistant
329
+ );
330
+ }
331
+
332
+ public accept() {
333
+ return Promise.resolve({} as any);
334
+ }
335
+ }
336
+
337
+ const createAISummaryLifecycleTask = (
338
+ data: TaskData = createAISummaryLifecycleTaskData(),
339
+ apiAIAssistant?: ApiAIAssistant
340
+ ): AISummaryLifecycleTask => new AISummaryLifecycleTask(data, apiAIAssistant);
341
+
342
+ const createAISummaryLifecycleTaskData = (
343
+ overrides: Partial<TaskData> & {conversationId?: string} = {}
344
+ ): TaskData => {
345
+ const {
346
+ conversationId = 'conversation-1',
347
+ interaction: interactionOverrides,
348
+ ...taskOverrides
349
+ } = overrides;
350
+ const interactionId = taskOverrides.interactionId ?? 'interaction-1';
351
+
352
+ return {
353
+ mediaResourceId: 'media-resource-1',
354
+ eventType: CC_EVENTS.AGENT_CONTACT_ASSIGNED,
355
+ agentId: 'agent-1',
356
+ destAgentId: '',
357
+ trackingId: 'tracking-1',
358
+ consultMediaResourceId: '',
359
+ interactionId,
360
+ orgId: 'org-1',
361
+ owner: 'agent-1',
362
+ queueMgr: 'queue-manager-1',
363
+ type: 'telephony',
364
+ isConferencing: false,
365
+ taskId: 'task-owner-1',
366
+ ...taskOverrides,
367
+ interaction: {
368
+ interactionId,
369
+ mainInteractionId: conversationId,
370
+ mediaType: 'telephony',
371
+ media: {
372
+ [interactionId]: {
373
+ mediaResourceId: 'media-resource-1',
374
+ },
375
+ },
376
+ callProcessingDetails: {},
377
+ ...(interactionOverrides as Record<string, unknown> | undefined),
378
+ },
379
+ } as TaskData;
380
+ };
381
+
60
382
  describe('webex.cc', () => {
61
383
  let webex;
62
384
  let mockApiAIAssistant;
@@ -130,6 +452,7 @@ describe('webex.cc', () => {
130
452
  config: {
131
453
  getAgentConfig: jest.fn(),
132
454
  getOutdialAniEntries: jest.fn(),
455
+ getWellbeingBreakIdleCode: jest.fn(),
133
456
  },
134
457
  webSocketManager: mockWebSocketManager,
135
458
  rtdWebSocketManager: {
@@ -168,15 +491,23 @@ describe('webex.cc', () => {
168
491
  setConfigFlags: jest.fn(),
169
492
  setWrapupData: jest.fn(),
170
493
  setAgentId: jest.fn(),
494
+ setAgentName: jest.fn(),
171
495
  setWebRtcEnabled: jest.fn(),
496
+ setAnswerCallOnWebexService: jest.fn(),
497
+ handleRealtimeWebsocketEvent: jest.fn(),
172
498
  registerIncomingCallEvent: jest.fn(),
173
499
  registerTaskListeners: jest.fn(),
174
500
  getTask: jest.fn(),
175
501
  getActiveTasks: jest.fn(),
502
+ applyEnableWxBetterTogether: jest.fn(),
503
+ syncWxAppMuteFromCallDetailsForAllTasks: jest.fn(),
504
+ refreshWxAppOfferObservabilityForAllTasks: jest.fn(),
176
505
  on: jest.fn(),
177
506
  off: jest.fn(),
178
507
  emit: jest.fn(),
179
508
  unregisterIncomingCallEvent: jest.fn(),
509
+ handleRealtimeWebsocketEvent: jest.fn(),
510
+ clearAISummaryState: jest.fn(),
180
511
  };
181
512
 
182
513
  mockMetricsManager = {
@@ -200,6 +531,7 @@ describe('webex.cc', () => {
200
531
 
201
532
  afterEach(() => {
202
533
  jest.clearAllMocks();
534
+ jest.restoreAllMocks();
203
535
  });
204
536
 
205
537
  it('should initialize services and logger proxy on ready event', () => {
@@ -266,7 +598,7 @@ describe('webex.cc', () => {
266
598
  });
267
599
 
268
600
  describe('register', () => {
269
- const mockAgentProfile: Profile = {
601
+ const createFreshAgentProfile = (overrides: Partial<Profile> = {}): Profile => ({
270
602
  agentId: 'agent123',
271
603
  agentMailId: '',
272
604
  agentName: 'John',
@@ -311,11 +643,18 @@ describe('webex.cc', () => {
311
643
  isEndConsultEnabled: false,
312
644
  agentDbId: '',
313
645
  allowConsultToQueue: false,
646
+ accessQueue: 'SPECIFIC',
647
+ accessEntryPoint: 'ALL',
648
+ accessBuddyTeam: 'ALL',
314
649
  agentPersonalStatsEnabled: false,
315
650
  isTimeoutDesktopInactivityEnabled: false,
316
651
  webRtcEnabled: true,
317
652
  lostConnectionRecoveryTimeout: 0,
318
- };
653
+ isWellnessBreakEnabled: false,
654
+ ...overrides,
655
+ });
656
+
657
+ const mockAgentProfile: Profile = createFreshAgentProfile();
319
658
 
320
659
  it('should register successfully and return agent profile', async () => {
321
660
  mockAgentProfile.aiFeature = {realtimeTranscripts: {enable: true}} as any;
@@ -326,6 +665,7 @@ describe('webex.cc', () => {
326
665
  data: {
327
666
  auxCodeId: 'auxCodeId',
328
667
  agentId: 'agentId',
668
+ agentSessionId: 'session-after-refresh',
329
669
  deviceType: LoginOption.EXTENSION,
330
670
  dn: '12345',
331
671
  },
@@ -365,7 +705,7 @@ describe('webex.cc', () => {
365
705
  resource: SUBSCRIBE_API,
366
706
  });
367
707
 
368
- // TODO: https://jira-eng-gpk2.cisco.com/jira/browse/SPARK-626777 Implement the de-register method and close the listener there
708
+ // SPARK-626777 tracks moving listener cleanup into the future de-register API.
369
709
  expect(mockTaskManager.on).toHaveBeenCalledWith(
370
710
  TASK_EVENTS.TASK_INCOMING,
371
711
  expect.any(Function)
@@ -398,15 +738,26 @@ describe('webex.cc', () => {
398
738
  module: CC_FILE,
399
739
  method: 'connectWebsocket',
400
740
  });
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
- });
741
+ expect(mockTaskManager.setConfigFlags).toHaveBeenCalledWith(
742
+ expect.objectContaining({
743
+ isEndTaskEnabled: mockAgentProfile.isEndTaskEnabled,
744
+ isEndConsultEnabled: mockAgentProfile.isEndConsultEnabled,
745
+ webRtcEnabled: mockAgentProfile.webRtcEnabled,
746
+ autoWrapup: mockAgentProfile.wrapUpData.wrapUpProps.autoWrapup ?? false,
747
+ aiFeature: mockAgentProfile.aiFeature,
748
+ consultTransfer: {
749
+ allowConsultToQueue: mockAgentProfile.allowConsultToQueue,
750
+ accessQueue: mockAgentProfile.accessQueue,
751
+ accessEntryPoint: mockAgentProfile.accessEntryPoint,
752
+ accessBuddyTeam: mockAgentProfile.accessBuddyTeam,
753
+ },
754
+ enableWxBetterTogether: false,
755
+ getWxAppUsersubPublished: expect.any(Function),
756
+ })
757
+ );
758
+ expect(mockTaskManager.clearAISummaryState).not.toHaveBeenCalled();
408
759
  expect(reloadSpy).toHaveBeenCalled();
409
- expect(result).toEqual(mockAgentProfile);
760
+ expect(result).toEqual({...mockAgentProfile, agentSessionId: 'session-after-refresh'});
410
761
  expect(mockMetricsManager.timeEvent).toHaveBeenCalledWith([
411
762
  METRIC_EVENT_NAMES.WEBSOCKET_REGISTER_SUCCESS,
412
763
  METRIC_EVENT_NAMES.WEBSOCKET_REGISTER_FAILED,
@@ -483,6 +834,25 @@ describe('webex.cc', () => {
483
834
  );
484
835
  });
485
836
 
837
+ it('clears wellness session context when registration fails after relogin', async () => {
838
+ const mockError = new Error('Error after silent relogin');
839
+ webex.cc.$config = {...webex.cc.$config, allowAutomatedRelogin: true};
840
+ jest.spyOn(webex.cc.services.config, 'getAgentConfig').mockResolvedValue({
841
+ ...mockAgentProfile,
842
+ webRtcEnabled: false,
843
+ aiFeature: undefined,
844
+ } as Profile);
845
+ mockWebSocketManager.initWebSocket.mockResolvedValue({agentId: 'agent123'});
846
+ jest.spyOn(webex.cc as any, 'silentRelogin').mockImplementation(async () => {
847
+ webex.cc['updateWellnessSession']('partial-session');
848
+ throw mockError;
849
+ });
850
+
851
+ await expect(webex.cc.register()).rejects.toThrow(mockError);
852
+
853
+ expect(webex.cc['currentAgentSessionId']).toBeUndefined();
854
+ });
855
+
486
856
  it('should log error if mercury connect fails but cc.register() should not fail', async () => {
487
857
  const mockError = new Error('Error while performing mercury connect');
488
858
  jest.spyOn(webex.internal.mercury, 'connect').mockRejectedValue(mockError);
@@ -619,8 +989,47 @@ describe('webex.cc', () => {
619
989
  expect(result).toEqual(mockAgentProfile);
620
990
  });
621
991
 
622
- it('should not connect RTD websocket when realtime transcripts feature is disabled', async () => {
623
- mockAgentProfile.aiFeature = {realtimeTranscripts: {enable: false}} as any;
992
+ it('should connect RTD websocket when only wellness breaks are enabled', async () => {
993
+ mockAgentProfile.aiFeature = {
994
+ realtimeTranscripts: {enable: false},
995
+ suggestedResponses: {enable: false},
996
+ } as any;
997
+ mockAgentProfile.isWellnessBreakEnabled = true;
998
+ jest.spyOn(webex.internal.mercury, 'connect').mockResolvedValue(true);
999
+ jest.spyOn(webex.cc.services.agent, 'reload').mockResolvedValue({
1000
+ data: {
1001
+ auxCodeId: 'auxCodeId',
1002
+ agentId: 'agentId',
1003
+ deviceType: LoginOption.EXTENSION,
1004
+ dn: '12345',
1005
+ },
1006
+ });
1007
+ jest.spyOn(webex.cc.services.config, 'getAgentConfig').mockResolvedValue(mockAgentProfile);
1008
+ mockWebSocketManager.initWebSocket.mockResolvedValue({agentId: 'agent123'});
1009
+
1010
+ await webex.cc.register();
1011
+
1012
+ expect(webex.cc.services.rtdWebSocketManager.initWebSocket).toHaveBeenCalledWith({
1013
+ body: {
1014
+ force: true,
1015
+ isKeepAliveEnabled: false,
1016
+ clientType: 'WebexCCSDK',
1017
+ allowMultiLogin: false,
1018
+ },
1019
+ resource: 'v1/realtime/subscribe',
1020
+ });
1021
+ expect(webex.cc.services.rtdWebSocketManager.on).toHaveBeenCalledWith(
1022
+ 'message',
1023
+ expect.any(Function)
1024
+ );
1025
+ });
1026
+
1027
+ it('should not connect RTD websocket when transcripts, suggestions, and wellness are disabled', async () => {
1028
+ mockAgentProfile.aiFeature = {
1029
+ realtimeTranscripts: {enable: false},
1030
+ suggestedResponses: {enable: false},
1031
+ } as any;
1032
+ mockAgentProfile.isWellnessBreakEnabled = false;
624
1033
  jest.spyOn(webex.internal.mercury, 'connect').mockResolvedValue(true);
625
1034
  jest.spyOn(webex.cc.services.agent, 'reload').mockResolvedValue({
626
1035
  data: {
@@ -643,80 +1052,983 @@ describe('webex.cc', () => {
643
1052
  expect.any(Function)
644
1053
  );
645
1054
  });
646
- });
647
1055
 
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
- };
1056
+ it('should connect RTD websocket when either generated summary organization flag is enabled', async () => {
1057
+ jest.spyOn(webex.internal.mercury, 'connect').mockResolvedValue(true);
1058
+ jest.spyOn(webex.cc.services.agent, 'reload').mockResolvedValue({
1059
+ data: {
1060
+ auxCodeId: 'auxCodeId',
1061
+ agentId: 'agentId',
1062
+ deviceType: LoginOption.EXTENSION,
1063
+ dn: '12345',
1064
+ },
1065
+ });
1066
+ mockWebSocketManager.initWebSocket.mockResolvedValue({agentId: 'agent123'});
1067
+
1068
+ for (const generatedSummaries of [
1069
+ {wrapUpSummariesEnabled: true, consultTransferSummariesEnabled: false},
1070
+ {wrapUpSummariesEnabled: false, consultTransferSummariesEnabled: true},
1071
+ ]) {
1072
+ jest.clearAllMocks();
1073
+ jest.spyOn(webex.cc.services.config, 'getAgentConfig').mockResolvedValue({
1074
+ ...mockAgentProfile,
1075
+ aiFeature: {generatedSummaries} as any,
1076
+ });
1077
+
1078
+ await webex.cc.register();
1079
+
1080
+ expect(webex.cc.services.rtdWebSocketManager.initWebSocket).toHaveBeenCalledWith({
1081
+ body: {
1082
+ force: true,
1083
+ isKeepAliveEnabled: false,
1084
+ clientType: 'WebexCCSDK',
1085
+ allowMultiLogin: false,
1086
+ },
1087
+ resource: 'v1/realtime/subscribe',
1088
+ });
1089
+ }
1090
+ });
655
1091
 
656
- webex.cc.agentConfig = {
657
- agentId: 'agentId',
658
- webRtcEnabled: true,
659
- loginVoiceOptions: ['BROWSER', 'EXTENSION', 'AGENT_DN'],
660
- };
1092
+ it.each([
1093
+ {
1094
+ title: 'aiFeature is absent',
1095
+ profileAgentId: 'profile-agent-without-ai-feature',
1096
+ defaultDn: 'normalized-dn-without-ai-feature',
1097
+ aiFeature: undefined,
1098
+ },
1099
+ {
1100
+ title: 'aiFeature has no optional feature objects',
1101
+ profileAgentId: 'profile-agent-with-empty-ai-feature',
1102
+ defaultDn: 'normalized-dn-with-empty-ai-feature',
1103
+ aiFeature: {} as any,
1104
+ },
1105
+ ])(
1106
+ 'should tolerate absent AI feature shapes without summary-driven RTD setup when $title',
1107
+ async ({profileAgentId, defaultDn, aiFeature}) => {
1108
+ const welcomeAgentId = 'welcome-agent-for-absent-ai-feature';
1109
+ const configuredProfile = createFreshAgentProfile({
1110
+ agentId: profileAgentId,
1111
+ defaultDn,
1112
+ dn: 'pre-register-dn',
1113
+ webRtcEnabled: true,
1114
+ aiFeature,
1115
+ });
1116
+ const expectedProfile = {...configuredProfile, dn: defaultDn};
1117
+ webex.cc.$config = {...webex.cc.$config, allowAutomatedRelogin: false};
1118
+ jest.spyOn(webex.internal.mercury, 'connect').mockResolvedValue(true);
1119
+ const configSpy = jest
1120
+ .spyOn(webex.cc.services.config, 'getAgentConfig')
1121
+ .mockResolvedValue(configuredProfile);
1122
+ mockWebSocketManager.initWebSocket.mockResolvedValue({agentId: welcomeAgentId});
1123
+
1124
+ await expect(webex.cc.register()).resolves.toEqual(expectedProfile);
1125
+
1126
+ expect(configSpy).toHaveBeenCalledWith('mockOrgId', welcomeAgentId);
1127
+ expect(webex.cc.services.rtdWebSocketManager.initWebSocket).not.toHaveBeenCalled();
1128
+ }
1129
+ );
661
1130
 
662
- const registerWebCallingLineSpy = jest.spyOn(
663
- webex.cc.webCallingService,
664
- 'registerWebCallingLine'
665
- );
1131
+ it.each([
1132
+ {
1133
+ title: 'all generated summary organization flags are disabled',
1134
+ aiFeature: {
1135
+ realtimeTranscripts: {enable: false},
1136
+ suggestedResponses: {enable: false},
1137
+ generatedSummaries: {
1138
+ wrapUpSummariesEnabled: false,
1139
+ consultTransferSummariesEnabled: false,
1140
+ },
1141
+ } as any,
1142
+ },
1143
+ ])(
1144
+ 'should keep registration operational without summary-driven RTD setup when $title',
1145
+ async ({aiFeature}) => {
1146
+ const welcomeAgentId = 'welcome-agent-with-disabled-summaries';
1147
+ const configuredProfile = createFreshAgentProfile({
1148
+ agentId: 'profile-agent-with-disabled-summaries',
1149
+ defaultDn: 'normalized-dn-with-disabled-summaries',
1150
+ dn: 'pre-register-dn',
1151
+ webRtcEnabled: true,
1152
+ aiFeature,
1153
+ });
1154
+ const expectedProfile = {...configuredProfile, dn: configuredProfile.defaultDn};
1155
+ webex.cc.$config = {...webex.cc.$config, allowAutomatedRelogin: false};
1156
+ const mercuryConnect = jest
1157
+ .spyOn(webex.internal.mercury, 'connect')
1158
+ .mockResolvedValue(true);
1159
+ const setupEventListenersSpy = jest.spyOn(webex.cc, 'setupEventListeners');
1160
+ const configSpy = jest
1161
+ .spyOn(webex.cc.services.config, 'getAgentConfig')
1162
+ .mockResolvedValue(configuredProfile);
1163
+ mockWebSocketManager.initWebSocket.mockResolvedValue({agentId: welcomeAgentId});
1164
+
1165
+ const result = await webex.cc.register();
1166
+
1167
+ expect(mockWebSocketManager.initWebSocket).toHaveBeenCalledWith({
1168
+ body: {
1169
+ force: true,
1170
+ isKeepAliveEnabled: false,
1171
+ clientType: 'WebexCCSDK',
1172
+ allowMultiLogin: false,
1173
+ },
1174
+ resource: SUBSCRIBE_API,
1175
+ });
1176
+ expect(configSpy).toHaveBeenCalledWith('mockOrgId', welcomeAgentId);
1177
+ expect(setupEventListenersSpy).toHaveBeenCalled();
1178
+ expect(mockTaskManager.on).toHaveBeenCalledWith(
1179
+ TASK_EVENTS.TASK_INCOMING,
1180
+ expect.any(Function)
1181
+ );
1182
+ expect(mockTaskManager.on).toHaveBeenCalledWith(
1183
+ TASK_EVENTS.TASK_HYDRATE,
1184
+ expect.any(Function)
1185
+ );
1186
+ expect(mockTaskManager.on).toHaveBeenCalledWith(
1187
+ TASK_EVENTS.TASK_MULTI_LOGIN_HYDRATE,
1188
+ expect.any(Function)
1189
+ );
1190
+ expect(mockWebSocketManager.on).toHaveBeenCalledWith('message', expect.any(Function));
1191
+ expect(mockTaskManager.setConfigFlags).toHaveBeenCalledWith({
1192
+ isEndTaskEnabled: configuredProfile.isEndTaskEnabled,
1193
+ isEndConsultEnabled: configuredProfile.isEndConsultEnabled,
1194
+ webRtcEnabled: configuredProfile.webRtcEnabled,
1195
+ autoWrapup: configuredProfile.wrapUpData.wrapUpProps.autoWrapup ?? false,
1196
+ aiFeature,
1197
+ getWxAppUsersubPublished: expect.any(Function),
1198
+ consultTransfer: {
1199
+ allowConsultToQueue: configuredProfile.allowConsultToQueue,
1200
+ accessQueue: configuredProfile.accessQueue,
1201
+ accessEntryPoint: configuredProfile.accessEntryPoint,
1202
+ accessBuddyTeam: configuredProfile.accessBuddyTeam,
1203
+ },
1204
+ enableWxBetterTogether: false,
1205
+ });
1206
+ expect(webex.cc.services.rtdWebSocketManager.initWebSocket).not.toHaveBeenCalled();
1207
+ expect(webex.cc.services.rtdWebSocketManager.on).not.toHaveBeenCalledWith(
1208
+ 'message',
1209
+ expect.any(Function)
1210
+ );
1211
+ expect(mercuryConnect).toHaveBeenCalled();
1212
+ expect(result).toEqual(expectedProfile);
1213
+ }
1214
+ );
1215
+ });
666
1216
 
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'],
1217
+ describe('AI summary lifecycle wiring', () => {
1218
+ const sentinels = [
1219
+ 'summary-sentinel-cc-lifecycle',
1220
+ 'section-key-sentinel-cc-lifecycle',
1221
+ 'section-value-sentinel-cc-lifecycle',
1222
+ 'adaptive-card-sentinel-cc-lifecycle',
1223
+ 'agent-name-sentinel-cc-lifecycle',
1224
+ ];
1225
+
1226
+ const createSummaryHarness = () => {
1227
+ const ActualTaskManager = jest.requireActual('../../../src/services/task/TaskManager')
1228
+ .default as typeof TaskManager;
1229
+ const webSocketManager = new EventEmitterDouble();
1230
+ const rtdWebSocketManager = new EventEmitterDouble();
1231
+ const connectionService = new EventEmitterDouble();
1232
+ const webCallingService = new EventEmitterDouble();
1233
+ const transportDeferreds: Deferred<void>[] = [];
1234
+ const pendingRequests = new Map<string, any>();
1235
+ const apiAIAssistant: any = {
1236
+ aiFeature: {
1237
+ id: 'test-ai-feature',
1238
+ generatedSummaries: {
1239
+ wrapUpSummariesEnabled: true,
1240
+ consultTransferSummariesEnabled: true,
685
1241
  },
686
1242
  },
687
- trackingId: 'notifs_52628',
688
- orgId: 'orgId',
689
- type: 'StationLoginSuccess',
690
- eventType: 'STATION_LOGIN',
1243
+ getSuggestedResponse: jest.fn(),
1244
+ fetchHistoricTranscripts: jest.fn(),
1245
+ setAIFeatureFlags: jest.fn((flags: AIFeatureFlags) => {
1246
+ apiAIAssistant.aiFeature = flags;
1247
+ }),
1248
+ setAgentId: jest.fn(),
1249
+ pendingRequests,
1250
+ sendEvent: jest.fn((_agentId: string, _interactionId: string, _eventType: string, eventName: string) => {
1251
+ if (eventName.includes('SUMMARY_RESPONSE')) {
1252
+ return Promise.resolve(undefined);
1253
+ }
1254
+
1255
+ const deferred = createDeferred<void>();
1256
+
1257
+ transportDeferreds.push(deferred);
1258
+
1259
+ return deferred.promise;
1260
+ }),
691
1261
  };
1262
+ apiAIAssistant.requestAndWaitForRtd = jest.fn(async (options: any) => {
1263
+ const publishTimestamp = Date.now();
1264
+ let resolveResult: (payload: any) => void = () => undefined;
1265
+ let rejectResult: (error: Error) => void = () => undefined;
1266
+ const result = new Promise((resolve, reject) => {
1267
+ resolveResult = resolve;
1268
+ rejectResult = reject;
1269
+ });
1270
+ const key = JSON.stringify([options.rtdEventType, options.correlationId]);
1271
+ pendingRequests.set(key, {
1272
+ eventType: options.rtdEventType,
1273
+ correlationId: options.correlationId,
1274
+ resolve: resolveResult,
1275
+ reject: rejectResult,
1276
+ result,
1277
+ });
1278
+ try {
1279
+ const acknowledgement = apiAIAssistant.sendEvent(
1280
+ options.agentId,
1281
+ options.interactionId,
1282
+ options.eventType,
1283
+ options.eventName,
1284
+ options.eventMetaData,
1285
+ undefined,
1286
+ undefined,
1287
+ publishTimestamp,
1288
+ options.timeout
1289
+ );
1290
+ const [payload] = await Promise.all([result, acknowledgement]);
1291
+ pendingRequests.delete(key);
1292
+ return payload;
1293
+ } catch (error) {
1294
+ pendingRequests.delete(key);
1295
+ throw error;
1296
+ }
1297
+ });
1298
+ apiAIAssistant.resolveFromRtdEvent = jest.fn(
1299
+ (eventType: string, correlationId: string, payload: any) => {
1300
+ const key = JSON.stringify([eventType, correlationId]);
1301
+ const request = pendingRequests.get(key);
1302
+ if (!request) return 'not-found';
1303
+ pendingRequests.delete(key);
1304
+ request.resolve(payload);
1305
+ return 'resolved';
1306
+ }
1307
+ );
1308
+ apiAIAssistant.clearAllRtdRequests = jest.fn(() => {
1309
+ pendingRequests.forEach((request) => {
1310
+ const error = new Error(AI_SUMMARY_REQUEST_CANCELLED) as Error & {
1311
+ data?: Record<string, unknown>;
1312
+ };
1313
+ error.data = {errorCode: AI_SUMMARY_REQUEST_CANCELLED};
1314
+ request.reject(error);
1315
+ });
1316
+ pendingRequests.clear();
1317
+ });
1318
+ const taskManager = new ActualTaskManager(
1319
+ apiAIAssistant as any,
1320
+ mockContact,
1321
+ webCallingService as any,
1322
+ webSocketManager as any,
1323
+ rtdWebSocketManager as any
1324
+ );
1325
+ const taskFactory = jest.requireMock('../../../src/services/task/TaskFactory')
1326
+ .default as {createTask: jest.Mock};
1327
+
1328
+ taskFactory.createTask.mockImplementation(
1329
+ (
1330
+ _contact,
1331
+ _webCallingService,
1332
+ taskData: TaskData,
1333
+ _configFlags,
1334
+ _wrapupData,
1335
+ _agentId,
1336
+ _agentName,
1337
+ _answerCallService,
1338
+ taskApiAIAssistant: ApiAIAssistant
1339
+ ) => createAISummaryLifecycleTask(taskData, taskApiAIAssistant)
1340
+ );
1341
+ const task = createAISummaryLifecycleTask(undefined, apiAIAssistant);
692
1342
 
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,
1343
+ taskManager.setConfigFlags({
1344
+ isEndTaskEnabled: true,
1345
+ isEndConsultEnabled: true,
1346
+ webRtcEnabled: false,
1347
+ autoWrapup: false,
1348
+ aiFeature: {
1349
+ generatedSummaries: {
1350
+ wrapUpSummariesEnabled: true,
1351
+ consultTransferSummariesEnabled: true,
1352
+ },
706
1353
  },
707
- notifsTrackingId: 'notifs_52628',
1354
+ } as any);
1355
+ taskManager.setAgentId('agent-1');
1356
+ taskManager.setWebRtcEnabled(false);
1357
+ (taskManager as any).taskCollection[task.data.interactionId] = task;
1358
+
1359
+ (webex.cc as any).taskManager = taskManager;
1360
+ webex.cc.apiAIAssistant = apiAIAssistant as any;
1361
+ webex.cc.services.webSocketManager = webSocketManager as any;
1362
+ webex.cc.services.rtdWebSocketManager = rtdWebSocketManager as any;
1363
+ webex.cc.services.connectionService = connectionService as any;
1364
+
1365
+ const emitRtdFrame = (type: string, data: Record<string, unknown>) => {
1366
+ rtdWebSocketManager.emit('message', JSON.stringify({type, data: {data}}));
1367
+ };
1368
+ const dispatchRtdFrame = (type: string, data: Record<string, unknown>) => {
1369
+ webex.cc['handleRTDWebsocketMessage'](JSON.stringify({type, data: {data}}));
1370
+ };
1371
+ const getApiAIAssistant = () => apiAIAssistant as any;
1372
+ const getSummaryMapCounts = () => {
1373
+ const api = getApiAIAssistant() as any;
1374
+ const manager = taskManager as any;
1375
+ const pendingRequests = Array.from(api.pendingRequests.values());
1376
+
1377
+ return {
1378
+ pendingPostCall: pendingRequests.filter(
1379
+ (request: any) => request.eventType === 'POST_CALL_SUMMARY'
1380
+ ).length,
1381
+ pendingMidCall: pendingRequests.filter(
1382
+ (request: any) => request.eventType === 'MID_CALL_SUMMARY'
1383
+ ).length,
1384
+ receiving: manager.receivingSummaryBuffer.size,
1385
+ featureEnablement: manager.pendingFeatureEnablement.size,
1386
+ };
1387
+ };
1388
+ const expectSummaryStateCleared = () => {
1389
+ expect(getSummaryMapCounts()).toEqual({
1390
+ pendingPostCall: 0,
1391
+ pendingMidCall: 0,
1392
+ receiving: 0,
1393
+ featureEnablement: 0,
1394
+ });
708
1395
  };
709
1396
 
710
- const stationLoginMock = jest
711
- .spyOn(webex.cc.services.agent, 'stationLogin')
712
- .mockResolvedValue(mockData as unknown as StationLoginSuccess);
1397
+ return {
1398
+ apiAIAssistant,
1399
+ connectionService,
1400
+ dispatchRtdFrame,
1401
+ emitRtdFrame,
1402
+ expectSummaryStateCleared,
1403
+ getApiAIAssistant,
1404
+ getSummaryMapCounts,
1405
+ rtdWebSocketManager,
1406
+ task,
1407
+ taskManager,
1408
+ transportDeferreds,
1409
+ webSocketManager,
1410
+ };
1411
+ };
713
1412
 
714
- const result = await webex.cc.stationLogin(options);
1413
+ const attachRtdMessageListener = (rtdWebSocketManager: EventEmitterDouble) => {
1414
+ rtdWebSocketManager.on('message', webex.cc['handleRTDWebsocketMessage']);
1415
+ };
715
1416
 
716
- expect(registerWebCallingLineSpy).toHaveBeenCalled();
717
- expect(stationLoginMock).toHaveBeenCalledWith({
718
- data: {
719
- dialNumber: 'agentId',
1417
+ const countAISummaryRequestFinalMetrics = () =>
1418
+ mockMetricsManager.trackEvent.mock.calls.filter(([eventName]) =>
1419
+ [
1420
+ METRIC_EVENT_NAMES.AI_SUMMARY_GET_POST_CALL_SUCCESS,
1421
+ METRIC_EVENT_NAMES.AI_SUMMARY_GET_POST_CALL_FAILED,
1422
+ METRIC_EVENT_NAMES.AI_SUMMARY_GET_MID_CALL_SUCCESS,
1423
+ METRIC_EVENT_NAMES.AI_SUMMARY_GET_MID_CALL_FAILED,
1424
+ ].includes(eventName)
1425
+ ).length;
1426
+
1427
+ const expectSentinelsNotObserved = () => {
1428
+ const observedArguments = JSON.stringify([
1429
+ LoggerProxy.log.mock.calls,
1430
+ LoggerProxy.info.mock.calls,
1431
+ LoggerProxy.warn.mock.calls,
1432
+ LoggerProxy.error.mock.calls,
1433
+ mockMetricsManager.trackEvent.mock.calls,
1434
+ mockMetricsManager.timeEvent.mock.calls,
1435
+ ]);
1436
+
1437
+ sentinels.forEach((sentinel) => {
1438
+ expect(observedArguments).not.toContain(sentinel);
1439
+ });
1440
+ };
1441
+
1442
+ const emitFeatureEnablement = (
1443
+ harness: ReturnType<typeof createSummaryHarness>,
1444
+ payload = {
1445
+ interactionId: 'interaction-1',
1446
+ postCallEnabled: true,
1447
+ midCallEnabled: true,
1448
+ actionTimestamp: 1,
1449
+ }
1450
+ ) => {
1451
+ harness.emitRtdFrame(CC_TASK_EVENTS.FEATURE_ENABLEMENT, payload);
1452
+ };
1453
+
1454
+ const dispatchFeatureEnablement = (
1455
+ harness: ReturnType<typeof createSummaryHarness>,
1456
+ payload = {
1457
+ interactionId: 'interaction-1',
1458
+ postCallEnabled: true,
1459
+ midCallEnabled: true,
1460
+ actionTimestamp: 1,
1461
+ }
1462
+ ) => {
1463
+ harness.dispatchRtdFrame(CC_TASK_EVENTS.FEATURE_ENABLEMENT, payload);
1464
+ };
1465
+
1466
+ const emitTaskLifecycleEvent = (
1467
+ harness: ReturnType<typeof createSummaryHarness>,
1468
+ eventType: CC_EVENTS,
1469
+ overrides: Partial<TaskData> & {conversationId?: string}
1470
+ ) => {
1471
+ const interactionId = overrides.interactionId ?? 'interaction-1';
1472
+
1473
+ harness.webSocketManager.emit(
1474
+ 'message',
1475
+ JSON.stringify({
1476
+ data: {
1477
+ ...createAISummaryLifecycleTaskData({
1478
+ mediaResourceId: interactionId,
1479
+ taskId: `task-owner-${interactionId}`,
1480
+ ...overrides,
1481
+ }),
1482
+ type: eventType,
1483
+ },
1484
+ })
1485
+ );
1486
+ };
1487
+
1488
+ const emitSentinelPostCallSummary = (
1489
+ harness: ReturnType<typeof createSummaryHarness>,
1490
+ conversationId = 'conversation-1'
1491
+ ) => {
1492
+ harness.emitRtdFrame(CC_TASK_EVENTS.POST_CALL_SUMMARY, {
1493
+ conversationId,
1494
+ summaryText: sentinels[0],
1495
+ sections: {
1496
+ [sentinels[1]]: sentinels[2],
1497
+ initialContactReason: sentinels[2],
1498
+ },
1499
+ adaptiveCard: {
1500
+ body: [{text: sentinels[3]}],
1501
+ },
1502
+ });
1503
+ };
1504
+
1505
+ const dispatchSentinelPostCallSummary = (
1506
+ harness: ReturnType<typeof createSummaryHarness>,
1507
+ conversationId = 'conversation-1'
1508
+ ) => {
1509
+ harness.dispatchRtdFrame(CC_TASK_EVENTS.POST_CALL_SUMMARY, {
1510
+ conversationId,
1511
+ summaryText: sentinels[0],
1512
+ sections: {
1513
+ [sentinels[1]]: sentinels[2],
1514
+ initialContactReason: sentinels[2],
1515
+ },
1516
+ adaptiveCard: {
1517
+ body: [{text: sentinels[3]}],
1518
+ },
1519
+ });
1520
+ };
1521
+
1522
+ const emitSentinelMidCallSummary = (
1523
+ harness: ReturnType<typeof createSummaryHarness>,
1524
+ conversationId = 'conversation-1'
1525
+ ) => {
1526
+ harness.emitRtdFrame(CC_TASK_EVENTS.MID_CALL_SUMMARY, {
1527
+ conversationId,
1528
+ summaryText: sentinels[0],
1529
+ agentName: sentinels[4],
1530
+ sections: {
1531
+ [sentinels[1]]: sentinels[2],
1532
+ reasonForTransferOrConsult: sentinels[2],
1533
+ },
1534
+ adaptiveCard: {
1535
+ body: [{text: sentinels[3]}],
1536
+ },
1537
+ });
1538
+ };
1539
+
1540
+ afterEach(() => {
1541
+ jest.useRealTimers();
1542
+ });
1543
+
1544
+ it('forwards task-manager handlers through ContactCenter trigger and delegates RTD messages', () => {
1545
+ const triggerSpy = jest.spyOn(webex.cc, 'trigger');
1546
+ const task = {data: {interactionId: 'interaction-1'}} as any;
1547
+
1548
+ webex.cc['handleTaskHydrate'](task);
1549
+ webex.cc['handleTaskMultiLoginHydrate'](task);
1550
+ webex.cc['handleTaskMerged'](task);
1551
+ webex.cc['handleCampaignPreviewReservation'](task);
1552
+ webex.cc['handleRTDWebsocketMessage']('summary-frame');
1553
+
1554
+ expect(triggerSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_HYDRATE, task);
1555
+ expect(triggerSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_MULTI_LOGIN_HYDRATE, task);
1556
+ expect(triggerSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_MERGED, task);
1557
+ expect(triggerSpy).toHaveBeenCalledWith(TASK_EVENTS.TASK_CAMPAIGN_PREVIEW_RESERVATION, task);
1558
+ expect(mockTaskManager.handleRealtimeWebsocketEvent).toHaveBeenCalledWith('summary-frame');
1559
+ });
1560
+
1561
+ it('clears active summary state on deregister', async () => {
1562
+ jest.useFakeTimers();
1563
+
1564
+ const harness = createSummaryHarness();
1565
+ const triggerSpy = jest.spyOn(webex.cc, 'trigger');
1566
+ const profile = {
1567
+ agentId: 'agent-1',
1568
+ webRtcEnabled: false,
1569
+ loginVoiceOptions: [LoginOption.EXTENSION],
1570
+ isEndTaskEnabled: true,
1571
+ isEndConsultEnabled: true,
1572
+ wrapUpData: {wrapUpProps: {autoWrapup: false}},
1573
+ aiFeature: {
1574
+ generatedSummaries: {
1575
+ wrapUpSummariesEnabled: true,
1576
+ consultTransferSummariesEnabled: true,
1577
+ },
1578
+ },
1579
+ } as any;
1580
+
1581
+ webex.cc.$config = {...webex.cc.$config, allowAutomatedRelogin: false};
1582
+ harness.webSocketManager.initWebSocket.mockResolvedValue({agentId: 'agent-1'});
1583
+ jest.spyOn(webex.cc.services.config, 'getAgentConfig').mockResolvedValue(profile);
1584
+
1585
+ await webex.cc.register();
1586
+ await flushMicrotasks();
1587
+
1588
+ expect(harness.rtdWebSocketManager.listenerCount('message')).toBe(1);
1589
+
1590
+ dispatchFeatureEnablement(harness);
1591
+ expect(harness.task.aiSummaryCapabilities).toEqual({
1592
+ midCallEnabled: true,
1593
+ postCallEnabled: true,
1594
+ });
1595
+
1596
+ dispatchFeatureEnablement(harness, {
1597
+ interactionId: 'orphan-before-deregister',
1598
+ postCallEnabled: true,
1599
+ midCallEnabled: true,
1600
+ actionTimestamp: 4,
1601
+ });
1602
+ harness.dispatchRtdFrame(CC_TASK_EVENTS.MID_CALL_SUMMARY_RESPONSE_SUBSEQUENT_AGENT, {
1603
+ conversationId: 'queued-before-deregister',
1604
+ summaryText: sentinels[0],
1605
+ });
1606
+ expect(jest.getTimerCount()).toBe(0);
1607
+ expect(harness.task.aiSummaryCapabilities).toEqual({
1608
+ midCallEnabled: true,
1609
+ postCallEnabled: true,
1610
+ });
1611
+ expect(harness.getSummaryMapCounts()).toEqual({
1612
+ pendingPostCall: 0,
1613
+ pendingMidCall: 0,
1614
+ receiving: 1,
1615
+ featureEnablement: 1,
1616
+ });
1617
+ expect(jest.getTimerCount()).toBe(0);
1618
+
1619
+ await webex.cc.deregister();
1620
+
1621
+ harness.expectSummaryStateCleared();
1622
+ expect(harness.task.aiSummaryCapabilities).toEqual({
1623
+ midCallEnabled: false,
1624
+ postCallEnabled: false,
1625
+ });
1626
+ expect(jest.getTimerCount()).toBe(0);
1627
+ expect(harness.rtdWebSocketManager.listenerCount('message')).toBe(0);
1628
+ triggerSpy.mockClear();
1629
+
1630
+ dispatchSentinelPostCallSummary(harness, 'queued-after-deregister');
1631
+
1632
+ expect(harness.getSummaryMapCounts()).toEqual({
1633
+ pendingPostCall: 0,
1634
+ pendingMidCall: 0,
1635
+ receiving: 0,
1636
+ featureEnablement: 0,
1637
+ });
1638
+ expect(triggerSpy).not.toHaveBeenCalled();
1639
+ expectSentinelsNotObserved();
1640
+ });
1641
+
1642
+ it('flushes a buffered receiving summary through real TaskManager task publication once the task is answered', () => {
1643
+ jest.useFakeTimers();
1644
+
1645
+ const harness = createSummaryHarness();
1646
+ const interactionId = 'receiver-arrival-interaction';
1647
+ const conversationId = interactionId;
1648
+ const receivingPayload = {
1649
+ conversationId,
1650
+ summaryText: sentinels[0],
1651
+ adaptiveCard: {body: [{text: sentinels[3]}]},
1652
+ };
1653
+ const receiverHandler = jest.fn();
1654
+ const observedOrder: string[] = [];
1655
+ let publishedTask: Task | undefined;
1656
+ let receiverEmitSpy: jest.SpyInstance | undefined;
1657
+
1658
+ harness.dispatchRtdFrame(CC_TASK_EVENTS.MID_CALL_SUMMARY_RESPONSE_SUBSEQUENT_AGENT, {
1659
+ ...receivingPayload,
1660
+ });
1661
+
1662
+ expect(harness.getSummaryMapCounts()).toEqual({
1663
+ pendingPostCall: 0,
1664
+ pendingMidCall: 0,
1665
+ receiving: 1,
1666
+ featureEnablement: 0,
1667
+ });
1668
+ expect(jest.getTimerCount()).toBe(0);
1669
+
1670
+ harness.taskManager.on(TASK_EVENTS.TASK_INCOMING, (task: Task) => {
1671
+ publishedTask = task;
1672
+ receiverEmitSpy = jest.spyOn(task, 'emit');
1673
+ task.on(TASK_EVENTS.TASK_ASSIGNED, () => observedOrder.push('answered'));
1674
+ task.on(TASK_EVENTS.TASK_MID_CALL_SUMMARY_RECEIVED, (payload) => {
1675
+ observedOrder.push('receiver-summary');
1676
+ receiverHandler(payload);
1677
+ });
1678
+ });
1679
+
1680
+ emitTaskLifecycleEvent(harness, CC_EVENTS.AGENT_CONTACT_RESERVED, {
1681
+ interactionId,
1682
+ conversationId,
1683
+ });
1684
+
1685
+ expect(publishedTask).toBe(harness.taskManager.getTask(interactionId));
1686
+ expect(publishedTask).toBeInstanceOf(Task);
1687
+ expect(receiverHandler).not.toHaveBeenCalled();
1688
+ expect(harness.getSummaryMapCounts().receiving).toBe(1);
1689
+
1690
+ emitTaskLifecycleEvent(harness, CC_EVENTS.AGENT_CONTACT_ASSIGNED, {
1691
+ interactionId,
1692
+ conversationId,
1693
+ });
1694
+
1695
+ expect(observedOrder).toEqual(['answered', 'receiver-summary']);
1696
+ expect(receiverHandler).toHaveBeenCalledTimes(1);
1697
+ expect(receiverHandler).toHaveBeenCalledWith(receivingPayload);
1698
+ expect(
1699
+ receiverEmitSpy?.mock.calls.filter(
1700
+ ([eventName]) => eventName === TASK_EVENTS.TASK_MID_CALL_SUMMARY_RECEIVED
1701
+ )
1702
+ ).toHaveLength(1);
1703
+ expect(harness.getSummaryMapCounts()).toEqual({
1704
+ pendingPostCall: 0,
1705
+ pendingMidCall: 0,
1706
+ receiving: 0,
1707
+ featureEnablement: 0,
1708
+ });
1709
+ expect(jest.getTimerCount()).toBe(0);
1710
+ expectSentinelsNotObserved();
1711
+ });
1712
+
1713
+ it('resolves a real post-call request through RTD and keeps summary sentinels out of metrics', async () => {
1714
+ jest.useFakeTimers();
1715
+
1716
+ const harness = createSummaryHarness();
1717
+
1718
+ attachRtdMessageListener(harness.rtdWebSocketManager);
1719
+ emitFeatureEnablement(harness);
1720
+ jest.clearAllMocks();
1721
+
1722
+ const postCallRequest = harness.task.requestPostCallSummary();
1723
+
1724
+ await flushMicrotasks();
1725
+ expect(harness.apiAIAssistant.sendEvent).toHaveBeenCalledWith(
1726
+ 'agent-1',
1727
+ 'interaction-1',
1728
+ AIAssistantEventType.CTI_EVENT,
1729
+ AIAssistantEventName.GET_POST_CALL_SUMMARY,
1730
+ expect.objectContaining({conversationId: 'conversation-1'}),
1731
+ undefined,
1732
+ undefined,
1733
+ expect.any(Number),
1734
+ 15000
1735
+ );
1736
+ emitSentinelPostCallSummary(harness);
1737
+ harness.transportDeferreds[0].resolve(undefined);
1738
+
1739
+ await expect(postCallRequest).resolves.toMatchObject({
1740
+ conversationId: 'conversation-1',
1741
+ summaryText: sentinels[0],
1742
+ });
1743
+ expect(harness.getSummaryMapCounts()).toEqual({
1744
+ pendingPostCall: 0,
1745
+ pendingMidCall: 0,
1746
+ receiving: 0,
1747
+ featureEnablement: 0,
1748
+ });
1749
+ expect(jest.getTimerCount()).toBe(0);
1750
+ expect(mockMetricsManager.trackEvent).toHaveBeenCalledWith(
1751
+ METRIC_EVENT_NAMES.AI_SUMMARY_GET_POST_CALL_SUCCESS,
1752
+ expect.objectContaining({
1753
+ conversationId: 'conversation-1',
1754
+ interactionId: 'interaction-1',
1755
+ }),
1756
+ ['operational']
1757
+ );
1758
+ harness.taskManager.clearAISummaryState();
1759
+ harness.expectSummaryStateCleared();
1760
+ expectSentinelsNotObserved();
1761
+ });
1762
+
1763
+ it('sends post-call responses using current task data after manager cleanup', async () => {
1764
+ jest.useFakeTimers();
1765
+
1766
+ const harness = createSummaryHarness();
1767
+ const interactionId = 'post-call-cleanup-interaction';
1768
+ const conversationId = 'post-call-cleanup-conversation';
1769
+ const apiAIAssistant = harness.getApiAIAssistant();
1770
+ let applicationTask: Task | undefined;
1771
+
1772
+ harness.taskManager.on(TASK_EVENTS.TASK_INCOMING, (task: Task) => {
1773
+ if (task.data.interactionId === interactionId) {
1774
+ applicationTask = task;
1775
+ }
1776
+ });
1777
+ emitTaskLifecycleEvent(harness, CC_EVENTS.AGENT_CONTACT_RESERVED, {
1778
+ interactionId,
1779
+ conversationId,
1780
+ });
1781
+ emitTaskLifecycleEvent(harness, CC_EVENTS.AGENT_CONTACT_ASSIGNED, {
1782
+ interactionId,
1783
+ conversationId,
1784
+ });
1785
+
1786
+ expect(applicationTask).toBe(harness.taskManager.getTask(interactionId));
1787
+ const retainedTask = applicationTask as Task;
1788
+
1789
+ dispatchFeatureEnablement(harness, {
1790
+ interactionId,
1791
+ postCallEnabled: true,
1792
+ midCallEnabled: true,
1793
+ actionTimestamp: 9,
1794
+ });
1795
+
1796
+ const postCallRequest = retainedTask.requestPostCallSummary();
1797
+
1798
+ await flushMicrotasks();
1799
+ expect(postCallRequest).toBeDefined();
1800
+ expect(harness.apiAIAssistant.sendEvent).toHaveBeenCalledWith(
1801
+ 'agent-1',
1802
+ interactionId,
1803
+ AIAssistantEventType.CTI_EVENT,
1804
+ AIAssistantEventName.GET_POST_CALL_SUMMARY,
1805
+ expect.objectContaining({conversationId}),
1806
+ undefined,
1807
+ undefined,
1808
+ expect.any(Number),
1809
+ 15000
1810
+ );
1811
+ harness.dispatchRtdFrame(CC_TASK_EVENTS.POST_CALL_SUMMARY, {
1812
+ conversationId,
1813
+ summaryText: sentinels[0],
1814
+ });
1815
+ harness.transportDeferreds[0].resolve(undefined);
1816
+
1817
+ await expect(postCallRequest).resolves.toMatchObject({
1818
+ conversationId,
1819
+ summaryText: sentinels[0],
1820
+ });
1821
+ expect(harness.getSummaryMapCounts()).toEqual({
1822
+ pendingPostCall: 0,
1823
+ pendingMidCall: 0,
1824
+ receiving: 0,
1825
+ featureEnablement: 0,
1826
+ });
1827
+
1828
+ emitTaskLifecycleEvent(harness, CC_EVENTS.AGENT_WRAPUP, {
1829
+ interactionId,
1830
+ conversationId,
1831
+ });
1832
+ emitTaskLifecycleEvent(harness, CC_EVENTS.AGENT_WRAPPEDUP, {
1833
+ interactionId,
1834
+ conversationId,
1835
+ });
1836
+
1837
+ expect(harness.taskManager.getTask(interactionId)).toBeUndefined();
1838
+ expect(harness.getSummaryMapCounts()).toEqual({
1839
+ pendingPostCall: 0,
1840
+ pendingMidCall: 0,
1841
+ receiving: 0,
1842
+ featureEnablement: 0,
1843
+ });
1844
+ expect(jest.getTimerCount()).toBe(0);
1845
+
1846
+ const requestCallsAfterRemoval = (apiAIAssistant as any).pendingRequests.size;
1847
+ const responseInteractionId = 'post-call-response-current-interaction';
1848
+ const responseConversationId = 'post-call-response-current-conversation';
1849
+
1850
+ retainedTask.updateTaskData(
1851
+ createAISummaryLifecycleTaskData({
1852
+ interactionId: responseInteractionId,
1853
+ conversationId: responseConversationId,
1854
+ }),
1855
+ true
1856
+ );
1857
+
1858
+ const responsePayload: AISummaryResponse = {
1859
+ summary: {initialContactReason: 'resolved'},
1860
+ feedback: 'thumbs_up',
1861
+ state: 'DEFAULT',
1862
+ wrapUpCode: 'resolved',
1863
+ numberOfTimesViewed: 1,
1864
+ numberOfTimesEdited: 0,
1865
+ numberOfTimesCopied: 0,
1866
+ };
1867
+
1868
+ await expect(
1869
+ retainedTask.sendPostCallSummaryResponse(responsePayload)
1870
+ ).resolves.toBeUndefined();
1871
+
1872
+ expect((apiAIAssistant as any).pendingRequests.size).toBe(requestCallsAfterRemoval);
1873
+ expect(harness.apiAIAssistant.sendEvent).toHaveBeenCalledTimes(2);
1874
+ expect(harness.apiAIAssistant.sendEvent).toHaveBeenNthCalledWith(
1875
+ 2,
1876
+ 'agent-1',
1877
+ responseInteractionId,
1878
+ AIAssistantEventType.CTI_EVENT,
1879
+ AIAssistantEventName.POST_CALL_SUMMARY_RESPONSE,
1880
+ {
1881
+ conversationId: responseConversationId,
1882
+ clientType: 'WxCC',
1883
+ action: AIAssistantEventName.POST_CALL_SUMMARY_RESPONSE,
1884
+ summary: {initialContactReason: 'resolved'},
1885
+ feedback: 'thumbs_up',
1886
+ wrapUpCode: 'resolved',
1887
+ numberOfTimesViewed: 1,
1888
+ numberOfTimesEdited: 0,
1889
+ numberOfTimesCopied: 0,
1890
+ state: 'DEFAULT',
1891
+ },
1892
+ undefined,
1893
+ undefined,
1894
+ expect.any(Number),
1895
+ 15000
1896
+ );
1897
+ });
1898
+
1899
+ it('cancels pending real public requests on deregister and ignores late HTTP settlement', async () => {
1900
+ const harness = createSummaryHarness();
1901
+ const unhandledRejections: unknown[] = [];
1902
+ const unhandledRejectionListener = jest.fn((reason) => {
1903
+ unhandledRejections.push(reason);
1904
+ });
1905
+
1906
+ attachRtdMessageListener(harness.rtdWebSocketManager);
1907
+ emitFeatureEnablement(harness);
1908
+ jest.clearAllMocks();
1909
+
1910
+ webex.cc.agentConfig = {
1911
+ agentId: 'agent-1',
1912
+ webRtcEnabled: false,
1913
+ loginVoiceOptions: [LoginOption.EXTENSION],
1914
+ };
1915
+
1916
+ process.on('unhandledRejection', unhandledRejectionListener);
1917
+ try {
1918
+ const postCallRequest = harness.task.requestPostCallSummary();
1919
+ const midCallRequest = harness.task.requestMidCallSummary('CONSULT');
1920
+ postCallRequest.catch(() => undefined);
1921
+ midCallRequest.catch(() => undefined);
1922
+
1923
+ await flushMicrotasks();
1924
+ expect(harness.transportDeferreds).toHaveLength(2);
1925
+
1926
+ await webex.cc.deregister();
1927
+ await flushEventLoopTurn();
1928
+
1929
+ expect(unhandledRejectionListener).not.toHaveBeenCalled();
1930
+ expect(unhandledRejections).toHaveLength(0);
1931
+ await expect(postCallRequest).rejects.toMatchObject({
1932
+ message: AI_SUMMARY_REQUEST_CANCELLED,
1933
+ data: {errorCode: AI_SUMMARY_REQUEST_CANCELLED},
1934
+ });
1935
+ await expect(midCallRequest).rejects.toMatchObject({
1936
+ message: AI_SUMMARY_REQUEST_CANCELLED,
1937
+ data: {errorCode: AI_SUMMARY_REQUEST_CANCELLED},
1938
+ });
1939
+ harness.expectSummaryStateCleared();
1940
+
1941
+ const finalMetricCountAfterCancellation = countAISummaryRequestFinalMetrics();
1942
+
1943
+ dispatchSentinelPostCallSummary(harness, 'queued-after-deregister');
1944
+ harness.transportDeferreds[0].resolve(undefined);
1945
+ harness.transportDeferreds[1].reject(new Error('late-http-rejected-after-deregister'));
1946
+ await flushEventLoopTurn();
1947
+
1948
+ expect(unhandledRejectionListener).not.toHaveBeenCalled();
1949
+ expect(unhandledRejections).toHaveLength(0);
1950
+ expect(countAISummaryRequestFinalMetrics()).toBe(finalMetricCountAfterCancellation);
1951
+ harness.expectSummaryStateCleared();
1952
+ expectSentinelsNotObserved();
1953
+ } finally {
1954
+ process.off('unhandledRejection', unhandledRejectionListener);
1955
+ harness.taskManager.clearAISummaryState();
1956
+ }
1957
+ });
1958
+ });
1959
+
1960
+ describe('stationLogin', () => {
1961
+ it('should login successfully with LoginOption.BROWSER and webrtc enabled', async () => {
1962
+ const mockTask = {};
1963
+ const options = {
1964
+ teamId: 'teamId',
1965
+ loginOption: LoginOption.BROWSER,
1966
+ };
1967
+
1968
+ webex.cc.agentConfig = {
1969
+ agentId: 'agentId',
1970
+ webRtcEnabled: true,
1971
+ loginVoiceOptions: ['BROWSER', 'EXTENSION', 'AGENT_DN'],
1972
+ };
1973
+
1974
+ const registerWebCallingLineSpy = jest.spyOn(
1975
+ webex.cc.webCallingService,
1976
+ 'registerWebCallingLine'
1977
+ );
1978
+
1979
+ const mockData = {
1980
+ data: {
1981
+ loginOption: LoginOption.BROWSER,
1982
+ agentId: 'agentId',
1983
+ teamId: 'teamId',
1984
+ siteId: 'siteId',
1985
+ roles: [AGENT],
1986
+ trackingId: '1234',
1987
+ eventType: 'DESKTOP_MESSAGE',
1988
+ channelsMap: {
1989
+ chat: ['25d8ggg7-4821-7de7-b626-36437adec509', '14e7fff7-7de7-4821-a919-36437adec509'],
1990
+ email: [
1991
+ '14e7fff7-7de7-4821-a919-36437adec509',
1992
+ '14e7fff7-7de7-4821-a919-36437adec509',
1993
+ '14e7fff7-7de7-4821-a919-36437adec509',
1994
+ ],
1995
+ social: [],
1996
+ telephony: ['14e7fff7-7de7-4821-a919-36437adec509'],
1997
+ },
1998
+ },
1999
+ trackingId: 'notifs_52628',
2000
+ orgId: 'orgId',
2001
+ type: 'StationLoginSuccess',
2002
+ eventType: 'STATION_LOGIN',
2003
+ };
2004
+
2005
+ const responseMock = {
2006
+ loginOption: LoginOption.BROWSER,
2007
+ agentId: 'agentId',
2008
+ teamId: 'teamId',
2009
+ siteId: 'siteId',
2010
+ roles: [AGENT],
2011
+ trackingId: '1234',
2012
+ eventType: 'DESKTOP_MESSAGE',
2013
+ mmProfile: {
2014
+ chat: 2,
2015
+ email: 3,
2016
+ social: 0,
2017
+ telephony: 1,
2018
+ },
2019
+ notifsTrackingId: 'notifs_52628',
2020
+ };
2021
+
2022
+ const stationLoginMock = jest
2023
+ .spyOn(webex.cc.services.agent, 'stationLogin')
2024
+ .mockResolvedValue(mockData as unknown as StationLoginSuccess);
2025
+
2026
+ const result = await webex.cc.stationLogin(options);
2027
+
2028
+ expect(registerWebCallingLineSpy).toHaveBeenCalled();
2029
+ expect(stationLoginMock).toHaveBeenCalledWith({
2030
+ data: {
2031
+ dialNumber: `${WEB_RTC_PREFIX}agentId`,
720
2032
  teamId: 'teamId',
721
2033
  deviceType: LoginOption.BROWSER,
722
2034
  isExtension: false,
@@ -734,6 +2046,7 @@ describe('webex.cc', () => {
734
2046
  METRIC_EVENT_NAMES.STATION_LOGIN_FAILED,
735
2047
  ]);
736
2048
  expect(result).toEqual(responseMock);
2049
+ expect(webex.cc.agentConfig.deviceType).toBe(LoginOption.BROWSER);
737
2050
 
738
2051
  const onSpy = jest.spyOn(mockTaskManager, 'on');
739
2052
  const emitSpy = jest.spyOn(webex.cc, 'trigger');
@@ -828,7 +2141,7 @@ describe('webex.cc', () => {
828
2141
  );
829
2142
  });
830
2143
 
831
- it('should not attempt mobius registration for LoginOption.BROWSER if webrtc is disabled', async () => {
2144
+ it('does not register a browser line during station login when WebRTC is disabled', async () => {
832
2145
  const options = {
833
2146
  teamId: 'teamId',
834
2147
  loginOption: LoginOption.BROWSER,
@@ -873,9 +2186,10 @@ describe('webex.cc', () => {
873
2186
  await webex.cc.stationLogin(options);
874
2187
 
875
2188
  expect(registerWebCallingLineSpy).not.toHaveBeenCalled();
2189
+ expect(webex.cc.webCallingService.setBrowserVoiceRequired).toHaveBeenCalledWith(false);
876
2190
  expect(stationLoginSpy).toHaveBeenCalledWith({
877
2191
  data: {
878
- dialNumber: 'agentId',
2192
+ dialNumber: `${WEB_RTC_PREFIX}agentId`,
879
2193
  teamId: 'teamId',
880
2194
  deviceType: LoginOption.BROWSER,
881
2195
  isExtension: false,
@@ -1007,21 +2321,790 @@ describe('webex.cc', () => {
1007
2321
 
1008
2322
  await expect(webex.cc.stationLogin(options)).rejects.toThrow(error.details.data.reason);
1009
2323
 
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
- );
2324
+ expect(LoggerProxy.log).toHaveBeenCalledWith(
2325
+ `Starting agent station login | loginOption: ${options.loginOption} teamId: ${options.teamId}`,
2326
+ {
2327
+ module: CC_FILE,
2328
+ method: 'stationLogin',
2329
+ }
2330
+ );
2331
+ expect(LoggerProxy.error).toHaveBeenCalledWith(
2332
+ `stationLogin failed with reason: ${error.details.data.reason}`,
2333
+ {module: CC_FILE, method: 'stationLogin', trackingId: error.details.trackingId}
2334
+ );
2335
+ });
2336
+
2337
+ it('should publish usersub and subscribe Mercury on station login when enableWxBetterTogether is true at init', async () => {
2338
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
2339
+ webex.internal.device = {
2340
+ userId: 'user-123',
2341
+ url: 'https://wdm.example.com/devices/dev-1',
2342
+ registered: true,
2343
+ register: jest.fn().mockResolvedValue(undefined),
2344
+ };
2345
+ webex.internal.mercury.connected = true;
2346
+ webex.internal.mercury.connect = jest.fn().mockResolvedValue(undefined);
2347
+ webex.cc.agentConfig = {
2348
+ agentId: 'agentId',
2349
+ webRtcEnabled: false,
2350
+ loginVoiceOptions: ['EXTENSION'],
2351
+ };
2352
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
2353
+
2354
+ const publishSpy = jest
2355
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
2356
+ .mockResolvedValue(undefined);
2357
+ const subscribeSpy = jest
2358
+ .spyOn(webex.cc['wxAppTelephonyMercurySync'], 'subscribe')
2359
+ .mockImplementation(() => {});
2360
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
2361
+
2362
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2363
+ data: {
2364
+ agentId: 'agentId',
2365
+ teamId: 'teamId',
2366
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
2367
+ },
2368
+ trackingId: 'track-1',
2369
+ } as StationLoginSuccess);
2370
+
2371
+ await webex.cc.stationLogin({
2372
+ teamId: 'teamId',
2373
+ loginOption: LoginOption.EXTENSION,
2374
+ dialNumber: '1001',
2375
+ });
2376
+
2377
+ expect(publishSpy).toHaveBeenCalledWith(true, {userId: 'user-123', trackPublishMetrics: true});
2378
+ expect(subscribeSpy).toHaveBeenCalledWith('agentId', expect.any(Function));
2379
+ expect(mockTaskManager.refreshWxAppOfferObservabilityForAllTasks).toHaveBeenCalled();
2380
+ });
2381
+
2382
+ it('should rollback wxApp config when post-station-login init fails', async () => {
2383
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
2384
+ webex.internal.device = {userId: 'user-123', url: 'https://wdm.example.com/devices/dev-1'};
2385
+ webex.cc.agentConfig = {
2386
+ agentId: 'agentId',
2387
+ webRtcEnabled: false,
2388
+ loginVoiceOptions: ['EXTENSION'],
2389
+ };
2390
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
2391
+ mockTaskManager.applyEnableWxBetterTogether(true);
2392
+
2393
+ jest
2394
+ .spyOn(webex.cc as never, 'publishAnswerOnWebexCrossClientState' as never)
2395
+ .mockRejectedValue(new Error('usersub publish failed'));
2396
+ const unsubscribeSpy = jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'unsubscribe');
2397
+
2398
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2399
+ data: {
2400
+ agentId: 'agentId',
2401
+ teamId: 'teamId',
2402
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
2403
+ },
2404
+ trackingId: 'track-1',
2405
+ } as StationLoginSuccess);
2406
+
2407
+ await webex.cc.stationLogin({
2408
+ teamId: 'teamId',
2409
+ loginOption: LoginOption.EXTENSION,
2410
+ dialNumber: '1001',
2411
+ });
2412
+
2413
+ expect(unsubscribeSpy).toHaveBeenCalled();
2414
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(false);
2415
+ expect(mockTaskManager.applyEnableWxBetterTogether).toHaveBeenCalledWith(false);
2416
+ });
2417
+
2418
+ it('should reset wxApp config when Mercury fails before usersub publish on station login', async () => {
2419
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
2420
+ webex.internal.device = {userId: 'user-123', url: 'https://wdm.example.com/devices/dev-1'};
2421
+ webex.cc.agentConfig = {
2422
+ agentId: 'agentId',
2423
+ webRtcEnabled: false,
2424
+ loginVoiceOptions: ['EXTENSION'],
2425
+ };
2426
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
2427
+ mockTaskManager.applyEnableWxBetterTogether(true);
2428
+
2429
+ const publishSpy = jest
2430
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
2431
+ .mockResolvedValue(undefined);
2432
+ jest
2433
+ .spyOn(webex.cc as any, 'ensureWxAppMercuryConnected')
2434
+ .mockRejectedValue(new Error('mercury connect failed'));
2435
+ const teardownSpy = jest.spyOn(webex.cc['webexCrossClientService'], 'teardown');
2436
+ const unsubscribeSpy = jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'unsubscribe');
2437
+ jest
2438
+ .spyOn(webex.cc as any, 'releaseWxAppMercuryResources')
2439
+ .mockResolvedValue(undefined);
2440
+ const metricSpy = jest.spyOn(mockMetricsManager, 'trackEvent');
2441
+
2442
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2443
+ data: {
2444
+ agentId: 'agentId',
2445
+ teamId: 'teamId',
2446
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
2447
+ },
2448
+ trackingId: 'track-1',
2449
+ } as StationLoginSuccess);
2450
+
2451
+ await webex.cc.stationLogin({
2452
+ teamId: 'teamId',
2453
+ loginOption: LoginOption.EXTENSION,
2454
+ dialNumber: '1001',
2455
+ });
2456
+
2457
+ expect(publishSpy).not.toHaveBeenCalled();
2458
+ expect(teardownSpy).not.toHaveBeenCalled();
2459
+ expect(unsubscribeSpy).toHaveBeenCalled();
2460
+ expect(metricSpy).toHaveBeenCalledWith(
2461
+ METRIC_EVENT_NAMES.WXAPP_SESSION_INIT_FAILED,
2462
+ expect.objectContaining({skipReason: 'mercury_subscribe_failed'}),
2463
+ ['operational', 'behavioral']
2464
+ );
2465
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(false);
2466
+ expect(mockTaskManager.applyEnableWxBetterTogether).toHaveBeenCalledWith(false);
2467
+ });
2468
+
2469
+ it('should record publish_failed when usersub publish fails after Mercury init', async () => {
2470
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
2471
+ webex.internal.device = {userId: 'user-123', url: 'https://wdm.example.com/devices/dev-1'};
2472
+ webex.cc.agentConfig = {
2473
+ agentId: 'agentId',
2474
+ webRtcEnabled: false,
2475
+ loginVoiceOptions: ['EXTENSION'],
2476
+ };
2477
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
2478
+ mockTaskManager.applyEnableWxBetterTogether(true);
2479
+
2480
+ jest.spyOn(webex.cc as any, 'ensureWxAppMercuryConnected').mockResolvedValue(undefined);
2481
+ jest
2482
+ .spyOn(webex.cc['wxAppTelephonyMercurySync'], 'subscribe')
2483
+ .mockImplementation(() => {});
2484
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
2485
+ jest
2486
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
2487
+ .mockRejectedValue(new Error('publish failed'));
2488
+ jest
2489
+ .spyOn(webex.cc as any, 'releaseWxAppMercuryResources')
2490
+ .mockResolvedValue(undefined);
2491
+ const metricSpy = jest.spyOn(mockMetricsManager, 'trackEvent');
2492
+
2493
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2494
+ data: {
2495
+ agentId: 'agentId',
2496
+ teamId: 'teamId',
2497
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
2498
+ },
2499
+ trackingId: 'track-1',
2500
+ } as StationLoginSuccess);
2501
+
2502
+ await webex.cc.stationLogin({
2503
+ teamId: 'teamId',
2504
+ loginOption: LoginOption.EXTENSION,
2505
+ dialNumber: '1001',
2506
+ });
2507
+
2508
+ expect(metricSpy).toHaveBeenCalledWith(
2509
+ METRIC_EVENT_NAMES.WXAPP_SESSION_INIT_FAILED,
2510
+ expect.objectContaining({skipReason: 'publish_failed', usersubPublished: false}),
2511
+ ['operational', 'behavioral']
2512
+ );
2513
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(false);
2514
+ });
2515
+
2516
+ it('should report retained usersub state when publish fails during re-init', async () => {
2517
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
2518
+ webex.internal.device = {userId: 'user-123', url: 'https://wdm.example.com/devices/dev-1'};
2519
+ webex.cc.agentConfig = {
2520
+ agentId: 'agentId',
2521
+ webRtcEnabled: false,
2522
+ loginVoiceOptions: ['EXTENSION'],
2523
+ };
2524
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
2525
+ mockTaskManager.applyEnableWxBetterTogether(true);
2526
+
2527
+ jest.spyOn(webex.cc as any, 'ensureWxAppMercuryConnected').mockResolvedValue(undefined);
2528
+ jest
2529
+ .spyOn(webex.cc['wxAppTelephonyMercurySync'], 'subscribe')
2530
+ .mockImplementation(() => {});
2531
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
2532
+ jest
2533
+ .spyOn(webex.cc['webexCrossClientService'], 'isAnswerCallsStateActive')
2534
+ .mockReturnValue(true);
2535
+ jest
2536
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
2537
+ .mockRejectedValue(new Error('publish failed'));
2538
+ jest
2539
+ .spyOn(webex.cc as any, 'releaseWxAppMercuryResources')
2540
+ .mockResolvedValue(undefined);
2541
+ const metricSpy = jest.spyOn(mockMetricsManager, 'trackEvent');
2542
+
2543
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2544
+ data: {
2545
+ agentId: 'agentId',
2546
+ teamId: 'teamId',
2547
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
2548
+ },
2549
+ trackingId: 'track-1',
2550
+ } as StationLoginSuccess);
2551
+
2552
+ await webex.cc.stationLogin({
2553
+ teamId: 'teamId',
2554
+ loginOption: LoginOption.EXTENSION,
2555
+ dialNumber: '1001',
2556
+ });
2557
+
2558
+ expect(metricSpy).toHaveBeenCalledWith(
2559
+ METRIC_EVENT_NAMES.WXAPP_SESSION_INIT_FAILED,
2560
+ expect.objectContaining({skipReason: 'publish_failed', usersubPublished: true}),
2561
+ ['operational', 'behavioral']
2562
+ );
2563
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(false);
2564
+ });
2565
+
2566
+ it('should register device before publishing usersub true on extension station login', async () => {
2567
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
2568
+ webex.internal.device = {
2569
+ userId: 'user-123',
2570
+ registered: false,
2571
+ register: jest.fn().mockImplementation(async function (this: {
2572
+ url?: string;
2573
+ registered?: boolean;
2574
+ }) {
2575
+ this.url = 'https://wdm.example.com/devices/dev-1';
2576
+ this.registered = true;
2577
+ }),
2578
+ };
2579
+ webex.internal.mercury = {
2580
+ connected: false,
2581
+ connect: jest.fn().mockResolvedValue(undefined),
2582
+ };
2583
+ webex.cc.agentConfig = {
2584
+ agentId: 'agentId',
2585
+ webRtcEnabled: false,
2586
+ loginVoiceOptions: ['EXTENSION'],
2587
+ };
2588
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
2589
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'subscribe').mockImplementation(() => {});
2590
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
2591
+
2592
+ const callOrder: string[] = [];
2593
+ jest.spyOn(webex.internal.device, 'register').mockImplementation(async function (this: {
2594
+ url?: string;
2595
+ registered?: boolean;
2596
+ }) {
2597
+ callOrder.push('device.register');
2598
+ this.url = 'https://wdm.example.com/devices/dev-1';
2599
+ this.registered = true;
2600
+ });
2601
+ jest
2602
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
2603
+ .mockImplementation(async (enable: boolean) => {
2604
+ if (enable === true && !webex.internal.device.url) {
2605
+ throw new Error('Device URL is unavailable for cross-client publish');
2606
+ }
2607
+ callOrder.push(enable ? 'publish:true' : 'publish:false');
2608
+ });
2609
+
2610
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2611
+ data: {
2612
+ agentId: 'agentId',
2613
+ teamId: 'teamId',
2614
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
2615
+ },
2616
+ trackingId: 'track-1',
2617
+ } as StationLoginSuccess);
2618
+
2619
+ await webex.cc.stationLogin({
2620
+ teamId: 'teamId',
2621
+ loginOption: LoginOption.EXTENSION,
2622
+ dialNumber: '1001',
2623
+ });
2624
+
2625
+ expect(callOrder).toEqual(['device.register', 'publish:true']);
2626
+ });
2627
+
2628
+ it('should register device before publishing forced usersub false when wxApp is disabled at station login', async () => {
2629
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: false};
2630
+ webex.internal.device = {
2631
+ userId: 'user-123',
2632
+ registered: false,
2633
+ register: jest.fn().mockImplementation(async function (this: {
2634
+ url?: string;
2635
+ registered?: boolean;
2636
+ }) {
2637
+ this.url = 'https://wdm.example.com/devices/dev-1';
2638
+ this.registered = true;
2639
+ }),
2640
+ };
2641
+ webex.internal.mercury = {
2642
+ connected: false,
2643
+ connect: jest.fn().mockResolvedValue(undefined),
2644
+ };
2645
+ webex.cc.agentConfig = {
2646
+ agentId: 'agentId',
2647
+ webRtcEnabled: false,
2648
+ loginVoiceOptions: ['EXTENSION'],
2649
+ };
2650
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
2651
+ jest
2652
+ .spyOn(webex.cc as any, 'releaseWxAppMercuryResources')
2653
+ .mockResolvedValue(undefined);
2654
+
2655
+ const callOrder: string[] = [];
2656
+ jest.spyOn(webex.internal.device, 'register').mockImplementation(async function (this: {
2657
+ url?: string;
2658
+ registered?: boolean;
2659
+ }) {
2660
+ callOrder.push('device.register');
2661
+ this.url = 'https://wdm.example.com/devices/dev-1';
2662
+ this.registered = true;
2663
+ });
2664
+ jest
2665
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
2666
+ .mockImplementation(async (enable: boolean) => {
2667
+ if (!webex.internal.device.url) {
2668
+ throw new Error('Device URL is unavailable for cross-client publish');
2669
+ }
2670
+ callOrder.push(enable ? 'publish:true' : 'publish:false');
2671
+ });
2672
+
2673
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2674
+ data: {
2675
+ agentId: 'agentId',
2676
+ teamId: 'teamId',
2677
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
2678
+ },
2679
+ trackingId: 'track-1',
2680
+ } as StationLoginSuccess);
2681
+
2682
+ await webex.cc.stationLogin({
2683
+ teamId: 'teamId',
2684
+ loginOption: LoginOption.EXTENSION,
2685
+ dialNumber: '1001',
2686
+ });
2687
+
2688
+ expect(callOrder).toEqual(['device.register', 'publish:false']);
2689
+ });
2690
+
2691
+ it('should retry forced false publish when wxApp is disabled at station login', async () => {
2692
+ jest.useFakeTimers();
2693
+ try {
2694
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: false};
2695
+ webex.internal.device = {userId: 'user-123', url: 'https://wdm.example.com/devices/dev-1'};
2696
+ webex.cc.agentConfig = {
2697
+ agentId: 'agentId',
2698
+ webRtcEnabled: false,
2699
+ loginVoiceOptions: ['EXTENSION'],
2700
+ };
2701
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
2702
+
2703
+ const publishSpy = jest
2704
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
2705
+ .mockRejectedValueOnce(new Error('usersub publish failed'))
2706
+ .mockResolvedValue(undefined);
2707
+ const scheduleRetrySpy = jest.spyOn(
2708
+ webex.cc as any,
2709
+ 'scheduleForcedFalsePublishRetry'
2710
+ );
2711
+ const teardownSpy = jest.spyOn(webex.cc['webexCrossClientService'], 'teardown');
2712
+ jest
2713
+ .spyOn(webex.cc as any, 'releaseWxAppMercuryResources')
2714
+ .mockResolvedValue(undefined);
2715
+
2716
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2717
+ data: {
2718
+ agentId: 'agentId',
2719
+ teamId: 'teamId',
2720
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
2721
+ },
2722
+ trackingId: 'track-1',
2723
+ } as StationLoginSuccess);
2724
+
2725
+ await webex.cc.stationLogin({
2726
+ teamId: 'teamId',
2727
+ loginOption: LoginOption.EXTENSION,
2728
+ dialNumber: '1001',
2729
+ });
2730
+
2731
+ expect(publishSpy).toHaveBeenCalledTimes(1);
2732
+ expect(scheduleRetrySpy).toHaveBeenCalled();
2733
+ expect(teardownSpy).not.toHaveBeenCalled();
2734
+
2735
+ jest.advanceTimersByTime(30_000);
2736
+ await publishSpy.mock.results[1]?.value;
2737
+
2738
+ expect(publishSpy).toHaveBeenCalledTimes(2);
2739
+ expect(publishSpy).toHaveBeenLastCalledWith(false, {userId: 'user-123', trackPublishMetrics: true});
2740
+ } finally {
2741
+ jest.useRealTimers();
2742
+ }
2743
+ });
2744
+
2745
+ it('should not publish usersub on BROWSER station login even when enableWxBetterTogether is true at init', async () => {
2746
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
2747
+ webex.internal.device = {userId: 'user-123', url: 'https://wdm.example.com/devices/dev-1'};
2748
+ webex.cc.agentConfig = {
2749
+ agentId: 'agentId',
2750
+ webRtcEnabled: true,
2751
+ loginVoiceOptions: ['BROWSER'],
2752
+ };
2753
+ webex.cc.webCallingService.loginOption = LoginOption.BROWSER;
2754
+
2755
+ const publishSpy = jest.spyOn(
2756
+ webex.cc['webexCrossClientService'],
2757
+ 'setManageWebexCallingInWxcc'
2758
+ );
2759
+
2760
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2761
+ data: {
2762
+ agentId: 'agentId',
2763
+ teamId: 'teamId',
2764
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
2765
+ },
2766
+ trackingId: 'track-1',
2767
+ } as StationLoginSuccess);
2768
+
2769
+ await webex.cc.stationLogin({
2770
+ teamId: 'teamId',
2771
+ loginOption: LoginOption.BROWSER,
2772
+ });
2773
+
2774
+ expect(publishSpy).not.toHaveBeenCalled();
2775
+ });
2776
+
2777
+ it('should force-publish usersub false on station login when enableWxBetterTogether is false at init', async () => {
2778
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: false};
2779
+ webex.internal.device = {userId: 'user-123', url: 'https://wdm.example.com/devices/dev-1'};
2780
+ webex.cc.agentConfig = {
2781
+ agentId: 'agentId',
2782
+ webRtcEnabled: false,
2783
+ loginVoiceOptions: ['EXTENSION'],
2784
+ };
2785
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
2786
+
2787
+ const publishSpy = jest
2788
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
2789
+ .mockResolvedValue(undefined);
2790
+ const teardownSpy = jest.spyOn(webex.cc['webexCrossClientService'], 'teardown');
2791
+ const unsubscribeSpy = jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'unsubscribe');
2792
+
2793
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2794
+ data: {
2795
+ agentId: 'agentId',
2796
+ teamId: 'teamId',
2797
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
2798
+ },
2799
+ trackingId: 'track-1',
2800
+ } as StationLoginSuccess);
2801
+
2802
+ await webex.cc.stationLogin({
2803
+ teamId: 'teamId',
2804
+ loginOption: LoginOption.EXTENSION,
2805
+ dialNumber: '1001',
2806
+ });
2807
+
2808
+ expect(publishSpy).toHaveBeenCalledWith(false, {userId: 'user-123', trackPublishMetrics: true});
2809
+ expect(teardownSpy).toHaveBeenCalled();
2810
+ expect(unsubscribeSpy).toHaveBeenCalled();
2811
+ expect(mockMetricsManager.trackEvent).toHaveBeenCalledWith(
2812
+ METRIC_EVENT_NAMES.WXAPP_SESSION_SKIPPED,
2813
+ expect.objectContaining({
2814
+ enableWxBetterTogether: false,
2815
+ skipReason: 'flag_disabled',
2816
+ }),
2817
+ ['operational', 'behavioral']
2818
+ );
2819
+ });
2820
+
2821
+ it('should not emit WXAPP_SESSION_INIT_FAILED when flag-disabled cleanup fails', async () => {
2822
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: false};
2823
+ webex.internal.device = {userId: 'user-123', url: 'https://wdm.example.com/devices/dev-1'};
2824
+ webex.cc.agentConfig = {
2825
+ agentId: 'agentId',
2826
+ webRtcEnabled: false,
2827
+ loginVoiceOptions: ['EXTENSION'],
2828
+ };
2829
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
2830
+
2831
+ jest
2832
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
2833
+ .mockRejectedValue(new Error('forced false publish failed'));
2834
+ const metricSpy = jest.spyOn(mockMetricsManager, 'trackEvent');
2835
+
2836
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2837
+ data: {
2838
+ agentId: 'agentId',
2839
+ teamId: 'teamId',
2840
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
2841
+ },
2842
+ trackingId: 'track-1',
2843
+ } as StationLoginSuccess);
2844
+
2845
+ await webex.cc.stationLogin({
2846
+ teamId: 'teamId',
2847
+ loginOption: LoginOption.EXTENSION,
2848
+ dialNumber: '1001',
2849
+ });
2850
+
2851
+ expect(metricSpy).not.toHaveBeenCalledWith(
2852
+ METRIC_EVENT_NAMES.WXAPP_SESSION_INIT_FAILED,
2853
+ expect.anything(),
2854
+ expect.anything()
2855
+ );
2856
+ });
2857
+
2858
+ it('should still publish usersub but record session init failed when Mercury is unavailable', async () => {
2859
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
2860
+ webex.internal.device = {
2861
+ userId: 'user-123',
2862
+ url: 'https://wdm.example.com/devices/dev-1',
2863
+ registered: true,
2864
+ register: jest.fn().mockResolvedValue(undefined),
2865
+ };
2866
+ delete webex.internal.mercury;
2867
+ webex.cc.agentConfig = {
2868
+ agentId: 'agentId',
2869
+ webRtcEnabled: false,
2870
+ loginVoiceOptions: ['EXTENSION'],
2871
+ };
2872
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
2873
+ mockTaskManager.applyEnableWxBetterTogether(true);
2874
+
2875
+ const publishSpy = jest
2876
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
2877
+ .mockResolvedValue(undefined);
2878
+ jest
2879
+ .spyOn(webex.cc['webexCrossClientService'], 'isAnswerCallsStateActive')
2880
+ .mockReturnValue(true);
2881
+ const metricSpy = jest.spyOn(mockMetricsManager, 'trackEvent');
2882
+
2883
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2884
+ data: {
2885
+ agentId: 'agentId',
2886
+ teamId: 'teamId',
2887
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
2888
+ },
2889
+ trackingId: 'track-1',
2890
+ } as StationLoginSuccess);
2891
+
2892
+ await webex.cc.stationLogin({
2893
+ teamId: 'teamId',
2894
+ loginOption: LoginOption.EXTENSION,
2895
+ dialNumber: '1001',
2896
+ });
2897
+
2898
+ expect(publishSpy).toHaveBeenCalledWith(true, {userId: 'user-123', trackPublishMetrics: true});
2899
+ expect(metricSpy).toHaveBeenCalledWith(
2900
+ METRIC_EVENT_NAMES.WXAPP_MERCURY_SUBSCRIBE_FAILED,
2901
+ expect.objectContaining({error: 'Mercury is unavailable for wxApp mute sync'}),
2902
+ ['operational', 'behavioral']
2903
+ );
2904
+ expect(metricSpy).not.toHaveBeenCalledWith(
2905
+ METRIC_EVENT_NAMES.WXAPP_SESSION_INIT_SUCCESS,
2906
+ expect.anything(),
2907
+ expect.anything()
2908
+ );
2909
+ expect(metricSpy).toHaveBeenCalledWith(
2910
+ METRIC_EVENT_NAMES.WXAPP_SESSION_INIT_FAILED,
2911
+ expect.objectContaining({skipReason: 'mercury_not_subscribed'}),
2912
+ ['operational', 'behavioral']
2913
+ );
2914
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(true);
2915
+ });
2916
+
2917
+ it('should record session init failed when userId is missing but not emit success', async () => {
2918
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
2919
+ webex.internal.device = {
2920
+ url: 'https://wdm.example.com/devices/dev-1',
2921
+ registered: true,
2922
+ register: jest.fn().mockResolvedValue(undefined),
2923
+ };
2924
+ webex.internal.mercury = {
2925
+ connected: true,
2926
+ connect: jest.fn().mockResolvedValue(undefined),
2927
+ on: jest.fn(),
2928
+ off: jest.fn(),
2929
+ };
2930
+ webex.cc.agentConfig = {
2931
+ agentId: 'agentId',
2932
+ webRtcEnabled: false,
2933
+ loginVoiceOptions: ['EXTENSION'],
2934
+ };
2935
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
2936
+ mockTaskManager.applyEnableWxBetterTogether(true);
2937
+
2938
+ const publishSpy = jest
2939
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
2940
+ .mockResolvedValue(undefined);
2941
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
2942
+ const metricSpy = jest.spyOn(mockMetricsManager, 'trackEvent');
2943
+
2944
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
2945
+ data: {
2946
+ agentId: 'agentId',
2947
+ teamId: 'teamId',
2948
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
2949
+ },
2950
+ trackingId: 'track-1',
2951
+ } as StationLoginSuccess);
2952
+
2953
+ await webex.cc.stationLogin({
2954
+ teamId: 'teamId',
2955
+ loginOption: LoginOption.EXTENSION,
2956
+ dialNumber: '1001',
2957
+ });
2958
+
2959
+ expect(publishSpy).not.toHaveBeenCalledWith(true, expect.anything());
2960
+ expect(metricSpy).not.toHaveBeenCalledWith(
2961
+ METRIC_EVENT_NAMES.WXAPP_SESSION_INIT_SUCCESS,
2962
+ expect.anything(),
2963
+ expect.anything()
2964
+ );
2965
+ expect(metricSpy).toHaveBeenCalledWith(
2966
+ METRIC_EVENT_NAMES.WXAPP_SESSION_INIT_FAILED,
2967
+ expect.objectContaining({skipReason: 'usersub_not_published'}),
2968
+ ['operational', 'behavioral']
2969
+ );
2970
+ expect(metricSpy).toHaveBeenCalledWith(
2971
+ METRIC_EVENT_NAMES.WXAPP_USERSUB_PUBLISH_FAILED,
2972
+ expect.objectContaining({skipReason: 'user_id_unavailable', usersubPublished: false}),
2973
+ ['operational', 'behavioral']
2974
+ );
2975
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(true);
2976
+ });
2977
+
2978
+ it('should report retained usersub state when userId is missing during re-init', async () => {
2979
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
2980
+ webex.internal.device = {
2981
+ url: 'https://wdm.example.com/devices/dev-1',
2982
+ registered: true,
2983
+ register: jest.fn().mockResolvedValue(undefined),
2984
+ };
2985
+ webex.internal.mercury = {
2986
+ connected: true,
2987
+ connect: jest.fn().mockResolvedValue(undefined),
2988
+ on: jest.fn(),
2989
+ off: jest.fn(),
2990
+ };
2991
+ webex.cc.agentConfig = {
2992
+ agentId: 'agentId',
2993
+ webRtcEnabled: false,
2994
+ loginVoiceOptions: ['EXTENSION'],
2995
+ };
2996
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
2997
+ mockTaskManager.applyEnableWxBetterTogether(true);
2998
+
2999
+ jest
3000
+ .spyOn(webex.cc['webexCrossClientService'], 'isAnswerCallsStateActive')
3001
+ .mockReturnValue(true);
3002
+ const publishSpy = jest
3003
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
3004
+ .mockResolvedValue(undefined);
3005
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
3006
+ const metricSpy = jest.spyOn(mockMetricsManager, 'trackEvent');
3007
+
3008
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
3009
+ data: {
3010
+ agentId: 'agentId',
3011
+ teamId: 'teamId',
3012
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
3013
+ },
3014
+ trackingId: 'track-1',
3015
+ } as StationLoginSuccess);
3016
+
3017
+ await webex.cc.stationLogin({
3018
+ teamId: 'teamId',
3019
+ loginOption: LoginOption.EXTENSION,
3020
+ dialNumber: '1001',
3021
+ });
3022
+
3023
+ expect(publishSpy).not.toHaveBeenCalledWith(true, expect.anything());
3024
+ expect(metricSpy).toHaveBeenCalledWith(
3025
+ METRIC_EVENT_NAMES.WXAPP_USERSUB_PUBLISH_FAILED,
3026
+ expect.objectContaining({skipReason: 'user_id_unavailable', usersubPublished: true}),
3027
+ ['operational', 'behavioral']
3028
+ );
3029
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(true);
3030
+ });
3031
+
3032
+ it('should clear stale usersub on login after prior session enabled wxApp then hard refresh', async () => {
3033
+ webex.internal.device = {userId: 'user-123', url: 'https://wdm.example.com/devices/dev-1'};
3034
+ webex.cc.agentConfig = {
3035
+ agentId: 'agentId',
3036
+ webRtcEnabled: false,
3037
+ loginVoiceOptions: ['EXTENSION'],
3038
+ };
3039
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
3040
+ webex.request = jest.fn().mockResolvedValue({body: {}});
3041
+
3042
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
3043
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
3044
+ data: {
3045
+ agentId: 'agentId',
3046
+ teamId: 'teamId',
3047
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
3048
+ },
3049
+ trackingId: 'track-1',
3050
+ } as StationLoginSuccess);
3051
+
3052
+ await webex.cc.stationLogin({
3053
+ teamId: 'teamId',
3054
+ loginOption: LoginOption.EXTENSION,
3055
+ dialNumber: '1001',
3056
+ });
3057
+
3058
+ webex.cc['webexCrossClientService'].teardown();
3059
+ webex.cc['wxAppTelephonyMercurySync'].unsubscribe();
3060
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: false};
3061
+
3062
+ const publishSpy = jest
3063
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
3064
+ .mockResolvedValue(undefined);
3065
+
3066
+ await webex.cc.stationLogin({
3067
+ teamId: 'teamId',
3068
+ loginOption: LoginOption.EXTENSION,
3069
+ dialNumber: '1001',
3070
+ });
3071
+
3072
+ expect(publishSpy).toHaveBeenCalledWith(false, {userId: 'user-123', trackPublishMetrics: true});
1021
3073
  });
1022
3074
  });
1023
3075
 
1024
3076
  describe('stationLogout', () => {
3077
+ it('should wait for browser voice deregistration to finish', async () => {
3078
+ let resolveDeregister: (() => void) | undefined;
3079
+ let signalDeregisterStarted: (() => void) | undefined;
3080
+ const deregisterStarted = new Promise<void>((resolve) => {
3081
+ signalDeregisterStarted = resolve;
3082
+ });
3083
+ jest
3084
+ .spyOn(webex.cc.webCallingService, 'deregisterWebCallingLine')
3085
+ .mockImplementation(
3086
+ () =>
3087
+ new Promise<void>((resolve) => {
3088
+ resolveDeregister = resolve;
3089
+ signalDeregisterStarted?.();
3090
+ })
3091
+ );
3092
+ jest.spyOn(webex.cc.services.agent, 'logout').mockResolvedValue({} as StationLogoutResponse);
3093
+
3094
+ let logoutResolved = false;
3095
+ const logout = webex.cc.stationLogout({logoutReason: 'Logout reason'}).then((result) => {
3096
+ logoutResolved = true;
3097
+ return result;
3098
+ });
3099
+
3100
+ await deregisterStarted;
3101
+ expect(logoutResolved).toBe(false);
3102
+
3103
+ resolveDeregister?.();
3104
+ await logout;
3105
+ expect(logoutResolved).toBe(true);
3106
+ });
3107
+
1025
3108
  it('should logout successfully', async () => {
1026
3109
  const data = {logoutReason: 'Logout reason'};
1027
3110
  const response = {};
@@ -1043,7 +3126,7 @@ describe('webex.cc', () => {
1043
3126
  });
1044
3127
 
1045
3128
  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
3129
+ // SPARK-626777 tracks moving listener cleanup into the future de-register API.
1047
3130
  // expect(mockTaskManager.unregisterIncomingCallEvent).toHaveBeenCalledWith();
1048
3131
  // expect(mockTaskManager.off).toHaveBeenCalledWith(
1049
3132
  // TASK_EVENTS.TASK_INCOMING,
@@ -1061,6 +3144,216 @@ describe('webex.cc', () => {
1061
3144
  ]);
1062
3145
  });
1063
3146
 
3147
+ it('should not publish usersub false on logout when wxApp was never enabled', async () => {
3148
+ webex.internal.device = {userId: 'user-123'};
3149
+ const publishSpy = jest
3150
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
3151
+ .mockResolvedValue(undefined);
3152
+ const teardownSpy = jest.spyOn(webex.cc['webexCrossClientService'], 'teardown');
3153
+ const unsubscribeSpy = jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'unsubscribe');
3154
+
3155
+ jest.spyOn(webex.cc.services.agent, 'logout').mockResolvedValue({
3156
+ trackingId: 'track-1',
3157
+ } as StationLogoutResponse);
3158
+
3159
+ await webex.cc.stationLogout({logoutReason: 'Logout reason'});
3160
+
3161
+ expect(publishSpy).not.toHaveBeenCalled();
3162
+ expect(teardownSpy).toHaveBeenCalled();
3163
+ expect(unsubscribeSpy).toHaveBeenCalled();
3164
+ });
3165
+
3166
+ it('should publish usersub false and teardown wxApp sync on logout when wxApp was enabled', async () => {
3167
+ webex.internal.device = {
3168
+ userId: 'user-123',
3169
+ url: 'https://wdm.example.com/devices/dev-1',
3170
+ registered: false,
3171
+ register: jest.fn().mockResolvedValue(undefined),
3172
+ unregister: jest.fn().mockResolvedValue(undefined),
3173
+ };
3174
+ webex.internal.mercury = {
3175
+ connected: false,
3176
+ connect: jest.fn().mockResolvedValue(undefined),
3177
+ disconnect: jest.fn().mockResolvedValue(undefined),
3178
+ };
3179
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'subscribe').mockImplementation(() => {});
3180
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
3181
+ webex.request = jest.fn().mockResolvedValue({body: {}});
3182
+ webex.cc['agentConfig'] = {
3183
+ agentId: 'agent-123',
3184
+ deviceType: LoginOption.EXTENSION,
3185
+ } as Profile;
3186
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
3187
+
3188
+ await (webex.cc as any).setManageWebexCallingInWxcc(true);
3189
+
3190
+ const publishSpy = jest
3191
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
3192
+ .mockResolvedValue(undefined);
3193
+ const teardownSpy = jest.spyOn(webex.cc['webexCrossClientService'], 'teardown');
3194
+ const unsubscribeSpy = jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'unsubscribe');
3195
+
3196
+ jest.spyOn(webex.cc.services.agent, 'logout').mockResolvedValue({
3197
+ trackingId: 'track-1',
3198
+ } as StationLogoutResponse);
3199
+
3200
+ await webex.cc.stationLogout({logoutReason: 'Logout reason'});
3201
+
3202
+ expect(publishSpy).toHaveBeenCalledWith(false, {userId: 'user-123', trackPublishMetrics: true});
3203
+ expect(teardownSpy).toHaveBeenCalled();
3204
+ expect(unsubscribeSpy).toHaveBeenCalled();
3205
+ });
3206
+
3207
+ it('should teardown wxApp state on logout even when usersub publish fails', async () => {
3208
+ webex.internal.device = {userId: 'user-123'};
3209
+ webex.cc['agentConfig'] = {
3210
+ agentId: 'agent-123',
3211
+ deviceType: LoginOption.EXTENSION,
3212
+ } as Profile;
3213
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
3214
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
3215
+ mockTaskManager.applyEnableWxBetterTogether(true);
3216
+
3217
+ jest.spyOn(webex.cc.services.agent, 'logout').mockResolvedValue({
3218
+ trackingId: 'track-1',
3219
+ } as StationLogoutResponse);
3220
+ jest
3221
+ .spyOn(webex.cc as never, 'publishAnswerOnWebexCrossClientState' as never)
3222
+ .mockRejectedValue(new Error('usersub publish failed'));
3223
+ const scheduleRetrySpy = jest.spyOn(
3224
+ webex.cc as any,
3225
+ 'scheduleCompensatingFalsePublishRetry'
3226
+ );
3227
+ const teardownSpy = jest.spyOn(webex.cc['webexCrossClientService'], 'teardown');
3228
+ const unsubscribeSpy = jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'unsubscribe');
3229
+
3230
+ const result = await webex.cc.stationLogout({logoutReason: 'Logout reason'});
3231
+
3232
+ expect(result).toEqual({trackingId: 'track-1'});
3233
+ expect(teardownSpy).toHaveBeenCalled();
3234
+ expect(unsubscribeSpy).toHaveBeenCalled();
3235
+ expect(scheduleRetrySpy).toHaveBeenCalled();
3236
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(true);
3237
+ });
3238
+
3239
+ it('should retry compensating false publish when teardown usersub publish fails on logout', async () => {
3240
+ jest.useFakeTimers();
3241
+ try {
3242
+ webex.internal.device = {
3243
+ userId: 'user-123',
3244
+ url: 'https://wdm.example.com/devices/dev-1',
3245
+ };
3246
+ webex.cc['agentConfig'] = {
3247
+ agentId: 'agent-123',
3248
+ deviceType: LoginOption.EXTENSION,
3249
+ } as Profile;
3250
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
3251
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
3252
+ mockTaskManager.applyEnableWxBetterTogether(true);
3253
+ webex.cc['webexCrossClientService'].answerCallsState = true;
3254
+
3255
+ jest.spyOn(webex.cc.services.agent, 'logout').mockResolvedValue({
3256
+ trackingId: 'track-1',
3257
+ } as StationLogoutResponse);
3258
+
3259
+ const publishSpy = jest
3260
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
3261
+ .mockRejectedValueOnce(new Error('usersub publish failed'))
3262
+ .mockResolvedValue(undefined);
3263
+ const teardownSpy = jest.spyOn(webex.cc['webexCrossClientService'], 'teardown');
3264
+ const unsubscribeSpy = jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'unsubscribe');
3265
+ jest
3266
+ .spyOn(webex.cc as any, 'releaseWxAppMercuryResources')
3267
+ .mockResolvedValue(undefined);
3268
+
3269
+ const result = await webex.cc.stationLogout({logoutReason: 'Logout reason'});
3270
+
3271
+ expect(result).toEqual({trackingId: 'track-1'});
3272
+ expect(publishSpy).toHaveBeenCalledTimes(1);
3273
+ expect(publishSpy).toHaveBeenCalledWith(false, {userId: 'user-123', trackPublishMetrics: true});
3274
+ expect(teardownSpy).toHaveBeenCalled();
3275
+ expect(unsubscribeSpy).toHaveBeenCalled();
3276
+
3277
+ jest.advanceTimersByTime(30_000);
3278
+ await publishSpy.mock.results[1]?.value;
3279
+
3280
+ expect(publishSpy).toHaveBeenCalledTimes(2);
3281
+ expect(publishSpy).toHaveBeenLastCalledWith(false, {userId: 'user-123', trackPublishMetrics: true});
3282
+ } finally {
3283
+ jest.useRealTimers();
3284
+ }
3285
+ });
3286
+
3287
+ it('should cancel compensating retry when station login succeeds before retry fires', async () => {
3288
+ jest.useFakeTimers();
3289
+ try {
3290
+ webex.internal.device = {
3291
+ userId: 'user-123',
3292
+ url: 'https://wdm.example.com/devices/dev-1',
3293
+ registered: false,
3294
+ register: jest.fn().mockResolvedValue(undefined),
3295
+ unregister: jest.fn().mockResolvedValue(undefined),
3296
+ };
3297
+ webex.internal.mercury = {
3298
+ connected: false,
3299
+ connect: jest.fn().mockResolvedValue(undefined),
3300
+ disconnect: jest.fn().mockResolvedValue(undefined),
3301
+ };
3302
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'subscribe').mockImplementation(() => {});
3303
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
3304
+ webex.cc['agentConfig'] = {
3305
+ agentId: 'agent-123',
3306
+ deviceType: LoginOption.EXTENSION,
3307
+ webRtcEnabled: false,
3308
+ loginVoiceOptions: ['EXTENSION'],
3309
+ } as Profile;
3310
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
3311
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
3312
+ mockTaskManager.applyEnableWxBetterTogether(true);
3313
+ webex.cc['webexCrossClientService'].answerCallsState = true;
3314
+
3315
+ jest.spyOn(webex.cc.services.agent, 'logout').mockResolvedValue({
3316
+ trackingId: 'track-1',
3317
+ } as StationLogoutResponse);
3318
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
3319
+ data: {
3320
+ agentId: 'agent-123',
3321
+ teamId: 'team-123',
3322
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
3323
+ },
3324
+ trackingId: 'track-2',
3325
+ } as StationLoginSuccess);
3326
+
3327
+ const publishSpy = jest
3328
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
3329
+ .mockRejectedValueOnce(new Error('usersub publish failed'))
3330
+ .mockResolvedValue(undefined);
3331
+ const teardownSpy = jest.spyOn(webex.cc['webexCrossClientService'], 'teardown');
3332
+ jest
3333
+ .spyOn(webex.cc as any, 'releaseWxAppMercuryResources')
3334
+ .mockResolvedValue(undefined);
3335
+
3336
+ await webex.cc.stationLogout({logoutReason: 'Logout reason'});
3337
+ await webex.cc.stationLogin({
3338
+ teamId: 'team-123',
3339
+ loginOption: LoginOption.EXTENSION,
3340
+ dialNumber: '1001',
3341
+ });
3342
+
3343
+ expect(publishSpy).toHaveBeenCalledTimes(2);
3344
+ expect(publishSpy).toHaveBeenNthCalledWith(1, false, {userId: 'user-123', trackPublishMetrics: true});
3345
+ expect(publishSpy).toHaveBeenNthCalledWith(2, true, {userId: 'user-123', trackPublishMetrics: true});
3346
+ expect(teardownSpy).toHaveBeenCalledTimes(1);
3347
+
3348
+ jest.advanceTimersByTime(30_000);
3349
+
3350
+ expect(publishSpy).toHaveBeenCalledTimes(2);
3351
+ expect(teardownSpy).toHaveBeenCalledTimes(1);
3352
+ } finally {
3353
+ jest.useRealTimers();
3354
+ }
3355
+ });
3356
+
1064
3357
  it('should handle error during stationLogout', async () => {
1065
3358
  const data = {logoutReason: 'Logout reason'};
1066
3359
  const error = {
@@ -1088,6 +3381,63 @@ describe('webex.cc', () => {
1088
3381
  });
1089
3382
 
1090
3383
  describe('setAgentStatus', () => {
3384
+ it('should reject browser voice state changes while WebRTC registration is unavailable', async () => {
3385
+ const webCallingService = webex.cc.webCallingService;
3386
+ jest.spyOn(webCallingService, 'isBrowserVoiceRequired').mockReturnValue(true);
3387
+ jest.spyOn(webCallingService, 'isVoiceReady').mockReturnValue(false);
3388
+ const stateChangeSpy = jest.spyOn(webex.cc.services.agent, 'stateChange');
3389
+
3390
+ await expect(
3391
+ webex.cc.setAgentState({state: 'Available', auxCodeId: '0'})
3392
+ ).rejects.toThrow(VOICE_CONNECTION_ERROR.NOT_READY);
3393
+
3394
+ expect(stateChangeSpy).not.toHaveBeenCalled();
3395
+ expect(getErrorDetailsSpy).toHaveBeenCalledWith(
3396
+ expect.objectContaining({
3397
+ message: VOICE_CONNECTION_ERROR.NOT_READY,
3398
+ details: expect.objectContaining({
3399
+ type: 'SDK_VALIDATION_ERROR',
3400
+ data: {reason: VOICE_CONNECTION_ERROR.NOT_READY},
3401
+ }),
3402
+ }),
3403
+ 'setAgentState',
3404
+ CC_FILE
3405
+ );
3406
+ expect(mockMetricsManager.trackEvent).toHaveBeenCalledWith(
3407
+ METRIC_EVENT_NAMES.AGENT_STATE_CHANGE_FAILED,
3408
+ expect.objectContaining({state: 'Available', auxCodeId: '0'}),
3409
+ ['behavioral', 'business', 'operational']
3410
+ );
3411
+ });
3412
+
3413
+ it('should allow an Idle transition while browser voice is unavailable', async () => {
3414
+ const webCallingService = webex.cc.webCallingService;
3415
+ jest.spyOn(webCallingService, 'isBrowserVoiceRequired').mockReturnValue(true);
3416
+ jest.spyOn(webCallingService, 'isVoiceReady').mockReturnValue(false);
3417
+ const payload = {state: 'Idle', auxCodeId: 'idle-code', agentId: 'agent-id'};
3418
+ const stateChangeSpy = jest
3419
+ .spyOn(webex.cc.services.agent, 'stateChange')
3420
+ .mockResolvedValue({data: payload});
3421
+
3422
+ await webex.cc.setAgentState(payload);
3423
+
3424
+ expect(stateChangeSpy).toHaveBeenCalledWith({data: payload});
3425
+ });
3426
+
3427
+ it('should preserve state changes when browser voice registration is not required', async () => {
3428
+ const webCallingService = webex.cc.webCallingService;
3429
+ jest.spyOn(webCallingService, 'isBrowserVoiceRequired').mockReturnValue(false);
3430
+ jest.spyOn(webCallingService, 'isVoiceReady').mockReturnValue(false);
3431
+ const expectedPayload = {state: 'Meeting', auxCodeId: '12345', agentId: '123'};
3432
+ const stateChangeSpy = jest
3433
+ .spyOn(webex.cc.services.agent, 'stateChange')
3434
+ .mockResolvedValue({data: expectedPayload});
3435
+
3436
+ await webex.cc.setAgentState(expectedPayload);
3437
+
3438
+ expect(stateChangeSpy).toHaveBeenCalledWith({data: expectedPayload});
3439
+ });
3440
+
1091
3441
  it('should set agent status successfully when status is Available', async () => {
1092
3442
  const expectedPayload = {
1093
3443
  state: 'Available',
@@ -1213,6 +3563,257 @@ describe('webex.cc', () => {
1213
3563
  });
1214
3564
  });
1215
3565
 
3566
+ describe('Agent Wellness Break SDK contracts', () => {
3567
+ const wellbeingCode = {
3568
+ id: 'wellbeing-code',
3569
+ name: 'WellbeingBreak',
3570
+ isSystem: true,
3571
+ isDefault: false,
3572
+ };
3573
+
3574
+ beforeEach(() => {
3575
+ webex.cc.agentConfig = {
3576
+ agentId: 'agent-1',
3577
+ isWellnessBreakEnabled: true,
3578
+ } as Profile;
3579
+ webex.cc['updateWellnessSession']('session-1');
3580
+ });
3581
+
3582
+ it('fetches the system idle code once per registration', async () => {
3583
+ const lookup = jest
3584
+ .spyOn(webex.cc.services.config, 'getWellbeingBreakIdleCode')
3585
+ .mockResolvedValue(wellbeingCode);
3586
+
3587
+ await expect(webex.cc.getWellbeingBreakIdleCode()).resolves.toEqual(wellbeingCode);
3588
+ await expect(webex.cc.getWellbeingBreakIdleCode()).resolves.toEqual(wellbeingCode);
3589
+
3590
+ expect(lookup).toHaveBeenCalledTimes(1);
3591
+ expect(lookup).toHaveBeenCalledWith('mockOrgId');
3592
+ });
3593
+
3594
+ it('does not cache an idle-code lookup that completes after a new registration starts', async () => {
3595
+ let resolveLookup: (idleCode: typeof wellbeingCode) => void = () => undefined;
3596
+ jest
3597
+ .spyOn(webex.cc.services.config, 'getWellbeingBreakIdleCode')
3598
+ .mockImplementation(
3599
+ () =>
3600
+ new Promise((resolve) => {
3601
+ resolveLookup = resolve;
3602
+ })
3603
+ );
3604
+
3605
+ const lookupPromise = webex.cc.getWellbeingBreakIdleCode();
3606
+ const staleLookup = expect(lookupPromise).rejects.toThrow(
3607
+ 'WELLNESS_BREAK_REGISTRATION_CHANGED'
3608
+ );
3609
+ jest
3610
+ .spyOn(webex.cc, 'connectWebsocket')
3611
+ .mockRejectedValue(new Error('replacement registration failed'));
3612
+
3613
+ await expect(webex.cc.register()).rejects.toThrow('replacement registration failed');
3614
+ resolveLookup(wellbeingCode);
3615
+
3616
+ await staleLookup;
3617
+ expect(webex.cc['wellbeingBreakIdleCode']).toBeUndefined();
3618
+ });
3619
+
3620
+ it('rejects the system idle-code lookup when wellness is disabled', async () => {
3621
+ webex.cc.agentConfig.isWellnessBreakEnabled = false;
3622
+
3623
+ await expect(webex.cc.getWellbeingBreakIdleCode()).rejects.toThrow(
3624
+ 'WELLNESS_BREAK_NOT_ENABLED'
3625
+ );
3626
+ expect(webex.cc.services.config.getWellbeingBreakIdleCode).not.toHaveBeenCalled();
3627
+ });
3628
+
3629
+ it('invalidates the wellness session only for a current-session multi-login close', () => {
3630
+ webex.cc['handleWebsocketMessage'](
3631
+ JSON.stringify({
3632
+ type: CC_EVENTS.AGENT_MULTI_LOGIN,
3633
+ data: {
3634
+ type: 'AgentMultiLoginCloseSession',
3635
+ agentSessionId: 'another-session',
3636
+ },
3637
+ })
3638
+ );
3639
+ expect(webex.cc['currentAgentSessionId']).toBe('session-1');
3640
+
3641
+ webex.cc['handleWebsocketMessage'](
3642
+ JSON.stringify({
3643
+ type: CC_EVENTS.AGENT_MULTI_LOGIN,
3644
+ data: {
3645
+ type: 'AgentMultiLoginCloseSession',
3646
+ agentSessionId: 'session-1',
3647
+ },
3648
+ })
3649
+ );
3650
+ expect(webex.cc['currentAgentSessionId']).toBeUndefined();
3651
+ });
3652
+
3653
+ it('emits primary wellness notifications regardless of notification session metadata', () => {
3654
+ const emitSpy = jest.spyOn(webex.cc, 'emit');
3655
+ const payload = {
3656
+ type: 'Wellness_Break_Handler',
3657
+ orgId: 'mockOrgId',
3658
+ trackingId: 'data-notification-tracking',
3659
+ data: {
3660
+ agentId: 'agent-1',
3661
+ orgId: 'mockOrgId',
3662
+ notifType: 'Wellness_Break_Handler',
3663
+ notifDetails: {
3664
+ actionEvent: 'SUGGEST_WELLNESS_BREAK',
3665
+ actionText: 'How about a break?',
3666
+ },
3667
+ data: {
3668
+ orgId: 'mockOrgId',
3669
+ agentSessionId: 'notification-session',
3670
+ interactionId: 'interaction-1',
3671
+ },
3672
+ },
3673
+ };
3674
+
3675
+ webex.cc['handleWebsocketMessage'](JSON.stringify(payload));
3676
+
3677
+ expect(emitSpy).toHaveBeenCalledWith(CC_EVENTS.WELLNESS_BREAK, {
3678
+ agentId: 'agent-1',
3679
+ orgId: 'mockOrgId',
3680
+ agentSessionId: 'notification-session',
3681
+ actionEvent: 'SUGGEST_WELLNESS_BREAK',
3682
+ actionText: 'How about a break?',
3683
+ interactionId: 'interaction-1',
3684
+ trackingId: 'data-notification-tracking',
3685
+ });
3686
+ });
3687
+
3688
+ it('routes data-socket wellness notifications without sending them to TaskManager', () => {
3689
+ const emitSpy = jest.spyOn(webex.cc, 'emit');
3690
+ const taskEventSpy = mockTaskManager.handleRealtimeWebsocketEvent;
3691
+ const wellnessMessage = JSON.stringify({
3692
+ type: 'Wellness_Break_Handler',
3693
+ orgId: 'mockOrgId',
3694
+ data: {
3695
+ agentId: 'agent-1',
3696
+ orgId: 'mockOrgId',
3697
+ notifType: 'Wellness_Break_Handler',
3698
+ notifDetails: {actionEvent: 'PROVIDE_WELLNESS_BREAK'},
3699
+ data: {orgId: 'mockOrgId', agentSessionId: 'notification-session'},
3700
+ },
3701
+ });
3702
+
3703
+ webex.cc['handleRTDWebsocketMessage'](wellnessMessage);
3704
+
3705
+ expect(emitSpy).toHaveBeenCalledWith(CC_EVENTS.WELLNESS_BREAK, {
3706
+ agentId: 'agent-1',
3707
+ orgId: 'mockOrgId',
3708
+ agentSessionId: 'notification-session',
3709
+ actionEvent: 'PROVIDE_WELLNESS_BREAK',
3710
+ });
3711
+ expect(taskEventSpy).not.toHaveBeenCalled();
3712
+
3713
+ const transcriptMessage = JSON.stringify({type: CC_EVENTS.REAL_TIME_TRANSCRIPTION});
3714
+ webex.cc['handleRTDWebsocketMessage'](transcriptMessage);
3715
+ expect(taskEventSpy).toHaveBeenCalledWith(transcriptMessage);
3716
+ });
3717
+
3718
+ it.each([
3719
+ ['SUGGEST_WELLNESS_BREAK', 'interactionId'],
3720
+ ['WELLNESS_BREAK_NOT_ALLOWED', 'InteractionId'],
3721
+ ])('normalizes the %s action and either interaction-id spelling', (actionEvent, key) => {
3722
+ const emitSpy = jest.spyOn(webex.cc, 'emit');
3723
+ webex.cc['handleWebsocketMessage'](
3724
+ JSON.stringify({
3725
+ type: 'Wellness_Break_Handler',
3726
+ orgId: 'mockOrgId',
3727
+ data: {
3728
+ agentId: 'agent-1',
3729
+ orgId: 'mockOrgId',
3730
+ notifType: 'Wellness_Break_Handler',
3731
+ notifDetails: {actionEvent},
3732
+ data: {
3733
+ orgId: 'mockOrgId',
3734
+ agentSessionId: 'session-1',
3735
+ [key]: 'interaction-2',
3736
+ },
3737
+ },
3738
+ })
3739
+ );
3740
+
3741
+ expect(emitSpy).toHaveBeenCalledWith(
3742
+ CC_EVENTS.WELLNESS_BREAK,
3743
+ expect.objectContaining({actionEvent, interactionId: 'interaction-2'})
3744
+ );
3745
+ });
3746
+
3747
+ it('does not promote uncontracted notification text fields', () => {
3748
+ const emitSpy = jest.spyOn(webex.cc, 'emit');
3749
+ webex.cc['handleWebsocketMessage'](
3750
+ JSON.stringify({
3751
+ type: 'Wellness_Break_Handler',
3752
+ orgId: 'mockOrgId',
3753
+ trackingId: 'notification-tracking',
3754
+ data: {
3755
+ agentId: 'agent-1',
3756
+ orgId: 'mockOrgId',
3757
+ notifType: 'Wellness_Break_Handler',
3758
+ notifDetails: {
3759
+ actionEvent: 'SUGGEST_WELLNESS_BREAK',
3760
+ actionText2: 'Uncontracted text',
3761
+ },
3762
+ data: {
3763
+ orgId: 'mockOrgId',
3764
+ agentSessionId: 'session-1',
3765
+ InteractionId: 'interaction-qa',
3766
+ },
3767
+ },
3768
+ })
3769
+ );
3770
+
3771
+ expect(emitSpy).toHaveBeenCalledWith(CC_EVENTS.WELLNESS_BREAK, {
3772
+ agentId: 'agent-1',
3773
+ orgId: 'mockOrgId',
3774
+ agentSessionId: 'session-1',
3775
+ actionEvent: 'SUGGEST_WELLNESS_BREAK',
3776
+ interactionId: 'interaction-qa',
3777
+ trackingId: 'notification-tracking',
3778
+ });
3779
+ });
3780
+
3781
+ it('ignores wellness events when the effective flag is disabled or identity is missing', () => {
3782
+ const emitSpy = jest.spyOn(webex.cc, 'emit');
3783
+ const payload = {
3784
+ type: 'Wellness_Break_Handler',
3785
+ orgId: 'mockOrgId',
3786
+ data: {
3787
+ agentId: 'agent-1',
3788
+ orgId: 'mockOrgId',
3789
+ notifType: 'Wellness_Break_Handler',
3790
+ notifDetails: {actionEvent: 'SUGGEST_WELLNESS_BREAK'},
3791
+ data: {orgId: 'mockOrgId', agentSessionId: 'session-1'},
3792
+ },
3793
+ };
3794
+
3795
+ webex.cc.agentConfig.isWellnessBreakEnabled = false;
3796
+ webex.cc['handleWebsocketMessage'](JSON.stringify(payload));
3797
+ webex.cc.agentConfig.isWellnessBreakEnabled = true;
3798
+ const {orgId: omittedOrgId, ...payloadWithoutEnvelopeOrg} = payload;
3799
+ expect(omittedOrgId).toBe('mockOrgId');
3800
+ webex.cc['handleWebsocketMessage'](JSON.stringify(payloadWithoutEnvelopeOrg));
3801
+
3802
+ expect(emitSpy).not.toHaveBeenCalledWith(CC_EVENTS.WELLNESS_BREAK, expect.anything());
3803
+ expect(mockMetricsManager.trackEvent).toHaveBeenCalledWith(
3804
+ METRIC_EVENT_NAMES.AI_ASSISTANT_WELLNESS_EVENT_INVALID,
3805
+ {reason: 'wellness_disabled'},
3806
+ ['operational']
3807
+ );
3808
+ expect(mockMetricsManager.trackEvent).toHaveBeenCalledWith(
3809
+ METRIC_EVENT_NAMES.AI_ASSISTANT_WELLNESS_EVENT_INVALID,
3810
+ {reason: 'missing_wellness_identity'},
3811
+ ['operational']
3812
+ );
3813
+ });
3814
+
3815
+ });
3816
+
1216
3817
  describe('getBuddyAgents', () => {
1217
3818
  it('should return buddy agents response when successful', async () => {
1218
3819
  const data: BuddyAgents = {state: 'Available', mediaType: 'telephony'};
@@ -1276,6 +3877,41 @@ describe('webex.cc', () => {
1276
3877
  ]);
1277
3878
  });
1278
3879
 
3880
+ it('should map Transfer action to an Available backend state filter', async () => {
3881
+ webex.cc.agentConfig = {agentProfileID: 'test-agent-profile-id'};
3882
+ const buddyAgentsResponse = {data: {agentList: []}};
3883
+ const buddyAgentsSpy = jest
3884
+ .spyOn(webex.cc.services.agent, 'buddyAgents')
3885
+ .mockResolvedValue(buddyAgentsResponse);
3886
+
3887
+ await webex.cc.getBuddyAgents({action: 'Transfer', mediaType: 'chat'});
3888
+
3889
+ expect(buddyAgentsSpy).toHaveBeenCalledWith({
3890
+ data: {
3891
+ agentProfileId: 'test-agent-profile-id',
3892
+ mediaType: 'chat',
3893
+ state: 'Available',
3894
+ },
3895
+ });
3896
+ });
3897
+
3898
+ it('should omit the backend state filter for Consult and default media type to telephony', async () => {
3899
+ webex.cc.agentConfig = {agentProfileID: 'test-agent-profile-id'};
3900
+ const buddyAgentsResponse = {data: {agentList: []}};
3901
+ const buddyAgentsSpy = jest
3902
+ .spyOn(webex.cc.services.agent, 'buddyAgents')
3903
+ .mockResolvedValue(buddyAgentsResponse);
3904
+
3905
+ await webex.cc.getBuddyAgents({action: 'Consult'});
3906
+
3907
+ expect(buddyAgentsSpy).toHaveBeenCalledWith({
3908
+ data: {
3909
+ agentProfileId: 'test-agent-profile-id',
3910
+ mediaType: 'telephony',
3911
+ },
3912
+ });
3913
+ });
3914
+
1279
3915
  it('should handle error', async () => {
1280
3916
  const data: BuddyAgents = {state: 'Available', mediaType: 'telephony'};
1281
3917
  webex.cc.agentConfig = {
@@ -1316,6 +3952,34 @@ describe('webex.cc', () => {
1316
3952
  });
1317
3953
 
1318
3954
  describe('silentRelogin', () => {
3955
+ it('preserves browser line registration when WebRTC is not required', async () => {
3956
+ webex.cc.agentConfig = {
3957
+ agentId: 'agentId',
3958
+ webRtcEnabled: false,
3959
+ } as Profile;
3960
+ jest.spyOn(webex.cc.services.agent, 'reload').mockResolvedValue({
3961
+ data: {
3962
+ auxCodeId: 'auxCodeId',
3963
+ agentId: 'agentId',
3964
+ deviceType: LoginOption.BROWSER,
3965
+ dn: '12345',
3966
+ },
3967
+ } as any);
3968
+ const registerWebCallingLineSpy = jest.spyOn(
3969
+ webex.cc.webCallingService,
3970
+ 'registerWebCallingLine'
3971
+ );
3972
+ const setBrowserVoiceRequiredSpy = jest.spyOn(
3973
+ webex.cc.webCallingService,
3974
+ 'setBrowserVoiceRequired'
3975
+ );
3976
+
3977
+ await webex.cc['silentRelogin']();
3978
+
3979
+ expect(registerWebCallingLineSpy).toHaveBeenCalled();
3980
+ expect(setBrowserVoiceRequiredSpy).toHaveBeenCalledWith(false);
3981
+ });
3982
+
1319
3983
  it('should perform silent relogin and set agent state to available', async () => {
1320
3984
  const mockReLoginResponse = {
1321
3985
  data: {
@@ -1334,6 +3998,7 @@ describe('webex.cc', () => {
1334
3998
  agentId: 'agentId',
1335
3999
  agentProfileID: 'test-agent-profile-id',
1336
4000
  isAgentLoggedIn: false,
4001
+ webRtcEnabled: true,
1337
4002
  } as Profile;
1338
4003
 
1339
4004
  const date = new Date();
@@ -1348,8 +4013,6 @@ describe('webex.cc', () => {
1348
4013
  );
1349
4014
 
1350
4015
  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
4016
  await webex.cc['silentRelogin']();
1354
4017
 
1355
4018
  expect(LoggerProxy.log).toHaveBeenCalledWith('Starting silent relogin process', {
@@ -1380,8 +4043,9 @@ describe('webex.cc', () => {
1380
4043
  expect(webex.cc.agentConfig.deviceType).toBe(LoginOption.BROWSER);
1381
4044
  expect(registerWebCallingLineSpy).toHaveBeenCalled();
1382
4045
  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();
4046
+ expect(webex.cc.webCallingService.setBrowserVoiceRequired).toHaveBeenCalledWith(true);
4047
+ // SPARK-626777 tracks moving listener cleanup into the future de-register API.
4048
+ // expect(eventForwarderRefreshSpy).toHaveBeenCalled();
1385
4049
  // expect(webSocketManagerOnSpy).toHaveBeenCalledWith('message', expect.any(Function));
1386
4050
  // expect(mockTaskManager.on).toHaveBeenCalledWith(
1387
4051
  // TASK_EVENTS.TASK_HYDRATE,
@@ -1496,12 +4160,89 @@ describe('webex.cc', () => {
1496
4160
  isAgentLoggedIn: false,
1497
4161
  } as Profile;
1498
4162
 
1499
- jest.spyOn(webex.cc.services.agent, 'reload').mockResolvedValue(mockReLoginResponse);
4163
+ jest.spyOn(webex.cc.services.agent, 'reload').mockResolvedValue(mockReLoginResponse);
4164
+
4165
+ await webex.cc['silentRelogin']();
4166
+
4167
+ expect(webex.cc.agentConfig.deviceType).toBe(LoginOption.AGENT_DN);
4168
+ expect(webex.cc.agentConfig.dn).toBe('67890');
4169
+ });
4170
+
4171
+ it('should publish usersub true on silent relogin when enableWxBetterTogether is true at init', async () => {
4172
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
4173
+ webex.internal.device = {
4174
+ userId: 'user-123',
4175
+ url: 'https://wdm.example.com/devices/dev-1',
4176
+ registered: true,
4177
+ register: jest.fn().mockResolvedValue(undefined),
4178
+ };
4179
+ webex.internal.mercury.connected = true;
4180
+ webex.internal.mercury.connect = jest.fn().mockResolvedValue(undefined);
4181
+ webex.cc.agentConfig = {
4182
+ agentId: 'agentId',
4183
+ agentProfileID: 'test-agent-profile-id',
4184
+ isAgentLoggedIn: false,
4185
+ } as Profile;
4186
+
4187
+ jest.spyOn(webex.cc.services.agent, 'reload').mockResolvedValue({
4188
+ data: {
4189
+ auxCodeId: 'auxCodeId',
4190
+ agentId: 'agentId',
4191
+ deviceType: LoginOption.EXTENSION,
4192
+ dn: '1001',
4193
+ teamId: 'teamId',
4194
+ lastStateChangeTimestamp: 1738575135188,
4195
+ lastIdleCodeChangeTimestamp: 1738575135189,
4196
+ },
4197
+ });
4198
+
4199
+ const publishSpy = jest
4200
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
4201
+ .mockResolvedValue(undefined);
4202
+ const subscribeSpy = jest
4203
+ .spyOn(webex.cc['wxAppTelephonyMercurySync'], 'subscribe')
4204
+ .mockImplementation(() => {});
4205
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
4206
+
4207
+ await webex.cc['silentRelogin']();
4208
+
4209
+ expect(publishSpy).toHaveBeenCalledWith(true, {userId: 'user-123', trackPublishMetrics: true});
4210
+ expect(subscribeSpy).toHaveBeenCalledWith('agentId', expect.any(Function));
4211
+ expect(mockTaskManager.refreshWxAppOfferObservabilityForAllTasks).toHaveBeenCalled();
4212
+ });
4213
+
4214
+ it('should force-publish usersub false on silent relogin when enableWxBetterTogether is false at init', async () => {
4215
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: false};
4216
+ webex.internal.device = {userId: 'user-123', url: 'https://wdm.example.com/devices/dev-1'};
4217
+ webex.cc.agentConfig = {
4218
+ agentId: 'agentId',
4219
+ agentProfileID: 'test-agent-profile-id',
4220
+ isAgentLoggedIn: false,
4221
+ } as Profile;
4222
+
4223
+ jest.spyOn(webex.cc.services.agent, 'reload').mockResolvedValue({
4224
+ data: {
4225
+ auxCodeId: 'auxCodeId',
4226
+ agentId: 'agentId',
4227
+ deviceType: LoginOption.EXTENSION,
4228
+ dn: '1001',
4229
+ teamId: 'teamId',
4230
+ lastStateChangeTimestamp: 1738575135188,
4231
+ lastIdleCodeChangeTimestamp: 1738575135189,
4232
+ },
4233
+ });
4234
+
4235
+ const publishSpy = jest
4236
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
4237
+ .mockResolvedValue(undefined);
4238
+ const teardownSpy = jest.spyOn(webex.cc['webexCrossClientService'], 'teardown');
4239
+ const unsubscribeSpy = jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'unsubscribe');
1500
4240
 
1501
4241
  await webex.cc['silentRelogin']();
1502
4242
 
1503
- expect(webex.cc.agentConfig.deviceType).toBe(LoginOption.AGENT_DN);
1504
- expect(webex.cc.agentConfig.dn).toBe('67890');
4243
+ expect(publishSpy).toHaveBeenCalledWith(false, {userId: 'user-123', trackPublishMetrics: true});
4244
+ expect(teardownSpy).toHaveBeenCalled();
4245
+ expect(unsubscribeSpy).toHaveBeenCalled();
1505
4246
  });
1506
4247
  });
1507
4248
 
@@ -1639,6 +4380,9 @@ describe('webex.cc', () => {
1639
4380
  {module: CC_FILE, method: `startOutdial`, trackingId: error.details.trackingId}
1640
4381
  );
1641
4382
  expect(getErrorDetailsSpy).toHaveBeenCalledWith(error, 'startOutdial', CC_FILE);
4383
+ expect(mockWebexRequest.uploadLogs).toHaveBeenCalledWith({
4384
+ correlationId: error.details.trackingId,
4385
+ });
1642
4386
  });
1643
4387
  });
1644
4388
 
@@ -1733,6 +4477,42 @@ describe('webex.cc', () => {
1733
4477
  deviceUnregisterSpy = jest.spyOn(webex.internal.device, 'unregister');
1734
4478
  });
1735
4479
 
4480
+ afterEach(() => {
4481
+ mockTaskManager.off.mockImplementation(() => undefined);
4482
+ mockTaskManager.clearAISummaryState.mockImplementation(() => undefined);
4483
+ mockRTDWebSocketManager.off.mockImplementation(() => undefined);
4484
+ mockRTDWebSocketManager.close.mockImplementation(() => undefined);
4485
+ });
4486
+
4487
+ it('invalidates wellness context before deregistration cleanup can fail', async () => {
4488
+ const cleanupError = new Error('cleanup failed');
4489
+ let rejectCleanup: (error: Error) => void = () => undefined;
4490
+ const cleanup = new Promise((resolve, reject) => {
4491
+ rejectCleanup = reject;
4492
+ });
4493
+ webex.cc.agentConfig = {
4494
+ ...webex.cc.agentConfig,
4495
+ isWellnessBreakEnabled: true,
4496
+ };
4497
+ webex.cc['updateWellnessSession']('session-1');
4498
+ jest.spyOn(webex.cc as any, 'teardownWxAppLocalState').mockReturnValue(cleanup);
4499
+ webex.cc.apiAIAssistant.requestWellnessBreak.mockRejectedValue(
4500
+ new Error('WELLNESS_BREAK_AGENT_SESSION_REQUIRED')
4501
+ );
4502
+
4503
+ const deregistration = webex.cc.deregister();
4504
+ const rejection = expect(deregistration).rejects.toThrow(cleanupError);
4505
+
4506
+ expect(webex.cc['currentAgentSessionId']).toBeUndefined();
4507
+ await expect(webex.cc.apiAIAssistant.requestWellnessBreak()).rejects.toThrow(
4508
+ 'WELLNESS_BREAK_AGENT_SESSION_REQUIRED'
4509
+ );
4510
+
4511
+ rejectCleanup(cleanupError);
4512
+ await rejection;
4513
+ expect(webex.cc['currentAgentSessionId']).toBeUndefined();
4514
+ });
4515
+
1736
4516
  it('should unregister successfully and clean up all resources when webrtc is enabled', async () => {
1737
4517
  webex.cc.services.rtdWebSocketManager = {
1738
4518
  isSocketClosed: false,
@@ -1741,6 +4521,18 @@ describe('webex.cc', () => {
1741
4521
  on: jest.fn(),
1742
4522
  } as any;
1743
4523
 
4524
+ webex.internal.device = {
4525
+ ...webex.internal.device,
4526
+ userId: 'user-123',
4527
+ unregister: jest.fn().mockResolvedValue(undefined),
4528
+ };
4529
+ deviceUnregisterSpy = jest.spyOn(webex.internal.device, 'unregister');
4530
+ const publishSpy = jest
4531
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
4532
+ .mockResolvedValue(undefined);
4533
+ const teardownSpy = jest.spyOn(webex.cc['webexCrossClientService'], 'teardown');
4534
+ const unsubscribeSpy = jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'unsubscribe');
4535
+
1744
4536
  await webex.cc.deregister();
1745
4537
 
1746
4538
  expect(mockTaskManager.off).toHaveBeenCalledWith(
@@ -1766,10 +4558,17 @@ describe('webex.cc', () => {
1766
4558
  );
1767
4559
 
1768
4560
  expect(mockWebSocketManager.close).toHaveBeenCalledWith(false, 'Unregistering the SDK');
1769
- expect(webex.cc.services.rtdWebSocketManager.close).toHaveBeenCalledWith(
4561
+ expect(webex.cc.services.rtdWebSocketManager.close).toHaveBeenNthCalledWith(
4562
+ 1,
4563
+ false,
4564
+ 'Unregistering the SDK'
4565
+ );
4566
+ expect(webex.cc.services.rtdWebSocketManager.close).toHaveBeenNthCalledWith(
4567
+ 2,
1770
4568
  false,
1771
4569
  'Unregistering the RTD websocket'
1772
4570
  );
4571
+ expect(webex.cc.services.rtdWebSocketManager.close).toHaveBeenCalledTimes(2);
1773
4572
  expect(webex.cc.agentConfig).toBeNull();
1774
4573
 
1775
4574
  expect(webex.internal.mercury.off).toHaveBeenCalledWith('online');
@@ -1781,6 +4580,7 @@ describe('webex.cc', () => {
1781
4580
  METRIC_EVENT_NAMES.WEBSOCKET_DEREGISTER_SUCCESS,
1782
4581
  METRIC_EVENT_NAMES.WEBSOCKET_DEREGISTER_FAIL,
1783
4582
  ]);
4583
+ expect(mockTaskManager.clearAISummaryState).toHaveBeenCalled();
1784
4584
  expect(mockMetricsManager.trackEvent).toHaveBeenCalledWith(
1785
4585
  METRIC_EVENT_NAMES.WEBSOCKET_DEREGISTER_SUCCESS,
1786
4586
  {},
@@ -1800,22 +4600,23 @@ describe('webex.cc', () => {
1800
4600
  const incomingCalls = mockTaskManager.off.mock.calls.filter(
1801
4601
  ([evt]) => evt === TASK_EVENTS.TASK_INCOMING
1802
4602
  );
1803
- expect(incomingCalls).toHaveLength(1);
1804
- const [, incomingCallback] = incomingCalls[0];
4603
+ expect(incomingCalls.length).toBeGreaterThanOrEqual(1);
4604
+ const [, incomingCallback] = incomingCalls[incomingCalls.length - 1];
1805
4605
  expect(incomingCallback).toBe(webex.cc['handleIncomingTask']);
1806
4606
 
1807
4607
  const hydrateCalls = mockTaskManager.off.mock.calls.filter(
1808
4608
  ([evt]) => evt === TASK_EVENTS.TASK_HYDRATE
1809
4609
  );
1810
- expect(hydrateCalls).toHaveLength(1);
1811
- const [, hydrateCallback] = hydrateCalls[0];
4610
+ expect(hydrateCalls.length).toBeGreaterThanOrEqual(1);
4611
+ const [, hydrateCallback] = hydrateCalls[hydrateCalls.length - 1];
1812
4612
  expect(hydrateCallback).toBe(webex.cc['handleTaskHydrate']);
1813
4613
 
1814
4614
  const multiLoginHydrateCalls = mockTaskManager.off.mock.calls.filter(
1815
4615
  ([evt]) => evt === TASK_EVENTS.TASK_MULTI_LOGIN_HYDRATE
1816
4616
  );
1817
- expect(multiLoginHydrateCalls).toHaveLength(1);
1818
- const [, multiLoginHydrateCallback] = multiLoginHydrateCalls[0];
4617
+ expect(multiLoginHydrateCalls.length).toBeGreaterThanOrEqual(1);
4618
+ const [, multiLoginHydrateCallback] =
4619
+ multiLoginHydrateCalls[multiLoginHydrateCalls.length - 1];
1819
4620
  expect(multiLoginHydrateCallback).toBe(webex.cc['handleTaskMultiLoginHydrate']);
1820
4621
 
1821
4622
  const messageCalls = mockWebSocketManager.off.mock.calls.filter(([evt]) => evt === 'message');
@@ -1829,6 +4630,39 @@ describe('webex.cc', () => {
1829
4630
  expect(connectionCalls).toHaveLength(1);
1830
4631
  const [, connectionCallback] = connectionCalls[0];
1831
4632
  expect(connectionCallback).toBe(webex.cc['handleConnectionLost']);
4633
+
4634
+ expect(publishSpy).not.toHaveBeenCalled();
4635
+ expect(teardownSpy).toHaveBeenCalled();
4636
+ expect(unsubscribeSpy).toHaveBeenCalled();
4637
+ });
4638
+
4639
+ it('should publish usersub false before device unregister when wxApp is active on deregister', async () => {
4640
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
4641
+ webex.cc['webexCrossClientService'].answerCallsState = true;
4642
+ webex.internal.device = {
4643
+ userId: 'user-123',
4644
+ url: 'https://wdm.example.com/devices/dev-1',
4645
+ unregister: jest.fn().mockResolvedValue(undefined),
4646
+ };
4647
+ deviceUnregisterSpy = jest.spyOn(webex.internal.device, 'unregister');
4648
+
4649
+ const callOrder: string[] = [];
4650
+ jest
4651
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
4652
+ .mockImplementation(async (enable: boolean) => {
4653
+ if (enable === false && !webex.internal.device.url) {
4654
+ throw new Error('Device URL is unavailable for cross-client publish');
4655
+ }
4656
+ callOrder.push(enable ? 'publish:true' : 'publish:false');
4657
+ });
4658
+ deviceUnregisterSpy.mockImplementation(async () => {
4659
+ callOrder.push('device.unregister');
4660
+ webex.internal.device.url = undefined;
4661
+ });
4662
+
4663
+ await webex.cc.deregister();
4664
+
4665
+ expect(callOrder).toEqual(['publish:false', 'device.unregister']);
1832
4666
  });
1833
4667
 
1834
4668
  it('should skip webCallingService and internal cleanup when webrtc is disabled', async () => {
@@ -1856,7 +4690,17 @@ describe('webex.cc', () => {
1856
4690
  expect(webex.internal.mercury.off).not.toHaveBeenCalled();
1857
4691
  expect(mercuryDisconnectSpy).not.toHaveBeenCalled();
1858
4692
  expect(deviceUnregisterSpy).not.toHaveBeenCalled();
1859
- expect(mockRTDWebSocketManager.close).toHaveBeenCalledWith(false, 'Unregistering the SDK');
4693
+ expect(mockRTDWebSocketManager.close).toHaveBeenNthCalledWith(
4694
+ 1,
4695
+ false,
4696
+ 'Unregistering the SDK'
4697
+ );
4698
+ expect(mockRTDWebSocketManager.close).toHaveBeenNthCalledWith(
4699
+ 2,
4700
+ false,
4701
+ 'Unregistering the RTD websocket'
4702
+ );
4703
+ expect(mockRTDWebSocketManager.close).toHaveBeenCalledTimes(2);
1860
4704
  });
1861
4705
 
1862
4706
  it('should skip internal mercury cleanup when loginVoiceOptions does not include BROWSER', async () => {
@@ -1874,10 +4718,149 @@ describe('webex.cc', () => {
1874
4718
  expect(deviceUnregisterSpy).not.toHaveBeenCalled();
1875
4719
 
1876
4720
  expect(mockWebSocketManager.close).toHaveBeenCalledWith(false, 'Unregistering the SDK');
1877
- expect(mockRTDWebSocketManager.close).toHaveBeenCalledWith(false, 'Unregistering the SDK');
4721
+ expect(mockRTDWebSocketManager.close).toHaveBeenNthCalledWith(
4722
+ 1,
4723
+ false,
4724
+ 'Unregistering the SDK'
4725
+ );
4726
+ expect(mockRTDWebSocketManager.close).toHaveBeenNthCalledWith(
4727
+ 2,
4728
+ false,
4729
+ 'Unregistering the RTD websocket'
4730
+ );
4731
+ expect(mockRTDWebSocketManager.close).toHaveBeenCalledTimes(2);
4732
+ expect(webex.cc.agentConfig).toBeNull();
4733
+ });
4734
+
4735
+ it('should teardown wxApp state on deregister even when usersub publish fails', async () => {
4736
+ webex.cc.agentConfig = {
4737
+ agentId: 'agentId',
4738
+ webRtcEnabled: false,
4739
+ loginVoiceOptions: [LoginOption.EXTENSION],
4740
+ };
4741
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
4742
+ webex.cc['webexCrossClientService'].answerCallsState = true;
4743
+ webex.internal.device = {
4744
+ userId: 'user-123',
4745
+ unregister: jest.fn().mockResolvedValue(undefined),
4746
+ };
4747
+
4748
+ jest
4749
+ .spyOn(webex.cc as never, 'publishAnswerOnWebexCrossClientState' as never)
4750
+ .mockRejectedValue(new Error('usersub publish failed'));
4751
+ const teardownSpy = jest.spyOn(webex.cc['webexCrossClientService'], 'teardown');
4752
+ const unsubscribeSpy = jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'unsubscribe');
4753
+
4754
+ await expect(webex.cc.deregister()).rejects.toThrow('usersub publish failed');
4755
+
4756
+ expect(teardownSpy).toHaveBeenCalled();
4757
+ expect(unsubscribeSpy).toHaveBeenCalled();
4758
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(false);
4759
+ expect(mockWebSocketManager.close).toHaveBeenCalledWith(false, 'Unregistering the SDK');
1878
4760
  expect(webex.cc.agentConfig).toBeNull();
1879
4761
  });
1880
4762
 
4763
+ it('should publish forced false during teardown when enable publish is still in flight', async () => {
4764
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
4765
+ webex.internal.device = {
4766
+ userId: 'user-123',
4767
+ url: 'https://wdm.example.com/devices/dev-1',
4768
+ };
4769
+
4770
+ let resolveEnable: () => void = () => {};
4771
+ const enableGate = new Promise<void>((resolve) => {
4772
+ resolveEnable = resolve;
4773
+ });
4774
+
4775
+ const publishSpy = jest
4776
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
4777
+ .mockImplementation(async (enable: boolean) => {
4778
+ if (enable) {
4779
+ await enableGate;
4780
+ }
4781
+ });
4782
+ jest
4783
+ .spyOn(webex.cc as any, 'releaseWxAppMercuryResources')
4784
+ .mockResolvedValue(undefined);
4785
+
4786
+ expect(webex.cc['webexCrossClientService'].answerCallsState).toBe(false);
4787
+
4788
+ const enableInFlight = (webex.cc as any).publishAnswerOnWebexCrossClientState(true);
4789
+
4790
+ await (webex.cc as any).teardownWxAppLocalState();
4791
+
4792
+ expect(publishSpy).toHaveBeenCalledWith(false, {userId: 'user-123', trackPublishMetrics: true});
4793
+
4794
+ resolveEnable();
4795
+ await enableInFlight;
4796
+ });
4797
+
4798
+ it('should release wxApp-owned Mercury and device on deregister', async () => {
4799
+ webex.cc.agentConfig = {
4800
+ agentId: 'agentId',
4801
+ webRtcEnabled: false,
4802
+ loginVoiceOptions: [LoginOption.EXTENSION],
4803
+ };
4804
+ webex.cc['wxAppMercuryConnectedByCc'] = true;
4805
+ webex.cc['wxAppDeviceRegisteredByCc'] = true;
4806
+ webex.internal.mercury.connected = true;
4807
+ webex.internal.device.registered = true;
4808
+
4809
+ const mercuryDisconnectSpy = jest
4810
+ .spyOn(webex.internal.mercury, 'disconnect')
4811
+ .mockResolvedValue(undefined);
4812
+ const deviceUnregisterSpy = jest
4813
+ .spyOn(webex.internal.device, 'unregister')
4814
+ .mockResolvedValue(undefined);
4815
+
4816
+ await webex.cc.deregister();
4817
+
4818
+ expect(mercuryDisconnectSpy).toHaveBeenCalled();
4819
+ expect(deviceUnregisterSpy).toHaveBeenCalled();
4820
+ expect(webex.cc['wxAppMercuryConnectedByCc']).toBe(false);
4821
+ expect(webex.cc['wxAppDeviceRegisteredByCc']).toBe(false);
4822
+ });
4823
+
4824
+ it('should retain wxApp Mercury ownership when disconnect fails and retry cleanup', async () => {
4825
+ webex.cc['wxAppMercuryConnectedByCc'] = true;
4826
+ webex.internal.mercury.connected = true;
4827
+
4828
+ const mercuryDisconnectSpy = jest
4829
+ .spyOn(webex.internal.mercury, 'disconnect')
4830
+ .mockRejectedValueOnce(new Error('disconnect failed'))
4831
+ .mockResolvedValueOnce(undefined);
4832
+
4833
+ await webex.cc['releaseWxAppMercuryResources']();
4834
+
4835
+ expect(mercuryDisconnectSpy).toHaveBeenCalledTimes(1);
4836
+ expect(webex.cc['wxAppMercuryConnectedByCc']).toBe(true);
4837
+
4838
+ await webex.cc['releaseWxAppMercuryResources']();
4839
+
4840
+ expect(mercuryDisconnectSpy).toHaveBeenCalledTimes(2);
4841
+ expect(webex.cc['wxAppMercuryConnectedByCc']).toBe(false);
4842
+ });
4843
+
4844
+ it('should retain wxApp device ownership when unregister fails and retry cleanup', async () => {
4845
+ webex.cc['wxAppDeviceRegisteredByCc'] = true;
4846
+ webex.internal.device.registered = true;
4847
+
4848
+ const deviceUnregisterSpy = jest
4849
+ .spyOn(webex.internal.device, 'unregister')
4850
+ .mockRejectedValueOnce(new Error('unregister failed'))
4851
+ .mockResolvedValueOnce(undefined);
4852
+
4853
+ await webex.cc['releaseWxAppMercuryResources']();
4854
+
4855
+ expect(deviceUnregisterSpy).toHaveBeenCalledTimes(1);
4856
+ expect(webex.cc['wxAppDeviceRegisteredByCc']).toBe(true);
4857
+
4858
+ await webex.cc['releaseWxAppMercuryResources']();
4859
+
4860
+ expect(deviceUnregisterSpy).toHaveBeenCalledTimes(2);
4861
+ expect(webex.cc['wxAppDeviceRegisteredByCc']).toBe(false);
4862
+ });
4863
+
1881
4864
  it('should handle errors during unregister and track metrics', async () => {
1882
4865
  const mockError = new Error('Failed to deregister device');
1883
4866
  webex.internal.device.unregister.mockRejectedValue(mockError);
@@ -1901,6 +4884,11 @@ describe('webex.cc', () => {
1901
4884
  module: CC_FILE,
1902
4885
  method: 'deregister',
1903
4886
  });
4887
+ expect(mockTaskManager.clearAISummaryState).toHaveBeenCalled();
4888
+ expect(webex.cc.services.rtdWebSocketManager.off).toHaveBeenCalledWith(
4889
+ 'message',
4890
+ webex.cc['handleRTDWebsocketMessage']
4891
+ );
1904
4892
 
1905
4893
  expect(mockMetricsManager.trackEvent).toHaveBeenCalledWith(
1906
4894
  METRIC_EVENT_NAMES.WEBSOCKET_DEREGISTER_FAIL,
@@ -2011,9 +4999,31 @@ describe('webex.cc', () => {
2011
4999
  });
2012
5000
  });
2013
5001
 
5002
+ it('does not emit an unknown server-controlled event type', () => {
5003
+ const payload = {
5004
+ type: 'UnhandledMessage',
5005
+ data: {foo: 'bar', type: 'MaliciousInjectedType'},
5006
+ };
5007
+
5008
+ messageCallback(JSON.stringify(payload));
5009
+
5010
+ expect(emitSpy).not.toHaveBeenCalledWith('MaliciousInjectedType', expect.anything());
5011
+ });
5012
+
5013
+ it('emits a known agent event type verbatim from data.type', () => {
5014
+ const sample = {foo: 'bar', type: CC_EVENTS.AGENT_STATE_CHANGE_SUCCESS};
5015
+
5016
+ messageCallback(
5017
+ JSON.stringify({type: CC_EVENTS.AGENT_STATE_CHANGE_SUCCESS, data: sample})
5018
+ );
5019
+
5020
+ expect(emitSpy).toHaveBeenCalledWith(CC_EVENTS.AGENT_STATE_CHANGE_SUCCESS, sample);
5021
+ });
5022
+
2014
5023
  it('should call webCallingService.setLoginOption with correct deviceType on AGENT_STATION_LOGIN_SUCCESS', () => {
2015
5024
  const setLoginOptionSpy = jest.spyOn(webex.cc.webCallingService, 'setLoginOption');
2016
- const deviceType = LoginOption.EXTENSION;
5025
+ const deviceType = LoginOption.BROWSER;
5026
+ webex.cc.agentConfig = {webRtcEnabled: true} as Profile;
2017
5027
  const payload = {
2018
5028
  trackingId: 'track-123',
2019
5029
  data: {
@@ -2031,10 +5041,97 @@ describe('webex.cc', () => {
2031
5041
  messageCallback(JSON.stringify(payload));
2032
5042
 
2033
5043
  expect(setLoginOptionSpy).toHaveBeenCalledWith(deviceType);
5044
+ expect(webex.cc.webCallingService.setBrowserVoiceRequired).not.toHaveBeenCalled();
5045
+ });
5046
+
5047
+ it('clears the local browser voice requirement after a multi-login on another device type', () => {
5048
+ const setBrowserVoiceRequiredSpy = jest.spyOn(
5049
+ webex.cc.webCallingService,
5050
+ 'setBrowserVoiceRequired'
5051
+ );
5052
+ const payload = {
5053
+ trackingId: 'track-123',
5054
+ data: {
5055
+ agentId: 'agent-id',
5056
+ teamId: 'team-id',
5057
+ siteId: 'site-id',
5058
+ roles: ['role1'],
5059
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
5060
+ deviceType: LoginOption.EXTENSION,
5061
+ type: CC_EVENTS.AGENT_STATION_LOGIN_SUCCESS,
5062
+ },
5063
+ type: CC_EVENTS.AGENT_STATION_LOGIN_SUCCESS,
5064
+ };
5065
+
5066
+ messageCallback(JSON.stringify(payload));
5067
+
5068
+ expect(setBrowserVoiceRequiredSpy).toHaveBeenCalledWith(false);
2034
5069
  });
5070
+
5071
+ it.each([
5072
+ [LoginOption.BROWSER, true, false, true],
5073
+ [LoginOption.BROWSER, true, true, false],
5074
+ [LoginOption.BROWSER, false, false, false],
5075
+ [LoginOption.EXTENSION, true, false, false],
5076
+ ])(
5077
+ 'should configure browser voice for loginOption=%s, webRtcEnabled=%s, disabled=%s',
5078
+ async (loginOption, webRtcEnabled, disableWebRTCRegistration, expected) => {
5079
+ webex.cc.agentConfig = {...webex.cc.agentConfig, webRtcEnabled} as Profile;
5080
+ webex.cc['$config'] = {...webex.cc['$config'], disableWebRTCRegistration};
5081
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
5082
+ data: {
5083
+ loginOption,
5084
+ agentId: 'agent-id',
5085
+ teamId: 'team-id',
5086
+ siteId: 'site-id',
5087
+ roles: [AGENT],
5088
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
5089
+ },
5090
+ trackingId: 'track-id',
5091
+ } as unknown as StationLoginSuccess);
5092
+ const setBrowserVoiceRequiredSpy = jest.spyOn(
5093
+ webex.cc.webCallingService,
5094
+ 'setBrowserVoiceRequired'
5095
+ );
5096
+ const registerWebCallingLineSpy = jest.spyOn(
5097
+ webex.cc.webCallingService,
5098
+ 'registerWebCallingLine'
5099
+ );
5100
+
5101
+ await webex.cc.stationLogin({teamId: 'team-id', loginOption});
5102
+
5103
+ expect(setBrowserVoiceRequiredSpy).toHaveBeenCalledWith(expected);
5104
+ if (expected) {
5105
+ expect(registerWebCallingLineSpy).toHaveBeenCalled();
5106
+ } else {
5107
+ expect(registerWebCallingLineSpy).not.toHaveBeenCalled();
5108
+ }
5109
+ }
5110
+ );
2035
5111
  });
2036
5112
 
2037
5113
  describe('API property exposure', () => {
5114
+ it('should expose the current voice connection snapshot and state change event', () => {
5115
+ const state = {
5116
+ status: VOICE_CONNECTION_STATUS.READY,
5117
+ lineStatus: 'registered',
5118
+ mobiusSocketStatus: 'connected',
5119
+ } as const;
5120
+ jest.spyOn(webex.cc.webCallingService, 'getVoiceConnectionState').mockReturnValue(state);
5121
+ const triggerSpy = jest.spyOn(webex.cc, 'trigger');
5122
+ expect(webex.cc.webCallingService.on).toHaveBeenCalledWith(
5123
+ VOICE_CONNECTION_EVENTS.STATE_CHANGE,
5124
+ expect.any(Function)
5125
+ );
5126
+
5127
+ expect(webex.cc.getVoiceConnectionState()).toEqual(state);
5128
+ const stateChangeHandler = webex.cc.webCallingService.on.mock.calls.find(
5129
+ ([event]) => event === VOICE_CONNECTION_EVENTS.STATE_CHANGE
5130
+ )[1];
5131
+ stateChangeHandler(state);
5132
+ expect(triggerSpy).toHaveBeenCalledWith(VOICE_CONNECTION_EVENTS.STATE_CHANGE, state);
5133
+ });
5134
+
2038
5135
  it('should provide getEntryPoints wrapper that delegates to EntryPoint', async () => {
2039
5136
  const spy = jest
2040
5137
  .spyOn(EntryPoint.prototype, 'getEntryPoints')
@@ -2128,6 +5225,55 @@ describe('webex.cc', () => {
2128
5225
  expect(result).toEqual(mockResp);
2129
5226
  });
2130
5227
 
5228
+ it('should preserve enableWxBetterTogether init flag across profile update logout/login', async () => {
5229
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
5230
+ webex.internal.device = {userId: 'user-123', url: 'https://wdm.example.com/devices/dev-1'};
5231
+ webex.cc.agentConfig = {
5232
+ ...webex.cc.agentConfig,
5233
+ agentId: 'agentId',
5234
+ webRtcEnabled: false,
5235
+ loginVoiceOptions: ['BROWSER', 'EXTENSION'],
5236
+ } as Profile;
5237
+ webex.cc.webCallingService.loginOption = LoginOption.BROWSER;
5238
+ webex.cc.webCallingService.setLoginOption = jest.fn((loginOption: LoginOption) => {
5239
+ webex.cc.webCallingService.loginOption = loginOption;
5240
+ });
5241
+ webex.cc['webexCrossClientService'].answerCallsState = true;
5242
+
5243
+ const publishSpy = jest
5244
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
5245
+ .mockResolvedValue(undefined);
5246
+ jest
5247
+ .spyOn(webex.cc['wxAppTelephonyMercurySync'], 'subscribe')
5248
+ .mockImplementation(() => {});
5249
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
5250
+ jest.spyOn(webex.cc as any, 'releaseWxAppMercuryResources').mockResolvedValue(undefined);
5251
+
5252
+ jest.spyOn(webex.cc.services.agent, 'logout').mockResolvedValue({
5253
+ trackingId: 'track-logout',
5254
+ } as StationLogoutResponse);
5255
+ jest.spyOn(webex.cc.services.agent, 'stationLogin').mockResolvedValue({
5256
+ data: {
5257
+ agentId: 'agentId',
5258
+ teamId: 'teamId',
5259
+ channelsMap: {chat: [], email: [], social: [], telephony: []},
5260
+ },
5261
+ trackingId: 'track-login',
5262
+ } as StationLoginSuccess);
5263
+
5264
+ webex.internal.mercury.connected = true;
5265
+
5266
+ await webex.cc.updateAgentProfile({
5267
+ teamId: 'teamId',
5268
+ loginOption: LoginOption.EXTENSION,
5269
+ dialNumber: '1001',
5270
+ });
5271
+
5272
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(true);
5273
+ expect(publishSpy).toHaveBeenCalledWith(false, {userId: 'user-123', trackPublishMetrics: true});
5274
+ expect(publishSpy).toHaveBeenCalledWith(true, {userId: 'user-123', trackPublishMetrics: true});
5275
+ });
5276
+
2131
5277
  it('should use provided teamId if passed in payload', async () => {
2132
5278
  const dataWithTeam = {
2133
5279
  teamId: 'newTeam',
@@ -2364,16 +5510,15 @@ describe('webex.cc', () => {
2364
5510
  mockError.details = {
2365
5511
  trackingId: 'test-tracking-id',
2366
5512
  orgId: 'mockOrgId',
2367
- error: 'Service error',
5513
+ type: 'OutdialAniEntriesFailed',
5514
+ data: {
5515
+ reason: 'Detailed service error',
5516
+ },
2368
5517
  };
2369
5518
 
2370
5519
  // Mock the service call to throw an error
2371
5520
  webex.cc.services.config.getOutdialAniEntries.mockRejectedValue(mockError);
2372
5521
 
2373
- // Mock getErrorDetails to return a detailed error
2374
- const detailedError = new Error('Detailed service error');
2375
- getErrorDetailsSpy.mockReturnValue({error: detailedError});
2376
-
2377
5522
  await expect(webex.cc.getOutdialAniEntries(mockParams)).rejects.toThrow(
2378
5523
  'Detailed service error'
2379
5524
  );
@@ -2398,9 +5543,20 @@ describe('webex.cc', () => {
2398
5543
  trackingId: 'test-tracking-id',
2399
5544
  }
2400
5545
  );
5546
+ expect(LoggerProxy.error).toHaveBeenCalledWith(
5547
+ 'getOutdialAniEntries failed with reason: Detailed service error',
5548
+ {
5549
+ module: CC_FILE,
5550
+ method: 'getOutdialAniEntries',
5551
+ trackingId: 'test-tracking-id',
5552
+ }
5553
+ );
2401
5554
 
2402
5555
  // Verify getErrorDetails was called
2403
5556
  expect(getErrorDetailsSpy).toHaveBeenCalledWith(mockError, 'getOutdialAniEntries', CC_FILE);
5557
+ expect(mockWebexRequest.uploadLogs).toHaveBeenCalledWith({
5558
+ correlationId: 'test-tracking-id',
5559
+ });
2404
5560
  });
2405
5561
 
2406
5562
  it('should throw error when orgId is not found', async () => {
@@ -2483,8 +5639,7 @@ describe('webex.cc', () => {
2483
5639
  });
2484
5640
 
2485
5641
  it('should handle error during acceptPreviewContact', async () => {
2486
- getErrorDetailsSpy.mockRestore();
2487
- getErrorDetailsSpy = jest.spyOn(Utils, 'getErrorDetails');
5642
+ getErrorDetailsSpy.mockClear();
2488
5643
 
2489
5644
  const error = {
2490
5645
  details: {
@@ -2510,6 +5665,9 @@ describe('webex.cc', () => {
2510
5665
  {module: CC_FILE, method: 'acceptPreviewContact', trackingId: error.details.trackingId}
2511
5666
  );
2512
5667
  expect(getErrorDetailsSpy).toHaveBeenCalledWith(error, 'acceptPreviewContact', CC_FILE);
5668
+ expect(mockWebexRequest.uploadLogs).toHaveBeenCalledWith({
5669
+ correlationId: error.details.trackingId,
5670
+ });
2513
5671
  });
2514
5672
  });
2515
5673
 
@@ -2547,8 +5705,7 @@ describe('webex.cc', () => {
2547
5705
  });
2548
5706
 
2549
5707
  it('should handle error during skipPreviewContact', async () => {
2550
- getErrorDetailsSpy.mockRestore();
2551
- getErrorDetailsSpy = jest.spyOn(Utils, 'getErrorDetails');
5708
+ getErrorDetailsSpy.mockClear();
2552
5709
 
2553
5710
  const error = {
2554
5711
  details: {
@@ -2574,6 +5731,9 @@ describe('webex.cc', () => {
2574
5731
  {module: CC_FILE, method: 'skipPreviewContact', trackingId: error.details.trackingId}
2575
5732
  );
2576
5733
  expect(getErrorDetailsSpy).toHaveBeenCalledWith(error, 'skipPreviewContact', CC_FILE);
5734
+ expect(mockWebexRequest.uploadLogs).toHaveBeenCalledWith({
5735
+ correlationId: error.details.trackingId,
5736
+ });
2577
5737
  });
2578
5738
  });
2579
5739
 
@@ -2611,8 +5771,7 @@ describe('webex.cc', () => {
2611
5771
  });
2612
5772
 
2613
5773
  it('should handle error during removePreviewContact', async () => {
2614
- getErrorDetailsSpy.mockRestore();
2615
- getErrorDetailsSpy = jest.spyOn(Utils, 'getErrorDetails');
5774
+ getErrorDetailsSpy.mockClear();
2616
5775
 
2617
5776
  const error = {
2618
5777
  details: {
@@ -2638,6 +5797,322 @@ describe('webex.cc', () => {
2638
5797
  {module: CC_FILE, method: 'removePreviewContact', trackingId: error.details.trackingId}
2639
5798
  );
2640
5799
  expect(getErrorDetailsSpy).toHaveBeenCalledWith(error, 'removePreviewContact', CC_FILE);
5800
+ expect(mockWebexRequest.uploadLogs).toHaveBeenCalledWith({
5801
+ correlationId: error.details.trackingId,
5802
+ });
5803
+ });
5804
+ });
5805
+
5806
+ describe('private setManageWebexCallingInWxcc (runtime toggle impl)', () => {
5807
+ beforeEach(() => {
5808
+ webex.internal.device = {
5809
+ userId: 'user-123',
5810
+ registered: false,
5811
+ register: jest.fn().mockResolvedValue(undefined),
5812
+ unregister: jest.fn().mockResolvedValue(undefined),
5813
+ };
5814
+ webex.internal.mercury = {
5815
+ connected: false,
5816
+ connect: jest.fn().mockResolvedValue(undefined),
5817
+ disconnect: jest.fn().mockResolvedValue(undefined),
5818
+ };
5819
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'subscribe').mockImplementation(() => {});
5820
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
5821
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: false};
5822
+ webex.cc['agentConfig'] = {
5823
+ agentId: 'agent-123',
5824
+ deviceType: LoginOption.EXTENSION,
5825
+ } as Profile;
5826
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
5827
+ webex.cc.webCallingService.setLoginOption = jest.fn((loginOption: LoginOption) => {
5828
+ webex.cc.webCallingService.loginOption = loginOption;
5829
+ });
5830
+ });
5831
+
5832
+ afterEach(() => {
5833
+ jest.restoreAllMocks();
5834
+ });
5835
+
5836
+ it('should update config, task manager, and publish usersub when enabled', async () => {
5837
+ const publishSpy = jest
5838
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
5839
+ .mockResolvedValue(undefined);
5840
+
5841
+ await (webex.cc as any).setManageWebexCallingInWxcc(true);
5842
+
5843
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(true);
5844
+ expect(mockTaskManager.applyEnableWxBetterTogether).toHaveBeenCalledWith(true);
5845
+ expect(publishSpy).toHaveBeenCalledWith(true, {userId: 'user-123', trackPublishMetrics: true});
5846
+ expect(mockTaskManager.refreshWxAppOfferObservabilityForAllTasks).toHaveBeenCalled();
5847
+ });
5848
+
5849
+ it('should publish false and update config when disabled after wxApp was enabled', async () => {
5850
+ webex.internal.device = {
5851
+ userId: 'user-123',
5852
+ url: 'https://wdm.example.com/devices/dev-1',
5853
+ };
5854
+ webex.request = jest.fn().mockResolvedValue({body: {}});
5855
+
5856
+ await (webex.cc as any).setManageWebexCallingInWxcc(true);
5857
+
5858
+ const publishSpy = jest
5859
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
5860
+ .mockResolvedValue(undefined);
5861
+
5862
+ await (webex.cc as any).setManageWebexCallingInWxcc(false);
5863
+
5864
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(false);
5865
+ expect(mockTaskManager.applyEnableWxBetterTogether).toHaveBeenCalledWith(false);
5866
+ expect(publishSpy).toHaveBeenCalledWith(false, {userId: 'user-123', trackPublishMetrics: true});
5867
+ });
5868
+
5869
+ it('should skip usersub publish when disabling without prior wxApp publish', async () => {
5870
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
5871
+ const publishSpy = jest
5872
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
5873
+ .mockResolvedValue(undefined);
5874
+
5875
+ await (webex.cc as any).setManageWebexCallingInWxcc(false);
5876
+
5877
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(false);
5878
+ expect(mockTaskManager.applyEnableWxBetterTogether).toHaveBeenCalledWith(false);
5879
+ expect(publishSpy).not.toHaveBeenCalled();
5880
+ });
5881
+
5882
+ it('should throw when enabling before login', async () => {
5883
+ webex.internal.device = undefined;
5884
+
5885
+ await expect((webex.cc as any).setManageWebexCallingInWxcc(true)).rejects.toThrow(
5886
+ 'Cannot publish answer-calls-on-wxcc: user is not logged in'
5887
+ );
5888
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(false);
5889
+ expect(mockTaskManager.applyEnableWxBetterTogether).not.toHaveBeenCalled();
5890
+ });
5891
+
5892
+ it('should throw when enabling on BROWSER (Desktop) login', async () => {
5893
+ webex.cc['agentConfig'] = {deviceType: LoginOption.BROWSER} as Profile;
5894
+ webex.cc.webCallingService.loginOption = LoginOption.BROWSER;
5895
+ const publishSpy = jest
5896
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
5897
+ .mockResolvedValue(undefined);
5898
+
5899
+ await expect((webex.cc as any).setManageWebexCallingInWxcc(true)).rejects.toThrow(
5900
+ 'setManageWebexCallingInWxcc requires EXTENSION or AGENT_DN station login'
5901
+ );
5902
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(false);
5903
+ expect(mockTaskManager.applyEnableWxBetterTogether).not.toHaveBeenCalled();
5904
+ expect(publishSpy).not.toHaveBeenCalled();
5905
+ });
5906
+
5907
+ it('should throw when enabling before station login', async () => {
5908
+ webex.cc['agentConfig'] = undefined as unknown as Profile;
5909
+ webex.cc.webCallingService.loginOption = undefined as unknown as LoginOption;
5910
+ const publishSpy = jest
5911
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
5912
+ .mockResolvedValue(undefined);
5913
+
5914
+ await expect((webex.cc as any).setManageWebexCallingInWxcc(true)).rejects.toThrow(
5915
+ 'setManageWebexCallingInWxcc requires EXTENSION or AGENT_DN station login'
5916
+ );
5917
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(false);
5918
+ expect(mockTaskManager.applyEnableWxBetterTogether).not.toHaveBeenCalled();
5919
+ expect(publishSpy).not.toHaveBeenCalled();
5920
+ });
5921
+
5922
+ it('should throw when webCallingService is BROWSER even if agentConfig deviceType is stale', async () => {
5923
+ webex.cc['agentConfig'] = {deviceType: LoginOption.EXTENSION} as Profile;
5924
+ webex.cc.webCallingService.loginOption = LoginOption.BROWSER;
5925
+ const publishSpy = jest
5926
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
5927
+ .mockResolvedValue(undefined);
5928
+
5929
+ await expect((webex.cc as any).setManageWebexCallingInWxcc(true)).rejects.toThrow(
5930
+ 'setManageWebexCallingInWxcc requires EXTENSION or AGENT_DN station login'
5931
+ );
5932
+ expect(publishSpy).not.toHaveBeenCalled();
5933
+ });
5934
+
5935
+ it('should publish usersub when enabling on AGENT_DN login', async () => {
5936
+ webex.cc['agentConfig'] = {
5937
+ agentId: 'agent-123',
5938
+ deviceType: LoginOption.AGENT_DN,
5939
+ } as Profile;
5940
+ const publishSpy = jest
5941
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
5942
+ .mockResolvedValue(undefined);
5943
+
5944
+ await (webex.cc as any).setManageWebexCallingInWxcc(true);
5945
+
5946
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(true);
5947
+ expect(publishSpy).toHaveBeenCalledWith(true, {userId: 'user-123', trackPublishMetrics: true});
5948
+ });
5949
+
5950
+ it('should no-op usersub publish when disabling before login', async () => {
5951
+ webex.internal.device = undefined;
5952
+ const publishSpy = jest
5953
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
5954
+ .mockResolvedValue(undefined);
5955
+
5956
+ await (webex.cc as any).setManageWebexCallingInWxcc(false);
5957
+
5958
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(false);
5959
+ expect(mockTaskManager.applyEnableWxBetterTogether).toHaveBeenCalledWith(false);
5960
+ expect(publishSpy).not.toHaveBeenCalled();
5961
+ });
5962
+
5963
+ it('should subscribe to wxApp Mercury mute sync when enabled', async () => {
5964
+ webex.cc['agentConfig'] = {agentId: 'agent-123'} as Profile;
5965
+ webex.internal.device = {
5966
+ ...webex.internal.device,
5967
+ registered: true,
5968
+ register: jest.fn().mockResolvedValue(undefined),
5969
+ };
5970
+ webex.internal.mercury.connected = true;
5971
+ webex.internal.mercury.connect = jest.fn().mockResolvedValue(undefined);
5972
+ jest
5973
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
5974
+ .mockResolvedValue(undefined);
5975
+ const subscribeSpy = jest
5976
+ .spyOn(webex.cc['wxAppTelephonyMercurySync'], 'subscribe')
5977
+ .mockImplementation(() => {});
5978
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
5979
+
5980
+ await (webex.cc as any).setManageWebexCallingInWxcc(true);
5981
+
5982
+ expect(subscribeSpy).toHaveBeenCalledWith('agent-123', expect.any(Function));
5983
+ });
5984
+
5985
+ it('should unsubscribe from wxApp Mercury mute sync when disabled', async () => {
5986
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
5987
+ jest
5988
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
5989
+ .mockResolvedValue(undefined);
5990
+ const unsubscribeSpy = jest
5991
+ .spyOn(webex.cc['wxAppTelephonyMercurySync'], 'unsubscribe')
5992
+ .mockImplementation(() => {});
5993
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
5994
+
5995
+ await (webex.cc as any).setManageWebexCallingInWxcc(false);
5996
+
5997
+ expect(unsubscribeSpy).toHaveBeenCalled();
5998
+ });
5999
+
6000
+ it('should register device and connect mercury when enabling wxApp sync', async () => {
6001
+ webex.cc['agentConfig'] = {agentId: 'agent-123'} as Profile;
6002
+ webex.internal.device = {
6003
+ userId: 'user-123',
6004
+ registered: false,
6005
+ register: jest.fn().mockResolvedValue(undefined),
6006
+ };
6007
+ webex.internal.mercury = {
6008
+ connected: false,
6009
+ connect: jest.fn().mockResolvedValue(undefined),
6010
+ };
6011
+ jest
6012
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
6013
+ .mockResolvedValue(undefined);
6014
+ const subscribeSpy = jest
6015
+ .spyOn(webex.cc['wxAppTelephonyMercurySync'], 'subscribe')
6016
+ .mockImplementation(() => {});
6017
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
6018
+
6019
+ await (webex.cc as any).setManageWebexCallingInWxcc(true);
6020
+
6021
+ expect(webex.internal.device.register).toHaveBeenCalled();
6022
+ expect(webex.internal.mercury.connect).toHaveBeenCalled();
6023
+ expect(subscribeSpy).toHaveBeenCalledWith('agent-123', expect.any(Function));
6024
+ });
6025
+
6026
+ it('should rollback config and task manager when usersub publish fails', async () => {
6027
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: false};
6028
+ jest
6029
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
6030
+ .mockRejectedValue(new Error('usersub failed'));
6031
+
6032
+ await expect((webex.cc as any).setManageWebexCallingInWxcc(true)).rejects.toThrow('usersub failed');
6033
+
6034
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(false);
6035
+ expect(mockTaskManager.applyEnableWxBetterTogether).toHaveBeenCalledWith(true);
6036
+ expect(mockTaskManager.applyEnableWxBetterTogether).toHaveBeenLastCalledWith(false);
6037
+ });
6038
+
6039
+ it('should rollback config and release Mercury resources when Mercury connect fails', async () => {
6040
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: false};
6041
+ const publishSpy = jest
6042
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
6043
+ .mockResolvedValue(undefined);
6044
+ jest
6045
+ .spyOn(webex.cc as any, 'ensureWxAppMercuryConnected')
6046
+ .mockRejectedValue(new Error('mercury connect failed'));
6047
+ const releaseSpy = jest
6048
+ .spyOn(webex.cc as any, 'releaseWxAppMercuryResources')
6049
+ .mockResolvedValue(undefined);
6050
+ const unsubscribeSpy = jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'unsubscribe');
6051
+ const teardownSpy = jest.spyOn(webex.cc['webexCrossClientService'], 'teardown');
6052
+
6053
+ await expect((webex.cc as any).setManageWebexCallingInWxcc(true)).rejects.toThrow(
6054
+ 'mercury connect failed'
6055
+ );
6056
+
6057
+ expect(webex.cc.isWxBetterTogetherEnabled()).toBe(false);
6058
+ expect(mockTaskManager.applyEnableWxBetterTogether).toHaveBeenLastCalledWith(false);
6059
+ expect(publishSpy).not.toHaveBeenCalled();
6060
+ expect(teardownSpy).not.toHaveBeenCalled();
6061
+ expect(unsubscribeSpy).toHaveBeenCalled();
6062
+ expect(releaseSpy).toHaveBeenCalled();
6063
+ });
6064
+
6065
+ it('should schedule compensating false retry when rollback publish fails after enable error', async () => {
6066
+ jest.useFakeTimers();
6067
+ try {
6068
+ webex.cc.$config = {...webex.cc.$config, enableWxBetterTogether: true};
6069
+ webex.internal.device = {userId: 'user-123', url: 'https://wdm.example.com/devices/dev-1'};
6070
+ webex.cc.agentConfig = {
6071
+ agentId: 'agent-123',
6072
+ deviceType: LoginOption.EXTENSION,
6073
+ };
6074
+ webex.cc.webCallingService.loginOption = LoginOption.EXTENSION;
6075
+
6076
+ const publishSpy = jest
6077
+ .spyOn(webex.cc['webexCrossClientService'], 'setManageWebexCallingInWxcc')
6078
+ .mockResolvedValueOnce(undefined)
6079
+ .mockRejectedValueOnce(new Error('compensating false failed'))
6080
+ .mockResolvedValue(undefined);
6081
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'subscribe').mockImplementation(() => {});
6082
+ jest.spyOn(webex.cc['wxAppTelephonyMercurySync'], 'isSubscribed').mockReturnValue(true);
6083
+ jest
6084
+ .spyOn(webex.cc as any, 'ensureWxAppMercuryConnected')
6085
+ .mockResolvedValue(undefined);
6086
+ jest
6087
+ .spyOn(webex.cc as any, 'releaseWxAppMercuryResources')
6088
+ .mockResolvedValue(undefined);
6089
+ jest
6090
+ .spyOn(mockTaskManager, 'syncWxAppMuteFromCallDetailsForAllTasks')
6091
+ .mockImplementation(() => {
6092
+ throw new Error('sync failed');
6093
+ });
6094
+ const scheduleRetrySpy = jest.spyOn(
6095
+ webex.cc as any,
6096
+ 'scheduleCompensatingFalsePublishRetry'
6097
+ );
6098
+
6099
+ await expect((webex.cc as any).setManageWebexCallingInWxcc(true)).rejects.toThrow(
6100
+ 'sync failed'
6101
+ );
6102
+
6103
+ expect(scheduleRetrySpy).toHaveBeenCalled();
6104
+ expect(publishSpy).toHaveBeenCalledTimes(2);
6105
+ expect(publishSpy).toHaveBeenNthCalledWith(1, true, {userId: 'user-123', trackPublishMetrics: true});
6106
+ expect(publishSpy).toHaveBeenNthCalledWith(2, false, {userId: 'user-123', trackPublishMetrics: true});
6107
+
6108
+ jest.advanceTimersByTime(30_000);
6109
+ await publishSpy.mock.results[2]?.value;
6110
+
6111
+ expect(publishSpy).toHaveBeenCalledTimes(3);
6112
+ expect(publishSpy).toHaveBeenLastCalledWith(false, {userId: 'user-123', trackPublishMetrics: true});
6113
+ } finally {
6114
+ jest.useRealTimers();
6115
+ }
2641
6116
  });
2642
6117
  });
2643
6118
  });