@uipath/ui-widgets-conversational-agent-chat 1.0.3 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/README.md +10 -6
  2. package/dist/ConversationalAgentChat.css +6406 -3113
  3. package/dist/ConversationalAgentChat.d.ts +1 -1
  4. package/dist/ConversationalAgentChat.d.ts.map +1 -1
  5. package/dist/ConversationalAgentChat.js +746 -181
  6. package/dist/ConversationalAgentChat.js.map +1 -1
  7. package/dist/ConversationalAgentChat.stories.d.ts +16 -1
  8. package/dist/ConversationalAgentChat.stories.d.ts.map +1 -1
  9. package/dist/ConversationalAgentChat.stories.js +5 -12
  10. package/dist/ConversationalAgentChat.stories.js.map +1 -1
  11. package/dist/components/AgentList.d.ts.map +1 -1
  12. package/dist/components/AgentList.js.map +1 -1
  13. package/dist/components/AgentSchemaForm/AgentSchemaField.d.ts +26 -0
  14. package/dist/components/AgentSchemaForm/AgentSchemaField.d.ts.map +1 -0
  15. package/dist/components/AgentSchemaForm/AgentSchemaField.js +104 -0
  16. package/dist/components/AgentSchemaForm/AgentSchemaField.js.map +1 -0
  17. package/dist/components/AgentSchemaForm/AgentSchemaForm.d.ts +38 -0
  18. package/dist/components/AgentSchemaForm/AgentSchemaForm.d.ts.map +1 -0
  19. package/dist/components/AgentSchemaForm/AgentSchemaForm.js +105 -0
  20. package/dist/components/AgentSchemaForm/AgentSchemaForm.js.map +1 -0
  21. package/dist/components/AgentSchemaForm/AgentSchemaForm.stories.d.ts +30 -0
  22. package/dist/components/AgentSchemaForm/AgentSchemaForm.stories.d.ts.map +1 -0
  23. package/dist/components/AgentSchemaForm/AgentSchemaForm.stories.js +236 -0
  24. package/dist/components/AgentSchemaForm/AgentSchemaForm.stories.js.map +1 -0
  25. package/dist/components/AgentSchemaForm/FieldShell.d.ts +12 -0
  26. package/dist/components/AgentSchemaForm/FieldShell.d.ts.map +1 -0
  27. package/dist/components/AgentSchemaForm/FieldShell.js +4 -0
  28. package/dist/components/AgentSchemaForm/FieldShell.js.map +1 -0
  29. package/dist/components/AgentSchemaForm/index.d.ts +5 -0
  30. package/dist/components/AgentSchemaForm/index.d.ts.map +1 -0
  31. package/dist/components/AgentSchemaForm/index.js +2 -0
  32. package/dist/components/AgentSchemaForm/index.js.map +1 -0
  33. package/dist/components/AgentSchemaForm/inputs/ArrayField.d.ts +7 -0
  34. package/dist/components/AgentSchemaForm/inputs/ArrayField.d.ts.map +1 -0
  35. package/dist/components/AgentSchemaForm/inputs/ArrayField.js +28 -0
  36. package/dist/components/AgentSchemaForm/inputs/ArrayField.js.map +1 -0
  37. package/dist/components/AgentSchemaForm/inputs/ObjectField.d.ts +8 -0
  38. package/dist/components/AgentSchemaForm/inputs/ObjectField.d.ts.map +1 -0
  39. package/dist/components/AgentSchemaForm/inputs/ObjectField.js +75 -0
  40. package/dist/components/AgentSchemaForm/inputs/ObjectField.js.map +1 -0
  41. package/dist/components/AgentSchemaForm/inputs/validation.d.ts +10 -0
  42. package/dist/components/AgentSchemaForm/inputs/validation.d.ts.map +1 -0
  43. package/dist/components/AgentSchemaForm/inputs/validation.js +41 -0
  44. package/dist/components/AgentSchemaForm/inputs/validation.js.map +1 -0
  45. package/dist/components/AgentSchemaForm/resolveSchema.d.ts +7 -0
  46. package/dist/components/AgentSchemaForm/resolveSchema.d.ts.map +1 -0
  47. package/dist/components/AgentSchemaForm/resolveSchema.js +162 -0
  48. package/dist/components/AgentSchemaForm/resolveSchema.js.map +1 -0
  49. package/dist/components/AgentSchemaForm/types.d.ts +34 -0
  50. package/dist/components/AgentSchemaForm/types.d.ts.map +1 -0
  51. package/dist/components/AgentSchemaForm/types.js +8 -0
  52. package/dist/components/AgentSchemaForm/types.js.map +1 -0
  53. package/dist/components/FeedbackDialog.d.ts +2 -1
  54. package/dist/components/FeedbackDialog.d.ts.map +1 -1
  55. package/dist/components/FeedbackDialog.js +6 -2
  56. package/dist/components/FeedbackDialog.js.map +1 -1
  57. package/dist/components/FilePreviewer.d.ts +16 -0
  58. package/dist/components/FilePreviewer.d.ts.map +1 -0
  59. package/dist/components/FilePreviewer.js +161 -0
  60. package/dist/components/FilePreviewer.js.map +1 -0
  61. package/dist/components/InputsPage.d.ts +18 -0
  62. package/dist/components/InputsPage.d.ts.map +1 -0
  63. package/dist/components/InputsPage.js +32 -0
  64. package/dist/components/InputsPage.js.map +1 -0
  65. package/dist/components/Loader.d.ts +6 -0
  66. package/dist/components/Loader.d.ts.map +1 -0
  67. package/dist/components/Loader.js +6 -0
  68. package/dist/components/Loader.js.map +1 -0
  69. package/dist/components/PdfJsViewer.d.ts +7 -0
  70. package/dist/components/PdfJsViewer.d.ts.map +1 -0
  71. package/dist/components/PdfJsViewer.js +220 -0
  72. package/dist/components/PdfJsViewer.js.map +1 -0
  73. package/dist/components/SettingsDialog/InputsSection.d.ts +15 -0
  74. package/dist/components/SettingsDialog/InputsSection.d.ts.map +1 -0
  75. package/dist/components/SettingsDialog/InputsSection.js +29 -0
  76. package/dist/components/SettingsDialog/InputsSection.js.map +1 -0
  77. package/dist/components/SettingsDialog/ProfileSection.d.ts +7 -0
  78. package/dist/components/SettingsDialog/ProfileSection.d.ts.map +1 -0
  79. package/dist/components/SettingsDialog/ProfileSection.js +146 -0
  80. package/dist/components/SettingsDialog/ProfileSection.js.map +1 -0
  81. package/dist/components/SettingsDialog/SettingsDialog.d.ts +33 -0
  82. package/dist/components/SettingsDialog/SettingsDialog.d.ts.map +1 -0
  83. package/dist/components/SettingsDialog/SettingsDialog.js +18 -0
  84. package/dist/components/SettingsDialog/SettingsDialog.js.map +1 -0
  85. package/dist/components/SettingsDialog/index.d.ts +3 -0
  86. package/dist/components/SettingsDialog/index.d.ts.map +1 -0
  87. package/dist/components/SettingsDialog/index.js +2 -0
  88. package/dist/components/SettingsDialog/index.js.map +1 -0
  89. package/dist/components/ToolConfirmation.d.ts +20 -0
  90. package/dist/components/ToolConfirmation.d.ts.map +1 -0
  91. package/dist/components/ToolConfirmation.js +20 -0
  92. package/dist/components/ToolConfirmation.js.map +1 -0
  93. package/dist/components/ToolConfirmationRenderer.d.ts +15 -0
  94. package/dist/components/ToolConfirmationRenderer.d.ts.map +1 -0
  95. package/dist/components/ToolConfirmationRenderer.js +53 -0
  96. package/dist/components/ToolConfirmationRenderer.js.map +1 -0
  97. package/dist/constants/attachments.d.ts +26 -0
  98. package/dist/constants/attachments.d.ts.map +1 -0
  99. package/dist/constants/attachments.js +30 -0
  100. package/dist/constants/attachments.js.map +1 -0
  101. package/dist/constants/countries.d.ts +251 -0
  102. package/dist/constants/countries.d.ts.map +1 -0
  103. package/dist/constants/countries.js +250 -0
  104. package/dist/constants/countries.js.map +1 -0
  105. package/dist/hooks/useResolvedAgent.d.ts +34 -0
  106. package/dist/hooks/useResolvedAgent.d.ts.map +1 -0
  107. package/dist/hooks/useResolvedAgent.js +99 -0
  108. package/dist/hooks/useResolvedAgent.js.map +1 -0
  109. package/dist/i18n/i18n.config.d.ts +2 -0
  110. package/dist/i18n/i18n.config.d.ts.map +1 -0
  111. package/dist/i18n/i18n.config.js +24 -0
  112. package/dist/i18n/i18n.config.js.map +1 -0
  113. package/dist/i18n/index.d.ts +2 -0
  114. package/dist/i18n/index.d.ts.map +1 -0
  115. package/dist/i18n/index.js +2 -0
  116. package/dist/i18n/index.js.map +1 -0
  117. package/dist/i18n/locales/en/index.json +317 -0
  118. package/dist/i18n/locales/keys/index.json +317 -0
  119. package/dist/icons/ConversationalAgentIcon.d.ts +7 -0
  120. package/dist/icons/ConversationalAgentIcon.d.ts.map +1 -0
  121. package/dist/icons/ConversationalAgentIcon.js +8 -0
  122. package/dist/icons/ConversationalAgentIcon.js.map +1 -0
  123. package/dist/icons/TimeIcon.d.ts +2 -0
  124. package/dist/icons/TimeIcon.d.ts.map +1 -0
  125. package/dist/icons/TimeIcon.js +3 -0
  126. package/dist/icons/TimeIcon.js.map +1 -0
  127. package/dist/index.d.ts +9 -1
  128. package/dist/index.d.ts.map +1 -1
  129. package/dist/index.js +3 -0
  130. package/dist/index.js.map +1 -1
  131. package/dist/types.d.ts +84 -2
  132. package/dist/types.d.ts.map +1 -1
  133. package/dist/types.js.map +1 -1
  134. package/dist/utils/normalizeValue.d.ts +7 -0
  135. package/dist/utils/normalizeValue.d.ts.map +1 -0
  136. package/dist/utils/normalizeValue.js +31 -0
  137. package/dist/utils/normalizeValue.js.map +1 -0
  138. package/dist/utils/resolveAgent.d.ts +17 -0
  139. package/dist/utils/resolveAgent.d.ts.map +1 -0
  140. package/dist/utils/resolveAgent.js +25 -0
  141. package/dist/utils/resolveAgent.js.map +1 -0
  142. package/dist/utils/telemetryUtils.d.ts +1 -1
  143. package/dist/utils/telemetryUtils.d.ts.map +1 -1
  144. package/dist/utils/telemetryUtils.js +2 -2
  145. package/dist/utils/telemetryUtils.js.map +1 -1
  146. package/dist/utils.d.ts +21 -3
  147. package/dist/utils.d.ts.map +1 -1
  148. package/dist/utils.js +61 -10
  149. package/dist/utils.js.map +1 -1
  150. package/dist/version.d.ts +1 -1
  151. package/dist/version.js +1 -1
  152. package/package.json +11 -5
