@uipath/ui-widgets-conversational-agent-chat 1.1.0 → 1.1.2

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 (79) hide show
  1. package/dist/ConversationalAgentChat.css +3591 -828
  2. package/dist/ConversationalAgentChat.d.ts +1 -1
  3. package/dist/ConversationalAgentChat.d.ts.map +1 -1
  4. package/dist/ConversationalAgentChat.js +309 -115
  5. package/dist/ConversationalAgentChat.js.map +1 -1
  6. package/dist/ConversationalAgentChat.stories.d.ts +2 -0
  7. package/dist/ConversationalAgentChat.stories.d.ts.map +1 -1
  8. package/dist/components/AgentSchemaForm/AgentSchemaField.d.ts.map +1 -1
  9. package/dist/components/AgentSchemaForm/AgentSchemaField.js +15 -7
  10. package/dist/components/AgentSchemaForm/AgentSchemaField.js.map +1 -1
  11. package/dist/components/AgentSchemaForm/AgentSchemaForm.js +2 -2
  12. package/dist/components/AgentSchemaForm/AgentSchemaForm.js.map +1 -1
  13. package/dist/components/AgentSchemaForm/inputs/ArrayField.d.ts.map +1 -1
  14. package/dist/components/AgentSchemaForm/inputs/ArrayField.js +3 -3
  15. package/dist/components/AgentSchemaForm/inputs/ArrayField.js.map +1 -1
  16. package/dist/components/AgentSchemaForm/inputs/ObjectField.js +2 -2
  17. package/dist/components/AgentSchemaForm/inputs/ObjectField.js.map +1 -1
  18. package/dist/components/ClientSideTool.d.ts +15 -0
  19. package/dist/components/ClientSideTool.d.ts.map +1 -0
  20. package/dist/components/ClientSideTool.js +20 -0
  21. package/dist/components/ClientSideTool.js.map +1 -0
  22. package/dist/components/ClientSideToolRenderer.d.ts +10 -0
  23. package/dist/components/ClientSideToolRenderer.d.ts.map +1 -0
  24. package/dist/components/ClientSideToolRenderer.js +56 -0
  25. package/dist/components/ClientSideToolRenderer.js.map +1 -0
  26. package/dist/components/FeedbackDialog.js +2 -2
  27. package/dist/components/FeedbackDialog.js.map +1 -1
  28. package/dist/components/FilePreviewer.d.ts +16 -0
  29. package/dist/components/FilePreviewer.d.ts.map +1 -0
  30. package/dist/components/FilePreviewer.js +161 -0
  31. package/dist/components/FilePreviewer.js.map +1 -0
  32. package/dist/components/InputsPage.js +3 -3
  33. package/dist/components/InputsPage.js.map +1 -1
  34. package/dist/components/PdfJsViewer.d.ts +7 -0
  35. package/dist/components/PdfJsViewer.d.ts.map +1 -0
  36. package/dist/components/PdfJsViewer.js +220 -0
  37. package/dist/components/PdfJsViewer.js.map +1 -0
  38. package/dist/components/SettingsDialog/InputsSection.js +2 -2
  39. package/dist/components/SettingsDialog/InputsSection.js.map +1 -1
  40. package/dist/components/SettingsDialog/ProfileSection.d.ts.map +1 -1
  41. package/dist/components/SettingsDialog/ProfileSection.js +3 -3
  42. package/dist/components/SettingsDialog/ProfileSection.js.map +1 -1
  43. package/dist/components/SettingsDialog/SettingsDialog.js +2 -2
  44. package/dist/components/SettingsDialog/SettingsDialog.js.map +1 -1
  45. package/dist/components/ToolConfirmationRenderer.d.ts.map +1 -1
  46. package/dist/components/ToolConfirmationRenderer.js +11 -10
  47. package/dist/components/ToolConfirmationRenderer.js.map +1 -1
  48. package/dist/constants/attachments.d.ts +26 -0
  49. package/dist/constants/attachments.d.ts.map +1 -0
  50. package/dist/constants/attachments.js +30 -0
  51. package/dist/constants/attachments.js.map +1 -0
  52. package/dist/hooks/useResolvedAgent.d.ts.map +1 -1
  53. package/dist/hooks/useResolvedAgent.js +8 -9
  54. package/dist/hooks/useResolvedAgent.js.map +1 -1
  55. package/dist/i18n/i18n.config.d.ts +17 -0
  56. package/dist/i18n/i18n.config.d.ts.map +1 -1
  57. package/dist/i18n/i18n.config.js +26 -7
  58. package/dist/i18n/i18n.config.js.map +1 -1
  59. package/dist/i18n/index.d.ts +1 -1
  60. package/dist/i18n/index.d.ts.map +1 -1
  61. package/dist/i18n/index.js +1 -1
  62. package/dist/i18n/index.js.map +1 -1
  63. package/dist/i18n/locales/en/index.json +13 -0
  64. package/dist/i18n/locales/keys/index.json +13 -0
  65. package/dist/i18n/useWidgetTranslation.d.ts +14 -0
  66. package/dist/i18n/useWidgetTranslation.d.ts.map +1 -0
  67. package/dist/i18n/useWidgetTranslation.js +16 -0
  68. package/dist/i18n/useWidgetTranslation.js.map +1 -0
  69. package/dist/types.d.ts +17 -5
  70. package/dist/types.d.ts.map +1 -1
  71. package/dist/types.js +1 -0
  72. package/dist/types.js.map +1 -1
  73. package/dist/utils.d.ts +12 -2
  74. package/dist/utils.d.ts.map +1 -1
  75. package/dist/utils.js +25 -1
  76. package/dist/utils.js.map +1 -1
  77. package/dist/version.d.ts +1 -1
  78. package/dist/version.js +1 -1
  79. package/package.json +4 -3
