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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/README.md +63 -6
  2. package/dist/ConversationalAgentChat.css +18184 -7
  3. package/dist/ConversationalAgentChat.d.ts +1 -1
  4. package/dist/ConversationalAgentChat.d.ts.map +1 -1
  5. package/dist/ConversationalAgentChat.js +617 -139
  6. package/dist/ConversationalAgentChat.js.map +1 -1
  7. package/dist/ConversationalAgentChat.stories.d.ts +14 -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/ConversationalAgentPickerChat.d.ts +4 -0
  12. package/dist/ConversationalAgentPickerChat.d.ts.map +1 -0
  13. package/dist/ConversationalAgentPickerChat.js +113 -0
  14. package/dist/ConversationalAgentPickerChat.js.map +1 -0
  15. package/dist/ConversationalAgentPickerChat.stories.d.ts +96 -0
  16. package/dist/ConversationalAgentPickerChat.stories.d.ts.map +1 -0
  17. package/dist/ConversationalAgentPickerChat.stories.js +209 -0
  18. package/dist/ConversationalAgentPickerChat.stories.js.map +1 -0
  19. package/dist/components/AgentList.d.ts +10 -0
  20. package/dist/components/AgentList.d.ts.map +1 -0
  21. package/dist/components/AgentList.js +20 -0
  22. package/dist/components/AgentList.js.map +1 -0
  23. package/dist/components/AgentSchemaForm/AgentSchemaField.d.ts +26 -0
  24. package/dist/components/AgentSchemaForm/AgentSchemaField.d.ts.map +1 -0
  25. package/dist/components/AgentSchemaForm/AgentSchemaField.js +96 -0
  26. package/dist/components/AgentSchemaForm/AgentSchemaField.js.map +1 -0
  27. package/dist/components/AgentSchemaForm/AgentSchemaForm.d.ts +38 -0
  28. package/dist/components/AgentSchemaForm/AgentSchemaForm.d.ts.map +1 -0
  29. package/dist/components/AgentSchemaForm/AgentSchemaForm.js +105 -0
  30. package/dist/components/AgentSchemaForm/AgentSchemaForm.js.map +1 -0
  31. package/dist/components/AgentSchemaForm/AgentSchemaForm.stories.d.ts +30 -0
  32. package/dist/components/AgentSchemaForm/AgentSchemaForm.stories.d.ts.map +1 -0
  33. package/dist/components/AgentSchemaForm/AgentSchemaForm.stories.js +236 -0
  34. package/dist/components/AgentSchemaForm/AgentSchemaForm.stories.js.map +1 -0
  35. package/dist/components/AgentSchemaForm/FieldShell.d.ts +12 -0
  36. package/dist/components/AgentSchemaForm/FieldShell.d.ts.map +1 -0
  37. package/dist/components/AgentSchemaForm/FieldShell.js +4 -0
  38. package/dist/components/AgentSchemaForm/FieldShell.js.map +1 -0
  39. package/dist/components/AgentSchemaForm/index.d.ts +5 -0
  40. package/dist/components/AgentSchemaForm/index.d.ts.map +1 -0
  41. package/dist/components/AgentSchemaForm/index.js +2 -0
  42. package/dist/components/AgentSchemaForm/index.js.map +1 -0
  43. package/dist/components/AgentSchemaForm/inputs/ArrayField.d.ts +7 -0
  44. package/dist/components/AgentSchemaForm/inputs/ArrayField.d.ts.map +1 -0
  45. package/dist/components/AgentSchemaForm/inputs/ArrayField.js +28 -0
  46. package/dist/components/AgentSchemaForm/inputs/ArrayField.js.map +1 -0
  47. package/dist/components/AgentSchemaForm/inputs/ObjectField.d.ts +8 -0
  48. package/dist/components/AgentSchemaForm/inputs/ObjectField.d.ts.map +1 -0
  49. package/dist/components/AgentSchemaForm/inputs/ObjectField.js +75 -0
  50. package/dist/components/AgentSchemaForm/inputs/ObjectField.js.map +1 -0
  51. package/dist/components/AgentSchemaForm/inputs/validation.d.ts +10 -0
  52. package/dist/components/AgentSchemaForm/inputs/validation.d.ts.map +1 -0
  53. package/dist/components/AgentSchemaForm/inputs/validation.js +41 -0
  54. package/dist/components/AgentSchemaForm/inputs/validation.js.map +1 -0
  55. package/dist/components/AgentSchemaForm/resolveSchema.d.ts +7 -0
  56. package/dist/components/AgentSchemaForm/resolveSchema.d.ts.map +1 -0
  57. package/dist/components/AgentSchemaForm/resolveSchema.js +162 -0
  58. package/dist/components/AgentSchemaForm/resolveSchema.js.map +1 -0
  59. package/dist/components/AgentSchemaForm/types.d.ts +34 -0
  60. package/dist/components/AgentSchemaForm/types.d.ts.map +1 -0
  61. package/dist/components/AgentSchemaForm/types.js +8 -0
  62. package/dist/components/AgentSchemaForm/types.js.map +1 -0
  63. package/dist/components/FeedbackDialog.d.ts +2 -1
  64. package/dist/components/FeedbackDialog.d.ts.map +1 -1
  65. package/dist/components/FeedbackDialog.js +6 -2
  66. package/dist/components/FeedbackDialog.js.map +1 -1
  67. package/dist/components/InputsPage.d.ts +18 -0
  68. package/dist/components/InputsPage.d.ts.map +1 -0
  69. package/dist/components/InputsPage.js +32 -0
  70. package/dist/components/InputsPage.js.map +1 -0
  71. package/dist/components/Loader.d.ts +6 -0
  72. package/dist/components/Loader.d.ts.map +1 -0
  73. package/dist/components/Loader.js +6 -0
  74. package/dist/components/Loader.js.map +1 -0
  75. package/dist/components/SettingsDialog/InputsSection.d.ts +15 -0
  76. package/dist/components/SettingsDialog/InputsSection.d.ts.map +1 -0
  77. package/dist/components/SettingsDialog/InputsSection.js +29 -0
  78. package/dist/components/SettingsDialog/InputsSection.js.map +1 -0
  79. package/dist/components/SettingsDialog/ProfileSection.d.ts +7 -0
  80. package/dist/components/SettingsDialog/ProfileSection.d.ts.map +1 -0
  81. package/dist/components/SettingsDialog/ProfileSection.js +146 -0
  82. package/dist/components/SettingsDialog/ProfileSection.js.map +1 -0
  83. package/dist/components/SettingsDialog/SettingsDialog.d.ts +33 -0
  84. package/dist/components/SettingsDialog/SettingsDialog.d.ts.map +1 -0
  85. package/dist/components/SettingsDialog/SettingsDialog.js +18 -0
  86. package/dist/components/SettingsDialog/SettingsDialog.js.map +1 -0
  87. package/dist/components/SettingsDialog/index.d.ts +3 -0
  88. package/dist/components/SettingsDialog/index.d.ts.map +1 -0
  89. package/dist/components/SettingsDialog/index.js +2 -0
  90. package/dist/components/SettingsDialog/index.js.map +1 -0
  91. package/dist/components/ToolConfirmation.d.ts +20 -0
  92. package/dist/components/ToolConfirmation.d.ts.map +1 -0
  93. package/dist/components/ToolConfirmation.js +20 -0
  94. package/dist/components/ToolConfirmation.js.map +1 -0
  95. package/dist/components/ToolConfirmationRenderer.d.ts +15 -0
  96. package/dist/components/ToolConfirmationRenderer.d.ts.map +1 -0
  97. package/dist/components/ToolConfirmationRenderer.js +52 -0
  98. package/dist/components/ToolConfirmationRenderer.js.map +1 -0
  99. package/dist/components/agentUtils.d.ts +4 -0
  100. package/dist/components/agentUtils.d.ts.map +1 -0
  101. package/dist/components/agentUtils.js +24 -0
  102. package/dist/components/agentUtils.js.map +1 -0
  103. package/dist/components/useFavorites.d.ts +7 -0
  104. package/dist/components/useFavorites.d.ts.map +1 -0
  105. package/dist/components/useFavorites.js +47 -0
  106. package/dist/components/useFavorites.js.map +1 -0
  107. package/dist/constants/countries.d.ts +251 -0
  108. package/dist/constants/countries.d.ts.map +1 -0
  109. package/dist/constants/countries.js +250 -0
  110. package/dist/constants/countries.js.map +1 -0
  111. package/dist/hooks/useResolvedAgent.d.ts +34 -0
  112. package/dist/hooks/useResolvedAgent.d.ts.map +1 -0
  113. package/dist/hooks/useResolvedAgent.js +99 -0
  114. package/dist/hooks/useResolvedAgent.js.map +1 -0
  115. package/dist/i18n/i18n.config.d.ts +2 -0
  116. package/dist/i18n/i18n.config.d.ts.map +1 -0
  117. package/dist/i18n/i18n.config.js +24 -0
  118. package/dist/i18n/i18n.config.js.map +1 -0
  119. package/dist/i18n/index.d.ts +2 -0
  120. package/dist/i18n/index.d.ts.map +1 -0
  121. package/dist/i18n/index.js +2 -0
  122. package/dist/i18n/index.js.map +1 -0
  123. package/dist/i18n/locales/en/index.json +306 -0
  124. package/dist/i18n/locales/keys/index.json +306 -0
  125. package/dist/icons/ConversationalAgentIcon.d.ts +7 -0
  126. package/dist/icons/ConversationalAgentIcon.d.ts.map +1 -0
  127. package/dist/icons/ConversationalAgentIcon.js +8 -0
  128. package/dist/icons/ConversationalAgentIcon.js.map +1 -0
  129. package/dist/icons/TimeIcon.d.ts +2 -0
  130. package/dist/icons/TimeIcon.d.ts.map +1 -0
  131. package/dist/icons/TimeIcon.js +3 -0
  132. package/dist/icons/TimeIcon.js.map +1 -0
  133. package/dist/index.d.ts +10 -1
  134. package/dist/index.d.ts.map +1 -1
  135. package/dist/index.js +4 -0
  136. package/dist/index.js.map +1 -1
  137. package/dist/types.d.ts +90 -3
  138. package/dist/types.d.ts.map +1 -1
  139. package/dist/types.js +2 -0
  140. package/dist/types.js.map +1 -1
  141. package/dist/utils/normalizeValue.d.ts +7 -0
  142. package/dist/utils/normalizeValue.d.ts.map +1 -0
  143. package/dist/utils/normalizeValue.js +31 -0
  144. package/dist/utils/normalizeValue.js.map +1 -0
  145. package/dist/utils/resolveAgent.d.ts +17 -0
  146. package/dist/utils/resolveAgent.d.ts.map +1 -0
  147. package/dist/utils/resolveAgent.js +25 -0
  148. package/dist/utils/resolveAgent.js.map +1 -0
  149. package/dist/utils/telemetryUtils.d.ts +1 -1
  150. package/dist/utils/telemetryUtils.d.ts.map +1 -1
  151. package/dist/utils/telemetryUtils.js +2 -2
  152. package/dist/utils/telemetryUtils.js.map +1 -1
  153. package/dist/utils.d.ts +11 -3
  154. package/dist/utils.d.ts.map +1 -1
  155. package/dist/utils.js +36 -9
  156. package/dist/utils.js.map +1 -1
  157. package/dist/version.d.ts +1 -1
  158. package/dist/version.js +1 -1
  159. package/package.json +10 -5