@@ -1,43 +1,145 @@
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";
3
- import { i18n } from "@lingui/core";
4
- import { Alert, AlertDescription, Button } from "@uipath/apollo-wind";
2
+ import { ApChat, AutopilotChatEvent, AutopilotChatMode, AutopilotChatPreHookAction, AutopilotChatService, } from "@uipath/apollo-react/material/components";
3
+ import { FontVariantToken } from "@uipath/apollo-core";
4
+ import i18next from "i18next";
5
+ import { Alert, AlertDescription, Button, Column, Dialog, DialogContent, DialogHeader, DialogTitle, PortalContainerProvider, } from "@uipath/apollo-wind";
5
6
  import { ConversationalAgent, FeedbackRating, SortOrder, } from "@uipath/uipath-typescript/conversational-agent";
6
- import { useCallback, useEffect, useLayoutEffect, useRef, useState, } from "react";
7
+ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, } from "react";
8
+ import { createRoot } from "react-dom/client";
9
+ import { useTranslation } from "react-i18next";
10
+ import { InputsPage } from "./components/InputsPage";
7
11
  import { FeedbackDialog } from "./components/FeedbackDialog";
12
+ import { Loader } from "./components/Loader";
13
+ import { SettingsDialog } from "./components/SettingsDialog";
14
+ import { createToolConfirmationRenderer, } from "./components/ToolConfirmationRenderer";
15
+ import { ALLOWED_ATTACHMENTS } from "./constants/attachments";
8
16
  import "./ConversationalAgentChat.css";
9
17
  import { TelemetryEvent, MessageWidget, TelemetryStatus, } from "./types";
10
- import { convertAttachmentToFile, createFileKey, getConversationHistoryDisplayItems, mapExchangesToChatMessages, normalizeInput, } from "./utils";
18
+ import { convertAttachmentToFile, createFileKey, getConversationHistoryDisplayItems, getFirstRunExperience, mapCitationSource, mapExchangesToChatMessages, normalizeInput, sortEvaluationSets, } from "./utils";
11
19
  import { trackTelemetry } from "./utils/telemetryUtils";