@@ -1,30 +1,41 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { ApChat, AutopilotChatEvent, AutopilotChatMode, AutopilotChatService, } from "@uipath/apollo-react/material/components";
2
+ import { ApChat, AutopilotChatEvent, AutopilotChatMode, AutopilotChatPreHookAction, AutopilotChatService, } from "@uipath/apollo-react/material/components";
3
3
  import { FontVariantToken } from "@uipath/apollo-core";
4
- import i18next from "i18next";
5
- import { Alert, AlertDescription, Button } from "@uipath/apollo-wind";
4
+ import { Alert, AlertDescription, Button, Column, Dialog, DialogContent, DialogHeader, DialogTitle, PortalContainerProvider, } from "@uipath/apollo-wind";
6
5
  import { ConversationalAgent, FeedbackRating, SortOrder, } from "@uipath/uipath-typescript/conversational-agent";
7
6
  import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, } from "react";
8
7
  import { createRoot } from "react-dom/client";
9
- import { useTranslation } from "react-i18next";
8
+ import { useWidgetTranslation } from "./i18n/useWidgetTranslation";
10
9
  import { InputsPage } from "./components/InputsPage";
11
10
  import { FeedbackDialog } from "./components/FeedbackDialog";
12
11
  import { Loader } from "./components/Loader";
13
12
  import { SettingsDialog } from "./components/SettingsDialog";
14
13
  import { createToolConfirmationRenderer, } from "./components/ToolConfirmationRenderer";
14
+ import { createClientSideToolRenderer, } from "./components/ClientSideToolRenderer";
15
+ import { ALLOWED_ATTACHMENTS } from "./constants/attachments";
15
16
  import "./ConversationalAgentChat.css";
16
17
  import { TelemetryEvent, MessageWidget, TelemetryStatus, } from "./types";
17
- import { convertAttachmentToFile, createFileKey, getConversationHistoryDisplayItems, mapCitationSource, mapExchangesToChatMessages, normalizeInput, sortEvaluationSets, } from "./utils";
18
+ import { convertAttachmentToFile, createFileKey, getConversationHistoryDisplayItems, getFirstRunExperience, mapCitationSource, mapExchangesToChatMessages, normalizeInput, sortEvaluationSets, } from "./utils";
18
19
  import { trackTelemetry } from "./utils/telemetryUtils";
19
- import { initI18n } from "./i18n";
20
+ import { getI18n } from "./i18n";
20
21
  import { resolveAgent as fetchAgentRelease } from "./utils/resolveAgent";
21
- initI18n();
22
+ import FilePreviewer from "./components/FilePreviewer";
23
+ // The widget's own i18next instance — never the shared default one, which a
24
+ // host (Studio Web) may already own. See i18n/i18n.config.ts.
25
+ const i18n = getI18n();
22
26
  const TOOL_CONFIRMATION_WIDGET_ID_PREFIX = "confirmation-";
27
+ // Exchanges per page when lazily loading a conversation's history. Pages are
28
+ // fetched newest-first and prepended as the user scrolls toward the top.
29
+ const EXCHANGES_PAGE_SIZE = 15;
30
+ // Watchdog for a session that never starts: buffered sends only flush on
31
+ // `sessionStarted`, so if it never arrives, surface an error instead of
32
+ // leaving the send silently pending.
33
+ const SESSION_START_TIMEOUT_MS = 30000;
23
34
  // Map widget Locale to Apollo supported locale to allow for locales not supported by Apollo
24
35
  function toApolloSupportedLocale(widgetLocale) {
25
36
  return widgetLocale === "keys" ? "en" : widgetLocale;
26
37
  }
27
- export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConversationId, externalUserId, inputSchema: inputSchemaProp, locale = "en", theme = "light", readOnly = false, overrideLabels, firstRunExperience, disabledFeatures, jobStartOverrides, isDebugMode = false, evaluationSets, addToEvalButtonLabel, onEvaluationSetClicked, onUserMessageSent, surfaceName, surfaceVersion, }) => {
38
+ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConversationId, externalUserId, inputSchema: inputSchemaProp, locale = "en", theme = "light", readOnly = false, overrideLabels, firstRunExperience, disabledFeatures, citationPreview = true, usePdfJsViewer = true, jobStartOverrides, isDebugMode = false, evaluationSets, addToEvalButtonLabel, onEvaluationSetClicked, onUserMessageSent, surfaceName, surfaceVersion, }) => {
28
39
  // `inputSchema` is an internal debug-only override. In normal usage the
29
40
  // schema is resolved from the agent release, so accepting it outside debug
30
41
  // mode would only confuse callers — reject the combination loudly.
@@ -32,10 +43,10 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
32
43
  throw new Error("`inputSchema` is only supported when `isDebugMode` is true; the agent's input schema is resolved automatically.");
33
44
  }
34
45
  // must change language before useTranslation is called to avoid stale translations