@@ -1,43 +1,128 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { ApChat, AutopilotChatEvent, AutopilotChatMode, AutopilotChatService, } from "@uipath/apollo-react/material/components";
3
- import { i18n } from "@lingui/core";
3
+ import { FontVariantToken } from "@uipath/apollo-core";
4
+ import i18next from "i18next";
4
5
  import { Alert, AlertDescription, Button } 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";
8
15
  import "./ConversationalAgentChat.css";
9
16
  import { TelemetryEvent, MessageWidget, TelemetryStatus, } from "./types";
10
- import { convertAttachmentToFile, createFileKey, getConversationHistoryDisplayItems, mapExchangesToChatMessages, normalizeInput, } from "./utils";
17
+ import { convertAttachmentToFile, createFileKey, getConversationHistoryDisplayItems, mapCitationSource, mapExchangesToChatMessages, normalizeInput, sortEvaluationSets, } from "./utils";
11
18
  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));
19
+ import { initI18n } from "./i18n";
20
+ import { resolveAgent as fetchAgentRelease } from "./utils/resolveAgent";
21
+ initI18n();
22
+ const TOOL_CONFIRMATION_WIDGET_ID_PREFIX = "confirmation-";
23
+ // Map widget Locale to Apollo supported locale to allow for locales not supported by Apollo
24
+ function toApolloSupportedLocale(widgetLocale) {
25
+ return widgetLocale === "keys" ? "en" : widgetLocale;
26
+ }
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, }) => {
28
+ // `inputSchema` is an internal debug-only override. In normal usage the
29
+ // schema is resolved from the agent release, so accepting it outside debug
30
+ // mode would only confuse callers — reject the combination loudly.
31
+ if (inputSchemaProp && !isDebugMode) {
32
+ throw new Error("`inputSchema` is only supported when `isDebugMode` is true; the agent's input schema is resolved automatically.");
33
+ }
34
+ // must change language before useTranslation is called to avoid stale translations
35
+ if (i18next.language !== locale) {
36
+ i18next.changeLanguage(locale);
37
+ }
38
+ const { t } = useTranslation();
39
+ const agentService = useRef(new ConversationalAgent(sdk, {
40
+ ...(externalUserId ? { externalUserId } : {}),
41
+ surfaceName,
42
+ surfaceVersion,
43
+ }));
16
44
  const currentConversation = useRef(null);
17
45
  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
46
  const themeRef = useRef(theme);
22
- themeRef.current = theme;
23
47
  const overrideLabelsRef = useRef(overrideLabels);
24
- overrideLabelsRef.current = overrideLabels;
25
48
  const disabledFeaturesRef = useRef(disabledFeatures);
26
- disabledFeaturesRef.current = disabledFeatures;
27
49
  const firstRunExperienceRef = useRef(firstRunExperience);
28
- firstRunExperienceRef.current = firstRunExperience;
29
- const onUserMessageSentRef = useRef(onUserMessageSent);
30
- onUserMessageSentRef.current = onUserMessageSent;
31
50
  const initialConversationConsumed = useRef(false);
51
+ const resolvedAgent = useRef(null);
52
+ const folderIdRef = useRef(folderId);
53
+ const toolConfirmationLabelsRef = useRef(null);
54
+ // Per-instance so unmounting one widget doesn't tear down another's React roots.
55
+ const toolConfirmationRenderer = useMemo(() => createToolConfirmationRenderer(), []);
56
+ // useLayoutEffect is ok here because the work is minimal enough that the cost is essentially zero
57
+ // needed because React 19 doesn't support ref writes on render
58
+ useLayoutEffect(() => {
59
+ themeRef.current = theme;
60
+ overrideLabelsRef.current = overrideLabels;
61
+ disabledFeaturesRef.current = disabledFeatures;
62
+ firstRunExperienceRef.current = firstRunExperience;
63
+ folderIdRef.current = folderId;
64
+ onEvaluationSetClickedRef.current = onEvaluationSetClicked;
65
+ onUserMessageSentRef.current = onUserMessageSent;
66
+ toolConfirmationLabelsRef.current = {
67
+ cancel: t("cancel"),
68
+ confirm: t("tool_confirmation_confirm"),
69
+ statusCancelled: t("tool_confirmation_status_cancelled"),
70
+ statusConfirmed: t("tool_confirmation_status_confirmed"),
71
+ };
72
+ }, [
73
+ theme,
74
+ overrideLabels,
75
+ disabledFeatures,
76
+ firstRunExperience,
77
+ onEvaluationSetClicked,
78
+ onUserMessageSent,
79
+ folderId,
80
+ t,
81
+ ]);
82
+ // Rebuild the SDK service when sdk or externalUserId change. Skip the first run because the
83
+ // useRef initializer above already built it with the initial values. The chat is re-initialized
84
+ // via initKey (which includes externalUserId) so dependent refs (session, currentConversation,
85
+ // activeExchange) are reset by onNewChat / initChat downstream.
86
+ const didMountAgentServiceRef = useRef(false);
87
+ useLayoutEffect(() => {
88
+ if (!didMountAgentServiceRef.current) {
89
+ didMountAgentServiceRef.current = true;
90
+ return;
91
+ }
92
+ agentService.current = new ConversationalAgent(sdk, externalUserId ? { externalUserId } : undefined);
93
+ }, [sdk, externalUserId]);
32
94
  const session = useRef(null);
33
95
  const pastConversations = useRef([]);
34
96
  const uploadedAttachments = useRef(new Map());
35
97
  const conversationsCursor = useRef(undefined);
98
+ const agentIdRef = useRef(undefined);
99
+ const agentKeyRef = useRef(undefined);
100
+ const searchTextRef = useRef("");
36
101
  const [chatService, setChatService] = useState();
37
102
  const [error, setError] = useState(null);
103
+ const [inputSchemaState, setInputSchemaState] = useState(null);
104
+ const [showInputPage, setShowInputPage] = useState(false);
105
+ const [agentNameState, setAgentNameState] = useState("");
106
+ // Bumped on New Chat to force a fresh <InputsPage> mount with cleared form state.
107
+ const [inputsInstance, setInputsInstance] = useState(0);
38
108
  const activeExchange = useRef(null);
39
109
  const [feedbackDialogOpen, setFeedbackDialogOpen] = useState(false);
110
+ const [feedbackIsPositive, setFeedbackIsPositive] = useState(false);
40
111
  const pendingFeedback = useRef(null);
112
+ const [hasMessages, setHasMessages] = useState(false);
113
+ const onEvaluationSetClickedRef = useRef(onEvaluationSetClicked);
114
+ const onUserMessageSentRef = useRef(onUserMessageSent);
115
+ const chatServiceRef = useRef(null);
116
+ const settingsRootRef = useRef(null);
117
+ // Last-applied agent inputs for the active conversation. Pre-populates the
118
+ // settings inputs form when reopened; cleared on New Chat.
119
+ const storedAgentInputs = useRef({});
120
+ // Mirrors `inputSchemaState` so the imperative `renderSettings` closure always
121
+ // sees the current schema without re-instantiating the chat service.
122
+ const inputSchemaStateRef = useRef(null);
123
+ useLayoutEffect(() => {
124
+ inputSchemaStateRef.current = inputSchemaState;
125
+ }, [inputSchemaState]);
41
126
  const setupExchangeHandlers = useCallback((exchange) => {
42
127
  if (!chatService)
43
128
  return;
@@ -45,71 +130,177 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
45
130
  trackTelemetry(TelemetryEvent.SendMessage, TelemetryStatus.Error, {
46
131
  error: error.message,
47
132
  });
48
- chatService.setError(error.message || "Something went wrong. Please try again.");
133
+ chatService.setError(error.message || t("error_generic"));
49
134
  });
50
135
  exchange.onMessageStart((message) => {
51
136
  if (message.startEvent.role === "assistant") {
52
137
  const messageId = message.messageId;
53
138
  const messageTimestamp = message.startEvent.timestamp;
139
+ const exchangeId = exchange.exchangeId;
140
+ // Shared envelope for the assistant stream (text, citation, done);
141
+ // only the chunk and `done` vary.
142
+ // stream: true so Apollo's actions row (copy, thumbs) renders —
143
+ // useIsStreamingMessage only listens to SendChunk events; the
144
+ // stream: false branch fires Response and leaves isStreaming stuck
145
+ // at true.
146
+ const sendAssistantChunk = (contentPartChunk, done = false) => {
147
+ chatService.sendResponse({
148
+ id: messageId,
149
+ contentPartChunk,
150
+ created_at: messageTimestamp,
151
+ widget: MessageWidget.AI,
152
+ stream: true,
153
+ done,
154
+ meta: { exchangeId },
155
+ });
156
+ };
54
157
  message.onContentPartStart((contentPart) => {
55
158
  if (contentPart.startEvent.mimeType.startsWith("text/")) {
56
- let fullResponse = "";
159
+ // Apollo dictates citation boundaries by chunk index — text and
160
+ // its citation share one index, the next text segment uses index+1.
161
+ let chunkIndex = 0;
162
+ let isFirstChunk = true;
57
163
  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
- });
164
+ if (chunk.citation?.startCitation && !isFirstChunk) {
165
+ chunkIndex++;
166
+ }
167
+ if (chunk.data !== undefined) {
168
+ sendAssistantChunk({ text: chunk.data, index: chunkIndex });
169
+ }
170
+ if (chunk.citation?.endCitation) {
171
+ for (const source of chunk.citation.endCitation.sources) {
172
+ sendAssistantChunk({
173
+ citation: mapCitationSource(source),
174
+ index: chunkIndex,
175
+ });
176
+ }
177
+ chunkIndex++;
178
+ }
179
+ isFirstChunk = false;
67
180
  });
68
181
  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
- });
182
+ sendAssistantChunk({ index: chunkIndex }, true);
77
183
  });
