@microsoft/omnichannel-chat-widget 1.8.2-main.5195aba → 1.8.2-main.d82a79b

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.
@@ -154,7 +154,6 @@ const setPreChatAndInitiateChat = async (facadeChatSDK, dispatch, setAdapter, is
154
154
  const optionalParams = {
155
155
  isProactiveChat
156
156
  };
157
- (0, _FirstMessageTrackerFromBot.createTrackingForFirstMessage)();
158
157
  await initStartChat(facadeChatSDK, dispatch, setAdapter, state, props, optionalParams);
159
158
  };
160
159
 
@@ -206,6 +205,7 @@ const initStartChat = async (facadeChatSDK, dispatch, setAdapter, state, props,
206
205
  const startChatOptionalParams = Object.assign({}, params, optionalParams, defaultOptionalParams);
207
206
  // startTime is used to determine if a message is history or new, better to be set before creating the adapter to get bandwidth
208
207
  const startTime = new Date().getTime();
208
+ (0, _FirstMessageTrackerFromBot.createTrackingForFirstMessage)();
209
209
  await facadeChatSDK.startChat(startChatOptionalParams);
210
210
  isStartChatSuccessful = true;
211
211
  await createAdapterAndSubscribe(facadeChatSDK, dispatch, setAdapter, startTime, props);
@@ -12,54 +12,96 @@ var _util = require("./util");
12
12
  // with different timeline, therefore this is a functional approach to track the events, instead of a class based approach
13
13
  const createTrackingForFirstMessage = () => {
14
14
  // Reset the tracking variables
15
- let startTracking = false;
16
- let stopTracking = false;
15
+ let isTracking = false;
17
16
  let startTime = 0;
18
17
  let stopTime = 0;
19
- let stopTrackingMessage;
18
+ let stopTrackingMessage = null;
20
19
  let flag = false;
20
+ let trackingTimeoutId;
21
+
22
+ /**
23
+ * Checks if the message payload is from a valid sender (not an agent).
24
+ * Returns false if the message is from an agent (tag 'public'), true otherwise.
25
+ */
21
26
  const isMessageFromValidSender = payload => {
22
27
  var _payload$tags;
23
- // agent scenario
24
28
  if (payload !== null && payload !== void 0 && (_payload$tags = payload.tags) !== null && _payload$tags !== void 0 && _payload$tags.includes("public")) {
25
29
  return false;
26
30
  }
27
31
  return true;
28
32
  };
33
+
34
+ /**
35
+ * Listener for widget load completion event.
36
+ * Starts tracking the time for the first bot message after widget loads.
37
+ * Sets a 5-second timeout to auto-reset if no bot message is received.
38
+ */
29
39
  const widgetLoadListener = _omnichannelChatComponents.BroadcastService.getMessageByEventName(_TelemetryConstants.TelemetryEvent.WidgetLoadComplete).subscribe(() => {
30
- if (startTracking) return;
31
- startTracking = true;
40
+ if (isTracking) return;
41
+ isTracking = true;
32
42
  startTime = new Date().getTime();
43
+ // Start a 5-second timeout to auto-stop tracking if not stopped
44
+ if (trackingTimeoutId) {
45
+ clearTimeout(trackingTimeoutId);
46
+ }
47
+ trackingTimeoutId = setTimeout(() => {
48
+ if (isTracking) {
49
+ // Reset state and disengage, no telemetry or FMLTrackingCompleted
50
+ isTracking = false;
51
+ startTime = 0;
52
+ stopTime = 0;
53
+ stopTrackingMessage = null;
54
+ trackingTimeoutId = undefined;
55
+ disconnectListener();
56
+ }
57
+ }, 10000); //adding more time since it meassures from widget load complete till message received
33
58
  });
59
+
60
+ /**
61
+ * Listener for new bot message event.
62
+ * If a valid bot message is received, stops tracking and logs telemetry.
63
+ * If the message is invalid, resets and disengages listeners.
64
+ */
34
65
  const newMessageListener = _omnichannelChatComponents.BroadcastService.getMessageByEventName(_TelemetryConstants.BroadcastEvent.NewMessageReceived).subscribe(message => {
35
66
  const payload = message.payload;
36
-
37
- // we only care for bot, so we need to check if the message is from the bot
38
- // pending to add typing message indicator signal detection
39
-
40
- if (isMessageFromValidSender(payload)) {
41
- if (startTracking && !stopTracking) {
42
- stopTime = new Date().getTime();
43
- const elapsedTime = stopTime - startTime;
44
- stopTracking = true;
45
- stopTrackingMessage = (0, _util.createTrackingMessage)(payload, "botMessage");
46
- notifyFMLTrackingCompleted();
47
- _TelemetryHelper.TelemetryHelper.logActionEvent(_TelemetryConstants.LogLevel.INFO, {
48
- Event: _TelemetryConstants.TelemetryEvent.BotFirstMessageLapTrack,
49
- Description: "First Message from Bot latency tracking",
50
- CustomProperties: {
51
- elapsedTime,
52
- widgetLoadedAt: startTime,
53
- botMessage: stopTrackingMessage
54
- }
55
- });
67
+ if (!isMessageFromValidSender(payload)) {
68
+ // If not valid, stop everything and clean up
69
+ isTracking = false;
70
+ if (trackingTimeoutId) {
71
+ clearTimeout(trackingTimeoutId);
72
+ trackingTimeoutId = undefined;
56
73
  }
74
+ disconnectListener();
75
+ return;
76
+ }
77
+ if (isTracking) {
78
+ isTracking = false;
79
+ // Clear the timeout if it exists
80
+ if (trackingTimeoutId) {
81
+ clearTimeout(trackingTimeoutId);
82
+ trackingTimeoutId = undefined;
83
+ }
84
+ stopTime = new Date().getTime();
85
+ const elapsedTime = stopTime - startTime;
86
+ stopTrackingMessage = (0, _util.createTrackingMessage)(payload, "botMessage");
87
+ notifyFMLTrackingCompleted();
88
+ _TelemetryHelper.TelemetryHelper.logActionEvent(_TelemetryConstants.LogLevel.INFO, {
89
+ Event: _TelemetryConstants.TelemetryEvent.BotFirstMessageLapTrack,
90
+ Description: "First Message from Bot latency tracking",
91
+ CustomProperties: {
92
+ elapsedTime,
93
+ widgetLoadedAt: startTime,
94
+ botMessage: stopTrackingMessage
95
+ }
96
+ });
97
+ disconnectListener();
57
98
  }
58
-
59
- // this track only first message, if coming from the bot or not
60
- // the only difference is that it logs only those from bot
61
- disconnectListener();
62
99
  });
100
+
101
+ /**
102
+ * Notifies that FML (First Message Latency) tracking is completed.
103
+ * Retries sending the completion event until acknowledged.
104
+ */
63
105
  const notifyFMLTrackingCompleted = () => {
64
106
  ackListener();
65
107
  // Retry sending until flag is true, but do not block the main thread
@@ -74,6 +116,11 @@ const createTrackingForFirstMessage = () => {
74
116
  }
75
117
  }, 100);
76
118
  };
119
+
120
+ /**
121
+ * Listener for FMLTrackingCompletedAck event.
122
+ * Sets the flag to true when acknowledgment is received.
123
+ */
77
124
  const ackListener = () => {
78
125
  const listen = _omnichannelChatComponents.BroadcastService.getMessageByEventName(_TelemetryConstants.BroadcastEvent.FMLTrackingCompletedAck).subscribe(() => {
79
126
  flag = true;
@@ -83,22 +130,32 @@ const createTrackingForFirstMessage = () => {
83
130
 
84
131
  // Rehydrate message is received when the widget is reloaded, this is to ensure that we are not tracking messages that are not part of the current conversation
85
132
  // No need to keep listerning for tracking, enforcing disconnection for the listners
133
+ /**
134
+ * Listener for widget rehydration event.
135
+ * Resets tracking and disconnects listeners when widget is reloaded.
136
+ */
86
137
  const rehydrateListener = _omnichannelChatComponents.BroadcastService.getMessageByEventName(_TelemetryConstants.TelemetryEvent.RehydrateMessageReceived).subscribe(() => {
87
- startTracking = false;
88
- stopTracking = false;
138
+ isTracking = false;
89
139
  disconnectListener();
90
140
  });
91
141
 
92
142
  // Rehydrate message is received when the widget is reloaded, this is to ensure that we are not tracking messages that are not part of the current conversation
93
143
  // No need to keep listerning for tracking, enforcing disconnection for the listners
144
+ /**
145
+ * Listener for history message event.
146
+ * Resets tracking and disconnects listeners when history is loaded.
147
+ */
94
148
  const historyListener = _omnichannelChatComponents.BroadcastService.getMessageByEventName(_TelemetryConstants.BroadcastEvent.HistoryMessageReceived).subscribe(() => {
95
- startTracking = false;
96
- stopTracking = false;
149
+ isTracking = false;
97
150
  disconnectListener();
98
151
  });
152
+
153
+ /**
154
+ * Listener for network disconnection event.
155
+ * Resets tracking, disconnects listeners, and logs a telemetry error.
156
+ */
99
157
  const offlineNetworkListener = _omnichannelChatComponents.BroadcastService.getMessageByEventName(_TelemetryConstants.TelemetryEvent.NetworkDisconnected).subscribe(() => {
100
- startTracking = false;
101
- stopTracking = false;
158
+ isTracking = false;
102
159
  disconnectListener();
103
160
  _TelemetryHelper.TelemetryHelper.logActionEvent(_TelemetryConstants.LogLevel.INFO, {
104
161
  Event: _TelemetryConstants.TelemetryEvent.BotFirstMessageLapTrackError,
@@ -107,7 +164,15 @@ const createTrackingForFirstMessage = () => {
107
164
  });
108
165
 
109
166
  // this is to ensure that we are not tracking messages that are not part of the current conversation
167
+ /**
168
+ * Disconnects all listeners and clears the tracking timeout.
169
+ * Used for cleanup when tracking is stopped or reset.
170
+ */
110
171
  const disconnectListener = () => {
172
+ if (trackingTimeoutId) {
173
+ clearTimeout(trackingTimeoutId);
174
+ trackingTimeoutId = undefined;
175
+ }
111
176
  historyListener.unsubscribe();
112
177
  rehydrateListener.unsubscribe();
113
178
  newMessageListener.unsubscribe();
@@ -17,14 +17,13 @@ let FirstResponseLatencyTracker = /*#__PURE__*/function () {
17
17
  function FirstResponseLatencyTracker() {
18
18
  _classCallCheck(this, FirstResponseLatencyTracker);
19
19
  _defineProperty(this, "isABotConversation", false);
20
- _defineProperty(this, "isStarted", false);
21
- _defineProperty(this, "isEnded", false);
20
+ _defineProperty(this, "isTracking", false);
22
21
  _defineProperty(this, "startTrackingMessage", void 0);
23
22
  _defineProperty(this, "stopTrackingMessage", void 0);
24
23
  _defineProperty(this, "isReady", false);
24
+ _defineProperty(this, "trackingTimeoutId", void 0);
25
25
  _defineProperty(this, "offlineNetworkListener", _omnichannelChatComponents.BroadcastService.getMessageByEventName(_TelemetryConstants.TelemetryEvent.NetworkDisconnected).subscribe(() => {
26
- this.isStarted = false;
27
- this.isEnded = false;
26
+ this.isTracking = false;
28
27
  _TelemetryHelper.TelemetryHelper.logActionEvent(_TelemetryConstants.LogLevel.INFO, {
29
28
  Event: _TelemetryConstants.TelemetryEvent.MessageStopLapTrackError,
30
29
  Description: "Tracker Stopped due to network disconnection"
@@ -72,7 +71,7 @@ let FirstResponseLatencyTracker = /*#__PURE__*/function () {
72
71
  value: function startTracking(payload) {
73
72
  if (!this.isReady) return;
74
73
  // this prevents to initiate tracking for multiple incoming messages
75
- if (this.isStarted) {
74
+ if (this.isTracking) {
76
75
  return;
77
76
  }
78
77
  // this is to ensure we track only messages where bot is engaged
@@ -80,10 +79,24 @@ let FirstResponseLatencyTracker = /*#__PURE__*/function () {
80
79
  return;
81
80
  }
82
81
  // control of states to prevent clashing of messages
83
- this.isStarted = true;
84
- this.isEnded = false;
82
+ this.isTracking = true;
85
83
  // The idea of using types is to enrich telemetry data
86
84
  this.startTrackingMessage = this.createTrackingMessage(payload, "userMessage");
85
+
86
+ // Start a 5-second timeout to auto-stop tracking if not stopped
87
+ if (this.trackingTimeoutId) {
88
+ clearTimeout(this.trackingTimeoutId);
89
+ }
90
+ this.trackingTimeoutId = setTimeout(() => {
91
+ // this means the start process is in progress, but the end wasn't called within the time limit
92
+ if (this.isTracking) {
93
+ // Reset state variables and skip stopTracking
94
+ this.isTracking = false;
95
+ this.startTrackingMessage = undefined;
96
+ this.stopTrackingMessage = undefined;
97
+ this.trackingTimeoutId = undefined;
98
+ }
99
+ }, 5000);
87
100
  }
88
101
  }, {
89
102
  key: "handleAgentMessage",
@@ -99,13 +112,16 @@ let FirstResponseLatencyTracker = /*#__PURE__*/function () {
99
112
  value: function stopTracking(payload) {
100
113
  var _this$stopTrackingMes, _this$startTrackingMe;
101
114
  // this prevents execution for multiple incoming messages from the bot.
102
- if (this.isEnded && !this.isStarted) {
115
+ if (!this.isTracking) {
103
116
  return;
104
117
  }
105
-
118
+ // Clear the timeout if it exists
119
+ if (this.trackingTimeoutId) {
120
+ clearTimeout(this.trackingTimeoutId);
121
+ this.trackingTimeoutId = undefined;
122
+ }
106
123
  // control of states to prevent clashing of messages
107
- this.isEnded = true;
108
- this.isStarted = false;
124
+ this.isTracking = false;
109
125
 
110
126
  // The idea of using types is to enrich telemetry data
111
127
  this.stopTrackingMessage = this.createTrackingMessage(payload, "botMessage");
@@ -160,12 +176,16 @@ let FirstResponseLatencyTracker = /*#__PURE__*/function () {
160
176
  if (!payload || !payload.Id) {
161
177
  throw new Error("Invalid payload");
162
178
  }
163
- if (!this.isMessageFromValidSender(payload)) return;
164
- if (this.isABotConversation && this.isStarted) {
179
+
180
+ // Only allow stopTracking if sender is valid and tracking is active
181
+ if (!this.isMessageFromValidSender(payload)) {
182
+ // Do not change isTracking or stopTrackingMessage
183
+ return;
184
+ }
185
+ if (this.isABotConversation && this.isTracking) {
165
186
  this.stopTracking(payload);
166
187
  }
167
188
  } catch (e) {
168
- console.error("FRL : error while trying to stop the tracker", e);
169
189
  _TelemetryHelper.TelemetryHelper.logActionEvent(_TelemetryConstants.LogLevel.ERROR, {
170
190
  Event: _TelemetryConstants.TelemetryEvent.MessageStopLapTrackError,
171
191
  Description: "Error while stopping the clock",
@@ -174,11 +194,6 @@ let FirstResponseLatencyTracker = /*#__PURE__*/function () {
174
194
  payload: payload
175
195
  }
176
196
  });
177
- //reset state
178
- this.startTrackingMessage = undefined;
179
- this.stopTrackingMessage = undefined;
180
- this.isStarted = false;
181
- this.isEnded = false;
182
197
  }
183
198
  }
184
199
  }, {
@@ -186,10 +201,13 @@ let FirstResponseLatencyTracker = /*#__PURE__*/function () {
186
201
  value: function deregister() {
187
202
  // Reset State
188
203
  this.isABotConversation = false;
189
- this.isStarted = false;
190
- this.isEnded = false;
204
+ this.isTracking = false;
191
205
  this.startTrackingMessage = undefined;
192
206
  this.stopTrackingMessage = undefined;
207
+ if (this.trackingTimeoutId) {
208
+ clearTimeout(this.trackingTimeoutId);
209
+ this.trackingTimeoutId = undefined;
210
+ }
193
211
  this.offlineNetworkListener.unsubscribe();
194
212
  this.fmltrackingListener.unsubscribe();
195
213
  this.rehydrateListener.unsubscribe();
@@ -6,6 +6,8 @@ Object.defineProperty(exports, "__esModule", {
6
6
  exports.polyfillMessagePayloadForEvent = exports.isHistoryMessage = exports.getScenarioType = exports.extractTimestampFromId = exports.createTrackingMessage = exports.buildMessagePayload = void 0;
7
7
  var _Constants = require("./Constants");
8
8
  var _Constants2 = require("../common/Constants");
9
+ const DELTA_WITHIN_LIMITS_IN_MS = 250;
10
+
9
11
  /**
10
12
  * Determines whether a given activity is a historical message.
11
13
  *
@@ -23,19 +25,21 @@ var _Constants2 = require("../common/Constants");
23
25
  * - If the ID is valid and the timestamp is older than the start time, the message is historical.
24
26
  */
25
27
  const isHistoryMessage = (activity, startTime) => {
26
- var _activity$channelData, _activity$channelData2;
28
+ var _activity$channelData;
27
29
  // Only process message activities
28
30
  if ((activity === null || activity === void 0 ? void 0 : activity.type) !== _Constants2.Constants.message) {
29
31
  return false;
30
32
  }
31
33
 
32
- // Legacy check for history message tag
33
- if (activity !== null && activity !== void 0 && (_activity$channelData = activity.channelData) !== null && _activity$channelData !== void 0 && (_activity$channelData2 = _activity$channelData.tags) !== null && _activity$channelData2 !== void 0 && _activity$channelData2.includes(_Constants2.Constants.historyMessageTag)) {
34
+ // Prioritize legacy history tag
35
+ if (activity !== null && activity !== void 0 && (_activity$channelData = activity.channelData) !== null && _activity$channelData !== void 0 && _activity$channelData.tags && activity.channelData.tags.includes(_Constants2.Constants.historyMessageTag)) {
34
36
  return true;
35
37
  }
36
38
  const activityId = extractTimestampFromId(activity);
37
39
  const isValidId = !isNaN(activityId) && activityId > 0;
38
- const isOlderThanStartTime = activityId < startTime;
40
+ const difference = startTime - activityId;
41
+ // Only consider historical if activityId < startTime and difference >= DELTA_WITHIN_LIMITS_IN_MS
42
+ const isOlderThanStartTime = activityId < startTime && difference >= DELTA_WITHIN_LIMITS_IN_MS;
39
43
  const isHistoryById = isValidId && isOlderThanStartTime;
40
44
  return isHistoryById;
41
45
  };
@@ -64,7 +68,7 @@ const extractTimestampFromId = activity => {
64
68
  };
65
69
  exports.extractTimestampFromId = extractTimestampFromId;
66
70
  const buildMessagePayload = (activity, userId) => {
67
- var _text, _text2, _activity$channelData3, _activity$from;
71
+ var _text, _text2, _activity$channelData2, _activity$from;
68
72
  return {
69
73
  // To identify hidden contents vs empty content
70
74
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -72,7 +76,7 @@ const buildMessagePayload = (activity, userId) => {
72
76
  type: activity === null || activity === void 0 ? void 0 : activity.type,
73
77
  timestamp: activity === null || activity === void 0 ? void 0 : activity.timestamp,
74
78
  userId: userId,
75
- tags: activity === null || activity === void 0 ? void 0 : (_activity$channelData3 = activity.channelData) === null || _activity$channelData3 === void 0 ? void 0 : _activity$channelData3.tags,
79
+ tags: (activity === null || activity === void 0 ? void 0 : (_activity$channelData2 = activity.channelData) === null || _activity$channelData2 === void 0 ? void 0 : _activity$channelData2.tags) || [],
76
80
  messageType: "",
77
81
  Id: activity === null || activity === void 0 ? void 0 : activity.id,
78
82
  role: activity === null || activity === void 0 ? void 0 : (_activity$from = activity.from) === null || _activity$from === void 0 ? void 0 : _activity$from.role,
@@ -98,9 +102,9 @@ const polyfillMessagePayloadForEvent = (activity, payload, conversationId) => {
98
102
  };
99
103
  exports.polyfillMessagePayloadForEvent = polyfillMessagePayloadForEvent;
100
104
  const getScenarioType = activity => {
101
- var _activity$from3, _activity$channelData4;
105
+ var _activity$from3, _activity$channelData3;
102
106
  const role = activity === null || activity === void 0 ? void 0 : (_activity$from3 = activity.from) === null || _activity$from3 === void 0 ? void 0 : _activity$from3.role;
103
- const tags = activity === null || activity === void 0 ? void 0 : (_activity$channelData4 = activity.channelData) === null || _activity$channelData4 === void 0 ? void 0 : _activity$channelData4.tags;
107
+ const tags = activity === null || activity === void 0 ? void 0 : (_activity$channelData3 = activity.channelData) === null || _activity$channelData3 === void 0 ? void 0 : _activity$channelData3.tags;
104
108
  if (role === _Constants2.Constants.userMessageTag) {
105
109
  return _Constants.ScenarioType.UserSendMessageStrategy;
106
110
  }
@@ -148,7 +148,6 @@ const setPreChatAndInitiateChat = async (facadeChatSDK, dispatch, setAdapter, is
148
148
  const optionalParams = {
149
149
  isProactiveChat
150
150
  };
151
- createTrackingForFirstMessage();
152
151
  await initStartChat(facadeChatSDK, dispatch, setAdapter, state, props, optionalParams);
153
152
  };
154
153
 
@@ -199,6 +198,7 @@ const initStartChat = async (facadeChatSDK, dispatch, setAdapter, state, props,
199
198
  const startChatOptionalParams = Object.assign({}, params, optionalParams, defaultOptionalParams);
200
199
  // startTime is used to determine if a message is history or new, better to be set before creating the adapter to get bandwidth
201
200
  const startTime = new Date().getTime();
201
+ createTrackingForFirstMessage();
202
202
  await facadeChatSDK.startChat(startChatOptionalParams);
203
203
  isStartChatSuccessful = true;
204
204
  await createAdapterAndSubscribe(facadeChatSDK, dispatch, setAdapter, startTime, props);
@@ -7,54 +7,96 @@ import { createTrackingMessage } from "./util";
7
7
  // with different timeline, therefore this is a functional approach to track the events, instead of a class based approach
8
8
  export const createTrackingForFirstMessage = () => {
9
9
  // Reset the tracking variables
10
- let startTracking = false;
11
- let stopTracking = false;
10
+ let isTracking = false;
12
11
  let startTime = 0;
13
12
  let stopTime = 0;
14
- let stopTrackingMessage;
13
+ let stopTrackingMessage = null;
15
14
  let flag = false;
15
+ let trackingTimeoutId;
16
+
17
+ /**
18
+ * Checks if the message payload is from a valid sender (not an agent).
19
+ * Returns false if the message is from an agent (tag 'public'), true otherwise.
20
+ */
16
21
  const isMessageFromValidSender = payload => {
17
22
  var _payload$tags;
18
- // agent scenario
19
23
  if (payload !== null && payload !== void 0 && (_payload$tags = payload.tags) !== null && _payload$tags !== void 0 && _payload$tags.includes("public")) {
20
24
  return false;
21
25
  }
22
26
  return true;
23
27
  };
28
+
29
+ /**
30
+ * Listener for widget load completion event.
31
+ * Starts tracking the time for the first bot message after widget loads.
32
+ * Sets a 5-second timeout to auto-reset if no bot message is received.
33
+ */
24
34
  const widgetLoadListener = BroadcastService.getMessageByEventName(TelemetryEvent.WidgetLoadComplete).subscribe(() => {
25
- if (startTracking) return;
26
- startTracking = true;
35
+ if (isTracking) return;
36
+ isTracking = true;
27
37
  startTime = new Date().getTime();
38
+ // Start a 5-second timeout to auto-stop tracking if not stopped
39
+ if (trackingTimeoutId) {
40
+ clearTimeout(trackingTimeoutId);
41
+ }
42
+ trackingTimeoutId = setTimeout(() => {
43
+ if (isTracking) {
44
+ // Reset state and disengage, no telemetry or FMLTrackingCompleted
45
+ isTracking = false;
46
+ startTime = 0;
47
+ stopTime = 0;
48
+ stopTrackingMessage = null;
49
+ trackingTimeoutId = undefined;
50
+ disconnectListener();
51
+ }
52
+ }, 10000); //adding more time since it meassures from widget load complete till message received
28
53
  });
54
+
55
+ /**
56
+ * Listener for new bot message event.
57
+ * If a valid bot message is received, stops tracking and logs telemetry.
58
+ * If the message is invalid, resets and disengages listeners.
59
+ */
29
60
  const newMessageListener = BroadcastService.getMessageByEventName(BroadcastEvent.NewMessageReceived).subscribe(message => {
30
61
  const payload = message.payload;
31
-
32
- // we only care for bot, so we need to check if the message is from the bot
33
- // pending to add typing message indicator signal detection
34
-
35
- if (isMessageFromValidSender(payload)) {
36
- if (startTracking && !stopTracking) {
37
- stopTime = new Date().getTime();
38
- const elapsedTime = stopTime - startTime;
39
- stopTracking = true;
40
- stopTrackingMessage = createTrackingMessage(payload, "botMessage");
41
- notifyFMLTrackingCompleted();
42
- TelemetryHelper.logActionEvent(LogLevel.INFO, {
43
- Event: TelemetryEvent.BotFirstMessageLapTrack,
44
- Description: "First Message from Bot latency tracking",
45
- CustomProperties: {
46
- elapsedTime,
47
- widgetLoadedAt: startTime,
48
- botMessage: stopTrackingMessage
49
- }
50
- });
62
+ if (!isMessageFromValidSender(payload)) {
63
+ // If not valid, stop everything and clean up
64
+ isTracking = false;
65
+ if (trackingTimeoutId) {
66
+ clearTimeout(trackingTimeoutId);
67
+ trackingTimeoutId = undefined;
51
68
  }
69
+ disconnectListener();
70
+ return;
71
+ }
72
+ if (isTracking) {
73
+ isTracking = false;
74
+ // Clear the timeout if it exists
75
+ if (trackingTimeoutId) {
76
+ clearTimeout(trackingTimeoutId);
77
+ trackingTimeoutId = undefined;
78
+ }
79
+ stopTime = new Date().getTime();
80
+ const elapsedTime = stopTime - startTime;
81
+ stopTrackingMessage = createTrackingMessage(payload, "botMessage");
82
+ notifyFMLTrackingCompleted();
83
+ TelemetryHelper.logActionEvent(LogLevel.INFO, {
84
+ Event: TelemetryEvent.BotFirstMessageLapTrack,
85
+ Description: "First Message from Bot latency tracking",
86
+ CustomProperties: {
87
+ elapsedTime,
88
+ widgetLoadedAt: startTime,
89
+ botMessage: stopTrackingMessage
90
+ }
91
+ });
92
+ disconnectListener();
52
93
  }
53
-
54
- // this track only first message, if coming from the bot or not
55
- // the only difference is that it logs only those from bot
56
- disconnectListener();
57
94
  });
95
+
96
+ /**
97
+ * Notifies that FML (First Message Latency) tracking is completed.
98
+ * Retries sending the completion event until acknowledged.
99
+ */
58
100
  const notifyFMLTrackingCompleted = () => {
59
101
  ackListener();
60
102
  // Retry sending until flag is true, but do not block the main thread
@@ -69,6 +111,11 @@ export const createTrackingForFirstMessage = () => {
69
111
  }
70
112
  }, 100);
71
113
  };
114
+
115
+ /**
116
+ * Listener for FMLTrackingCompletedAck event.
117
+ * Sets the flag to true when acknowledgment is received.
118
+ */
72
119
  const ackListener = () => {
73
120
  const listen = BroadcastService.getMessageByEventName(BroadcastEvent.FMLTrackingCompletedAck).subscribe(() => {
74
121
  flag = true;
@@ -78,22 +125,32 @@ export const createTrackingForFirstMessage = () => {
78
125
 
79
126
  // Rehydrate message is received when the widget is reloaded, this is to ensure that we are not tracking messages that are not part of the current conversation
80
127
  // No need to keep listerning for tracking, enforcing disconnection for the listners
128
+ /**
129
+ * Listener for widget rehydration event.
130
+ * Resets tracking and disconnects listeners when widget is reloaded.
131
+ */
81
132
  const rehydrateListener = BroadcastService.getMessageByEventName(TelemetryEvent.RehydrateMessageReceived).subscribe(() => {
82
- startTracking = false;
83
- stopTracking = false;
133
+ isTracking = false;
84
134
  disconnectListener();
85
135
  });
86
136
 
87
137
  // Rehydrate message is received when the widget is reloaded, this is to ensure that we are not tracking messages that are not part of the current conversation
88
138
  // No need to keep listerning for tracking, enforcing disconnection for the listners
139
+ /**
140
+ * Listener for history message event.
141
+ * Resets tracking and disconnects listeners when history is loaded.
142
+ */
89
143
  const historyListener = BroadcastService.getMessageByEventName(BroadcastEvent.HistoryMessageReceived).subscribe(() => {
90
- startTracking = false;
91
- stopTracking = false;
144
+ isTracking = false;
92
145
  disconnectListener();
93
146
  });
147
+
148
+ /**
149
+ * Listener for network disconnection event.
150
+ * Resets tracking, disconnects listeners, and logs a telemetry error.
151
+ */
94
152
  const offlineNetworkListener = BroadcastService.getMessageByEventName(TelemetryEvent.NetworkDisconnected).subscribe(() => {
95
- startTracking = false;
96
- stopTracking = false;
153
+ isTracking = false;
97
154
  disconnectListener();
98
155
  TelemetryHelper.logActionEvent(LogLevel.INFO, {
99
156
  Event: TelemetryEvent.BotFirstMessageLapTrackError,
@@ -102,7 +159,15 @@ export const createTrackingForFirstMessage = () => {
102
159
  });
103
160
 
104
161
  // this is to ensure that we are not tracking messages that are not part of the current conversation
162
+ /**
163
+ * Disconnects all listeners and clears the tracking timeout.
164
+ * Used for cleanup when tracking is stopped or reset.
165
+ */
105
166
  const disconnectListener = () => {
167
+ if (trackingTimeoutId) {
168
+ clearTimeout(trackingTimeoutId);
169
+ trackingTimeoutId = undefined;
170
+ }
106
171
  historyListener.unsubscribe();
107
172
  rehydrateListener.unsubscribe();
108
173
  newMessageListener.unsubscribe();
@@ -11,14 +11,13 @@ export let FirstResponseLatencyTracker = /*#__PURE__*/function () {
11
11
  function FirstResponseLatencyTracker() {
12
12
  _classCallCheck(this, FirstResponseLatencyTracker);
13
13
  _defineProperty(this, "isABotConversation", false);
14
- _defineProperty(this, "isStarted", false);
15
- _defineProperty(this, "isEnded", false);
14
+ _defineProperty(this, "isTracking", false);
16
15
  _defineProperty(this, "startTrackingMessage", void 0);
17
16
  _defineProperty(this, "stopTrackingMessage", void 0);
18
17
  _defineProperty(this, "isReady", false);
18
+ _defineProperty(this, "trackingTimeoutId", void 0);
19
19
  _defineProperty(this, "offlineNetworkListener", BroadcastService.getMessageByEventName(TelemetryEvent.NetworkDisconnected).subscribe(() => {
20
- this.isStarted = false;
21
- this.isEnded = false;
20
+ this.isTracking = false;
22
21
  TelemetryHelper.logActionEvent(LogLevel.INFO, {
23
22
  Event: TelemetryEvent.MessageStopLapTrackError,
24
23
  Description: "Tracker Stopped due to network disconnection"
@@ -66,7 +65,7 @@ export let FirstResponseLatencyTracker = /*#__PURE__*/function () {
66
65
  value: function startTracking(payload) {
67
66
  if (!this.isReady) return;
68
67
  // this prevents to initiate tracking for multiple incoming messages
69
- if (this.isStarted) {
68
+ if (this.isTracking) {
70
69
  return;
71
70
  }
72
71
  // this is to ensure we track only messages where bot is engaged
@@ -74,10 +73,24 @@ export let FirstResponseLatencyTracker = /*#__PURE__*/function () {
74
73
  return;
75
74
  }
76
75
  // control of states to prevent clashing of messages
77
- this.isStarted = true;
78
- this.isEnded = false;
76
+ this.isTracking = true;
79
77
  // The idea of using types is to enrich telemetry data
80
78
  this.startTrackingMessage = this.createTrackingMessage(payload, "userMessage");
79
+
80
+ // Start a 5-second timeout to auto-stop tracking if not stopped
81
+ if (this.trackingTimeoutId) {
82
+ clearTimeout(this.trackingTimeoutId);
83
+ }
84
+ this.trackingTimeoutId = setTimeout(() => {
85
+ // this means the start process is in progress, but the end wasn't called within the time limit
86
+ if (this.isTracking) {
87
+ // Reset state variables and skip stopTracking
88
+ this.isTracking = false;
89
+ this.startTrackingMessage = undefined;
90
+ this.stopTrackingMessage = undefined;
91
+ this.trackingTimeoutId = undefined;
92
+ }
93
+ }, 5000);
81
94
  }
82
95
  }, {
83
96
  key: "handleAgentMessage",
@@ -93,13 +106,16 @@ export let FirstResponseLatencyTracker = /*#__PURE__*/function () {
93
106
  value: function stopTracking(payload) {
94
107
  var _this$stopTrackingMes, _this$startTrackingMe;
95
108
  // this prevents execution for multiple incoming messages from the bot.
96
- if (this.isEnded && !this.isStarted) {
109
+ if (!this.isTracking) {
97
110
  return;
98
111
  }
99
-
112
+ // Clear the timeout if it exists
113
+ if (this.trackingTimeoutId) {
114
+ clearTimeout(this.trackingTimeoutId);
115
+ this.trackingTimeoutId = undefined;
116
+ }
100
117
  // control of states to prevent clashing of messages
101
- this.isEnded = true;
102
- this.isStarted = false;
118
+ this.isTracking = false;
103
119
 
104
120
  // The idea of using types is to enrich telemetry data
105
121
  this.stopTrackingMessage = this.createTrackingMessage(payload, "botMessage");
@@ -154,12 +170,16 @@ export let FirstResponseLatencyTracker = /*#__PURE__*/function () {
154
170
  if (!payload || !payload.Id) {
155
171
  throw new Error("Invalid payload");
156
172
  }
157
- if (!this.isMessageFromValidSender(payload)) return;
158
- if (this.isABotConversation && this.isStarted) {
173
+
174
+ // Only allow stopTracking if sender is valid and tracking is active
175
+ if (!this.isMessageFromValidSender(payload)) {
176
+ // Do not change isTracking or stopTrackingMessage
177
+ return;
178
+ }
179
+ if (this.isABotConversation && this.isTracking) {
159
180
  this.stopTracking(payload);
160
181
  }
161
182
  } catch (e) {
162
- console.error("FRL : error while trying to stop the tracker", e);
163
183
  TelemetryHelper.logActionEvent(LogLevel.ERROR, {
164
184
  Event: TelemetryEvent.MessageStopLapTrackError,
165
185
  Description: "Error while stopping the clock",
@@ -168,11 +188,6 @@ export let FirstResponseLatencyTracker = /*#__PURE__*/function () {
168
188
  payload: payload
169
189
  }
170
190
  });
171
- //reset state
172
- this.startTrackingMessage = undefined;
173
- this.stopTrackingMessage = undefined;
174
- this.isStarted = false;
175
- this.isEnded = false;
176
191
  }
177
192
  }
178
193
  }, {
@@ -180,10 +195,13 @@ export let FirstResponseLatencyTracker = /*#__PURE__*/function () {
180
195
  value: function deregister() {
181
196
  // Reset State
182
197
  this.isABotConversation = false;
183
- this.isStarted = false;
184
- this.isEnded = false;
198
+ this.isTracking = false;
185
199
  this.startTrackingMessage = undefined;
186
200
  this.stopTrackingMessage = undefined;
201
+ if (this.trackingTimeoutId) {
202
+ clearTimeout(this.trackingTimeoutId);
203
+ this.trackingTimeoutId = undefined;
204
+ }
187
205
  this.offlineNetworkListener.unsubscribe();
188
206
  this.fmltrackingListener.unsubscribe();
189
207
  this.rehydrateListener.unsubscribe();
@@ -1,5 +1,7 @@
1
1
  import { ScenarioType } from "./Constants";
2
2
  import { Constants } from "../common/Constants";
3
+ const DELTA_WITHIN_LIMITS_IN_MS = 250;
4
+
3
5
  /**
4
6
  * Determines whether a given activity is a historical message.
5
7
  *
@@ -17,19 +19,21 @@ import { Constants } from "../common/Constants";
17
19
  * - If the ID is valid and the timestamp is older than the start time, the message is historical.
18
20
  */
19
21
  export const isHistoryMessage = (activity, startTime) => {
20
- var _activity$channelData, _activity$channelData2;
22
+ var _activity$channelData;
21
23
  // Only process message activities
22
24
  if ((activity === null || activity === void 0 ? void 0 : activity.type) !== Constants.message) {
23
25
  return false;
24
26
  }
25
27
 
26
- // Legacy check for history message tag
27
- if (activity !== null && activity !== void 0 && (_activity$channelData = activity.channelData) !== null && _activity$channelData !== void 0 && (_activity$channelData2 = _activity$channelData.tags) !== null && _activity$channelData2 !== void 0 && _activity$channelData2.includes(Constants.historyMessageTag)) {
28
+ // Prioritize legacy history tag
29
+ if (activity !== null && activity !== void 0 && (_activity$channelData = activity.channelData) !== null && _activity$channelData !== void 0 && _activity$channelData.tags && activity.channelData.tags.includes(Constants.historyMessageTag)) {
28
30
  return true;
29
31
  }
30
32
  const activityId = extractTimestampFromId(activity);
31
33
  const isValidId = !isNaN(activityId) && activityId > 0;
32
- const isOlderThanStartTime = activityId < startTime;
34
+ const difference = startTime - activityId;
35
+ // Only consider historical if activityId < startTime and difference >= DELTA_WITHIN_LIMITS_IN_MS
36
+ const isOlderThanStartTime = activityId < startTime && difference >= DELTA_WITHIN_LIMITS_IN_MS;
33
37
  const isHistoryById = isValidId && isOlderThanStartTime;
34
38
  return isHistoryById;
35
39
  };
@@ -56,7 +60,7 @@ export const extractTimestampFromId = activity => {
56
60
  return activityId;
57
61
  };
58
62
  export const buildMessagePayload = (activity, userId) => {
59
- var _text, _text2, _activity$channelData3, _activity$from;
63
+ var _text, _text2, _activity$channelData2, _activity$from;
60
64
  return {
61
65
  // To identify hidden contents vs empty content
62
66
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -64,7 +68,7 @@ export const buildMessagePayload = (activity, userId) => {
64
68
  type: activity === null || activity === void 0 ? void 0 : activity.type,
65
69
  timestamp: activity === null || activity === void 0 ? void 0 : activity.timestamp,
66
70
  userId: userId,
67
- tags: activity === null || activity === void 0 ? void 0 : (_activity$channelData3 = activity.channelData) === null || _activity$channelData3 === void 0 ? void 0 : _activity$channelData3.tags,
71
+ tags: (activity === null || activity === void 0 ? void 0 : (_activity$channelData2 = activity.channelData) === null || _activity$channelData2 === void 0 ? void 0 : _activity$channelData2.tags) || [],
68
72
  messageType: "",
69
73
  Id: activity === null || activity === void 0 ? void 0 : activity.id,
70
74
  role: activity === null || activity === void 0 ? void 0 : (_activity$from = activity.from) === null || _activity$from === void 0 ? void 0 : _activity$from.role,
@@ -88,9 +92,9 @@ export const polyfillMessagePayloadForEvent = (activity, payload, conversationId
88
92
  };
89
93
  };
90
94
  export const getScenarioType = activity => {
91
- var _activity$from3, _activity$channelData4;
95
+ var _activity$from3, _activity$channelData3;
92
96
  const role = activity === null || activity === void 0 ? void 0 : (_activity$from3 = activity.from) === null || _activity$from3 === void 0 ? void 0 : _activity$from3.role;
93
- const tags = activity === null || activity === void 0 ? void 0 : (_activity$channelData4 = activity.channelData) === null || _activity$channelData4 === void 0 ? void 0 : _activity$channelData4.tags;
97
+ const tags = activity === null || activity === void 0 ? void 0 : (_activity$channelData3 = activity.channelData) === null || _activity$channelData3 === void 0 ? void 0 : _activity$channelData3.tags;
94
98
  if (role === Constants.userMessageTag) {
95
99
  return ScenarioType.UserSendMessageStrategy;
96
100
  }
@@ -1,11 +1,11 @@
1
1
  import { MessagePayload } from "./Constants";
2
2
  export declare class FirstResponseLatencyTracker {
3
3
  private isABotConversation;
4
- private isStarted;
5
- private isEnded;
4
+ private isTracking;
6
5
  private startTrackingMessage?;
7
6
  private stopTrackingMessage?;
8
7
  private isReady;
8
+ private trackingTimeoutId?;
9
9
  constructor();
10
10
  private createTrackingMessage;
11
11
  private startTracking;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@microsoft/omnichannel-chat-widget",
3
- "version": "1.8.2-main.5195aba",
3
+ "version": "1.8.2-main.d82a79b",
4
4
  "description": "Microsoft Omnichannel Chat Widget",
5
5
  "main": "lib/cjs/index.js",
6
6
  "types": "lib/types/index.d.ts",
@@ -86,7 +86,7 @@
86
86
  "dependencies": {
87
87
  "@azure/core-tracing": "^1.2.0",
88
88
  "@microsoft/applicationinsights-web": "^3.3.6",
89
- "@microsoft/omnichannel-chat-components": "1.1.12",
89
+ "@microsoft/omnichannel-chat-components": "1.1.13",
90
90
  "@microsoft/omnichannel-chat-sdk": "^1.11.4",
91
91
  "@opentelemetry/api": "^1.9.0",
92
92
  "abort-controller": "^3",