35
- if (i18next.language !== locale) {
36
- i18next.changeLanguage(locale);
46
+ if (i18n.language !== locale) {
47
+ i18n.changeLanguage(locale);
37
48
  }
38
- const { t } = useTranslation();
49
+ const { t } = useWidgetTranslation();
39
50
  const agentService = useRef(new ConversationalAgent(sdk, {
40
51
  ...(externalUserId ? { externalUserId } : {}),
41
52
  surfaceName,
@@ -53,6 +64,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
53
64
  const toolConfirmationLabelsRef = useRef(null);
54
65
  // Per-instance so unmounting one widget doesn't tear down another's React roots.
55
66
  const toolConfirmationRenderer = useMemo(() => createToolConfirmationRenderer(), []);
67
+ const clientSideToolRenderer = useMemo(() => createClientSideToolRenderer(), []);
56
68
  // useLayoutEffect is ok here because the work is minimal enough that the cost is essentially zero
57
69
  // needed because React 19 doesn't support ref writes on render
58
70
  useLayoutEffect(() => {
@@ -63,6 +75,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
63
75
  folderIdRef.current = folderId;
64
76
  onEvaluationSetClickedRef.current = onEvaluationSetClicked;
65
77
  onUserMessageSentRef.current = onUserMessageSent;
78
+ citationPreviewRef.current = citationPreview;
66
79
  toolConfirmationLabelsRef.current = {
67
80
  cancel: t("cancel"),
68
81
  confirm: t("tool_confirmation_confirm"),
@@ -76,6 +89,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
76
89
  firstRunExperience,
77
90
  onEvaluationSetClicked,
78
91
  onUserMessageSent,
92
+ citationPreview,
79
93
  folderId,
80
94
  t,
81
95
  ]);
@@ -95,6 +109,9 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
95
109
  const pastConversations = useRef([]);
96
110
  const uploadedAttachments = useRef(new Map());
97
111
  const conversationsCursor = useRef(undefined);
112
+ // Cursor for the active conversation's exchange history. Reset whenever a
113
+ // conversation is opened/started; undefined means no older pages remain.
114
+ const exchangesCursor = useRef(undefined);
98
115
  const agentIdRef = useRef(undefined);
99
116
  const agentKeyRef = useRef(undefined);
100
117
  const searchTextRef = useRef("");
@@ -109,6 +126,9 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
109
126
  const [feedbackDialogOpen, setFeedbackDialogOpen] = useState(false);
110
127
  const [feedbackIsPositive, setFeedbackIsPositive] = useState(false);
111
128
  const pendingFeedback = useRef(null);
129
+ // Citation source-document preview, opened from a citation click.
130
+ const [citationPreviewData, setCitationPreviewData] = useState(null);
131
+ const citationPreviewRef = useRef(citationPreview);
112
132
  const [hasMessages, setHasMessages] = useState(false);
113
133
  const onEvaluationSetClickedRef = useRef(onEvaluationSetClicked);
114
134
  const onUserMessageSentRef = useRef(onUserMessageSent);
@@ -249,12 +269,98 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
249
269
  const toolInput = startEvent.input
250
270
  ? normalizeInput(startEvent.input)
251
271
  : {};
272
+ const { isClientSideTool, outputSchema } = startEvent;
252
273
  pendingToolCalls.set(toolCall.toolCallId, {
253
274
  toolName: startEvent.toolName,
254
275
  toolInput,
255
276
  startTimeIso,
256
277
  spinnerSent: false,
257
278
  });
279
+ const completeToolCallSpinner = (
280
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
281
+ output, isError, cancelled) => {
282
+ if (!pendingToolCalls.has(toolCall.toolCallId))
283
+ return;
284
+ const pending = pendingToolCalls.get(toolCall.toolCallId);
285
+ if (pending && !pending.spinnerSent) {
286
+ sendToolCallSpinner(toolCall.toolCallId);
287
+ }
288
+ const endTimeIso = new Date().toISOString();
289
+ chatService.sendResponse({
290
+ id: toolCall.toolCallId,
291
+ content: t("performing_action_message", {
292
+ action: startEvent.toolName,
293
+ }),
294
+ created_at: endTimeIso,
295
+ widget: MessageWidget.ApolloAgentsToolCall,
296
+ meta: {
297
+ toolName: startEvent.toolName,
298
+ input: toolInput,
299
+ startTime: startTimeIso,
300
+ output,
301
+ endTime: endTimeIso,
302
+ isError,
303
+ ...(cancelled && { cancelled: true }),
304
+ },
305
+ });
306
+ pendingToolCalls.delete(toolCall.toolCallId);
307
+ };
308
+ toolCall.onToolCallEnd((endEvent) => {
309
+ completeToolCallSpinner(endEvent.output, endEvent.isError ?? false);
310
+ });
311
+ // Handle client-side tool execution
312
+ toolCall.onExecutingToolCall(() => {
313
+ if (!isClientSideTool)
314
+ return;
315
+ const clientSideWidgetId = `client-side-tool-${toolCall.toolCallId}`;
316
+ // Build default values from output schema properties
317
+ const outputSchemaObj = (outputSchema ?? {
318
+ type: "object",
319
+ properties: {},
320
+ });
321
+ const outputSchemaProps = outputSchemaObj.properties ?? {};
322
+ const defaultValues = {};
323
+ for (const key of Object.keys(outputSchemaProps)) {
324
+ defaultValues[key] = null;
325
+ }
326
+ chatService.sendResponse({
327
+ id: clientSideWidgetId,
328
+ content: t("performing_action_message", {
329
+ action: startEvent.toolName,
330
+ }),
331
+ created_at: new Date().toISOString(),
332
+ widget: MessageWidget.ClientSideToolInput,
333
+ stream: false,
334
+ done: true,
335
+ meta: {
336
+ toolName: startEvent.toolName,
337
+ inputSchema: outputSchemaObj,
338
+ defaultValues,
339
+ isCompleted: false,
340
+ onSubmit: (formData) => {
341
+ const conversation = chatService.getConversation();
342
+ const messageToUpdate = conversation?.find((m) => m.id === clientSideWidgetId);
343
+ if (messageToUpdate?.meta) {
344
+ messageToUpdate.meta.isCompleted = true;
345
+ }
346
+ completeToolCallSpinner(formData, false);
347
+ toolCall.sendToolCallEnd({
348
+ output: formData,
349
+ isError: false,
350
+ });
351
+ },
352
+ onCancel: () => {
353
+ const conversation = chatService.getConversation();
354
+ const messageToUpdate = conversation?.find((m) => m.id === clientSideWidgetId);
355
+ if (messageToUpdate?.meta) {
356
+ messageToUpdate.meta.isCompleted = true;
357
+ }
358
+ completeToolCallSpinner(null, false, true);
359
+ toolCall.sendToolCallEnd({ cancelled: true });
360
+ },
361
+ },
362
+ });
363
+ });
258
364
  // New flow: confirmation is a property of the tool call itself.
259
365
  if (startEvent.requireConfirmation) {
260
366
  sendToolConfirmationWidget({
@@ -271,6 +377,11 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
271
377
  });
272
378
  },
273
379
  onCancel: () => {
380
+ // For client-side tools, the server suppresses endToolCall
381
+ // so update spinner locally
382
+ if (isClientSideTool) {
383
+ completeToolCallSpinner(null, false, true);
384
+ }
274
385
  toolCall.sendToolCallConfirm({ approved: false });
275
386
  },
276
387
  });
@@ -279,29 +390,6 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
279
390
  // No confirmation needed — show spinner immediately.
280
391
  sendToolCallSpinner(toolCall.toolCallId);
281
392
  }
282
- toolCall.onToolCallEnd((endEvent) => {
283
- const pending = pendingToolCalls.get(toolCall.toolCallId);
284
- if (pending?.spinnerSent) {
285
- const endTimeIso = new Date().toISOString();
286
- chatService.sendResponse({
287
- id: toolCall.toolCallId,
288
- content: t("performing_action_message", {
289
- action: startEvent.toolName,
290
- }),
291
- created_at: endTimeIso,
292
- widget: MessageWidget.ApolloAgentsToolCall,
293
- meta: {
294
- toolName: startEvent.toolName,
295
- input: toolInput,
296
- startTime: startTimeIso,
297
- output: endEvent.output,
298
- endTime: endTimeIso,
299
- isError: endEvent.isError,
300
- },
301
- });
302
- }
303
- pendingToolCalls.delete(toolCall.toolCallId);
304
- });
305
393
  });