78
184
  }
79
185
  });
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
- : {};
186
+ // Track tool calls so we can defer the spinner when an interrupt arrives
187
+ const pendingToolCalls = new Map();
188
+ const sendToolCallSpinner = (toolCallId) => {
189
+ const pending = pendingToolCalls.get(toolCallId);
190
+ if (!pending || pending.spinnerSent)
191
+ return;
192
+ pending.spinnerSent = true;
86
193
  chatService.sendResponse({
87
- id: toolCall.toolCallId,
88
- content: `Performing ${startEvent.toolName}`,
89
- created_at: startTimeIso,
194
+ id: toolCallId,
195
+ content: t("performing_action_message", {
196
+ action: pending.toolName,
197
+ }),
198
+ created_at: pending.startTimeIso,
90
199
  widget: MessageWidget.ApolloAgentsToolCall,
91
200
  meta: {
92
- toolName: startEvent.toolName,
93
- input: toolInput,
94
- startTime: startTimeIso,
201
+ toolName: pending.toolName,
202
+ input: pending.toolInput,
203
+ startTime: pending.startTimeIso,
95
204
  },
96
205
  });
97
- toolCall.onToolCallEnd((endEvent) => {
98
- const endTimeIso = new Date().toISOString();
206
+ };
207
+ // Caller supplies the approve/reject channel.
208
+ const sendToolConfirmationWidget = (params) => {
209
+ const widgetMessageId = `${TOOL_CONFIRMATION_WIDGET_ID_PREFIX}${params.toolCallId}`;
210
+ const confirmationData = {
211
+ toolCallId: params.toolCallId,
212
+ toolName: params.toolName,
213
+ inputSchema: params.inputSchema ?? {},
214
+ inputValue: params.inputValue,
215
+ };
216
+ const createdAt = new Date().toISOString();
217
+ const sendUpdate = (isCompleted, wasRejected) => {
99
218
  chatService.sendResponse({
100
- id: toolCall.toolCallId,
101
- content: `Performing ${startEvent.toolName}`,
102
- created_at: endTimeIso,
103
- widget: MessageWidget.ApolloAgentsToolCall,
219
+ id: widgetMessageId,
220
+ content: t("tool_confirmation_required"),
221
+ created_at: createdAt,
222
+ widget: MessageWidget.ToolConfirmation,
223
+ stream: false,
224
+ done: true,
104
225
  meta: {
105
- toolName: startEvent.toolName,
106
- input: toolInput,
107
- startTime: startTimeIso,
108
- output: endEvent.output,
109
- endTime: endTimeIso,
110
- isError: endEvent.isError,
226
+ confirmationData,
227
+ isCompleted,
228
+ wasRejected,
229
+ // Unreachable once completed (the form's buttons are gone),
230
+ // but kept on the meta so its shape stays stable.
231
+ onApprove: handleApprove,
232
+ onCancel: handleCancel,
111
233
  },
112
234
  });
235
+ };
236
+ const handleApprove = (endValue) => {
237
+ sendUpdate(true, false);
238
+ params.onApprove(endValue.input);
239
+ };
240
+ const handleCancel = () => {
241
+ sendUpdate(true, true);
242
+ params.onCancel();
243
+ };
244
+ sendUpdate(false, false);
245
+ };
246
+ message.onToolCallStart((toolCall) => {
247
+ const startEvent = toolCall.startEvent;
248
+ const startTimeIso = new Date().toISOString();
249
+ const toolInput = startEvent.input
250
+ ? normalizeInput(startEvent.input)
251
+ : {};
252
+ pendingToolCalls.set(toolCall.toolCallId, {
253
+ toolName: startEvent.toolName,
254
+ toolInput,
255
+ startTimeIso,
256
+ spinnerSent: false,
257
+ });
258
+ // New flow: confirmation is a property of the tool call itself.
259
+ if (startEvent.requireConfirmation) {
260
+ sendToolConfirmationWidget({
261
+ toolCallId: toolCall.toolCallId,
262
+ toolName: startEvent.toolName,
263
+ inputSchema: startEvent.inputSchema,
264
+ inputValue: startEvent.input,
265
+ onApprove: (input) => {
266
+ sendToolCallSpinner(toolCall.toolCallId);
267
+ const approvedInput = input ?? startEvent.input ?? {};
268
+ toolCall.sendToolCallConfirm({
269
+ approved: true,
270
+ input: approvedInput,
271
+ });
272
+ },
273
+ onCancel: () => {
274
+ toolCall.sendToolCallConfirm({ approved: false });
275
+ },
276
+ });
277
+ }
278
+ else {
279
+ // No confirmation needed — show spinner immediately.
280
+ sendToolCallSpinner(toolCall.toolCallId);
281
+ }
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);
113
304
  });
114
305
  });