12
- const DEFAULT_FOOTER_DISCLAIMER = "Agent can make mistakes. Please double check the responses.";
13
- const DEFAULT_INPUT_PLACEHOLDER = "Talk with your agent...";
14
- export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConversationId, locale = "en", theme = "light", readOnly = false, overrideLabels, firstRunExperience, disabledFeatures, onUserMessageSent, }) => {
15
- const agentService = useRef(new ConversationalAgent(sdk));
20
+ import { initI18n } from "./i18n";
21
+ import { resolveAgent as fetchAgentRelease } from "./utils/resolveAgent";
22
+ import FilePreviewer from "./components/FilePreviewer";
23
+ initI18n();
24
+ const TOOL_CONFIRMATION_WIDGET_ID_PREFIX = "confirmation-";
25
+ // Exchanges per page when lazily loading a conversation's history. Pages are
26
+ // fetched newest-first and prepended as the user scrolls toward the top.
27
+ const EXCHANGES_PAGE_SIZE = 15;
28
+ // Watchdog for a session that never starts: buffered sends only flush on
29
+ // `sessionStarted`, so if it never arrives, surface an error instead of
30
+ // leaving the send silently pending.
31
+ const SESSION_START_TIMEOUT_MS = 30000;
32
+ // Map widget Locale to Apollo supported locale to allow for locales not supported by Apollo
33
+ function toApolloSupportedLocale(widgetLocale) {
34
+ return widgetLocale === "keys" ? "en" : widgetLocale;
35
+ }
36
+ 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, }) => {
37
+ // `inputSchema` is an internal debug-only override. In normal usage the
38
+ // schema is resolved from the agent release, so accepting it outside debug
39
+ // mode would only confuse callers — reject the combination loudly.
40
+ if (inputSchemaProp && !isDebugMode) {
41
+ throw new Error("`inputSchema` is only supported when `isDebugMode` is true; the agent's input schema is resolved automatically.");
42
+ }
43
+ // must change language before useTranslation is called to avoid stale translations
44
+ if (i18next.language !== locale) {
45
+ i18next.changeLanguage(locale);
46
+ }
47
+ const { t } = useTranslation();
48
+ const agentService = useRef(new ConversationalAgent(sdk, {
49
+ ...(externalUserId ? { externalUserId } : {}),
50
+ surfaceName,
51
+ surfaceVersion,
52
+ }));
16
53
  const currentConversation = useRef(null);
17
54
  const initializedFor = useRef(null);
18
- // Refs for values used in initChat that shouldn't trigger re-initialization
19
- const localeRef = useRef(locale);
20
- localeRef.current = locale;
21
55
  const themeRef = useRef(theme);
22
- themeRef.current = theme;
23
56
  const overrideLabelsRef = useRef(overrideLabels);
24
- overrideLabelsRef.current = overrideLabels;
25
57
  const disabledFeaturesRef = useRef(disabledFeatures);
26
- disabledFeaturesRef.current = disabledFeatures;
27
58
  const firstRunExperienceRef = useRef(firstRunExperience);
28
- firstRunExperienceRef.current = firstRunExperience;
29
- const onUserMessageSentRef = useRef(onUserMessageSent);
30
- onUserMessageSentRef.current = onUserMessageSent;
31
59
  const initialConversationConsumed = useRef(false);
60
+ const resolvedAgent = useRef(null);
61
+ const folderIdRef = useRef(folderId);
62
+ const toolConfirmationLabelsRef = useRef(null);
63
+ // Per-instance so unmounting one widget doesn't tear down another's React roots.
64
+ const toolConfirmationRenderer = useMemo(() => createToolConfirmationRenderer(), []);
65
+ // useLayoutEffect is ok here because the work is minimal enough that the cost is essentially zero
66
+ // needed because React 19 doesn't support ref writes on render
67
+ useLayoutEffect(() => {
68
+ themeRef.current = theme;
69
+ overrideLabelsRef.current = overrideLabels;
70
+ disabledFeaturesRef.current = disabledFeatures;
71
+ firstRunExperienceRef.current = firstRunExperience;
72
+ folderIdRef.current = folderId;
73
+ onEvaluationSetClickedRef.current = onEvaluationSetClicked;
74
+ onUserMessageSentRef.current = onUserMessageSent;
75
+ citationPreviewRef.current = citationPreview;
76
+ toolConfirmationLabelsRef.current = {
77
+ cancel: t("cancel"),
78
+ confirm: t("tool_confirmation_confirm"),
79
+ statusCancelled: t("tool_confirmation_status_cancelled"),
80
+ statusConfirmed: t("tool_confirmation_status_confirmed"),
81
+ };
82
+ }, [
83
+ theme,
84
+ overrideLabels,
85
+ disabledFeatures,
86
+ firstRunExperience,
87
+ onEvaluationSetClicked,
88
+ onUserMessageSent,
89
+ citationPreview,
90
+ folderId,
91
+ t,
92
+ ]);
93
+ // Rebuild the SDK service when sdk or externalUserId change. Skip the first run because the
94
+ // useRef initializer above already built it with the initial values. The chat is re-initialized
95
+ // via initKey (which includes externalUserId) so dependent refs (session, currentConversation,
96
+ // activeExchange) are reset by onNewChat / initChat downstream.
97
+ const didMountAgentServiceRef = useRef(false);
98
+ useLayoutEffect(() => {
99
+ if (!didMountAgentServiceRef.current) {
100
+ didMountAgentServiceRef.current = true;
101
+ return;
102
+ }
103
+ agentService.current = new ConversationalAgent(sdk, externalUserId ? { externalUserId } : undefined);
104
+ }, [sdk, externalUserId]);
32
105
  const session = useRef(null);
33
106
  const pastConversations = useRef([]);
34
107
  const uploadedAttachments = useRef(new Map());
35
108
  const conversationsCursor = useRef(undefined);
109
+ // Cursor for the active conversation's exchange history. Reset whenever a
110
+ // conversation is opened/started; undefined means no older pages remain.
111
+ const exchangesCursor = useRef(undefined);
112
+ const agentIdRef = useRef(undefined);
113
+ const agentKeyRef = useRef(undefined);
114
+ const searchTextRef = useRef("");
36
115
  const [chatService, setChatService] = useState();
37
116
  const [error, setError] = useState(null);
117
+ const [inputSchemaState, setInputSchemaState] = useState(null);
118
+ const [showInputPage, setShowInputPage] = useState(false);
119
+ const [agentNameState, setAgentNameState] = useState("");
120
+ // Bumped on New Chat to force a fresh <InputsPage> mount with cleared form state.
121
+ const [inputsInstance, setInputsInstance] = useState(0);
38
122
  const activeExchange = useRef(null);
39
123
  const [feedbackDialogOpen, setFeedbackDialogOpen] = useState(false);
124
+ const [feedbackIsPositive, setFeedbackIsPositive] = useState(false);
40
125
  const pendingFeedback = useRef(null);
126
+ // Citation source-document preview, opened from a citation click.
127
+ const [citationPreviewData, setCitationPreviewData] = useState(null);
128
+ const citationPreviewRef = useRef(citationPreview);
129
+ const [hasMessages, setHasMessages] = useState(false);
130
+ const onEvaluationSetClickedRef = useRef(onEvaluationSetClicked);
131
+ const onUserMessageSentRef = useRef(onUserMessageSent);
132
+ const chatServiceRef = useRef(null);
133
+ const settingsRootRef = useRef(null);
134
+ // Last-applied agent inputs for the active conversation. Pre-populates the
135
+ // settings inputs form when reopened; cleared on New Chat.
136
+ const storedAgentInputs = useRef({});
137
+ // Mirrors `inputSchemaState` so the imperative `renderSettings` closure always
138
+ // sees the current schema without re-instantiating the chat service.
139
+ const inputSchemaStateRef = useRef(null);
140
+ useLayoutEffect(() => {
141
+ inputSchemaStateRef.current = inputSchemaState;
142
+ }, [inputSchemaState]);
41
143
  const setupExchangeHandlers = useCallback((exchange) => {
42
144
  if (!chatService)
43
145
  return;
@@ -45,71 +147,177 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
45
147
  trackTelemetry(TelemetryEvent.SendMessage, TelemetryStatus.Error, {
46
148
  error: error.message,
47
149
  });
48
- chatService.setError(error.message || "Something went wrong. Please try again.");
150
+ chatService.setError(error.message || t("error_generic"));
49
151
  });
50
152
  exchange.onMessageStart((message) => {
51
153
  if (message.startEvent.role === "assistant") {
52
154
  const messageId = message.messageId;
53
155
  const messageTimestamp = message.startEvent.timestamp;
156
+ const exchangeId = exchange.exchangeId;
157
+ // Shared envelope for the assistant stream (text, citation, done);
158
+ // only the chunk and `done` vary.
159
+ // stream: true so Apollo's actions row (copy, thumbs) renders —
160
+ // useIsStreamingMessage only listens to SendChunk events; the
161
+ // stream: false branch fires Response and leaves isStreaming stuck
162
+ // at true.
163
+ const sendAssistantChunk = (contentPartChunk, done = false) => {
164
+ chatService.sendResponse({
165
+ id: messageId,
166
+ contentPartChunk,
167
+ created_at: messageTimestamp,
168
+ widget: MessageWidget.AI,
169
+ stream: true,
170
+ done,
171
+ meta: { exchangeId },
172
+ });
173
+ };
54
174
  message.onContentPartStart((contentPart) => {
55
175
  if (contentPart.startEvent.mimeType.startsWith("text/")) {
56
- let fullResponse = "";
176
+ // Apollo dictates citation boundaries by chunk index — text and
177
+ // its citation share one index, the next text segment uses index+1.
178
+ let chunkIndex = 0;
179
+ let isFirstChunk = true;
57
180
  contentPart.onChunk((chunk) => {
58
- fullResponse += chunk.data;
59
- chatService.sendResponse({
60
- id: messageId,
61
- content: chunk.data,
62
- created_at: messageTimestamp,
63
- widget: MessageWidget.AI,
64
- stream: true,
65
- done: false,
66
- });
181
+ if (chunk.citation?.startCitation && !isFirstChunk) {
182
+ chunkIndex++;
183
+ }
184
+ if (chunk.data !== undefined) {
185
+ sendAssistantChunk({ text: chunk.data, index: chunkIndex });
186
+ }
187
+ if (chunk.citation?.endCitation) {
188
+ for (const source of chunk.citation.endCitation.sources) {
189
+ sendAssistantChunk({
190
+ citation: mapCitationSource(source),
191
+ index: chunkIndex,
192
+ });
193
+ }
194
+ chunkIndex++;
195
+ }
196
+ isFirstChunk = false;
67
197
  });
68
198
  contentPart.onContentPartEnd(() => {
69
- chatService.sendResponse({
70
- id: messageId,
71
- content: fullResponse,
72
- created_at: messageTimestamp,
73
- widget: MessageWidget.AI,
74
- stream: false,
75
- done: true,
76
- });
199
+ sendAssistantChunk({ index: chunkIndex }, true);
77
200
  });
78
201
  }
79
202
  });
80
- message.onToolCallStart((toolCall) => {
81
- const startEvent = toolCall.startEvent;
82
- const startTimeIso = new Date().toISOString();
83
- const toolInput = startEvent.input
84
- ? normalizeInput(startEvent.input)
85
- : {};
203
+ // Track tool calls so we can defer the spinner when an interrupt arrives
204
+ const pendingToolCalls = new Map();
205
+ const sendToolCallSpinner = (toolCallId) => {
206
+ const pending = pendingToolCalls.get(toolCallId);
207
+ if (!pending || pending.spinnerSent)
208
+ return;
209
+ pending.spinnerSent = true;
86
210
  chatService.sendResponse({
87
- id: toolCall.toolCallId,
88
- content: `Performing ${startEvent.toolName}`,
89
- created_at: startTimeIso,
211
+ id: toolCallId,
212
+ content: t("performing_action_message", {
213
+ action: pending.toolName,
214
+ }),
215
+ created_at: pending.startTimeIso,
90
216
  widget: MessageWidget.ApolloAgentsToolCall,
91
217
  meta: {
92
- toolName: startEvent.toolName,
93
- input: toolInput,
94
- startTime: startTimeIso,
218
+ toolName: pending.toolName,
219
+ input: pending.toolInput,
220
+ startTime: pending.startTimeIso,
95
221
  },
96
222
  });
97
- toolCall.onToolCallEnd((endEvent) => {
98
- const endTimeIso = new Date().toISOString();
223
+ };
224
+ // Caller supplies the approve/reject channel.
225
+ const sendToolConfirmationWidget = (params) => {
226
+ const widgetMessageId = `${TOOL_CONFIRMATION_WIDGET_ID_PREFIX}${params.toolCallId}`;
227
+ const confirmationData = {
228
+ toolCallId: params.toolCallId,
229
+ toolName: params.toolName,
230
+ inputSchema: params.inputSchema ?? {},
231
+ inputValue: params.inputValue,
232
+ };
233
+ const createdAt = new Date().toISOString();
234
+ const sendUpdate = (isCompleted, wasRejected) => {
99
235
  chatService.sendResponse({
100
- id: toolCall.toolCallId,
101
- content: `Performing ${startEvent.toolName}`,
102
- created_at: endTimeIso,
103
- widget: MessageWidget.ApolloAgentsToolCall,
236
+ id: widgetMessageId,
237
+ content: t("tool_confirmation_required"),
238
+ created_at: createdAt,
239
+ widget: MessageWidget.ToolConfirmation,
240
+ stream: false,
241
+ done: true,
104
242
  meta: {
105
- toolName: startEvent.toolName,
106
- input: toolInput,
107
- startTime: startTimeIso,
108
- output: endEvent.output,
109
- endTime: endTimeIso,
110
- isError: endEvent.isError,
243
+ confirmationData,
244
+ isCompleted,
245
+ wasRejected,
246
+ // Unreachable once completed (the form's buttons are gone),
247
+ // but kept on the meta so its shape stays stable.
248
+ onApprove: handleApprove,
249
+ onCancel: handleCancel,
111
250
  },
112
251
  });
252
+ };
253
+ const handleApprove = (endValue) => {
254
+ sendUpdate(true, false);
255
+ params.onApprove(endValue.input);
256
+ };
257
+ const handleCancel = () => {
258
+ sendUpdate(true, true);
259
+ params.onCancel();
260
+ };
261
+ sendUpdate(false, false);
262
+ };
263
+ message.onToolCallStart((toolCall) => {
264
+ const startEvent = toolCall.startEvent;
265
+ const startTimeIso = new Date().toISOString();
266
+ const toolInput = startEvent.input
267
+ ? normalizeInput(startEvent.input)
268
+ : {};
269
+ pendingToolCalls.set(toolCall.toolCallId, {
270
+ toolName: startEvent.toolName,
271
+ toolInput,
272
+ startTimeIso,
273
+ spinnerSent: false,
274
+ });
275
+ // New flow: confirmation is a property of the tool call itself.
276
+ if (startEvent.requireConfirmation) {
277
+ sendToolConfirmationWidget({
278
+ toolCallId: toolCall.toolCallId,
279
+ toolName: startEvent.toolName,
280
+ inputSchema: startEvent.inputSchema,
281
+ inputValue: startEvent.input,
282
+ onApprove: (input) => {
283
+ sendToolCallSpinner(toolCall.toolCallId);
284
+ const approvedInput = input ?? startEvent.input ?? {};
285
+ toolCall.sendToolCallConfirm({
286
+ approved: true,
287
+ input: approvedInput,
288
+ });
289
+ },
290
+ onCancel: () => {
291
+ toolCall.sendToolCallConfirm({ approved: false });
292
+ },
293
+ });
294
+ }
295
+ else {
296
+ // No confirmation needed — show spinner immediately.
297
+ sendToolCallSpinner(toolCall.toolCallId);
298
+ }
299
+ toolCall.onToolCallEnd((endEvent) => {
300
+ const pending = pendingToolCalls.get(toolCall.toolCallId);
301
+ if (pending?.spinnerSent) {
302
+ const endTimeIso = new Date().toISOString();
303
+ chatService.sendResponse({
304
+ id: toolCall.toolCallId,
305
+ content: t("performing_action_message", {
306
+ action: startEvent.toolName,
307
+ }),
308
+ created_at: endTimeIso,
309
+ widget: MessageWidget.ApolloAgentsToolCall,
310
+ meta: {
311
+ toolName: startEvent.toolName,
312
+ input: toolInput,
313
+ startTime: startTimeIso,
314
+ output: endEvent.output,
315
+ endTime: endTimeIso,
316
+ isError: endEvent.isError,
317
+ },
318
+ });
319
+ }
320
+ pendingToolCalls.delete(toolCall.toolCallId);
113
321
  });
114
322
  });
115
323
  }
@@ -119,8 +327,48 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
119
327
  chatService.sendOutputStreamEvent({ turnComplete: true });
120
328
  chatService.setShowLoading(false);
121
329
  chatService.setWaiting(false);
330
+ setHasMessages(true);
122
331
  });
123
- }, [chatService]);
332
+ }, [chatService, t]);
333
+ const resolveAgent = useCallback(async () => {
334
+ let effectiveAgentId = agentId;
335
+ let effectiveFolderId = folderIdRef.current;
336
+ // When the host passes only existingConversationId, derive the agent from
337
+ // the conversation so the header title + FRE still render for empty replays.
338
+ if (effectiveAgentId == null && existingConversationId) {
339
+ if (!currentConversation.current &&
340
+ !initialConversationConsumed.current) {
341
+ const existing = await agentService.current.conversations.getById(existingConversationId);
342
+ currentConversation.current = existing;
343
+ initialConversationConsumed.current = true;
344
+ }
345
+ const conv = currentConversation.current;
346
+ if (conv?.agentId != null) {
347
+ effectiveAgentId = conv.agentId;
348
+ effectiveFolderId = conv.folderId;
349
+ }
350
+ }
351
+ if (effectiveAgentId == null)
352
+ return undefined;
353
+ if (resolvedAgent.current?.id === effectiveAgentId) {
354
+ const cachedFolderId = resolvedAgent.current.folderId;
355
+ if (effectiveFolderId == null || cachedFolderId === effectiveFolderId) {
356
+ return resolvedAgent.current;
357
+ }
358
+ }
359
+ const release = await fetchAgentRelease(sdk, effectiveAgentId, effectiveFolderId, { externalUserId });
360
+ if (!release)
361
+ return undefined;
362
+ resolvedAgent.current = release;
363
+ folderIdRef.current = release.folderId;
364
+ return release;
365
+ }, [agentId, existingConversationId, sdk, externalUserId]);
366
+ const setConversationHistory = useCallback((next, allLoaded) => {
367
+ pastConversations.current = next;
368
+ if (!chatService)
369
+ return;
370
+ chatService.setHistory(getConversationHistoryDisplayItems(next, t("new_chat")), allLoaded);
371
+ }, [chatService, t]);
124
372
  const getConversation = useCallback(async () => {
125
373
  if (currentConversation.current) {
126
374
  return currentConversation.current;
@@ -132,32 +380,126 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
132
380
  initialConversationConsumed.current = true;
133
381
  return existing;
134
382
  }
135
- if (!agentId || !folderId) {
136
- throw new Error("Either conversationId or agentId and folderId must be provided");
383
+ const agent = await resolveAgent();
384
+ if (!agent) {
385
+ throw new Error(t("error_missing_conversation_params"));
137
386
  }
138
- const newConversation = await agentService.current.conversations.create(agentId, folderId);
387
+ const newConversation = await agent.conversations.create(jobStartOverrides ? { jobStartOverrides } : undefined);
139
388
  currentConversation.current = newConversation;
389
+ // Show the new conversation in the sidebar immediately so its label
390
+ // (auto-generated by the service after the first exchange) can refresh
391
+ // in place via onLabelUpdated rather than waiting for a history reload.
392
+ setConversationHistory([newConversation, ...pastConversations.current]);
140
393
  return newConversation;
141
- }, [agentId, folderId, existingConversationId]);
394
+ }, [
395
+ existingConversationId,
396
+ jobStartOverrides,
397
+ resolveAgent,
398
+ setConversationHistory,
399
+ t,
400
+ ]);
142
401
  const getSessionHelper = useCallback(async () => {
143
402
  if (session.current) {
144
403
  return session.current;
145
404
  }
146
405
  const conversation = await getConversation();
147
406
  const sessionHelper = agentService.current.conversations.startSession(conversation.id, { echo: false });
148
- return new Promise((resolve) => {
149
- sessionHelper.onSessionStarted(() => {
150
- session.current = sessionHelper;
151
- resolve(sessionHelper);
152
- });
407
+ // Mark active before registering handlers so a synchronous sessionStarted
408
+ // can't lose the `session.current === sessionHelper` guard race below.
409
+ session.current = sessionHelper;
410
+ // Refresh the sidebar label when the service auto-generates one (or the
411
+ // label is updated via the API). Bind to this session's conversation id
412
+ // so a stale event from an orphaned session can't mislabel the active one.
413
+ sessionHelper.onLabelUpdated(({ label }) => {
414
+ setConversationHistory(pastConversations.current.map((c) => c.id === conversation.id ? { ...c, label } : c));
415
+ });
416
+ // Buffer outgoing events until the server confirms the session is started,
417
+ // then flush — so a send never blocks on the sessionStarted round-trip.
418
+ // Combined with ending the session on switch (see endActiveSession), a
419
+ // reopened conversation starts fresh and its buffered send flushes as soon
420
+ // as the fresh sessionStarted arrives.
421
+ sessionHelper.pauseEmits();
422
+ const startTimeout = setTimeout(() => {
423
+ // Ignore a session abandoned by a switch/unmount so it can't error on the
424
+ // now-active conversation. If the active session never started, nothing
425
+ // flushes the buffer — surface an error and clear it so a retry can build
426
+ // a fresh session rather than reusing this permanently-paused one.
427
+ if (session.current !== sessionHelper)
428
+ return;
429
+ if (sessionHelper.isEmitPaused) {
430
+ session.current = null;
431
+ chatService?.setError(t("error_session_start_timeout"));
432
+ }
433
+ }, SESSION_START_TIMEOUT_MS);
434
+ sessionHelper.onSessionStarted(() => {
435
+ clearTimeout(startTimeout);
436
+ if (session.current !== sessionHelper)
437
+ return;
438
+ sessionHelper.resumeEmits();
153
439
  });
154
- }, [getConversation]);
440
+ sessionHelper.onErrorStart((error) => {
441
+ clearTimeout(startTimeout);
442
+ if (session.current !== sessionHelper)
443
+ return;
444
+ session.current = null;
445
+ chatService?.setError(error.message || t("error_generic"));
446
+ });
447
+ return sessionHelper;
448
+ }, [chatService, getConversation, setConversationHistory, t]);
449
+ // End the session on conversation switch/unmount so a reopen starts fresh and
450
+ // gets a new `sessionStarted` — reusing a stale session hangs the send. The
451
+ // in-flight exchange is left running (ending it is reserved for onStopResponse),
452
+ // so switching away from a busy conversation and reopening resumes its turn.
453
+ const endActiveSession = useCallback(() => {
454
+ try {
455
+ session.current?.sendSessionEnd();
456
+ }
457
+ catch {
458
+ /* session already closed */
459
+ }
460
+ activeExchange.current = null;
461
+ session.current = null;
462
+ }, []);
155
463
  const onNewChat = useCallback(() => {
464
+ endActiveSession();
156
465
  currentConversation.current = null;
157
466
  session.current = null;
158
467
  activeExchange.current = null;
468
+ exchangesCursor.current = undefined;
469
+ storedAgentInputs.current = {};
470
+ setHasMessages(false);
471
+ // Re-show the InputsPage with a cleared form when the agent's schema has
472
+ // required inputs. Bumping the counter forces an unmount/remount via the
473
+ // key on <InputsPage>, which resets internal form state.
474
+ if ((inputSchemaState?.required?.length ?? 0) > 0) {
475
+ setInputsInstance((n) => n + 1);
476
+ setShowInputPage(true);
477
+ }
159
478
  trackTelemetry(TelemetryEvent.NewChat, TelemetryStatus.Success);
479
+ }, [endActiveSession, inputSchemaState]);
480
+ const buildHistoryFilterOptions = useCallback(() => {
481
+ // The SDK's URL builder calls value.toString() without a null check, so
482
+ // omit any param that is undefined/empty rather than passing it as such.
483
+ const opts = {};
484
+ if (agentKeyRef.current)
485
+ opts.agentKey = agentKeyRef.current;
486
+ if (agentIdRef.current !== undefined)
487
+ opts.agentId = agentIdRef.current;
488
+ if (searchTextRef.current)
489
+ opts.label = searchTextRef.current;
490
+ return opts;
160
491
  }, []);