306
394
  }
307
395
  });
@@ -387,23 +475,68 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
387
475
  }
388
476
  const conversation = await getConversation();
389
477
  const sessionHelper = agentService.current.conversations.startSession(conversation.id, { echo: false });
478
+ // Mark active before registering handlers so a synchronous sessionStarted
479
+ // can't lose the `session.current === sessionHelper` guard race below.
480
+ session.current = sessionHelper;
390
481
  // Refresh the sidebar label when the service auto-generates one (or the
391
482
  // label is updated via the API). Bind to this session's conversation id
392
483
  // so a stale event from an orphaned session can't mislabel the active one.
393
484
  sessionHelper.onLabelUpdated(({ label }) => {
394
485
  setConversationHistory(pastConversations.current.map((c) => c.id === conversation.id ? { ...c, label } : c));
395
486
  });
396
- return new Promise((resolve) => {
397
- sessionHelper.onSessionStarted(() => {
398
- session.current = sessionHelper;
399
- resolve(sessionHelper);
400
- });
487
+ // Buffer outgoing events until the server confirms the session is started,
488
+ // then flush — so a send never blocks on the sessionStarted round-trip.
489
+ // Combined with ending the session on switch (see endActiveSession), a
490
+ // reopened conversation starts fresh and its buffered send flushes as soon
491
+ // as the fresh sessionStarted arrives.
492
+ sessionHelper.pauseEmits();
493
+ const startTimeout = setTimeout(() => {
494
+ // Ignore a session abandoned by a switch/unmount so it can't error on the
495
+ // now-active conversation. If the active session never started, nothing
496
+ // flushes the buffer — surface an error and clear it so a retry can build
497
+ // a fresh session rather than reusing this permanently-paused one.
498
+ if (session.current !== sessionHelper)
499
+ return;
500
+ if (sessionHelper.isEmitPaused) {
501
+ session.current = null;
502
+ chatService?.setError(t("error_session_start_timeout"));
503
+ }
504
+ }, SESSION_START_TIMEOUT_MS);
505
+ sessionHelper.onSessionStarted(() => {
506
+ clearTimeout(startTimeout);
507
+ if (session.current !== sessionHelper)
508
+ return;
509
+ sessionHelper.resumeEmits();
510
+ });
511
+ sessionHelper.onErrorStart((error) => {
512
+ clearTimeout(startTimeout);
513
+ if (session.current !== sessionHelper)
514
+ return;
515
+ session.current = null;
516
+ chatService?.setError(error.message || t("error_generic"));
401
517
  });
402
- }, [getConversation, setConversationHistory]);
518
+ return sessionHelper;
519
+ }, [chatService, getConversation, setConversationHistory, t]);
520
+ // End the session on conversation switch/unmount so a reopen starts fresh and
521
+ // gets a new `sessionStarted` — reusing a stale session hangs the send. The
522
+ // in-flight exchange is left running (ending it is reserved for onStopResponse),
523
+ // so switching away from a busy conversation and reopening resumes its turn.
524
+ const endActiveSession = useCallback(() => {
525
+ try {
526
+ session.current?.sendSessionEnd();
527
+ }
528
+ catch {
529
+ /* session already closed */
530
+ }
531
+ activeExchange.current = null;
532
+ session.current = null;
533
+ }, []);
403
534
  const onNewChat = useCallback(() => {
535
+ endActiveSession();
404
536
  currentConversation.current = null;
405
537
  session.current = null;
406
538
  activeExchange.current = null;
539
+ exchangesCursor.current = undefined;
407
540
  storedAgentInputs.current = {};
408
541
  setHasMessages(false);
409
542
  // Re-show the InputsPage with a cleared form when the agent's schema has
@@ -414,7 +547,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
414
547
  setShowInputPage(true);
415
548
  }
416
549
  trackTelemetry(TelemetryEvent.NewChat, TelemetryStatus.Success);
417
- }, [inputSchemaState]);
550
+ }, [endActiveSession, inputSchemaState]);
418
551
  const buildHistoryFilterOptions = useCallback(() => {
419
552
  // The SDK's URL builder calls value.toString() without a null check, so
420
553
  // omit any param that is undefined/empty rather than passing it as such.
@@ -573,11 +706,21 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
573
706
  }
574
707
  }