115
306
  }
@@ -119,8 +310,48 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
119
310
  chatService.sendOutputStreamEvent({ turnComplete: true });
120
311
  chatService.setShowLoading(false);
121
312
  chatService.setWaiting(false);
313
+ setHasMessages(true);
122
314
  });
123
- }, [chatService]);
315
+ }, [chatService, t]);
316
+ const resolveAgent = useCallback(async () => {
317
+ let effectiveAgentId = agentId;
318
+ let effectiveFolderId = folderIdRef.current;
319
+ // When the host passes only existingConversationId, derive the agent from
320
+ // the conversation so the header title + FRE still render for empty replays.
321
+ if (effectiveAgentId == null && existingConversationId) {
322
+ if (!currentConversation.current &&
323
+ !initialConversationConsumed.current) {
324
+ const existing = await agentService.current.conversations.getById(existingConversationId);
325
+ currentConversation.current = existing;
326
+ initialConversationConsumed.current = true;
327
+ }
328
+ const conv = currentConversation.current;
329
+ if (conv?.agentId != null) {
330
+ effectiveAgentId = conv.agentId;
331
+ effectiveFolderId = conv.folderId;
332
+ }
333
+ }
334
+ if (effectiveAgentId == null)
335
+ return undefined;
336
+ if (resolvedAgent.current?.id === effectiveAgentId) {
337
+ const cachedFolderId = resolvedAgent.current.folderId;
338
+ if (effectiveFolderId == null || cachedFolderId === effectiveFolderId) {
339
+ return resolvedAgent.current;
340
+ }
341
+ }
342
+ const release = await fetchAgentRelease(sdk, effectiveAgentId, effectiveFolderId, { externalUserId });
343
+ if (!release)
344
+ return undefined;
345
+ resolvedAgent.current = release;
346
+ folderIdRef.current = release.folderId;
347
+ return release;
348
+ }, [agentId, existingConversationId, sdk, externalUserId]);
349
+ const setConversationHistory = useCallback((next, allLoaded) => {
350
+ pastConversations.current = next;
351
+ if (!chatService)
352
+ return;
353
+ chatService.setHistory(getConversationHistoryDisplayItems(next, t("new_chat")), allLoaded);
354
+ }, [chatService, t]);
124
355
  const getConversation = useCallback(async () => {
125
356
  if (currentConversation.current) {
126
357
  return currentConversation.current;
@@ -132,32 +363,81 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
132
363
  initialConversationConsumed.current = true;
133
364
  return existing;
134
365
  }
135
- if (!agentId || !folderId) {
136
- throw new Error("Either conversationId or agentId and folderId must be provided");
366
+ const agent = await resolveAgent();
367
+ if (!agent) {
368
+ throw new Error(t("error_missing_conversation_params"));
137
369
  }
138
- const newConversation = await agentService.current.conversations.create(agentId, folderId);
370
+ const newConversation = await agent.conversations.create(jobStartOverrides ? { jobStartOverrides } : undefined);
139
371
  currentConversation.current = newConversation;
372
+ // Show the new conversation in the sidebar immediately so its label
373
+ // (auto-generated by the service after the first exchange) can refresh
374
+ // in place via onLabelUpdated rather than waiting for a history reload.
375
+ setConversationHistory([newConversation, ...pastConversations.current]);
140
376
  return newConversation;
141
- }, [agentId, folderId, existingConversationId]);
377
+ }, [
378
+ existingConversationId,
379
+ jobStartOverrides,
380
+ resolveAgent,
381
+ setConversationHistory,
382
+ t,
383
+ ]);
142
384
  const getSessionHelper = useCallback(async () => {
143
385
  if (session.current) {
144
386
  return session.current;
145
387
  }
146
388
  const conversation = await getConversation();
147
389
  const sessionHelper = agentService.current.conversations.startSession(conversation.id, { echo: false });
390
+ // Refresh the sidebar label when the service auto-generates one (or the
391
+ // label is updated via the API). Bind to this session's conversation id
392
+ // so a stale event from an orphaned session can't mislabel the active one.
393
+ sessionHelper.onLabelUpdated(({ label }) => {
394
+ setConversationHistory(pastConversations.current.map((c) => c.id === conversation.id ? { ...c, label } : c));
395
+ });
148
396
  return new Promise((resolve) => {
149
397
  sessionHelper.onSessionStarted(() => {
150
398
  session.current = sessionHelper;
151
399
  resolve(sessionHelper);
152
400
  });
153
401
  });
154
- }, [getConversation]);
402
+ }, [getConversation, setConversationHistory]);
155
403
  const onNewChat = useCallback(() => {
156
404
  currentConversation.current = null;
157
405
  session.current = null;
158
406
  activeExchange.current = null;
407
+ storedAgentInputs.current = {};
408
+ setHasMessages(false);
409
+ // Re-show the InputsPage with a cleared form when the agent's schema has
410
+ // required inputs. Bumping the counter forces an unmount/remount via the
411
+ // key on <InputsPage>, which resets internal form state.
412
+ if ((inputSchemaState?.required?.length ?? 0) > 0) {
413
+ setInputsInstance((n) => n + 1);
414
+ setShowInputPage(true);
415
+ }
159
416
  trackTelemetry(TelemetryEvent.NewChat, TelemetryStatus.Success);
417
+ }, [inputSchemaState]);
418
+ const buildHistoryFilterOptions = useCallback(() => {
419
+ // The SDK's URL builder calls value.toString() without a null check, so
420
+ // omit any param that is undefined/empty rather than passing it as such.
421
+ const opts = {};
422
+ if (agentKeyRef.current)
423
+ opts.agentKey = agentKeyRef.current;
424
+ if (agentIdRef.current !== undefined)
425
+ opts.agentId = agentIdRef.current;
426
+ if (searchTextRef.current)
427
+ opts.label = searchTextRef.current;
428
+ return opts;
160
429
  }, []);