492
+ const fetchFirstHistoryPage = useCallback(async () => {
493
+ if (!chatService)
494
+ return;
495
+ const result = await agentService.current.conversations.getAll({
496
+ sort: SortOrder.Descending,
497
+ pageSize: 20,
498
+ ...buildHistoryFilterOptions(),
499
+ });
500
+ conversationsCursor.current = result.nextCursor;
501
+ setConversationHistory(result.items, !result.hasNextPage);
502
+ }, [buildHistoryFilterOptions, chatService, setConversationHistory]);
161
503
  const onHistoryLoadMore = useCallback(async () => {
162
504
  if (!chatService)
163
505
  return;
@@ -169,21 +511,25 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
169
511
  sort: SortOrder.Descending,
170
512
  pageSize: 20,
171
513
  cursor: conversationsCursor.current,
514
+ ...buildHistoryFilterOptions(),
172
515
  });
173
516
  conversationsCursor.current = result.nextCursor;
174
517
  pastConversations.current = [...pastConversations.current, ...result.items];
175
- chatService.appendOlderHistoryItems(getConversationHistoryDisplayItems(result.items), !result.hasNextPage);
176
- }, [chatService]);
518
+ chatService.appendOlderHistoryItems(getConversationHistoryDisplayItems(result.items, t("new_chat")), !result.hasNextPage);
519
+ }, [buildHistoryFilterOptions, chatService, t]);
520
+ const onHistorySearch = useCallback(async ({ searchText }) => {
521
+ searchTextRef.current = searchText;
522
+ await fetchFirstHistoryPage();
523
+ }, [fetchFirstHistoryPage]);
177
524
  const onClickDeleteConversation = useCallback(async (id) => {
178
525
  if (!chatService)
179
526
  return;
180
527
  await agentService.current.conversations.deleteById(id);
181
- pastConversations.current = pastConversations.current.filter((c) => c.id !== id);
182
- chatService.setHistory(getConversationHistoryDisplayItems(pastConversations.current));
528
+ setConversationHistory(pastConversations.current.filter((c) => c.id !== id));
183
529
  if (currentConversation.current?.id === id) {
184
530
  onNewChat();
185
531
  }
186
- }, [chatService, onNewChat]);
532
+ }, [chatService, onNewChat, setConversationHistory]);
187
533
  const onSendMessage = useCallback(async (data) => {
188
534
  try {
189
535
  // required for debug-mode hosts that need to gate agent execution on the first user message
@@ -219,9 +565,9 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
219
565
  trackTelemetry(TelemetryEvent.SendMessage, TelemetryStatus.Error, {
220
566
  error: errorMessage,
221
567
  });
222
- chatService?.setError(`Failed to send message: ${errorMessage}`);
568
+ chatService?.setError(t("error_send_message", { errorMessage }));
223
569
  }
224
- }, [chatService, getSessionHelper, setupExchangeHandlers]);
570
+ }, [chatService, getSessionHelper, setupExchangeHandlers, t]);
225
571
  const processAttachmentsInBatch = useCallback(async (attachmentBatch) => {
226
572
  if (!chatService)
227
573
  return;
@@ -272,7 +618,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
272
618
  // Handle any failed uploads
273
619
  const failedUploads = results.filter((result) => !result.success);
274
620
  if (failedUploads.length > 0) {
275
- chatService.setError("Failed to upload attachments. Please try again.");
621
+ chatService.setError(t("error_upload_attachments"));
276
622
  for (const failedUpload of failedUploads) {
277
623
  const key = createFileKey(failedUpload.attachment);
278
624
  uploadedAttachments.current.delete(key);
@@ -288,12 +634,22 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
288
634
  }
289
635
  }
290
636
  }
291
- }, [chatService, processAttachmentsInBatch]);
292
- const fetchExchanges = useCallback(async (conversationId) => {
637
+ }, [chatService, processAttachmentsInBatch, t]);
638
+ // Fetch one page of a conversation's exchanges, newest-first, advancing
639
+ // `exchangesCursor` so the next call returns the chunk immediately older.
640
+ // The returned page is sorted chronologically (ascending) so messages render
641
+ // top-to-bottom; callers prepend each older page above the existing ones.
642
+ const fetchExchanges = useCallback(async (conversationId, cursor) => {
293
643
  const conversation = await agentService.current.conversations.getById(conversationId);
294
- const allExchanges = (await conversation.exchanges.getAll()).items;
295
- allExchanges.sort((a, b) => new Date(a.createdTime).getTime() - new Date(b.createdTime).getTime());
296
- return allExchanges;
644
+ const result = await conversation.exchanges.getAll({
645
+ pageSize: EXCHANGES_PAGE_SIZE,
646
+ exchangeSort: SortOrder.Descending,
647
+ messageSort: SortOrder.Ascending,
648
+ ...(cursor ? { cursor } : {}),
649
+ });
650
+ exchangesCursor.current = result.nextCursor;
651
+ const exchanges = [...result.items].sort((a, b) => new Date(a.createdTime).getTime() - new Date(b.createdTime).getTime());
652
+ return { exchanges, hasNextPage: result.hasNextPage };
297
653
  }, []);