575
708
  }, [chatService, processAttachmentsInBatch, t]);
576
- const fetchExchanges = useCallback(async (conversationId) => {
709
+ // Fetch one page of a conversation's exchanges, newest-first, advancing
710
+ // `exchangesCursor` so the next call returns the chunk immediately older.
711
+ // The returned page is sorted chronologically (ascending) so messages render
712
+ // top-to-bottom; callers prepend each older page above the existing ones.
713
+ const fetchExchanges = useCallback(async (conversationId, cursor) => {
577
714
  const conversation = await agentService.current.conversations.getById(conversationId);
578
- const allExchanges = (await conversation.exchanges.getAll()).items;
579
- allExchanges.sort((a, b) => new Date(a.createdTime).getTime() - new Date(b.createdTime).getTime());
580
- return allExchanges;
715
+ const result = await conversation.exchanges.getAll({
716
+ pageSize: EXCHANGES_PAGE_SIZE,
717
+ exchangeSort: SortOrder.Descending,
718
+ messageSort: SortOrder.Ascending,
719
+ ...(cursor ? { cursor } : {}),
720
+ });
721
+ exchangesCursor.current = result.nextCursor;
722
+ const exchanges = [...result.items].sort((a, b) => new Date(a.createdTime).getTime() - new Date(b.createdTime).getTime());
723
+ return { exchanges, hasNextPage: result.hasNextPage };
581
724
  }, []);
582
725
  const onClickOpenConversation = useCallback(async (id) => {
583
726
  if (!chatService)
@@ -588,10 +731,12 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
588
731
  const selectedConversation = pastConversations.current.find((c) => c.id === id);
589
732
  if (!selectedConversation)
590
733
  return;
734
+ endActiveSession();
591
735
  currentConversation.current = selectedConversation;
592
736
  session.current = null;
593
- const allExchanges = await fetchExchanges(selectedConversation.id);
594
- const messages = mapExchangesToChatMessages(allExchanges);
737
+ exchangesCursor.current = undefined;
738
+ const { exchanges } = await fetchExchanges(selectedConversation.id);
739
+ const messages = mapExchangesToChatMessages(exchanges);
595
740
  chatService.setConversation(messages);
596
741
  setHasMessages(messages.length > 0);
597
742
  trackTelemetry(TelemetryEvent.OpenConversation, TelemetryStatus.Success, {
@@ -606,7 +751,31 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
606
751
  });
607
752
  chatService.setError(t("error_open_conversation", { errorMessage }));
608
753
  }
609
- }, [chatService, fetchExchanges, t]);
754
+ }, [chatService, endActiveSession, fetchExchanges, t]);
755
+ // Apollo fires this when the user scrolls to the top of the message list.
756
+ // Prepend the next older page; signal `done` (no more pages) so Apollo stops
757
+ // requesting once the cursor is exhausted.
758
+ const onConversationLoadMore = useCallback(async () => {
759
+ if (!chatService)
760
+ return;
761
+ const conversationId = currentConversation.current?.id;
762
+ if (!conversationId || !exchangesCursor.current) {
763
+ chatService.prependOlderMessages([], true);
764
+ return;
765
+ }
766
+ try {
767
+ const { exchanges, hasNextPage } = await fetchExchanges(conversationId, exchangesCursor.current);
768
+ chatService.prependOlderMessages(mapExchangesToChatMessages(exchanges), !hasNextPage);
769
+ }
770
+ catch (err) {
771
+ chatService.prependOlderMessages([], true);
772
+ const errorMessage = err instanceof Error ? err.message : String(err);
773
+ trackTelemetry(TelemetryEvent.OpenConversation, TelemetryStatus.Error, {
774
+ conversationId,
775
+ error: errorMessage,
776
+ });
777
+ }
778
+ }, [chatService, fetchExchanges]);
610
779
  const initChat = useCallback(async () => {
611
780
  const initKey = `${agentId}-${folderId}-${existingConversationId ?? ""}-${externalUserId ?? ""}`;
612
781
  try {
@@ -637,30 +806,10 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
637
806
  setAgentNameState(agentName);
638
807
  setShowInputPage(true);
639
808
  }
640
- // If the agent provides any first-run appearance data, show only what
641
- // the agent provides. The `firstRunExperience` prop is a fallback used
642
- // when the agent has no welcome title, description, or starting
643
- // prompts at all — it must not be mixed with partial agent data.
644
- const appearance = agentRelease?.appearance;
645
- const agentSuggestions = (appearance?.startingPrompts ?? []).map((prompt) => ({
646
- label: prompt.displayPrompt,
647
- prompt: prompt.actualPrompt,
648
- }));
649
- const agentHasFre = !!appearance?.welcomeTitle ||
650
- !!appearance?.welcomeDescription ||
651
- agentSuggestions.length > 0;
652
- const hostFallback = firstRunExperienceRef.current;
653
- const firstRunExperienceConfig = agentHasFre
654
- ? {
655
- title: appearance?.welcomeTitle ?? "",
656
- description: appearance?.welcomeDescription ?? "",
657
- suggestions: agentSuggestions,
658
- }
659
- : {
660
- title: hostFallback?.title ?? "",
661
- description: hostFallback?.description ?? "",
662
- suggestions: hostFallback?.suggestions ?? [],
663
- };
809
+ // Resolve the first-run experience: the host-provided config wins so
810
+ // callers can override the welcome copy and starting prompts, falling
811
+ // back to the agent's own appearance.
812
+ const firstRunExperienceConfig = getFirstRunExperience(firstRunExperienceRef.current, agentRelease?.appearance);
664
813
  // Persists agent inputs against the active conversation via
665
814
  // updateConversation. Server-side this applies to all subsequent
666
815
  // messages; we don't prepend per send.
@@ -691,7 +840,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
691
840
  : "no-agent";
692
841
  const conversationId = currentConversation.current?.id ?? "no-conv";
693
842
  const inputsResetKey = `${profileResetKey}-${conversationId}`;
694
- root.render(_jsx(SettingsDialog, { profileResetKey: profileResetKey, conversationalAgent: agentService.current, onClose: () => chatServiceRef.current?.toggleSettings(false), inputSchema: inputSchemaStateRef.current, initialInputs: storedAgentInputs.current, onApplyInputs: handleApplySettingsInputs, inputsResetKey: inputsResetKey }));
843
+ root.render(_jsx(PortalContainerProvider, { children: _jsx(SettingsDialog, { profileResetKey: profileResetKey, conversationalAgent: agentService.current, onClose: () => chatServiceRef.current?.toggleSettings(false), inputSchema: inputSchemaStateRef.current, initialInputs: storedAgentInputs.current, onApplyInputs: handleApplySettingsInputs, inputsResetKey: inputsResetKey }) }));
695
844
  };
696
845
  const chatServiceInstance = AutopilotChatService.Instantiate({
697
846
  instanceName: `agent-${agentId}-${folderId}`,
@@ -700,7 +849,11 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
700
849
  locale: toApolloSupportedLocale(locale),
701
850
  theme: themeRef.current,
702
851
  readOnly,
703
- firstRunExperience: firstRunExperienceConfig,
852
+ firstRunExperience: firstRunExperienceConfig && {
853
+ title: firstRunExperienceConfig.title ?? "",
854
+ description: firstRunExperienceConfig.description ?? "",
855
+ suggestions: firstRunExperienceConfig.suggestions ?? [],
856
+ },
704
857
  overrideLabels: {
705
858
  title: overrideLabelsRef.current?.title ?? agentName,
706
859
  footerDisclaimer: overrideLabelsRef.current?.footerDisclaimer ??
@@ -709,7 +862,50 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
709
862
  t("chat_input_placeholder"),
710
863
  },
711
864
  paginatedHistory: true,
865
+ paginatedMessages: true,
712
866
  settingsRenderer: renderSettings,
867
+ preHooks: {
868
+ [AutopilotChatPreHookAction.CitationClick]: async (citationData) => {
869
+ // When preview is disabled, or the citation is not a
870
+ // context-grounding citation (no download_url to a source
871
+ // document), fall through to Apollo's default handling.
872
+ if (!citationPreviewRef.current)
873
+ return true;
874
+ const { citation } = citationData;
875
+ if (!citation?.download_url)
876
+ return true;
877
+ const pageNumber = Number(citation.page_number) || 1;
878
+ try {
879
+ const blob = await agentService.current.downloadCitationSource({
880
+ title: citation.title,
881
+ number: citation.number ?? citation.id ?? 0,
882
+ downloadUrl: citation.download_url,
883
+ pageNumber: String(pageNumber),
884
+ });
885
+ const file = new File([blob], citation.title, {
886
+ type: blob.type,
887
+ });
888
+ setCitationPreviewData({
889
+ file,
890
+ title: citation.title,
891
+ pageNumber,
892
+ });
893
+ }
894
+ catch (e) {
895
+ // Consume the click and surface the error in-dialog. Falling
896
+ // through to Apollo's default would re-open the auth-gated
897
+ // download_url in a new tab, which is exactly the 401 this
898
+ // preview replaces.
899
+ console.error("Failed to load citation document", e);
900
+ setCitationPreviewData({
901
+ title: citation.title,
902
+ pageNumber,
903
+ error: true,
904
+ });
905
+ }
906
+ return false;
907
+ },
908
+ },
713
909
  // Apollo's ApChat defaults message text to fontSizeM (14px); the
714
910
  // deprecated portal-shell chat used a larger size, so bump primary
715
911
  // text and markdown body tokens to fontSizeL (16px) to match.
@@ -741,10 +937,14 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
741
937
  },
742
938
  });