430
+ const fetchFirstHistoryPage = useCallback(async () => {
431
+ if (!chatService)
432
+ return;
433
+ const result = await agentService.current.conversations.getAll({
434
+ sort: SortOrder.Descending,
435
+ pageSize: 20,
436
+ ...buildHistoryFilterOptions(),
437
+ });
438
+ conversationsCursor.current = result.nextCursor;
439
+ setConversationHistory(result.items, !result.hasNextPage);
440
+ }, [buildHistoryFilterOptions, chatService, setConversationHistory]);
161
441
  const onHistoryLoadMore = useCallback(async () => {
162
442
  if (!chatService)
163
443
  return;
@@ -169,21 +449,25 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
169
449
  sort: SortOrder.Descending,
170
450
  pageSize: 20,
171
451
  cursor: conversationsCursor.current,
452
+ ...buildHistoryFilterOptions(),
172
453
  });
173
454
  conversationsCursor.current = result.nextCursor;
174
455
  pastConversations.current = [...pastConversations.current, ...result.items];
175
- chatService.appendOlderHistoryItems(getConversationHistoryDisplayItems(result.items), !result.hasNextPage);
176
- }, [chatService]);
456
+ chatService.appendOlderHistoryItems(getConversationHistoryDisplayItems(result.items, t("new_chat")), !result.hasNextPage);
457
+ }, [buildHistoryFilterOptions, chatService, t]);
458
+ const onHistorySearch = useCallback(async ({ searchText }) => {
459
+ searchTextRef.current = searchText;
460
+ await fetchFirstHistoryPage();
461
+ }, [fetchFirstHistoryPage]);
177
462
  const onClickDeleteConversation = useCallback(async (id) => {
178
463
  if (!chatService)
179
464
  return;
180
465
  await agentService.current.conversations.deleteById(id);
181
- pastConversations.current = pastConversations.current.filter((c) => c.id !== id);
182
- chatService.setHistory(getConversationHistoryDisplayItems(pastConversations.current));
466
+ setConversationHistory(pastConversations.current.filter((c) => c.id !== id));
183
467
  if (currentConversation.current?.id === id) {
184
468
  onNewChat();
185
469
  }
186
- }, [chatService, onNewChat]);
470
+ }, [chatService, onNewChat, setConversationHistory]);
187
471
  const onSendMessage = useCallback(async (data) => {
188
472
  try {
189
473
  // required for debug-mode hosts that need to gate agent execution on the first user message
@@ -219,9 +503,9 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
219
503
  trackTelemetry(TelemetryEvent.SendMessage, TelemetryStatus.Error, {
220
504
  error: errorMessage,
221
505
  });
222
- chatService?.setError(`Failed to send message: ${errorMessage}`);
506
+ chatService?.setError(t("error_send_message", { errorMessage }));
223
507
  }
224
- }, [chatService, getSessionHelper, setupExchangeHandlers]);
508
+ }, [chatService, getSessionHelper, setupExchangeHandlers, t]);
225
509
  const processAttachmentsInBatch = useCallback(async (attachmentBatch) => {
226
510
  if (!chatService)
227
511
  return;
@@ -272,7 +556,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
272
556
  // Handle any failed uploads
273
557
  const failedUploads = results.filter((result) => !result.success);
274
558
  if (failedUploads.length > 0) {
275
- chatService.setError("Failed to upload attachments. Please try again.");
559
+ chatService.setError(t("error_upload_attachments"));
276
560
  for (const failedUpload of failedUploads) {
277
561
  const key = createFileKey(failedUpload.attachment);
278
562
  uploadedAttachments.current.delete(key);
@@ -288,7 +572,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
288
572
  }
289
573
  }
290
574
  }
291
- }, [chatService, processAttachmentsInBatch]);
575
+ }, [chatService, processAttachmentsInBatch, t]);
292
576
  const fetchExchanges = useCallback(async (conversationId) => {
293
577
  const conversation = await agentService.current.conversations.getById(conversationId);
294
578
  const allExchanges = (await conversation.exchanges.getAll()).items;
@@ -307,7 +591,9 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
307
591
  currentConversation.current = selectedConversation;
308
592
  session.current = null;
309
593
  const allExchanges = await fetchExchanges(selectedConversation.id);
310
- chatService.setConversation(mapExchangesToChatMessages(allExchanges));
594
+ const messages = mapExchangesToChatMessages(allExchanges);
595
+ chatService.setConversation(messages);
596
+ setHasMessages(messages.length > 0);
311
597
  trackTelemetry(TelemetryEvent.OpenConversation, TelemetryStatus.Success, {
312
598
  conversationId: id,
313
599
  });
@@ -318,68 +604,157 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
318
604
  conversationId: id,
319
605
  error: errorMessage,
320
606
  });