298
654
  const onClickOpenConversation = useCallback(async (id) => {
299
655
  if (!chatService)
@@ -304,10 +660,14 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
304
660
  const selectedConversation = pastConversations.current.find((c) => c.id === id);
305
661
  if (!selectedConversation)
306
662
  return;
663
+ endActiveSession();
307
664
  currentConversation.current = selectedConversation;
308
665
  session.current = null;
309
- const allExchanges = await fetchExchanges(selectedConversation.id);
310
- chatService.setConversation(mapExchangesToChatMessages(allExchanges));
666
+ exchangesCursor.current = undefined;
667
+ const { exchanges } = await fetchExchanges(selectedConversation.id);
668
+ const messages = mapExchangesToChatMessages(exchanges);
669
+ chatService.setConversation(messages);
670
+ setHasMessages(messages.length > 0);
311
671
  trackTelemetry(TelemetryEvent.OpenConversation, TelemetryStatus.Success, {
312
672
  conversationId: id,
313
673
  });
@@ -318,69 +678,212 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
318
678
  conversationId: id,
319
679
  error: errorMessage,
320
680
  });
321
- chatService.setError(`Failed to open conversation: ${errorMessage}`);
681
+ chatService.setError(t("error_open_conversation", { errorMessage }));
682
+ }
683
+ }, [chatService, endActiveSession, fetchExchanges, t]);
684
+ // Apollo fires this when the user scrolls to the top of the message list.
685
+ // Prepend the next older page; signal `done` (no more pages) so Apollo stops
686
+ // requesting once the cursor is exhausted.
687
+ const onConversationLoadMore = useCallback(async () => {
688
+ if (!chatService)
689
+ return;
690
+ const conversationId = currentConversation.current?.id;
691
+ if (!conversationId || !exchangesCursor.current) {
692
+ chatService.prependOlderMessages([], true);
693
+ return;
694
+ }
695
+ try {
696
+ const { exchanges, hasNextPage } = await fetchExchanges(conversationId, exchangesCursor.current);
697
+ chatService.prependOlderMessages(mapExchangesToChatMessages(exchanges), !hasNextPage);
698
+ }
699
+ catch (err) {
700
+ chatService.prependOlderMessages([], true);
701
+ const errorMessage = err instanceof Error ? err.message : String(err);
702
+ trackTelemetry(TelemetryEvent.OpenConversation, TelemetryStatus.Error, {
703
+ conversationId,
704
+ error: errorMessage,
705
+ });
322
706
  }
323
707
  }, [chatService, fetchExchanges]);