743
939
  chatServiceRef.current = chatServiceInstance;
940
+ if (!disabledFeaturesRef.current?.attachments) {
941
+ chatServiceInstance.setAllowedAttachments(ALLOWED_ATTACHMENTS);
942
+ }
744
943
  if (existingConversationId) {
745
944
  const conversation = await getConversation();
746
- const allExchanges = await fetchExchanges(conversation.id);
747
- chatServiceInstance.setConversation(mapExchangesToChatMessages(allExchanges));
945
+ exchangesCursor.current = undefined;
946
+ const { exchanges } = await fetchExchanges(conversation.id);
947
+ chatServiceInstance.setConversation(mapExchangesToChatMessages(exchanges));
748
948
  }
749
949
  else {
750
950
  // AutopilotChatService is a singleton, so it may still hold the
@@ -844,9 +1044,6 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
844
1044
  useEffect(() => {
845
1045
  const initKey = `${agentId}-${folderId}-${existingConversationId ?? ""}-${externalUserId ?? ""}`;
846
1046
  if (initializedFor.current !== initKey) {
847
- // initChat is async; its setStates run after awaits, not synchronously
848
- // inside the effect body. The lint rule can't see that.
849
- // eslint-disable-next-line react-hooks/set-state-in-effect
850
1047
  initChat();
851
1048
  }
852
1049
  }, [agentId, folderId, existingConversationId, externalUserId, initChat]);
@@ -864,28 +1061,16 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
864
1061
  // Close the SDK session on unmount so the WebSocket doesn't linger.
865
1062
  useEffect(() => {
866
1063
  return () => {
867
- try {
868
- activeExchange.current?.sendExchangeEnd();
869
- }
870
- catch {
871
- /* exchange already ended */
872
- }
873
- try {
874
- session.current?.sendSessionEnd();
875
- }
876
- catch {
877
- /* session already closed */
878
- }
879
- activeExchange.current = null;
880
- session.current = null;
1064
+ endActiveSession();
881
1065
  };
882
- }, []);
883
- // Release React state held by the imperative tool-confirmation roots.
1066
+ }, [endActiveSession]);
1067
+ // Release React state held by the imperative tool-confirmation and client-side tool roots.
884
1068
  useEffect(() => {
885
1069
  return () => {
886
1070
  toolConfirmationRenderer.unmountAll();
1071
+ clientSideToolRenderer.unmountAll();
887
1072
  };
888
- }, [toolConfirmationRenderer]);
1073
+ }, [toolConfirmationRenderer, clientSideToolRenderer]);
889
1074
  // Register event handlers after chatService is available