321
- chatService.setError(`Failed to open conversation: ${errorMessage}`);
607
+ chatService.setError(t("error_open_conversation", { errorMessage }));
322
608
  }
323
- }, [chatService, fetchExchanges]);
609
+ }, [chatService, fetchExchanges, t]);
324
610
  const initChat = useCallback(async () => {
325
- const initKey = `${agentId}-${folderId}-${existingConversationId ?? ""}`;
611
+ const initKey = `${agentId}-${folderId}-${existingConversationId ?? ""}-${externalUserId ?? ""}`;
326
612
  try {
327
613
  initializedFor.current = initKey;
328
- const agentRelease = agentId && folderId
329
- ? await agentService.current.getById(agentId, folderId)
330
- : undefined;
614
+ const agentRelease = await resolveAgent();
615
+ agentIdRef.current = agentRelease?.id;
616
+ agentKeyRef.current = agentRelease?.releaseKey;
331
617
  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
618
+ // In debug mode the agent (and its derived schema) may not be resolvable,
619
+ // so an explicit `inputSchema` override takes precedence. Normal usage
620
+ // always derives the schema from the resolved agent release.
621
+ // TODO(sdk-typing): drop the cast once @uipath/uipath-typescript exposes
622
+ // inputSchema on AgentRelease. The API returns it but the SDK type
623
+ // definitions don't include it yet.
624
+ const inputSchema = (isDebugMode ? inputSchemaProp : undefined) ??
625
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
626
+ agentRelease?.inputSchema;
627
+ // Show input page if there's an inputSchema with required properties and
628
+ // this is a new conversation. Optional-only schemas use the settings panel.
629
+ // Skip when resuming an existing conversation — its inputs were already
630
+ // captured at creation time. The exception is debug mode, where the host
631
+ // opens an empty conversation up front, so inputs are still collected here.
632
+ const hasRequiredInputs = (inputSchema?.required?.length ?? 0) > 0;
633
+ // Persist the schema regardless of `hasRequiredInputs` so the settings
634
+ // panel can render optional-input editing.
635
+ setInputSchemaState(inputSchema ?? null);
636
+ if (hasRequiredInputs && (!existingConversationId || isDebugMode)) {
637
+ setAgentNameState(agentName);
638
+ setShowInputPage(true);
639
+ }
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
336
654
  ? {
337
- title: firstRunExperienceRef.current.title ?? "",
338
- description: firstRunExperienceRef.current.description ?? "",
339
- suggestions: firstRunExperienceRef.current.suggestions ?? [],
655
+ title: appearance?.welcomeTitle ?? "",
656
+ description: appearance?.welcomeDescription ?? "",
657
+ suggestions: agentSuggestions,
340
658
  }
341
659
  : {
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
- })),
660
+ title: hostFallback?.title ?? "",
661
+ description: hostFallback?.description ?? "",
662
+ suggestions: hostFallback?.suggestions ?? [],
349
663
  };