324
708
  const initChat = useCallback(async () => {
325
- const initKey = `${agentId}-${folderId}-${existingConversationId ?? ""}`;
709
+ const initKey = `${agentId}-${folderId}-${existingConversationId ?? ""}-${externalUserId ?? ""}`;
326
710
  try {
327
711
  initializedFor.current = initKey;
328
- const agentRelease = agentId && folderId
329
- ? await agentService.current.getById(agentId, folderId)
330
- : undefined;
712
+ const agentRelease = await resolveAgent();
713
+ agentIdRef.current = agentRelease?.id;
714
+ agentKeyRef.current = agentRelease?.releaseKey;
331
715
  const agentName = agentRelease?.name ?? "";
332
- // All-or-nothing first-run experience configuration
333
- // If an override is passed use it, otherwise use the agent's default.
334
- // Finally, if the agent has no default, use fallbacks/empty values
335
- const firstRunExperienceConfig = firstRunExperienceRef.current
336
- ? {
337
- title: firstRunExperienceRef.current.title ?? "",
338
- description: firstRunExperienceRef.current.description ?? "",
339
- suggestions: firstRunExperienceRef.current.suggestions ?? [],
716
+ // In debug mode the agent (and its derived schema) may not be resolvable,
717
+ // so an explicit `inputSchema` override takes precedence. Normal usage
718
+ // always derives the schema from the resolved agent release.
719
+ // TODO(sdk-typing): drop the cast once @uipath/uipath-typescript exposes
720
+ // inputSchema on AgentRelease. The API returns it but the SDK type
721
+ // definitions don't include it yet.
722
+ const inputSchema = (isDebugMode ? inputSchemaProp : undefined) ??
723
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
724
+ agentRelease?.inputSchema;
725
+ // Show input page if there's an inputSchema with required properties and
726
+ // this is a new conversation. Optional-only schemas use the settings panel.
727
+ // Skip when resuming an existing conversation — its inputs were already
728
+ // captured at creation time. The exception is debug mode, where the host
729
+ // opens an empty conversation up front, so inputs are still collected here.
730
+ const hasRequiredInputs = (inputSchema?.required?.length ?? 0) > 0;
731
+ // Persist the schema regardless of `hasRequiredInputs` so the settings
732
+ // panel can render optional-input editing.
733
+ setInputSchemaState(inputSchema ?? null);
734
+ if (hasRequiredInputs && (!existingConversationId || isDebugMode)) {
735
+ setAgentNameState(agentName);
736
+ setShowInputPage(true);
737
+ }
738
+ // Resolve the first-run experience: the host-provided config wins so
739
+ // callers can override the welcome copy and starting prompts, falling
740
+ // back to the agent's own appearance.
741
+ const firstRunExperienceConfig = getFirstRunExperience(firstRunExperienceRef.current, agentRelease?.appearance);
742
+ // Persists agent inputs against the active conversation via
743
+ // updateConversation. Server-side this applies to all subsequent
744
+ // messages; we don't prepend per send.
745
+ const handleApplySettingsInputs = async (inputs) => {
746
+ const conversationId = currentConversation.current?.id;
747
+ if (!conversationId) {
748
+ throw new Error(t("error_missing_conversation_params"));
340
749
  }
341
- : {
342
- title: agentRelease?.appearance?.welcomeTitle ||
343
- (agentName ? `Welcome to ${agentName}!` : ""),
344
- description: agentRelease?.appearance?.welcomeDescription || "",
345
- suggestions: (agentRelease?.appearance?.startingPrompts || []).map((prompt) => ({
346
- label: prompt.displayPrompt,
347
- prompt: prompt.actualPrompt,
348
- })),
349
- };
750
+ await agentService.current.conversations.updateById(conversationId, {
751
+ agentInput: { inline: inputs },
752
+ });
753
+ storedAgentInputs.current = inputs;
754
+ };
755
+ // TODO: if Apollo adds more renderer slots (footer, first-run, etc.),
756
+ // extract this mount/unmount plumbing into a `useApolloRenderer` hook.
757
+ const renderSettings = (element) => {
758
+ // Apollo clears `element.innerHTML` before every call to the renderer.
759
+ // Reusing a React root would leave its virtual DOM out of sync with the
760
+ // wiped real DOM, so we unmount and recreate on every invocation.
761
+ if (settingsRootRef.current) {
762
+ settingsRootRef.current.unmount();
763
+ settingsRootRef.current = null;
764
+ }
765
+ const root = createRoot(element);
766
+ settingsRootRef.current = root;
767
+ const profileResetKey = agentId != null && folderId != null
768
+ ? `${agentId}-${folderId}`
769
+ : "no-agent";
770
+ const conversationId = currentConversation.current?.id ?? "no-conv";
771
+ const inputsResetKey = `${profileResetKey}-${conversationId}`;
772
+ 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 }) }));
773
+ };
350
774
  const chatServiceInstance = AutopilotChatService.Instantiate({
351
775
  instanceName: `agent-${agentId}-${folderId}`,
352
776
  config: {
353
777
  mode: AutopilotChatMode.Embedded,
354
- locale: localeRef.current,
778
+ locale: toApolloSupportedLocale(locale),
355
779
  theme: themeRef.current,
356
780
  readOnly,
357
- firstRunExperience: firstRunExperienceConfig,
781
+ firstRunExperience: firstRunExperienceConfig && {
782
+ title: firstRunExperienceConfig.title ?? "",
783
+ description: firstRunExperienceConfig.description ?? "",
784
+ suggestions: firstRunExperienceConfig.suggestions ?? [],
785
+ },
358
786
  overrideLabels: {
359
787
  title: overrideLabelsRef.current?.title ?? agentName,
360
788
  footerDisclaimer: overrideLabelsRef.current?.footerDisclaimer ??
361
- DEFAULT_FOOTER_DISCLAIMER,
789
+ t("disclaimer_message"),
362
790
  inputPlaceholder: overrideLabelsRef.current?.inputPlaceholder ??
363
- DEFAULT_INPUT_PLACEHOLDER,
791
+ t("chat_input_placeholder"),
364
792
  },
365
793
  paginatedHistory: true,
794
+ paginatedMessages: true,
795
+ settingsRenderer: renderSettings,
796
+ preHooks: {
797
+ [AutopilotChatPreHookAction.CitationClick]: async (citationData) => {
798
+ // When preview is disabled, or the citation is not a
799
+ // context-grounding citation (no download_url to a source
800
+ // document), fall through to Apollo's default handling.
801
+ if (!citationPreviewRef.current)
802
+ return true;
803
+ const { citation } = citationData;
804
+ if (!citation?.download_url)
805
+ return true;
806
+ const pageNumber = Number(citation.page_number) || 1;
807
+ try {
808
+ const blob = await agentService.current.downloadCitationSource({
809
+ title: citation.title,
810
+ number: citation.number ?? citation.id ?? 0,
811
+ downloadUrl: citation.download_url,
812
+ pageNumber: String(pageNumber),
813
+ });
814
+ const file = new File([blob], citation.title, {
815
+ type: blob.type,
816
+ });
817
+ setCitationPreviewData({
818
+ file,
819
+ title: citation.title,
820
+ pageNumber,
821
+ });
822
+ }
823
+ catch (e) {
824
+ // Consume the click and surface the error in-dialog. Falling
825
+ // through to Apollo's default would re-open the auth-gated
826
+ // download_url in a new tab, which is exactly the 401 this
827
+ // preview replaces.
828
+ console.error("Failed to load citation document", e);
829
+ setCitationPreviewData({
830
+ title: citation.title,
831
+ pageNumber,
832
+ error: true,
833
+ });
834
+ }
835
+ return false;
836
+ },
837
+ },
838
+ // Apollo's ApChat defaults message text to fontSizeM (14px); the
839
+ // deprecated portal-shell chat used a larger size, so bump primary
840
+ // text and markdown body tokens to fontSizeL (16px) to match.
841
+ spacing: {
842
+ primaryFontToken: FontVariantToken.fontSizeL,
843
+ primaryBoldFontToken: FontVariantToken.fontSizeLBold,
844
+ suggestionFontToken: FontVariantToken.fontSizeL,
845
+ markdownTokens: {
846
+ p: FontVariantToken.fontSizeL,
847
+ li: FontVariantToken.fontSizeL,
848
+ th: FontVariantToken.fontSizeL,
849
+ td: FontVariantToken.fontSizeL,
850
+ em: FontVariantToken.fontSizeL,
851
+ del: FontVariantToken.fontSizeL,
852
+ strong: FontVariantToken.fontSizeLBold,
853
+ link: FontVariantToken.fontSizeL,
854
+ },
855
+ },
366
856
  disabledFeatures: {
367
857
  fullScreen: true,
368
858
  preview: true,
369
859
  close: true,
370
- ...(!agentId || !folderId ? { newChat: true, history: true } : {}),
860
+ // Apollo defaults `settings: true`; flip it so our gear renders
861
+ // by default. Consumers can still opt out via `disabledFeatures`.
862
+ settings: false,
863
+ ...(!agentId ? { newChat: true, history: true } : {}),
371
864
  ...disabledFeaturesRef.current,
372
865
  },
373
866
  },
374
867
  });