890
1075
  useEffect(() => {
891
1076
  if (!chatService)
@@ -900,11 +1085,15 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
900
1085
  if (cancelled)
901
1086
  return;
902
1087
  }
903
- unsubscribers.push(chatService.on(AutopilotChatEvent.NewChat, onNewChat), chatService.on(AutopilotChatEvent.Request, onSendMessage), chatService.on(AutopilotChatEvent.SetAttachments, onSetAttachments), chatService.on(AutopilotChatEvent.OpenConversation, onClickOpenConversation), chatService.on(AutopilotChatEvent.DeleteConversation, onClickDeleteConversation), chatService.on(AutopilotChatEvent.HistoryLoadMore, onHistoryLoadMore), chatService.on(AutopilotChatEvent.HistorySearch, onHistorySearch), chatService.on(AutopilotChatEvent.Feedback, onFeedback), chatService.on(AutopilotChatEvent.StopResponse, onStopResponse));
1088
+ unsubscribers.push(chatService.on(AutopilotChatEvent.NewChat, onNewChat), chatService.on(AutopilotChatEvent.Request, onSendMessage), chatService.on(AutopilotChatEvent.SetAttachments, onSetAttachments), chatService.on(AutopilotChatEvent.OpenConversation, onClickOpenConversation), chatService.on(AutopilotChatEvent.DeleteConversation, onClickDeleteConversation), chatService.on(AutopilotChatEvent.HistoryLoadMore, onHistoryLoadMore), chatService.on(AutopilotChatEvent.ConversationLoadMore, onConversationLoadMore), chatService.on(AutopilotChatEvent.HistorySearch, onHistorySearch), chatService.on(AutopilotChatEvent.Feedback, onFeedback), chatService.on(AutopilotChatEvent.StopResponse, onStopResponse));
904
1089
  chatService.injectMessageRenderer({
905
1090
  name: MessageWidget.ToolConfirmation,
906
1091
  render: (container, message) => toolConfirmationRenderer.render(container, message, toolConfirmationLabelsRef.current ?? undefined),
907
1092
  });
1093
+ chatService.injectMessageRenderer({
1094
+ name: MessageWidget.ClientSideToolInput,
1095
+ render: (container, message) => clientSideToolRenderer.render(container, message),
1096
+ });
908
1097
  }