664
+ // Persists agent inputs against the active conversation via
665
+ // updateConversation. Server-side this applies to all subsequent
666
+ // messages; we don't prepend per send.
667
+ const handleApplySettingsInputs = async (inputs) => {
668
+ const conversationId = currentConversation.current?.id;
669
+ if (!conversationId) {
670
+ throw new Error(t("error_missing_conversation_params"));
671
+ }
672
+ await agentService.current.conversations.updateById(conversationId, {
673
+ agentInput: { inline: inputs },
674
+ });
675
+ storedAgentInputs.current = inputs;
676
+ };
677
+ // TODO: if Apollo adds more renderer slots (footer, first-run, etc.),
678
+ // extract this mount/unmount plumbing into a `useApolloRenderer` hook.
679
+ const renderSettings = (element) => {
680
+ // Apollo clears `element.innerHTML` before every call to the renderer.
681
+ // Reusing a React root would leave its virtual DOM out of sync with the
682
+ // wiped real DOM, so we unmount and recreate on every invocation.
683
+ if (settingsRootRef.current) {
684
+ settingsRootRef.current.unmount();
685
+ settingsRootRef.current = null;
686
+ }
687
+ const root = createRoot(element);
688
+ settingsRootRef.current = root;
689
+ const profileResetKey = agentId != null && folderId != null
690
+ ? `${agentId}-${folderId}`
691
+ : "no-agent";
692
+ const conversationId = currentConversation.current?.id ?? "no-conv";
693
+ 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 }));
695
+ };
350
696
  const chatServiceInstance = AutopilotChatService.Instantiate({
697
+ instanceName: `agent-${agentId}-${folderId}`,
351
698
  config: {
352
699
  mode: AutopilotChatMode.Embedded,
353
- locale: localeRef.current,
700
+ locale: toApolloSupportedLocale(locale),
354
701
  theme: themeRef.current,
355
702
  readOnly,
356
703
  firstRunExperience: firstRunExperienceConfig,
357
704
  overrideLabels: {
358
705
  title: overrideLabelsRef.current?.title ?? agentName,
359
706
  footerDisclaimer: overrideLabelsRef.current?.footerDisclaimer ??
360
- DEFAULT_FOOTER_DISCLAIMER,
707
+ t("disclaimer_message"),
361
708
  inputPlaceholder: overrideLabelsRef.current?.inputPlaceholder ??
362
- DEFAULT_INPUT_PLACEHOLDER,
709
+ t("chat_input_placeholder"),
363
710
  },
364
711
  paginatedHistory: true,
712
+ settingsRenderer: renderSettings,
713
+ // Apollo's ApChat defaults message text to fontSizeM (14px); the
714
+ // deprecated portal-shell chat used a larger size, so bump primary
715
+ // text and markdown body tokens to fontSizeL (16px) to match.
716
+ spacing: {
717
+ primaryFontToken: FontVariantToken.fontSizeL,
718
+ primaryBoldFontToken: FontVariantToken.fontSizeLBold,
719
+ suggestionFontToken: FontVariantToken.fontSizeL,
720
+ markdownTokens: {
721
+ p: FontVariantToken.fontSizeL,
722
+ li: FontVariantToken.fontSizeL,
723
+ th: FontVariantToken.fontSizeL,
724
+ td: FontVariantToken.fontSizeL,
725
+ em: FontVariantToken.fontSizeL,
726
+ del: FontVariantToken.fontSizeL,
727
+ strong: FontVariantToken.fontSizeLBold,
728
+ link: FontVariantToken.fontSizeL,
729
+ },
730
+ },
365
731
  disabledFeatures: {
366
732
  fullScreen: true,
367
733
  preview: true,
368
734
  close: true,
369
- ...(!agentId || !folderId ? { newChat: true, history: true } : {}),
735
+ // Apollo defaults `settings: true`; flip it so our gear renders
736
+ // by default. Consumers can still opt out via `disabledFeatures`.
737
+ settings: false,
738
+ ...(!agentId ? { newChat: true, history: true } : {}),
370
739
  ...disabledFeaturesRef.current,
371
740
  },
372
741
  },
373
742
  });
743
+ chatServiceRef.current = chatServiceInstance;
374
744
  if (existingConversationId) {
375
745
  const conversation = await getConversation();
376
746
  const allExchanges = await fetchExchanges(conversation.id);
377
747
  chatServiceInstance.setConversation(mapExchangesToChatMessages(allExchanges));
378
748
  }
749
+ else {
750
+ // AutopilotChatService is a singleton, so it may still hold the
751
+ // previous agent's messages. Reset before showing the new agent.
752
+ chatServiceInstance.setConversation([]);
753
+ }
379
754
  setChatService(chatServiceInstance);
380
755
  }
381
756
  catch (err) {
382
- const message = err instanceof Error ? err.message : "Failed to initialize chat";
757
+ const message = err instanceof Error ? err.message : t("error_initialize_chat");
383
758
  setError(message);
384
759
  initializedFor.current = null;
385
760
  }
@@ -387,9 +762,15 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
387
762
  agentId,
388
763
  folderId,
389
764
  existingConversationId,
765
+ externalUserId,
766
+ inputSchemaProp,
767
+ isDebugMode,
768
+ locale,
390
769
  readOnly,
770
+ resolveAgent,
391
771
  getConversation,
392
772
  fetchExchanges,
773
+ t,
393
774
  ]);
394
775
  const handleReload = useCallback(() => {
395
776
  initializedFor.current = null;
@@ -408,17 +789,27 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
408
789
  chatService.setShowLoading(false);
409
790
  chatService.setWaiting(false);
410
791
  }, [chatService]);
792
+ const onCustomHeaderActionClicked = useCallback((action) => {
793
+ if (action.id.startsWith("eval-")) {
794
+ const evaluationSetId = action.id.replace("eval-", "");
795
+ onEvaluationSetClickedRef.current?.(evaluationSetId);
796
+ }
797
+ }, []);
411
798
  const onFeedback = useCallback((data) => {
412
799
  pendingFeedback.current = data;
800
+ setFeedbackIsPositive(!!data.action.details?.isPositive);
413
801
  setFeedbackDialogOpen(true);
414
802
  }, []);
