@cleartrip/talos-use-chat-controller 1.5.0 → 1.6.0-beta-260708-2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/ChatDispatcherProvider.d.ts +2 -2
  2. package/dist/ChatDispatcherProvider.d.ts.map +1 -1
  3. package/dist/index.d.ts +1 -0
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/services/index.d.ts +3 -3
  6. package/dist/services/index.d.ts.map +1 -1
  7. package/dist/services/type.d.ts +17 -6
  8. package/dist/services/type.d.ts.map +1 -1
  9. package/dist/stream/WidgetStore.d.ts +15 -0
  10. package/dist/stream/WidgetStore.d.ts.map +1 -0
  11. package/dist/stream/index.d.ts +4 -0
  12. package/dist/stream/index.d.ts.map +1 -0
  13. package/dist/stream/parser.d.ts +4 -0
  14. package/dist/stream/parser.d.ts.map +1 -0
  15. package/dist/talos-use-chat-controller.browser.cjs.js +1 -1
  16. package/dist/talos-use-chat-controller.browser.cjs.js.map +1 -1
  17. package/dist/talos-use-chat-controller.browser.esm.js +1 -1
  18. package/dist/talos-use-chat-controller.browser.esm.js.map +1 -1
  19. package/dist/talos-use-chat-controller.cjs.js +480 -164
  20. package/dist/talos-use-chat-controller.cjs.js.map +1 -1
  21. package/dist/talos-use-chat-controller.esm.js +484 -169
  22. package/dist/talos-use-chat-controller.esm.js.map +1 -1
  23. package/dist/talos-use-chat-controller.umd.js +483 -167
  24. package/dist/talos-use-chat-controller.umd.js.map +1 -1
  25. package/dist/type.d.ts +35 -3
  26. package/dist/type.d.ts.map +1 -1
  27. package/dist/useChatAction.d.ts +3 -0
  28. package/dist/useChatAction.d.ts.map +1 -1
  29. package/dist/useChatController.d.ts +4 -1
  30. package/dist/useChatController.d.ts.map +1 -1
  31. package/dist/useChatTransport.d.ts +24 -0
  32. package/dist/useChatTransport.d.ts.map +1 -0
  33. package/dist/useContextSummary.d.ts +13 -0
  34. package/dist/useContextSummary.d.ts.map +1 -0
  35. package/dist/util.d.ts +3 -1
  36. package/dist/util.d.ts.map +1 -1
  37. package/package.json +6 -6
@@ -1,10 +1,10 @@
1
- import { __awaiter, __generator, __assign, __rest, __spreadArray } from 'tslib';
2
- import { useCallback, useMemo, useState, useRef, useEffect, createContext, useContext } from 'react';
1
+ import { __assign, __awaiter, __generator, __rest, __spreadArray } from 'tslib';
2
+ import { useCallback, useState, useRef, useEffect, useMemo, createContext, useContext } from 'react';
3
3
  import { v4 } from 'uuid';
4
- import { useChat, ChatEventName } from '@cleartrip/talos-use-chat';
5
- import { formatISOTime, isEmpty } from '@cleartrip/talos-general-utils';
6
- import { NavigateSubType, ActionType, WidgetType } from '@cleartrip/talos-widget-types';
4
+ import { getSessionIdHeader, formatISOTime, isEmpty } from '@cleartrip/talos-general-utils';
5
+ import { NavigateSubType, ActionType, Plugins, WidgetType, StreamKind, Signal, Protocol } from '@cleartrip/talos-widget-types';
7
6
  import { baseFetch, REQUEST_METHODS } from '@cleartrip/talos-network';
7
+ import { useChat, ChatEventName } from '@cleartrip/talos-use-chat';
8
8
  import { jsx } from 'react/jsx-runtime';
9
9
 