868
+ chatServiceRef.current = chatServiceInstance;
869
+ if (!disabledFeaturesRef.current?.attachments) {
870
+ chatServiceInstance.setAllowedAttachments(ALLOWED_ATTACHMENTS);
871
+ }
375
872
  if (existingConversationId) {
376
873
  const conversation = await getConversation();
377
- const allExchanges = await fetchExchanges(conversation.id);
378
- chatServiceInstance.setConversation(mapExchangesToChatMessages(allExchanges));
874
+ exchangesCursor.current = undefined;
875
+ const { exchanges } = await fetchExchanges(conversation.id);
876
+ chatServiceInstance.setConversation(mapExchangesToChatMessages(exchanges));
877
+ }
878
+ else {
879
+ // AutopilotChatService is a singleton, so it may still hold the
880
+ // previous agent's messages. Reset before showing the new agent.
881
+ chatServiceInstance.setConversation([]);
379
882
  }
380
883
  setChatService(chatServiceInstance);
381
884
  }
382
885
  catch (err) {
383
- const message = err instanceof Error ? err.message : "Failed to initialize chat";
886
+ const message = err instanceof Error ? err.message : t("error_initialize_chat");
384
887
  setError(message);
385
888
  initializedFor.current = null;
386
889
  }
@@ -388,9 +891,15 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
388
891
  agentId,
389
892
  folderId,
390
893
  existingConversationId,
894
+ externalUserId,
895
+ inputSchemaProp,
896
+ isDebugMode,
897
+ locale,
391
898
  readOnly,
899
+ resolveAgent,
392
900
  getConversation,
393
901
  fetchExchanges,
902
+ t,
394
903
  ]);
395
904
  const handleReload = useCallback(() => {
396
905
  initializedFor.current = null;
@@ -409,17 +918,27 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
409
918
  chatService.setShowLoading(false);
410
919
  chatService.setWaiting(false);
411
920
  }, [chatService]);
921
+ const onCustomHeaderActionClicked = useCallback((action) => {
922
+ if (action.id.startsWith("eval-")) {
923
+ const evaluationSetId = action.id.replace("eval-", "");
924
+ onEvaluationSetClickedRef.current?.(evaluationSetId);
925
+ }
926
+ }, []);
412
927
  const onFeedback = useCallback((data) => {
413
928
  pendingFeedback.current = data;
929
+ setFeedbackIsPositive(!!data.action.details?.isPositive);
414
930
  setFeedbackDialogOpen(true);
415
931
  }, []);
416
932
  const onFeedbackSubmit = useCallback((comment) => {
417
933
  const data = pendingFeedback.current;
418
- if (data) {
934
+ // Streamed messages may not have meta.exchangeId yet; guard against it
935
+ // so a missing id doesn't throw and leave the dialog stuck open.
936
+ const exchangeId = data?.message.meta?.exchangeId;
937
+ if (data && exchangeId) {
419
938
  const rating = data.action.details?.isPositive
420
939
  ? FeedbackRating.Positive
421
940
  : FeedbackRating.Negative;
422
- currentConversation.current?.exchanges?.createFeedback(data.message.meta.exchangeId, {
941
+ currentConversation.current?.exchanges?.createFeedback(exchangeId, {
423
942
  rating,
424
943
  comment,
425
944
  });
@@ -431,68 +950,55 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
431
950
  setFeedbackDialogOpen(false);
432
951
  }, []);
433
952
  const onFeedbackCancel = useCallback(() => {
953
+ // Apollo's internal Feedback handler marks the message with `feedback`
954
+ // as soon as the thumb is clicked, which collapses the actions row to
955
+ // the chosen (disabled) thumb. If the user then cancels the dialog,
956
+ // re-send the message without `feedback` so the row reverts to both
957
+ // thumbs and the click can be retried.
958
+ const messageId = pendingFeedback.current?.message.id;
959
+ if (messageId && chatService) {
960
+ const current = chatService
961
+ .getConversation()
962
+ .find((m) => m.id === messageId);
963
+ if (current?.feedback) {
964
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
965
+ const { feedback: _feedback, ...withoutFeedback } = current;
966
+ chatService.sendResponse(withoutFeedback);
967
+ }
968
+ }
434
969
  pendingFeedback.current = null;
435
970
  setFeedbackDialogOpen(false);
436
- }, []);
437
- // Initialize chat service on mount and when agentId/folderId changes
971
+ }, [chatService]);
972
+ // Initialize chat service on mount and when agentId/folderId/externalUserId/existingConversationId changes
438
973
  useEffect(() => {
439
- const initKey = `${agentId}-${folderId}-${existingConversationId ?? ""}`;
974
+ const initKey = `${agentId}-${folderId}-${existingConversationId ?? ""}-${externalUserId ?? ""}`;
440
975
  if (initializedFor.current !== initKey) {
441
976
  initChat();
442
977
  }
443
- }, [agentId, folderId, existingConversationId, initChat]);
444
- // End the WebSocket session and tear down the chat service singleton when
445
- // the agent changes or the component unmounts. Removing the singleton from
446
- // AutopilotChatService's private static instance map (rather than calling
447
- // newChat()) gives a complete reset on revisit — fresh conversation array,
448
- // fresh locale/theme, no stale internal state.
978
+ }, [agentId, folderId, existingConversationId, externalUserId, initChat]);
449
979
  useEffect(() => {
450
- const instanceName = `agent-${agentId}-${folderId}`;
451
980
  return () => {
452
- const conversation = currentConversation.current;
453
- currentConversation.current = null;
454
- session.current = null;
455
- activeExchange.current = null;
456
- if (conversation) {
457
- try {
458
- conversation.endSession();
459
- }
460
- catch {
461
- // best effort; the session may already be closed
462
- }
463
- }
464
- // Private-field reach-in: AutopilotChatService keeps a static map of
465
- // its singletons keyed by instanceName. Deleting the entry forces the
466
- // next Instantiate() call for this agent to construct a fresh service.
467
- const instances = AutopilotChatService._instances;
468
- if (instances) {
469
- delete instances[instanceName];
981
+ if (settingsRootRef.current) {
982
+ settingsRootRef.current.unmount();
983
+ settingsRootRef.current = null;
470
984
  }
471
985
  };
472
- }, [agentId, folderId]);
473
- // Update locale/theme on the existing service. Locale must be set
474
- // synchronously (not in an effect) so that when ApChat remounts via
475
- // key={locale}, its LocaleProvider reads the correct value from
476
- // chatService.getLocale() on first render.
477
- // Sync locale to the service and Lingui before ApChat remounts via
478
- // key={locale}. Uses useLayoutEffect so the values are set before the
479
- // browser paints. We set _locale directly instead of calling
480
- // setLocale()/activate() because those publish events that trigger
481
- // setState in other components.
482
- useLayoutEffect(() => {
483
- if (chatService && chatService.getLocale() !== locale) {
484
- /* eslint-disable @typescript-eslint/no-explicit-any, react-hooks/immutability */
485
- // Mutating internal properties directly to avoid triggering event-bus
486
- // side effects (setState in other components). The key={locale} on
487
- // ApChat ensures a clean remount that reads these values.
488
- chatService._locale = locale;
489
- i18n._locale = locale;
490
- /* eslint-enable @typescript-eslint/no-explicit-any, react-hooks/immutability */
491
- }
492
- }, [chatService, locale]);
986
+ }, []);
493
987
  useEffect(() => {
494
988
  chatService?.setTheme(theme);
495
989
  }, [chatService, theme]);