415
803
  const onFeedbackSubmit = useCallback((comment) => {
416
804
  const data = pendingFeedback.current;
417
- if (data) {
805
+ // Streamed messages may not have meta.exchangeId yet; guard against it
806
+ // so a missing id doesn't throw and leave the dialog stuck open.
807
+ const exchangeId = data?.message.meta?.exchangeId;
808
+ if (data && exchangeId) {
418
809
  const rating = data.action.details?.isPositive
419
810
  ? FeedbackRating.Positive
420
811
  : FeedbackRating.Negative;
421
- currentConversation.current?.exchanges?.createFeedback(data.message.meta.exchangeId, {
812
+ currentConversation.current?.exchanges?.createFeedback(exchangeId, {
422
813
  rating,
423
814
  comment,
424
815
  });
@@ -430,39 +821,71 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
430
821
  setFeedbackDialogOpen(false);
431
822
  }, []);
432
823
  const onFeedbackCancel = useCallback(() => {
824
+ // Apollo's internal Feedback handler marks the message with `feedback`
825
+ // as soon as the thumb is clicked, which collapses the actions row to
826
+ // the chosen (disabled) thumb. If the user then cancels the dialog,
827
+ // re-send the message without `feedback` so the row reverts to both
828
+ // thumbs and the click can be retried.
829
+ const messageId = pendingFeedback.current?.message.id;
830
+ if (messageId && chatService) {
831
+ const current = chatService
832
+ .getConversation()
833
+ .find((m) => m.id === messageId);
834
+ if (current?.feedback) {
835
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
836
+ const { feedback: _feedback, ...withoutFeedback } = current;
837
+ chatService.sendResponse(withoutFeedback);
838
+ }
839
+ }
433
840
  pendingFeedback.current = null;
434
841
  setFeedbackDialogOpen(false);
435
- }, []);
436
- // Initialize chat service on mount and when agentId/folderId changes
842
+ }, [chatService]);
843
+ // Initialize chat service on mount and when agentId/folderId/externalUserId/existingConversationId changes
437
844
  useEffect(() => {
438
- const initKey = `${agentId}-${folderId}-${existingConversationId ?? ""}`;
845
+ const initKey = `${agentId}-${folderId}-${existingConversationId ?? ""}-${externalUserId ?? ""}`;
439
846
  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
440
850
  initChat();
441
851
  }
442
- }, [agentId, folderId, existingConversationId, initChat]);
443
- // Update locale/theme on the existing service. Locale must be set
444
- // synchronously (not in an effect) so that when ApChat remounts via
445
- // key={locale}, its LocaleProvider reads the correct value from
446
- // chatService.getLocale() on first render.
447
- // Sync locale to the service and Lingui before ApChat remounts via
448
- // key={locale}. Uses useLayoutEffect so the values are set before the
449
- // browser paints. We set _locale directly instead of calling
450
- // setLocale()/activate() because those publish events that trigger
451
- // setState in other components.
452
- useLayoutEffect(() => {
453
- if (chatService && chatService.getLocale() !== locale) {
454
- /* eslint-disable @typescript-eslint/no-explicit-any, react-hooks/immutability */
455
- // Mutating internal properties directly to avoid triggering event-bus
456
- // side effects (setState in other components). The key={locale} on
457
- // ApChat ensures a clean remount that reads these values.
458
- chatService._locale = locale;
459
- i18n._locale = locale;
460
- /* eslint-enable @typescript-eslint/no-explicit-any, react-hooks/immutability */
461
- }
462
- }, [chatService, locale]);
852
+ }, [agentId, folderId, existingConversationId, externalUserId, initChat]);
853
+ useEffect(() => {
854
+ return () => {
855
+ if (settingsRootRef.current) {
856
+ settingsRootRef.current.unmount();
857
+ settingsRootRef.current = null;
858
+ }
859
+ };
860
+ }, []);
463
861
  useEffect(() => {
464
862
  chatService?.setTheme(theme);
465
863
  }, [chatService, theme]);
864
+ // Close the SDK session on unmount so the WebSocket doesn't linger.
865
+ useEffect(() => {
866
+ 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;
881
+ };
882
+ }, []);
883
+ // Release React state held by the imperative tool-confirmation roots.
884
+ useEffect(() => {
885
+ return () => {
886
+ toolConfirmationRenderer.unmountAll();
887
+ };
888
+ }, [toolConfirmationRenderer]);
466
889
  // Register event handlers after chatService is available
467
890
  useEffect(() => {
468
891
  if (!chatService)
@@ -471,24 +894,20 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
471
894
  const unsubscribers = [];
472
895
  const registerEvents = async () => {
473
896
  try {
474
- if (agentId && folderId) {
475
- const result = await agentService.current.conversations.getAll({
476
- sort: SortOrder.Descending,
477
- pageSize: 20,
478
- });
897
+ if (agentId) {
898
+ await fetchFirstHistoryPage();
479
899
  // only register handlers if the component is still mounted
480
900
  if (cancelled)
481
901
  return;
482
- conversationsCursor.current = result.nextCursor;
483
- pastConversations.current = result.items;
484
- chatService.setHistory(getConversationHistoryDisplayItems(pastConversations.current), !result.hasNextPage);
485
902
  }
486
- 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));
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));
904
+ chatService.injectMessageRenderer({
905
+ name: MessageWidget.ToolConfirmation,
906
+ render: (container, message) => toolConfirmationRenderer.render(container, message, toolConfirmationLabelsRef.current ?? undefined),
907
+ });
487
908
  }
488
909
  catch (err) {
489
- const message = err instanceof Error
490
- ? err.message
491
- : "Failed to load conversation history";
910
+ const message = err instanceof Error ? err.message : t("error_load_history");
492
911
  setError(message);
493
912
  }
494
913
  };
@@ -498,16 +917,75 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
498
917
  unsubscribers.forEach((unsub) => unsub());
499
918
  };
500
919
  }, [
920
+ agentId,
501
921
  chatService,
922
+ fetchFirstHistoryPage,
923
+ folderId,
502
924
  onClickDeleteConversation,
503
925
  onClickOpenConversation,
504
926
  onFeedback,
505
927
  onHistoryLoadMore,
928
+ onHistorySearch,
506
929
  onNewChat,
507
930
  onSendMessage,
508
931
  onSetAttachments,
509
932
  onStopResponse,
933
+ t,
934
+ toolConfirmationRenderer,
935
+ ]);
936
+ useEffect(() => {
937
+ if (!chatService ||
938
+ !isDebugMode ||
939
+ !evaluationSets ||
940
+ evaluationSets.length === 0) {
941
+ return;
942
+ }
943
+ const label = addToEvalButtonLabel || t("add_to_evaluation_set");
944
+ const sortedSets = sortEvaluationSets(evaluationSets);
945
+ const headerAction = {
946
+ id: "add-to-eval-button",
947
+ name: label,
948
+ description: label,
949
+ disabled: !hasMessages,
950
+ children: sortedSets.map((s) => ({
951
+ id: `eval-${s.id}`,
952
+ name: s.name,
953
+ description: t("add_to_evaluation_set_named", { name: s.name }),
954
+ disabled: s.isDisabled,
955
+ })),
956
+ };
957
+ chatService.setCustomHeaderActions([headerAction]);
958
+ const unsubscribe = chatService.on(AutopilotChatEvent.CustomHeaderActionClicked, onCustomHeaderActionClicked);
959
+ return () => {
960
+ unsubscribe?.();
961
+ };
962
+ }, [
963
+ chatService,
964
+ isDebugMode,
965
+ evaluationSets,
966
+ addToEvalButtonLabel,
967
+ hasMessages,
968
+ onCustomHeaderActionClicked,
969
+ t,
510
970
  ]);
511
- 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 })] }));
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"));
980
+ }
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 })] }));
512
990
  };
513
991
  //# sourceMappingURL=ConversationalAgentChat.js.map