10
10
  var API_ENDPOINTS = {
@@ -20,22 +20,21 @@ var API_ENDPOINTS = {
20
20
  var ChatService = (function () {
21
21
  function ChatService(network) {
22
22
  var _a = network !== null && network !== void 0 ? network : {}, headers = _a.headers, body = _a.body, domain = _a.domain;
23
- this.headers = (headers !== null && headers !== void 0 ? headers : {});
23
+ this.headers = __assign(__assign({}, headers), getSessionIdHeader());
24
24
  this.basePayload = body !== null && body !== void 0 ? body : {};
25
25
  this.domain = domain || '';
26
26
  }
27
- ChatService.prototype.fetchChatId = function () {
27
+ ChatService.prototype.fetchChatId = function (forceNewChat) {
28
+ if (forceNewChat === void 0) { forceNewChat = false; }
28
29
  return __awaiter(this, void 0, void 0, function () {
29
- var referenceId, mergedPayload, mergedHeaders, response;
30
- return __generator(this, function (_a) {
31
- switch (_a.label) {
30
+ var _a, _b, referenceId, _c, pageId, mergedPayload, mergedHeaders, response;
31
+ return __generator(this, function (_d) {
32
+ switch (_d.label) {
32
33
  case 0:
33
- referenceId = this.basePayload.referenceId;
34
- mergedPayload = {
35
- payload: {
34
+ _a = this.basePayload, _b = _a.referenceId, referenceId = _b === void 0 ? "" : _b, _c = _a.pageId, pageId = _c === void 0 ? "" : _c;
35
+ mergedPayload = __assign(__assign({ payload: {
36
36
  tripId: referenceId,
37
- }
38
- };
37
+ } }, (pageId && { pageId: pageId })), { init: forceNewChat });
39
38
  mergedHeaders = __assign({}, this.headers);
40
39
  return [4, baseFetch({
41
40
  url: API_ENDPOINTS.GET_CHAT_ID,
@@ -45,7 +44,7 @@ var ChatService = (function () {
45
44
  domain: this.domain,
46
45
  })];
47
46
  case 1:
48
- response = _a.sent();
47
+ response = _d.sent();
49
48
  return [2, response];
50
49
  }
51
50
  });
@@ -196,7 +195,7 @@ var ChatService = (function () {
196
195
  }());
197
196
 
198
197
  var useChatAction = function (props) {
199
- var sendMessage = props.sendMessage, getPreviousChatById = props.getPreviousChatById, handleCreateNewChat = props.handleCreateNewChat, handleBackButtonClick = props.handleBackButtonClick, handleShowNativeActions = props.handleShowNativeActions, retryUpload = props.retryUpload, retryMessage = props.retryMessage, handleRetryFromError = props.handleRetryFromError, getPreviousChats = props.getPreviousChats, handleFeedbackSubmission = props.handleFeedbackSubmission, triggerTracking = props.triggerTracking, handleCloseCurrentChat = props.handleCloseCurrentChat, handleThumbsDownFeedback = props.handleThumbsDownFeedback, baseTrackingData = props.baseTrackingData;
198
+ var sendMessage = props.sendMessage, getPreviousChatById = props.getPreviousChatById, handleCreateNewChat = props.handleCreateNewChat, handleBackButtonClick = props.handleBackButtonClick, handleShowNativeActions = props.handleShowNativeActions, retryUpload = props.retryUpload, retryMessage = props.retryMessage, handleRetryFromError = props.handleRetryFromError, getPreviousChats = props.getPreviousChats, handleFeedbackSubmission = props.handleFeedbackSubmission, triggerTracking = props.triggerTracking, handleCloseCurrentChat = props.handleCloseCurrentChat, handleThumbsDownFeedback = props.handleThumbsDownFeedback, handleOpenChatbot = props.handleOpenChatbot, handleCloseChatbot = props.handleCloseChatbot, baseTrackingData = props.baseTrackingData, customDispatcher = props.dispatcher;
200
199
  var dispatch = function (action) { return __awaiter(void 0, void 0, void 0, function () {
201
200
  var type, _a, _b, message, rest, id, subType, _c, isNativeActionsEnabled, messageId, messageId, _d, eventName, eventData, mergedEventData, _e, isFeedbackSubmitted, messageId, chatId, feedbackValue, feedbackValue;
202
201
  return __generator(this, function (_f) {
@@ -218,24 +217,26 @@ var useChatAction = function (props) {
218
217
  case ActionType.SET_IS_FEEDBACK_SUBMITTED: return [3, 15];
219
218
  case ActionType.HANDLE_THUMBS_DOWN_FEEDBACK: return [3, 16];
220
219
  case ActionType.CLOSE_CURRENT_CHAT: return [3, 17];
220
+ case ActionType.OPEN_CHATBOT: return [3, 18];
221
+ case ActionType.CLOSE_CHATBOT: return [3, 19];
221
222
  }
222
- return [3, 18];
223
+ return [3, 20];
223
224
  case 1:
224
225
  _b = action.payload, message = _b.message, rest = __rest(_b, ["message"]);
225
226
  return [4, sendMessage(message, rest)];
226
227
  case 2:
227
228
  _f.sent();
228
- return [3, 19];
229
+ return [3, 23];
229
230
  case 3:
230
231
  id = action.payload.id;
231
232
  return [4, getPreviousChatById(id)];
232
233
  case 4:
233
234
  _f.sent();
234
- return [3, 19];
235
+ return [3, 23];
235
236
  case 5:
236
237
  {
237
238
  handleCreateNewChat();
238
- return [3, 19];
239
+ return [3, 23];
239
240
  }
240
241
  case 6:
241
242
  {
@@ -243,66 +244,80 @@ var useChatAction = function (props) {
243
244
  if (subType === NavigateSubType.BACK) {
244
245
  handleBackButtonClick();
245
246
  }
246
- return [3, 19];
247
+ return [3, 23];
247
248
  }
248
249
  case 7:
249
250
  {
250
251
  _c = action.payload.isNativeActionsEnabled, isNativeActionsEnabled = _c === void 0 ? true : _c;
251
252
  handleShowNativeActions(isNativeActionsEnabled);
252
- return [3, 19];
253
+ return [3, 23];
253
254
  }
254
255
  case 8:
255
256
  messageId = action.payload.messageId;
256
257
  return [4, retryUpload(messageId)];
257
258
  case 9:
258
259
  _f.sent();
259
- return [3, 19];
260
+ return [3, 23];
260
261
  case 10:
261
262
  messageId = action.payload.messageId;
262
263
  return [4, retryMessage(messageId)];
263
264
  case 11:
264
265
  _f.sent();
265
- return [3, 19];
266
+ return [3, 23];
266
267
  case 12:
267
268
  {
268
269
  handleRetryFromError();
269
- return [3, 19];
270
+ return [3, 23];
270
271
  }
271
272
  case 13:
272
273
  {
273
274
  getPreviousChats();
274
- return [3, 19];
275
+ return [3, 23];
275
276
  }
276
277
  case 14:
277
278
  {
278
279
  _d = action.payload, eventName = _d.eventName, eventData = _d.eventData;
279
280
  mergedEventData = __assign(__assign({}, baseTrackingData), eventData);
280
281
  triggerTracking === null || triggerTracking === void 0 ? void 0 : triggerTracking({ eventName: eventName, eventData: mergedEventData });
281
- return [3, 19];
282
+ return [3, 23];
282
283
  }
283
284
  case 15:
284
285
  {
285
286
  _e = action.payload, isFeedbackSubmitted = _e.isFeedbackSubmitted, messageId = _e.messageId, chatId = _e.chatId, feedbackValue = _e.feedbackValue;
286
287
  handleFeedbackSubmission(chatId, messageId, isFeedbackSubmitted, feedbackValue);
287
- return [3, 19];
288
+ return [3, 23];
288
289
  }
289
290
  case 16:
290
291
  {
291
292
  feedbackValue = action.payload.feedbackValue;
292
293
  handleThumbsDownFeedback(feedbackValue);
293
- return [3, 19];
294
+ return [3, 23];
294
295
  }
295
296
  case 17:
296
297
  {
297
298
  handleCloseCurrentChat();
298
- return [3, 19];
299
+ return [3, 23];
299
300
  }
300
301
  case 18:
301
302
  {
302
- console.warn("[useChatAction] Unhandled action type: ".concat(type));
303
+ handleOpenChatbot();
304
+ return [3, 23];
303
305
  }
304
- _f.label = 19;
305
- case 19: return [2];
306
+ case 19:
307
+ {
308
+ handleCloseChatbot();
309
+ return [3, 23];
310
+ }
311
+ case 20:
312
+ if (!customDispatcher) return [3, 22];
313
+ return [4, customDispatcher(action)];
314
+ case 21:
315
+ _f.sent();
316
+ return [3, 23];
317
+ case 22:
318
+ console.warn("[useChatAction] Unhandled action type: ".concat(type));
319
+ _f.label = 23;
320
+ case 23: return [2];
306
321
  }
307
322
  });
308
323
  }); };
@@ -336,6 +351,11 @@ var ConversationMessageRole;
336
351
  ConversationMessageRole["BOT"] = "BOT";
337
352
  })(ConversationMessageRole || (ConversationMessageRole = {}));
338
353
 
354
+ var ChatCapability;
355
+ (function (ChatCapability) {
356
+ ChatCapability["CONVERSATIONAL"] = "conversational";
357
+ ChatCapability["SEARCH"] = "search";
358
+ })(ChatCapability || (ChatCapability = {}));
339
359
  var ChatStatus;
340
360
  (function (ChatStatus) {
341
361
  ChatStatus["ON_GOING"] = "ON_GOING";
@@ -453,6 +473,267 @@ var parseConversationMessages = function (messages) {
453
473
  var getTurnSequence = function (messages, type) {
454
474
  return messages.filter(function (m) { return m.type === type; }).length;
455
475
  };
476
+ var indexPluginsByType = function (plugins) {
477
+ if (plugins === void 0) { plugins = []; }
478
+ var byType = new Map();
479
+ for (var _i = 0, plugins_1 = plugins; _i < plugins_1.length; _i++) {
480
+ var plugin = plugins_1[_i];
481
+ if (byType.has(plugin.type)) {
482
+ console.warn("[talos] Duplicate plugin type \"".concat(plugin.type, "\". Only one plugin per type is allowed; ignoring the extra one."));
483
+ continue;
484
+ }
485
+ byType.set(plugin.type, plugin);
486
+ }
487
+ return byType;
488
+ };
489
+ var getPluginDispatcher = function (pluginsByType) {
490
+ var _a;
491
+ var plugin = pluginsByType.get(Plugins.DISPATCHER);
492
+ return (_a = plugin === null || plugin === void 0 ? void 0 : plugin.dispatcher) !== null && _a !== void 0 ? _a : undefined;
493
+ };
494
+
495
+ var useContextSummary = function (_a) {
496
+ var chatService = _a.chatService;
497
+ var _b = useState(false), isContextSummaryLoading = _b[0], setIsContextSummaryLoading = _b[1];
498
+ var _c = useState(null), contextSummary = _c[0], setContextSummary = _c[1];
499
+ var _d = useState(null), contextSummaryError = _d[0], setContextSummaryError = _d[1];
500
+ var fetchContextSummary = useCallback(function (sessionId) { return __awaiter(void 0, void 0, void 0, function () {
501
+ var payload, response;
502
+ return __generator(this, function (_a) {
503
+ switch (_a.label) {
504
+ case 0:
505
+ _a.trys.push([0, 2, 3, 4]);
506
+ setContextSummaryError(false);
507
+ setIsContextSummaryLoading(true);
508
+ payload = buildBotPayload({ kind: BotMessageKind.INIT }, sessionId);
509
+ return [4, chatService.getBotResponse(payload)];
510
+ case 1:
511
+ response = _a.sent();
512
+ setContextSummary(response);
513
+ return [3, 4];
514
+ case 2:
515
+ _a.sent();
516
+ setContextSummaryError(true);
517
+ return [3, 4];
518
+ case 3:
519
+ setIsContextSummaryLoading(false);
520
+ return [7];
521
+ case 4: return [2];
522
+ }
523
+ });
524
+ }); }, [chatService]);
525
+ return {
526
+ isContextSummaryLoading: isContextSummaryLoading,
527
+ contextSummary: contextSummary,
528
+ contextSummaryError: contextSummaryError,
529
+ fetchContextSummary: fetchContextSummary,
530
+ };
531
+ };
532
+
533
+ var replaceMerge = function (current, incoming) { return (__assign(__assign({}, current), { data: __assign(__assign({}, current.data), incoming) })); };
534
+ var defaultResolver = function () { return replaceMerge; };
535
+ var withStreamMeta = function (w, streamId, isStreaming) {
536
+ var _a;
537
+ return (__assign(__assign({}, w), { metaData: __assign(__assign({}, ((_a = w.metaData) !== null && _a !== void 0 ? _a : {})), { streamId: streamId, isStreaming: isStreaming }) }));
538
+ };
539
+ var WidgetStore = (function () {
540
+ function WidgetStore(mergeFor) {
541
+ if (mergeFor === void 0) { mergeFor = defaultResolver; }
542
+ this.mergeFor = mergeFor;
543
+ this.order = [];
544
+ this.byId = new Map();
545
+ this.autoKey = 0;
546
+ }
547
+ WidgetStore.prototype.reset = function () {
548
+ this.order = [];
549
+ this.byId = new Map();
550
+ this.autoKey = 0;
551
+ };
552
+ WidgetStore.prototype.apply = function (op) {
553
+ if (op.kind === StreamKind.STANDALONE) {
554
+ this.push("w-".concat(this.autoKey++), op.widget);
555
+ return;
556
+ }
557
+ if (op.kind === StreamKind.CHUNK) {
558
+ var current = this.byId.get(op.streamId);
559
+ if (!current) {
560
+ this.push(op.streamId, withStreamMeta(op.widget, op.streamId, true));
561
+ }
562
+ else {
563
+ this.push(op.streamId, this.mergeFor(current.type)(current, op.widget.data));
564
+ }
565
+ return;
566
+ }
567
+ var w = this.byId.get(op.streamId);
568
+ if (w)
569
+ this.push(op.streamId, withStreamMeta(w, op.streamId, false));
570
+ };
571
+ WidgetStore.prototype.closeOpenStreams = function () {
572
+ var _this = this;
573
+ this.order.forEach(function (key) {
574
+ var _a, _b;
575
+ var w = _this.byId.get(key);
576
+ if ((_a = w === null || w === void 0 ? void 0 : w.metaData) === null || _a === void 0 ? void 0 : _a.isStreaming) {
577
+ _this.push(key, withStreamMeta(w, (_b = w.metaData.streamId) !== null && _b !== void 0 ? _b : key, false));
578
+ }
579
+ });
580
+ };
581
+ WidgetStore.prototype.toArray = function () {
582
+ var _this = this;
583
+ return this.order
584
+ .map(function (key) { return _this.byId.get(key); })
585
+ .filter(function (w) { return Boolean(w); });
586
+ };
587
+ WidgetStore.prototype.push = function (key, widget) {
588
+ if (!this.byId.has(key))
589
+ this.order.push(key);
590
+ this.byId.set(key, widget);
591
+ };
592
+ return WidgetStore;
593
+ }());
594
+
595
+ var initialParserState = function () { return ({ openStreamId: null }); };
596
+ function frameToOp(frame, state) {
597
+ if ("signal" in frame) {
598
+ if (frame.signal === Signal.START) {
599
+ state.openStreamId = frame.streamId;
600
+ return null;
601
+ }
602
+ state.openStreamId = null;
603
+ return { kind: StreamKind.CLOSE, streamId: frame.streamId };
604
+ }
605
+ return state.openStreamId
606
+ ? { kind: StreamKind.CHUNK, streamId: state.openStreamId, widget: frame }
607
+ : { kind: StreamKind.STANDALONE, widget: frame };
608
+ }
609
+
610
+ var isLandingFrame = function (frame) {
611
+ return typeof frame === "object" &&
612
+ frame !== null &&
613
+ !("signal" in frame) &&
614
+ !("type" in frame) &&
615
+ ("heading" in frame || "suggestions" in frame);
616
+ };
617
+ var scheduleOncePerFrame = function (fn) {
618
+ var scheduled = false;
619
+ var schedule = typeof requestAnimationFrame !== "undefined"
620
+ ? requestAnimationFrame
621
+ : function (cb) { return setTimeout(cb, 16); };
622
+ return function () {
623
+ if (scheduled)
624
+ return;
625
+ scheduled = true;
626
+ schedule(function () {
627
+ scheduled = false;
628
+ fn();
629
+ });
630
+ };
631
+ };
632
+ var useChatTransport = function (props) {
633
+ var _a = props.protocol, protocol = _a === void 0 ? Protocol.DEFAULT : _a, network = props.network, chatService = props.chatService, resolveMerge = props.resolveMerge, buildBody = props.buildBody;
634
+ var _b = useChat({ network: network, buildBody: buildBody }), chat = _b.chat, status = _b.status, chatSend = _b.send, stop = _b.stop;
635
+ var storeRef = useRef();
636
+ if (!storeRef.current)
637
+ storeRef.current = new WidgetStore(resolveMerge);
638
+ var stateRef = useRef(initialParserState());
639
+ var sinkRef = useRef(null);
640
+ var flushRef = useRef();
641
+ if (!flushRef.current) {
642
+ flushRef.current = scheduleOncePerFrame(function () {
643
+ if (sinkRef.current)
644
+ sinkRef.current.update(storeRef.current.toArray());
645
+ });
646
+ }
647
+ useEffect(function () {
648
+ var store = storeRef.current;
649
+ var onChunk = function (_a) {
650
+ var _b, _c;
651
+ var chunk = _a.chunk;
652
+ if (!sinkRef.current)
653
+ return;
654
+ var envelope;
655
+ try {
656
+ envelope = JSON.parse(chunk);
657
+ }
658
+ catch (_d) {
659
+ return;
660
+ }
661
+ var frame = envelope === null || envelope === void 0 ? void 0 : envelope.data;
662
+ if (!frame)
663
+ return;
664
+ if (isLandingFrame(frame)) {
665
+ (_c = (_b = sinkRef.current).onLanding) === null || _c === void 0 ? void 0 : _c.call(_b, frame);
666
+ return;
667
+ }
668
+ var op = frameToOp(frame, stateRef.current);
669
+ if (op)
670
+ store.apply(op);
671
+ flushRef.current();
672
+ };
673
+ var onComplete = function () {
674
+ var sink = sinkRef.current;
675
+ if (!sink)
676
+ return;
677
+ store.closeOpenStreams();
678
+ sink.update(store.toArray());
679
+ sink.done();
680
+ sinkRef.current = null;
681
+ };
682
+ var onError = function (_a) {
683
+ var error = _a.error;
684
+ var sink = sinkRef.current;
685
+ if (!sink)
686
+ return;
687
+ store.closeOpenStreams();
688
+ sink.error(error);
689
+ sinkRef.current = null;
690
+ };
691
+ var offChunk = chat.on(ChatEventName.CHUNK, onChunk);
692
+ var offComplete = chat.on(ChatEventName.COMPLETE, onComplete);
693
+ var offError = chat.on(ChatEventName.ERROR, onError);
694
+ return function () {
695
+ offChunk();
696
+ offComplete();
697
+ offError();
698
+ };
699
+ }, [chat]);
700
+ var send = useCallback(function (payload, sink) { return __awaiter(void 0, void 0, void 0, function () {
701
+ var res, _a, _b, chunks, _c, metadata, error_1;
702
+ var _d;
703
+ return __generator(this, function (_e) {
704
+ switch (_e.label) {
705
+ case 0:
706
+ if (protocol === Protocol.STREAMED) {
707
+ storeRef.current.reset();
708
+ stateRef.current = initialParserState();
709
+ sinkRef.current = sink;
710
+ chatSend(payload);
711
+ return [2];
712
+ }
713
+ _e.label = 1;
714
+ case 1:
715
+ _e.trys.push([1, 3, , 4]);
716
+ return [4, chatService.getBotResponse(payload)];
717
+ case 2:
718
+ res = _e.sent();
719
+ _a = (_d = res === null || res === void 0 ? void 0 : res.data) !== null && _d !== void 0 ? _d : {}, _b = _a.chunks, chunks = _b === void 0 ? [] : _b, _c = _a.metadata, metadata = _c === void 0 ? {} : _c;
720
+ sink.update(chunks);
721
+ sink.done(metadata);
722
+ return [3, 4];
723
+ case 3:
724
+ error_1 = _e.sent();
725
+ sink.error(error_1);
726
+ return [3, 4];
727
+ case 4: return [2];
728
+ }
729
+ });
730
+ }); }, [protocol, chatSend, chatService]);
731
+ var abort = useCallback(function () {
732
+ stop();
733
+ sinkRef.current = null;
734
+ }, [stop]);
735
+ return { chat: chat, status: status, send: send, abort: abort };
736
+ };
456
737
 
457
738
  var BOT_ERROR_RESPONSE = function (errorId, retryPayload) {
458
739
  return {
@@ -503,21 +784,30 @@ var BOT_ERROR_RESPONSE = function (errorId, retryPayload) {
503
784
  var ANIMATION_DURATION = 300;
504
785
 
505
786
  var useChatController = function (config) {
506
- var network = config.network, triggerTracking = config.triggerTracking, baseTrackingData = config.baseTrackingData;
507
- var _a = useChat(config), chat = _a.chat, status = _a.status, baseSendMessage = _a.sendMessage, stop = _a.stop;
787
+ var network = config.network, triggerTracking = config.triggerTracking, baseTrackingData = config.baseTrackingData, plugins = config.plugins, _a = config.capability; _a === void 0 ? ChatCapability.CONVERSATIONAL : _a; var open = config.open, onOpenChatbot = config.onOpenChatbot, onCloseChatbot = config.onCloseChatbot, protocol = config.protocol, resolveMerge = config.resolveMerge, buildBody = config.buildBody;
508
788
  var chatService = useMemo(function () { return new ChatService(network); }, [network]);
509
- var _b = useState({}), messages = _b[0], setMessages = _b[1];
510
- var _c = useState(false), isInitialLoading = _c[0], setIsInitialLoading = _c[1];
511
- var _d = useState(false), isReplyLoading = _d[0], setIsReplyLoading = _d[1];
512
- var _e = useState([]), chatStack = _e[0], setChatStack = _e[1];
513
- var _f = useState(null), previousChats = _f[0], setPreviousChats = _f[1];
514
- var _g = useState(false), previousChatLoading = _g[0], setPreviousChatLoading = _g[1];
515
- var _h = useState(null), previousChatError = _h[0], setPreviousChatError = _h[1];
516
- var _j = useState(false), showNativeActions = _j[0], setShowNativeActions = _j[1];
517
- var _k = useState(false), isNewChat = _k[0], setIsNewChat = _k[1];
789
+ var defaultBuildBody = useCallback(function (payload) {
790
+ var _a;
791
+ return (__assign(__assign({}, payload), { payload: __assign(__assign({}, payload.payload), ((_a = network === null || network === void 0 ? void 0 : network.body) !== null && _a !== void 0 ? _a : {})) }));
792
+ }, [network]);
793
+ var pluginsByType = useMemo(function () { return indexPluginsByType(plugins); }, [plugins]);
794
+ var dispatcher = useMemo(function () { return getPluginDispatcher(pluginsByType); }, [pluginsByType]);
795
+ var _b = useChatTransport({ protocol: protocol, network: network, chatService: chatService, resolveMerge: resolveMerge, buildBody: buildBody !== null && buildBody !== void 0 ? buildBody : defaultBuildBody }), chat = _b.chat, status = _b.status, transportSend = _b.send, stop = _b.abort;
796
+ var _c = useState({}), messages = _c[0], setMessages = _c[1];
797
+ var _d = useState(false), isInitialLoading = _d[0], setIsInitialLoading = _d[1];
798
+ var _e = useState(false), isReplyLoading = _e[0], setIsReplyLoading = _e[1];
799
+ var _f = useState([]), chatStack = _f[0], setChatStack = _f[1];
800
+ var _g = useState(null), previousChats = _g[0], setPreviousChats = _g[1];
801
+ var _h = useState(false), previousChatLoading = _h[0], setPreviousChatLoading = _h[1];
802
+ var _j = useState(null), previousChatError = _j[0], setPreviousChatError = _j[1];
803
+ var _k = useState(false), showNativeActions = _k[0], setShowNativeActions = _k[1];
804
+ var _l = useState(false), isNewChat = _l[0], setIsNewChat = _l[1];
805
+ var _m = useContextSummary({ chatService: chatService }), isContextSummaryLoading = _m.isContextSummaryLoading, contextSummary = _m.contextSummary, contextSummaryError = _m.contextSummaryError, fetchContextSummary = _m.fetchContextSummary;
518
806
  var presentedRef = useRef(new Map());
519
807
  var screenRefs = useRef([]);
520
808
  var timeoutRef = useRef(null);
809
+ var summaryEnabledRef = useRef(false);
810
+ var summaryFetchedRef = useRef(false);
521
811
  var hasPresented = useCallback(function (cid, id) {
522
812
  var _a, _b;
523
813
  return (_b = (_a = presentedRef.current.get(cid)) === null || _a === void 0 ? void 0 : _a.has(id)) !== null && _b !== void 0 ? _b : false;
@@ -542,82 +832,90 @@ var useChatController = function (config) {
542
832
  var _a;
543
833
  return ((_a = chatStack[chatStack.length - 1]) === null || _a === void 0 ? void 0 : _a.id) || "";
544
834
  }, [chatStack]);
835
+ var patchMessageChunks = function (chatId, messageId, widgets) {
836
+ setMessages(function (prev) {
837
+ var _a;
838
+ var chat = prev[chatId];
839
+ if (!chat)
840
+ return prev;
841
+ return __assign(__assign({}, prev), (_a = {}, _a[chatId] = __assign(__assign({}, chat), { messages: chat.messages.map(function (m) { return (m.id === messageId ? __assign(__assign({}, m), { chunks: widgets }) : m); }) }), _a));
842
+ });
843
+ };
545
844
  var handleBotMessage = function (variant, chatId) {
845
+ var _a, _b;
546
846
  if (chatId === void 0) { chatId = currentChatId; }
547
- return __awaiter(void 0, void 0, void 0, function () {
548
- var isInit, responseStatus, handedOffToAgent, turnSequence, payload, response, _a, _b, _c, chunks_1, _d, metadata, messageId_1, errorId_1;
549
- var _e, _f, _g;
550
- return __generator(this, function (_h) {
551
- switch (_h.label) {
552
- case 0:
553
- isInit = variant.kind === BotMessageKind.INIT;
554
- handedOffToAgent = false;
555
- turnSequence = getTurnSequence((_f = (_e = messages[chatId]) === null || _e === void 0 ? void 0 : _e.messages) !== null && _f !== void 0 ? _f : [], "BOT_MESSAGE") + 1;
556
- _h.label = 1;
557
- case 1:
558
- _h.trys.push([1, 3, 4, 5]);
559
- if (!isInit) {
560
- setIsReplyLoading(true);
561
- }
562
- payload = buildBotPayload(variant, chatId);
563
- return [4, chatService.getBotResponse(payload)];
564
- case 2:
565
- response = _h.sent();
566
- _a = response.data, _b = _a === void 0 ? {} : _a, _c = _b.chunks, chunks_1 = _c === void 0 ? [] : _c, _d = _b.metadata, metadata = _d === void 0 ? {} : _d;
567
- responseStatus = 'success';
568
- handedOffToAgent = (_g = metadata.handedOffToAgent) !== null && _g !== void 0 ? _g : false;
569
- messageId_1 = v4();
570
- if (isInit)
571
- seedPresented(chatId, [messageId_1]);
572
- setMessages(function (prev) {
573
- var _a;
574
- var _b, _c;
575
- return (__assign(__assign({}, prev), (_a = {}, _a[chatId] = __assign(__assign({}, prev[chatId]), { messages: __spreadArray(__spreadArray([], ((_c = (_b = prev[chatId]) === null || _b === void 0 ? void 0 : _b.messages) !== null && _c !== void 0 ? _c : []), true), [
576
- {
577
- id: messageId_1,
578
- type: "BOT_MESSAGE",
579
- chunks: __spreadArray([], chunks_1, true),
580
- metaData: { createdAt: formatISOTime(new Date().toISOString()), messageId: messageId_1 },
581
- },
582
- ], false), status: ChatStatus.ON_GOING }), _a)));
583
- });
584
- return [3, 5];
585
- case 3:
586
- _h.sent();
587
- errorId_1 = v4();
588
- setMessages(function (prev) {
589
- var _a;
590
- var _b, _c;
591
- return (__assign(__assign({}, prev), (_a = {}, _a[chatId] = __assign(__assign({}, prev[chatId]), { messages: __spreadArray(__spreadArray([], ((_c = (_b = prev[chatId]) === null || _b === void 0 ? void 0 : _b.messages) !== null && _c !== void 0 ? _c : []), true), [BOT_ERROR_RESPONSE(errorId_1, variant)], false) }), _a)));
592
- });
593
- responseStatus = 'failed';
594
- return [3, 5];
595
- case 4:
596
- if (!isInit) {
597
- setIsReplyLoading(false);
598
- if (handedOffToAgent) {
599
- dispatch({
600
- type: ActionType.RAVEN_TRACKING,
601
- payload: {
602
- eventName: "u_ai_chat_agent_handoff",
603
- eventData: { action_name: "chat_agent_handoff", turn_sequence: turnSequence, chat_session_id: chatId },
604
- },
605
- });
606
- }
607
- else {
608
- dispatch({
609
- type: ActionType.RAVEN_TRACKING,
610
- payload: {
611
- eventName: "u_ai_chat_bot_response",
612
- eventData: { chat_session_id: chatId, response_status: responseStatus, turn_sequence: turnSequence },
613
- },
614
- });
615
- }
616
- }
617
- return [7];
618
- case 5: return [2];
619
- }
620
- });
847
+ var isInit = variant.kind === BotMessageKind.INIT;
848
+ var turnSequence = getTurnSequence((_b = (_a = messages[chatId]) === null || _a === void 0 ? void 0 : _a.messages) !== null && _b !== void 0 ? _b : [], "BOT_MESSAGE") + 1;
849
+ var messageId = v4();
850
+ if (!isInit)
851
+ setIsReplyLoading(true);
852
+ if (isInit)
853
+ seedPresented(chatId, [messageId]);
854
+ setMessages(function (prev) {
855
+ var _a;
856
+ var _b, _c;
857
+ return (__assign(__assign({}, prev), (_a = {}, _a[chatId] = __assign(__assign({}, prev[chatId]), { messages: __spreadArray(__spreadArray([], ((_c = (_b = prev[chatId]) === null || _b === void 0 ? void 0 : _b.messages) !== null && _c !== void 0 ? _c : []), true), [
858
+ {
859
+ id: messageId,
860
+ type: "BOT_MESSAGE",
861
+ chunks: [],
862
+ metaData: { createdAt: formatISOTime(new Date().toISOString()), messageId: messageId },
863
+ },
864
+ ], false), status: ChatStatus.ON_GOING }), _a)));
865
+ });
866
+ var trackResult = function (responseStatus, handedOffToAgent) {
867
+ if (isInit)
868
+ return;
869
+ setIsReplyLoading(false);
870
+ if (handedOffToAgent) {
871
+ dispatch({
872
+ type: ActionType.RAVEN_TRACKING,
873
+ payload: {
874
+ eventName: "u_ai_chat_agent_handoff",
875
+ eventData: { action_name: "chat_agent_handoff", turn_sequence: turnSequence, chat_session_id: chatId },
876
+ },
877
+ });
878
+ }
879
+ else {
880
+ dispatch({
881
+ type: ActionType.RAVEN_TRACKING,
882
+ payload: {
883
+ eventName: "u_ai_chat_bot_response",
884
+ eventData: { chat_session_id: chatId, response_status: responseStatus, turn_sequence: turnSequence },
885
+ },
886
+ });
887
+ }
888
+ };
889
+ return new Promise(function (resolve) {
890
+ var sink = {
891
+ update: function (widgets) { return patchMessageChunks(chatId, messageId, widgets); },
892
+ onLanding: function (content) {
893
+ if (!isInit)
894
+ return;
895
+ setMessages(function (prev) {
896
+ var _a;
897
+ return (__assign(__assign({}, prev), (_a = {}, _a[chatId] = __assign(__assign({}, prev[chatId]), { landingContent: content, messages: [] }), _a)));
898
+ });
899
+ },
900
+ done: function (metadata) {
901
+ var _a;
902
+ trackResult("success", (_a = metadata === null || metadata === void 0 ? void 0 : metadata.handedOffToAgent) !== null && _a !== void 0 ? _a : false);
903
+ resolve();
904
+ },
905
+ error: function () {
906
+ setMessages(function (prev) {
907
+ var _a;
908
+ var chat = prev[chatId];
909
+ if (!chat)
910
+ return prev;
911
+ var errorMsg = BOT_ERROR_RESPONSE(messageId, variant);
912
+ return __assign(__assign({}, prev), (_a = {}, _a[chatId] = __assign(__assign({}, chat), { messages: chat.messages.map(function (m) { return (m.id === messageId ? errorMsg : m); }) }), _a));
913
+ });
914
+ trackResult("failed", false);
915
+ resolve();
916
+ },
917
+ };
918
+ transportSend(buildBotPayload(variant, chatId), sink);
621
919
  });
622
920
  };
623
921
  var handleRetryMessage = function (messageId) { return __awaiter(void 0, void 0, void 0, function () {
@@ -661,56 +959,61 @@ var useChatController = function (config) {
661
959
  }
662
960
  });
663
961
  }); };
664
- var seedInitialChat = function () { return __awaiter(void 0, void 0, void 0, function () {
665
- var response, latestSessionId, newChat;
666
- return __generator(this, function (_a) {
667
- switch (_a.label) {
668
- case 0:
669
- _a.trys.push([0, 6, 7, 8]);
670
- setIsInitialLoading(true);
671
- return [4, chatService.fetchChatId()];
672
- case 1:
673
- response = _a.sent();
674
- latestSessionId = response.data.latestSessionId;
675
- newChat = isEmpty(latestSessionId);
676
- setIsNewChat(newChat);
677
- if (newChat) {
678
- latestSessionId = v4();
679
- }
680
- setChatStack([{ type: ChatPageType.CHAT, id: latestSessionId }]);
681
- if (!newChat) return [3, 3];
682
- return [4, handleBotMessage({ kind: BotMessageKind.INIT }, latestSessionId)];
683
- case 2:
684
- _a.sent();
685
- return [3, 5];
686
- case 3: return [4, handleConversationFetch(latestSessionId)];
687
- case 4:
688
- _a.sent();
689
- _a.label = 5;
690
- case 5: return [3, 8];
691
- case 6:
692
- _a.sent();
693
- setChatStack([{ type: ChatPageType.CHAT_ERROR, retry: { kind: ChatErrorKind.INITIAL } }]);
694
- return [3, 8];
695
- case 7:
696
- setIsInitialLoading(false);
697
- return [7];
698
- case 8: return [2];
699
- }
962
+ var seedInitialChat = function (forceNewChat) {
963
+ if (forceNewChat === void 0) { forceNewChat = false; }
964
+ return __awaiter(void 0, void 0, void 0, function () {
965
+ var response, _a, latestSessionId, _b, summaryEnabled, newChat;
966
+ return __generator(this, function (_c) {
967
+ switch (_c.label) {
968
+ case 0:
969
+ _c.trys.push([0, 6, , 7]);
970
+ setIsInitialLoading(true);
971
+ return [4, chatService.fetchChatId(forceNewChat)];
972
+ case 1:
973
+ response = _c.sent();
974
+ _a = response.data, latestSessionId = _a.latestSessionId, _b = _a.summaryEnabled, summaryEnabled = _b === void 0 ? false : _b;
975
+ newChat = isEmpty(latestSessionId);
976
+ setIsNewChat(newChat);
977
+ summaryEnabledRef.current = !newChat && summaryEnabled;
978
+ if (newChat) {
979
+ latestSessionId = v4();
980
+ }
981
+ setChatStack([{ type: ChatPageType.CHAT, id: latestSessionId }]);
982
+ if (!newChat) return [3, 3];
983
+ return [4, handleBotMessage({ kind: BotMessageKind.INIT }, latestSessionId)];
984
+ case 2:
985
+ _c.sent();
986
+ setIsInitialLoading(false);
987
+ return [3, 5];
988
+ case 3: return [4, handleConversationFetch(latestSessionId)];
989
+ case 4:
990
+ _c.sent();
991
+ setIsInitialLoading(false);
992
+ _c.label = 5;
993
+ case 5: return [3, 7];
994
+ case 6:
995
+ _c.sent();
996
+ setChatStack([{ type: ChatPageType.CHAT_ERROR, retry: { kind: ChatErrorKind.INITIAL } }]);
997
+ setIsInitialLoading(false);
998
+ return [3, 7];
999
+ case 7: return [2];
1000
+ }
1001
+ });
700
1002
  });
701
- }); };
1003
+ };
702
1004
  useEffect(function () {
703
1005
  seedInitialChat();
704
1006
  }, []);
705
- var handleChunk = useCallback(function (_a) {
706
- _a.chunk; _a.chatId;
707
- }, []);
708
1007
  useEffect(function () {
709
- var removeChunkListener = chat.on(ChatEventName.CHUNK, handleChunk);
710
- return function () {
711
- removeChunkListener();
712
- };
713
- }, [chat, handleChunk]);
1008
+ if (!open) {
1009
+ summaryFetchedRef.current = false;
1010
+ return;
1011
+ }
1012
+ if (summaryFetchedRef.current || isInitialLoading || !currentChatId || isNewChat || !summaryEnabledRef.current)
1013
+ return;
1014
+ summaryFetchedRef.current = true;
1015
+ fetchContextSummary(currentChatId);
1016
+ }, [open, isInitialLoading, currentChatId, isNewChat, fetchContextSummary]);
714
1017
  var pushUserMessage = function (message) {
715
1018
  var userMessageWidget = formUserMessageWidget({ message: message });
716
1019
  var id = v4();
@@ -747,7 +1050,7 @@ var useChatController = function (config) {
747
1050
  }
748
1051
  return [2];
749
1052
  });
750
- }); }, [baseSendMessage, pushUserMessage]);
1053
+ }); }, [pushUserMessage]);
751
1054
  var resetPreviousChats = function () {
752
1055
  setPreviousChatError(false);
753
1056
  setPreviousChats(null);
@@ -797,7 +1100,7 @@ var useChatController = function (config) {
797
1100
  var handleCreateNewChat = function () {
798
1101
  clearChatStack();
799
1102
  clearMessages();
800
- seedInitialChat();
1103
+ seedInitialChat(true);
801
1104
  setShowNativeActions(false);
802
1105
  dispatch({
803
1106
  type: ActionType.RAVEN_TRACKING,
@@ -1040,6 +1343,12 @@ var useChatController = function (config) {
1040
1343
  return (__assign(__assign({}, prev), (_a = {}, _a[currentChatId] = __assign(__assign({}, prev[currentChatId]), { status: ChatStatus.CLOSED }), _a)));
1041
1344
  });
1042
1345
  };
1346
+ var handleOpenChatbot = function () {
1347
+ onOpenChatbot === null || onOpenChatbot === void 0 ? void 0 : onOpenChatbot();
1348
+ };
1349
+ var handleCloseChatbot = function () {
1350
+ onCloseChatbot === null || onCloseChatbot === void 0 ? void 0 : onCloseChatbot();
1351
+ };
1043
1352
  var handleThumbsDownFeedback = function (feedbackValue) {
1044
1353
  var _a, _b;
1045
1354
  var turnSequence = getTurnSequence((_b = (_a = messages[currentChatId]) === null || _a === void 0 ? void 0 : _a.messages) !== null && _b !== void 0 ? _b : [], "USER_MESSAGE");
@@ -1058,7 +1367,7 @@ var useChatController = function (config) {
1058
1367
  }
1059
1368
  };
1060
1369
  }, []);
1061
- var _l = useChatAction({
1370
+ var _o = useChatAction({
1062
1371
  retryUpload: retryUpload,
1063
1372
  retryMessage: handleRetryMessage,
1064
1373
  sendMessage: sendMessage,
@@ -1072,8 +1381,11 @@ var useChatController = function (config) {
1072
1381
  triggerTracking: triggerTracking,
1073
1382
  handleCloseCurrentChat: handleCloseCurrentChat,
1074
1383
  handleThumbsDownFeedback: handleThumbsDownFeedback,
1384
+ handleOpenChatbot: handleOpenChatbot,
1385
+ handleCloseChatbot: handleCloseChatbot,
1075
1386
  baseTrackingData: baseTrackingData,
1076
- }), dispatch = _l.dispatch, dispatchAll = _l.dispatchAll;
1387
+ dispatcher: dispatcher,
1388
+ }), dispatch = _o.dispatch, dispatchAll = _o.dispatchAll;
1077
1389
  return {
1078
1390
  currentChatId: currentChatId,
1079
1391
  chat: chat,
@@ -1085,6 +1397,9 @@ var useChatController = function (config) {
1085
1397
  isInitialLoading: isInitialLoading,
1086
1398
  isReplyLoading: isReplyLoading,
1087
1399
  isNewChat: isNewChat,
1400
+ isContextSummaryLoading: isContextSummaryLoading,
1401
+ contextSummary: contextSummary,
1402
+ contextSummaryError: contextSummaryError,
1088
1403
  screenRefs: screenRefs,
1089
1404
  showNativeActions: showNativeActions,
1090
1405
  chatService: chatService,
@@ -1156,5 +1471,5 @@ var useChatNetwork = function () {
1156
1471
  return { chatService: chatService };
1157
1472
  };
1158
1473
 
1159
- export { BotMessageKind, ChatDispatchProvider, ChatErrorKind, ChatNetworkProvider, ChatPageType, ChatStatus, ConversationMessageRole, UploadStatus, useAppDispatch, useChatAction, useChatContext, useChatController, useChatNetwork, useDispatch, useDispatchAll, usePresentation };
1474
+ export { BotMessageKind, ChatCapability, ChatDispatchProvider, ChatErrorKind, ChatNetworkProvider, ChatPageType, ChatStatus, ConversationMessageRole, UploadStatus, useAppDispatch, useChatAction, useChatContext, useChatController, useChatNetwork, useContextSummary, useDispatch, useDispatchAll, usePresentation };
1160
1475
  //# sourceMappingURL=talos-use-chat-controller.esm.js.map