909
1098
  catch (err) {
910
1099
  const message = err instanceof Error ? err.message : t("error_load_history");
@@ -923,6 +1112,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
923
1112
  folderId,
924
1113
  onClickDeleteConversation,
925
1114
  onClickOpenConversation,
1115
+ onConversationLoadMore,
926
1116
  onFeedback,
927
1117
  onHistoryLoadMore,
928
1118
  onHistorySearch,
@@ -932,6 +1122,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
932
1122
  onStopResponse,
933
1123
  t,
934
1124
  toolConfirmationRenderer,
1125
+ clientSideToolRenderer,
935
1126
  ]);
936
1127
  useEffect(() => {
937
1128
  if (!chatService ||
@@ -968,24 +1159,27 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
968
1159
  onCustomHeaderActionClicked,
969
1160
  t,
970
1161
  ]);
971
- return (_jsxs("div", { className: "uipath-conversational-agent-chat", children: [!error && showInputPage && inputSchemaState && (_jsx(InputsPage, { agentName: agentNameState, inputSchema: inputSchemaState, onSubmit: async (data) => {
972
- const inputs = data;
973
- if (isDebugMode && existingConversationId) {
974
- await agentService.current.conversations.updateById(existingConversationId, { agentInput: { inline: inputs } });
975
- }
976
- else {
977
- const agent = await resolveAgent();
978
- if (!agent) {
979
- throw new Error(t("error_missing_conversation_params"));
1162
+ return (_jsx("div", { className: "uipath-conversational-agent-chat", children: _jsxs(PortalContainerProvider, { children: [!error && showInputPage && inputSchemaState && (_jsx(InputsPage, { agentName: agentNameState, inputSchema: inputSchemaState, onSubmit: async (data) => {
1163
+ const inputs = data;
1164
+ if (isDebugMode && existingConversationId) {
1165
+ await agentService.current.conversations.updateById(existingConversationId, { agentInput: { inline: inputs } });
980
1166
  }
981
- const conversation = await agent.conversations.create({
982
- ...(jobStartOverrides ? { jobStartOverrides } : {}),
983
- agentInput: { inline: inputs },
984
- });
985
- currentConversation.current = conversation;
986
- }
987
- storedAgentInputs.current = inputs;
988
- setShowInputPage(false);
989
- } }, `${agentId}-${inputsInstance}`)), error && (_jsxs("div", { className: "info-container", children: [_jsx(Alert, { variant: "destructive", children: _jsx(AlertDescription, { children: error }) }), _jsx(Button, { variant: "outline", onClick: handleReload, children: t("reload") })] })), !error && !chatService && (_jsxs("div", { className: "info-container", children: [_jsx("div", { children: t("loading") }), _jsx(Loader, {})] })), !error && chatService && !showInputPage && (_jsx(ApChat, { chatServiceInstance: chatService, locale: toApolloSupportedLocale(locale), theme: theme, enableInternalThemeProvider: true }, locale)), _jsx(FeedbackDialog, { open: feedbackDialogOpen, isPositive: feedbackIsPositive, onOpenChange: setFeedbackDialogOpen, onSubmit: onFeedbackSubmit, onCancel: onFeedbackCancel })] }));
1167
+ else {
1168
+ const agent = await resolveAgent();
1169
+ if (!agent) {
1170
+ throw new Error(t("error_missing_conversation_params"));
1171
+ }
1172
+ const conversation = await agent.conversations.create({
1173
+ ...(jobStartOverrides ? { jobStartOverrides } : {}),
1174
+ agentInput: { inline: inputs },
1175
+ });
1176
+ currentConversation.current = conversation;
1177
+ }
1178
+ storedAgentInputs.current = inputs;
1179
+ setShowInputPage(false);
1180
+ } }, `${agentId}-${inputsInstance}`)), error && (_jsxs("div", { className: "info-container", children: [_jsx(Alert, { variant: "destructive", children: _jsx(AlertDescription, { children: error }) }), _jsx(Button, { variant: "outline", onClick: handleReload, children: t("reload") })] })), !error && !chatService && (_jsxs("div", { className: "info-container", children: [_jsx("div", { children: t("loading") }), _jsx(Loader, {})] })), !error && chatService && !showInputPage && (_jsx(ApChat, { chatServiceInstance: chatService, locale: toApolloSupportedLocale(locale), theme: theme, enableInternalThemeProvider: true }, locale)), _jsx(FeedbackDialog, { open: feedbackDialogOpen, isPositive: feedbackIsPositive, onOpenChange: setFeedbackDialogOpen, onSubmit: onFeedbackSubmit, onCancel: onFeedbackCancel }), _jsx(Dialog, { open: !!citationPreviewData, onOpenChange: (open) => {
1181
+ if (!open)
1182
+ setCitationPreviewData(null);
1183
+ }, children: citationPreviewData && (_jsxs(DialogContent, { className: "sm:max-w-4xl", children: [_jsx(DialogHeader, { children: _jsx(DialogTitle, { children: citationPreviewData.title }) }), citationPreviewData.error ? (_jsx(Column, { w: "full", align: "center", justify: "center", style: { height: "60vh", maxHeight: "600px" }, children: t("file_preview_error") })) : (_jsx(FilePreviewer, { file: citationPreviewData.file, usePdfJs: usePdfJsViewer, pageNumber: citationPreviewData.pageNumber, iframeParams: `#page=${citationPreviewData.pageNumber}` }))] })) })] }) }));
990
1184
  };
991
1185
  //# sourceMappingURL=ConversationalAgentChat.js.map