990
+ // Close the SDK session on unmount so the WebSocket doesn't linger.
991
+ useEffect(() => {
992
+ return () => {
993
+ endActiveSession();
994
+ };
995
+ }, [endActiveSession]);
996
+ // Release React state held by the imperative tool-confirmation roots.
997
+ useEffect(() => {
998
+ return () => {
999
+ toolConfirmationRenderer.unmountAll();
1000
+ };
1001
+ }, [toolConfirmationRenderer]);
496
1002
  // Register event handlers after chatService is available
497
1003
  useEffect(() => {
498
1004
  if (!chatService)
@@ -501,24 +1007,20 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
501
1007
  const unsubscribers = [];
502
1008
  const registerEvents = async () => {
503
1009
  try {
504
- if (agentId && folderId) {
505
- const result = await agentService.current.conversations.getAll({
506
- sort: SortOrder.Descending,
507
- pageSize: 20,
508
- });
1010
+ if (agentId) {
1011
+ await fetchFirstHistoryPage();
509
1012
  // only register handlers if the component is still mounted
510
1013
  if (cancelled)
511
1014
  return;
512
- conversationsCursor.current = result.nextCursor;
513
- pastConversations.current = result.items;
514
- chatService.setHistory(getConversationHistoryDisplayItems(pastConversations.current), !result.hasNextPage);
515
1015
  }
516
- 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.Feedback, onFeedback), chatService.on(AutopilotChatEvent.StopResponse, onStopResponse));
1016
+ 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));
1017
+ chatService.injectMessageRenderer({
1018
+ name: MessageWidget.ToolConfirmation,
1019
+ render: (container, message) => toolConfirmationRenderer.render(container, message, toolConfirmationLabelsRef.current ?? undefined),
1020
+ });
517
1021
  }
518
1022
  catch (err) {
519
- const message = err instanceof Error
520
- ? err.message
521
- : "Failed to load conversation history";
1023
+ const message = err instanceof Error ? err.message : t("error_load_history");
522
1024
  setError(message);
523
1025
  }
524
1026
  };
@@ -528,16 +1030,79 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
528
1030
  unsubscribers.forEach((unsub) => unsub());
529
1031
  };
530
1032
  }, [
1033
+ agentId,
531
1034
  chatService,
1035
+ fetchFirstHistoryPage,
1036
+ folderId,
532
1037
  onClickDeleteConversation,
533
1038
  onClickOpenConversation,
1039
+ onConversationLoadMore,
534
1040
  onFeedback,
535
1041
  onHistoryLoadMore,
1042
+ onHistorySearch,
536
1043
  onNewChat,
537
1044
  onSendMessage,
538
1045
  onSetAttachments,
539
1046
  onStopResponse,
1047
+ t,
1048
+ toolConfirmationRenderer,
540
1049
  ]);
541
- return (_jsxs("div", { className: "uipath-conversational-agent-chat", children: [error && (_jsxs("div", { className: "info-container", children: [_jsx(Alert, { variant: "destructive", children: _jsx(AlertDescription, { children: error }) }), _jsx(Button, { variant: "outline", onClick: handleReload, children: "Reload" })] })), !error && !chatService && (_jsx("div", { className: "info-container", children: _jsx(Alert, { children: _jsx(AlertDescription, { children: "Loading..." }) }) })), !error && chatService && (_jsx(ApChat, { chatServiceInstance: chatService, locale: locale, theme: theme, enableInternalThemeProvider: true }, locale)), _jsx(FeedbackDialog, { open: feedbackDialogOpen, onOpenChange: setFeedbackDialogOpen, onSubmit: onFeedbackSubmit, onCancel: onFeedbackCancel })] }));
1050
+ useEffect(() => {
1051
+ if (!chatService ||
1052
+ !isDebugMode ||
1053
+ !evaluationSets ||
1054
+ evaluationSets.length === 0) {
1055
+ return;
1056
+ }
1057
+ const label = addToEvalButtonLabel || t("add_to_evaluation_set");
1058
+ const sortedSets = sortEvaluationSets(evaluationSets);
1059
+ const headerAction = {
1060
+ id: "add-to-eval-button",
1061
+ name: label,
1062
+ description: label,
1063
+ disabled: !hasMessages,
1064
+ children: sortedSets.map((s) => ({
1065
+ id: `eval-${s.id}`,
1066
+ name: s.name,
1067
+ description: t("add_to_evaluation_set_named", { name: s.name }),
1068
+ disabled: s.isDisabled,
1069
+ })),
1070
+ };
1071
+ chatService.setCustomHeaderActions([headerAction]);
1072
+ const unsubscribe = chatService.on(AutopilotChatEvent.CustomHeaderActionClicked, onCustomHeaderActionClicked);
1073
+ return () => {
1074
+ unsubscribe?.();
1075
+ };
1076
+ }, [
1077
+ chatService,
1078
+ isDebugMode,
1079
+ evaluationSets,
1080
+ addToEvalButtonLabel,
1081
+ hasMessages,
1082
+ onCustomHeaderActionClicked,
1083
+ t,
1084
+ ]);
1085
+ return (_jsx("div", { className: "uipath-conversational-agent-chat", children: _jsxs(PortalContainerProvider, { children: [!error && showInputPage && inputSchemaState && (_jsx(InputsPage, { agentName: agentNameState, inputSchema: inputSchemaState, onSubmit: async (data) => {
1086
+ const inputs = data;
1087
+ if (isDebugMode && existingConversationId) {
1088
+ await agentService.current.conversations.updateById(existingConversationId, { agentInput: { inline: inputs } });
1089
+ }
1090
+ else {
1091
+ const agent = await resolveAgent();
1092
+ if (!agent) {
1093
+ throw new Error(t("error_missing_conversation_params"));
1094
+ }
1095
+ const conversation = await agent.conversations.create({
1096
+ ...(jobStartOverrides ? { jobStartOverrides } : {}),
1097
+ agentInput: { inline: inputs },
1098
+ });
1099
+ currentConversation.current = conversation;
1100
+ }
1101
+ storedAgentInputs.current = inputs;
1102
+ setShowInputPage(false);
1103
+ } }, `${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) => {
1104
+ if (!open)
1105
+ setCitationPreviewData(null);
1106
+ }, 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}` }))] })) })] }) }));
542
1107
  };
543
1108
  //# sourceMappingURL=ConversationalAgentChat.js.map