@uipath/ui-widgets-conversational-agent-chat 1.0.3 → 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.
- package/README.md +10 -6
- package/dist/ConversationalAgentChat.css +3542 -3258
- package/dist/ConversationalAgentChat.d.ts +1 -1
- package/dist/ConversationalAgentChat.d.ts.map +1 -1
- package/dist/ConversationalAgentChat.js +612 -164
- package/dist/ConversationalAgentChat.js.map +1 -1
- package/dist/ConversationalAgentChat.stories.d.ts +14 -1
- package/dist/ConversationalAgentChat.stories.d.ts.map +1 -1
- package/dist/ConversationalAgentChat.stories.js +5 -12
- package/dist/ConversationalAgentChat.stories.js.map +1 -1
- package/dist/components/AgentList.d.ts.map +1 -1
- package/dist/components/AgentList.js.map +1 -1
- package/dist/components/AgentSchemaForm/AgentSchemaField.d.ts +26 -0
- package/dist/components/AgentSchemaForm/AgentSchemaField.d.ts.map +1 -0
- package/dist/components/AgentSchemaForm/AgentSchemaField.js +96 -0
- package/dist/components/AgentSchemaForm/AgentSchemaField.js.map +1 -0
- package/dist/components/AgentSchemaForm/AgentSchemaForm.d.ts +38 -0
- package/dist/components/AgentSchemaForm/AgentSchemaForm.d.ts.map +1 -0
- package/dist/components/AgentSchemaForm/AgentSchemaForm.js +105 -0
- package/dist/components/AgentSchemaForm/AgentSchemaForm.js.map +1 -0
- package/dist/components/AgentSchemaForm/AgentSchemaForm.stories.d.ts +30 -0
- package/dist/components/AgentSchemaForm/AgentSchemaForm.stories.d.ts.map +1 -0
- package/dist/components/AgentSchemaForm/AgentSchemaForm.stories.js +236 -0
- package/dist/components/AgentSchemaForm/AgentSchemaForm.stories.js.map +1 -0
- package/dist/components/AgentSchemaForm/FieldShell.d.ts +12 -0
- package/dist/components/AgentSchemaForm/FieldShell.d.ts.map +1 -0
- package/dist/components/AgentSchemaForm/FieldShell.js +4 -0
- package/dist/components/AgentSchemaForm/FieldShell.js.map +1 -0
- package/dist/components/AgentSchemaForm/index.d.ts +5 -0
- package/dist/components/AgentSchemaForm/index.d.ts.map +1 -0
- package/dist/components/AgentSchemaForm/index.js +2 -0
- package/dist/components/AgentSchemaForm/index.js.map +1 -0
- package/dist/components/AgentSchemaForm/inputs/ArrayField.d.ts +7 -0
- package/dist/components/AgentSchemaForm/inputs/ArrayField.d.ts.map +1 -0
- package/dist/components/AgentSchemaForm/inputs/ArrayField.js +28 -0
- package/dist/components/AgentSchemaForm/inputs/ArrayField.js.map +1 -0
- package/dist/components/AgentSchemaForm/inputs/ObjectField.d.ts +8 -0
- package/dist/components/AgentSchemaForm/inputs/ObjectField.d.ts.map +1 -0
- package/dist/components/AgentSchemaForm/inputs/ObjectField.js +75 -0
- package/dist/components/AgentSchemaForm/inputs/ObjectField.js.map +1 -0
- package/dist/components/AgentSchemaForm/inputs/validation.d.ts +10 -0
- package/dist/components/AgentSchemaForm/inputs/validation.d.ts.map +1 -0
- package/dist/components/AgentSchemaForm/inputs/validation.js +41 -0
- package/dist/components/AgentSchemaForm/inputs/validation.js.map +1 -0
- package/dist/components/AgentSchemaForm/resolveSchema.d.ts +7 -0
- package/dist/components/AgentSchemaForm/resolveSchema.d.ts.map +1 -0
- package/dist/components/AgentSchemaForm/resolveSchema.js +162 -0
- package/dist/components/AgentSchemaForm/resolveSchema.js.map +1 -0
- package/dist/components/AgentSchemaForm/types.d.ts +34 -0
- package/dist/components/AgentSchemaForm/types.d.ts.map +1 -0
- package/dist/components/AgentSchemaForm/types.js +8 -0
- package/dist/components/AgentSchemaForm/types.js.map +1 -0
- package/dist/components/FeedbackDialog.d.ts +2 -1
- package/dist/components/FeedbackDialog.d.ts.map +1 -1
- package/dist/components/FeedbackDialog.js +6 -2
- package/dist/components/FeedbackDialog.js.map +1 -1
- package/dist/components/InputsPage.d.ts +18 -0
- package/dist/components/InputsPage.d.ts.map +1 -0
- package/dist/components/InputsPage.js +32 -0
- package/dist/components/InputsPage.js.map +1 -0
- package/dist/components/Loader.d.ts +6 -0
- package/dist/components/Loader.d.ts.map +1 -0
- package/dist/components/Loader.js +6 -0
- package/dist/components/Loader.js.map +1 -0
- package/dist/components/SettingsDialog/InputsSection.d.ts +15 -0
- package/dist/components/SettingsDialog/InputsSection.d.ts.map +1 -0
- package/dist/components/SettingsDialog/InputsSection.js +29 -0
- package/dist/components/SettingsDialog/InputsSection.js.map +1 -0
- package/dist/components/SettingsDialog/ProfileSection.d.ts +7 -0
- package/dist/components/SettingsDialog/ProfileSection.d.ts.map +1 -0
- package/dist/components/SettingsDialog/ProfileSection.js +146 -0
- package/dist/components/SettingsDialog/ProfileSection.js.map +1 -0
- package/dist/components/SettingsDialog/SettingsDialog.d.ts +33 -0
- package/dist/components/SettingsDialog/SettingsDialog.d.ts.map +1 -0
- package/dist/components/SettingsDialog/SettingsDialog.js +18 -0
- package/dist/components/SettingsDialog/SettingsDialog.js.map +1 -0
- package/dist/components/SettingsDialog/index.d.ts +3 -0
- package/dist/components/SettingsDialog/index.d.ts.map +1 -0
- package/dist/components/SettingsDialog/index.js +2 -0
- package/dist/components/SettingsDialog/index.js.map +1 -0
- package/dist/components/ToolConfirmation.d.ts +20 -0
- package/dist/components/ToolConfirmation.d.ts.map +1 -0
- package/dist/components/ToolConfirmation.js +20 -0
- package/dist/components/ToolConfirmation.js.map +1 -0
- package/dist/components/ToolConfirmationRenderer.d.ts +15 -0
- package/dist/components/ToolConfirmationRenderer.d.ts.map +1 -0
- package/dist/components/ToolConfirmationRenderer.js +52 -0
- package/dist/components/ToolConfirmationRenderer.js.map +1 -0
- package/dist/constants/countries.d.ts +251 -0
- package/dist/constants/countries.d.ts.map +1 -0
- package/dist/constants/countries.js +250 -0
- package/dist/constants/countries.js.map +1 -0
- package/dist/hooks/useResolvedAgent.d.ts +34 -0
- package/dist/hooks/useResolvedAgent.d.ts.map +1 -0
- package/dist/hooks/useResolvedAgent.js +99 -0
- package/dist/hooks/useResolvedAgent.js.map +1 -0
- package/dist/i18n/i18n.config.d.ts +2 -0
- package/dist/i18n/i18n.config.d.ts.map +1 -0
- package/dist/i18n/i18n.config.js +24 -0
- package/dist/i18n/i18n.config.js.map +1 -0
- package/dist/i18n/index.d.ts +2 -0
- package/dist/i18n/index.d.ts.map +1 -0
- package/dist/i18n/index.js +2 -0
- package/dist/i18n/index.js.map +1 -0
- package/dist/i18n/locales/en/index.json +306 -0
- package/dist/i18n/locales/keys/index.json +306 -0
- package/dist/icons/ConversationalAgentIcon.d.ts +7 -0
- package/dist/icons/ConversationalAgentIcon.d.ts.map +1 -0
- package/dist/icons/ConversationalAgentIcon.js +8 -0
- package/dist/icons/ConversationalAgentIcon.js.map +1 -0
- package/dist/icons/TimeIcon.d.ts +2 -0
- package/dist/icons/TimeIcon.d.ts.map +1 -0
- package/dist/icons/TimeIcon.js +3 -0
- package/dist/icons/TimeIcon.js.map +1 -0
- package/dist/index.d.ts +9 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/types.d.ts +73 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/normalizeValue.d.ts +7 -0
- package/dist/utils/normalizeValue.d.ts.map +1 -0
- package/dist/utils/normalizeValue.js +31 -0
- package/dist/utils/normalizeValue.js.map +1 -0
- package/dist/utils/resolveAgent.d.ts +17 -0
- package/dist/utils/resolveAgent.d.ts.map +1 -0
- package/dist/utils/resolveAgent.js +25 -0
- package/dist/utils/resolveAgent.js.map +1 -0
- package/dist/utils/telemetryUtils.d.ts +1 -1
- package/dist/utils/telemetryUtils.d.ts.map +1 -1
- package/dist/utils/telemetryUtils.js +2 -2
- package/dist/utils/telemetryUtils.js.map +1 -1
- package/dist/utils.d.ts +11 -3
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +36 -9
- package/dist/utils.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- 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 {
|
|
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
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
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 || "
|
|
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
|
-
|
|
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
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
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
|
-
|
|
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
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
const
|
|
84
|
-
|
|
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:
|
|
88
|
-
content:
|
|
89
|
-
|
|
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:
|
|
93
|
-
input: toolInput,
|
|
94
|
-
startTime: startTimeIso,
|
|
201
|
+
toolName: pending.toolName,
|
|
202
|
+
input: pending.toolInput,
|
|
203
|
+
startTime: pending.startTimeIso,
|
|
95
204
|
},
|
|
96
205
|
});
|
|
97
|
-
|
|
98
|
-
|
|
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:
|
|
101
|
-
content:
|
|
102
|
-
created_at:
|
|
103
|
-
widget: MessageWidget.
|
|
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
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
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
|
-
|
|
136
|
-
|
|
366
|
+
const agent = await resolveAgent();
|
|
367
|
+
if (!agent) {
|
|
368
|
+
throw new Error(t("error_missing_conversation_params"));
|
|
137
369
|
}
|
|
138
|
-
const newConversation = await
|
|
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
|
-
}, [
|
|
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
|
|
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(
|
|
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("
|
|
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
|
-
|
|
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,69 +604,157 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
318
604
|
conversationId: id,
|
|
319
605
|
error: errorMessage,
|
|
320
606
|
});
|
|
321
|
-
chatService.setError(
|
|
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 =
|
|
329
|
-
|
|
330
|
-
|
|
614
|
+
const agentRelease = await resolveAgent();
|
|
615
|
+
agentIdRef.current = agentRelease?.id;
|
|
616
|
+
agentKeyRef.current = agentRelease?.releaseKey;
|
|
331
617
|
const agentName = agentRelease?.name ?? "";
|
|
332
|
-
//
|
|
333
|
-
//
|
|
334
|
-
//
|
|
335
|
-
|
|
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:
|
|
338
|
-
description:
|
|
339
|
-
suggestions:
|
|
655
|
+
title: appearance?.welcomeTitle ?? "",
|
|
656
|
+
description: appearance?.welcomeDescription ?? "",
|
|
657
|
+
suggestions: agentSuggestions,
|
|
340
658
|
}
|
|
341
659
|
: {
|
|
342
|
-
title:
|
|
343
|
-
|
|
344
|
-
|
|
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({
|
|
351
697
|
instanceName: `agent-${agentId}-${folderId}`,
|
|
352
698
|
config: {
|
|
353
699
|
mode: AutopilotChatMode.Embedded,
|
|
354
|
-
locale:
|
|
700
|
+
locale: toApolloSupportedLocale(locale),
|
|
355
701
|
theme: themeRef.current,
|
|
356
702
|
readOnly,
|
|
357
703
|
firstRunExperience: firstRunExperienceConfig,
|
|
358
704
|
overrideLabels: {
|
|
359
705
|
title: overrideLabelsRef.current?.title ?? agentName,
|
|
360
706
|
footerDisclaimer: overrideLabelsRef.current?.footerDisclaimer ??
|
|
361
|
-
|
|
707
|
+
t("disclaimer_message"),
|
|
362
708
|
inputPlaceholder: overrideLabelsRef.current?.inputPlaceholder ??
|
|
363
|
-
|
|
709
|
+
t("chat_input_placeholder"),
|
|
364
710
|
},
|
|
365
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
|
+
},
|
|
366
731
|
disabledFeatures: {
|
|
367
732
|
fullScreen: true,
|
|
368
733
|
preview: true,
|
|
369
734
|
close: true,
|
|
370
|
-
|
|
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 } : {}),
|
|
371
739
|
...disabledFeaturesRef.current,
|
|
372
740
|
},
|
|
373
741
|
},
|
|
374
742
|
});
|
|
743
|
+
chatServiceRef.current = chatServiceInstance;
|
|
375
744
|
if (existingConversationId) {
|
|
376
745
|
const conversation = await getConversation();
|
|
377
746
|
const allExchanges = await fetchExchanges(conversation.id);
|
|
378
747
|
chatServiceInstance.setConversation(mapExchangesToChatMessages(allExchanges));
|
|
379
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
|
+
}
|
|
380
754
|
setChatService(chatServiceInstance);
|
|
381
755
|
}
|
|
382
756
|
catch (err) {
|
|
383
|
-
const message = err instanceof Error ? err.message : "
|
|
757
|
+
const message = err instanceof Error ? err.message : t("error_initialize_chat");
|
|
384
758
|
setError(message);
|
|
385
759
|
initializedFor.current = null;
|
|
386
760
|
}
|
|
@@ -388,9 +762,15 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
388
762
|
agentId,
|
|
389
763
|
folderId,
|
|
390
764
|
existingConversationId,
|
|
765
|
+
externalUserId,
|
|
766
|
+
inputSchemaProp,
|
|
767
|
+
isDebugMode,
|
|
768
|
+
locale,
|
|
391
769
|
readOnly,
|
|
770
|
+
resolveAgent,
|
|
392
771
|
getConversation,
|
|
393
772
|
fetchExchanges,
|
|
773
|
+
t,
|
|
394
774
|
]);
|
|
395
775
|
const handleReload = useCallback(() => {
|
|
396
776
|
initializedFor.current = null;
|
|
@@ -409,17 +789,27 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
409
789
|
chatService.setShowLoading(false);
|
|
410
790
|
chatService.setWaiting(false);
|
|
411
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
|
+
}, []);
|
|
412
798
|
const onFeedback = useCallback((data) => {
|
|
413
799
|
pendingFeedback.current = data;
|
|
800
|
+
setFeedbackIsPositive(!!data.action.details?.isPositive);
|
|
414
801
|
setFeedbackDialogOpen(true);
|
|
415
802
|
}, []);
|
|
416
803
|
const onFeedbackSubmit = useCallback((comment) => {
|
|
417
804
|
const data = pendingFeedback.current;
|
|
418
|
-
|
|
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) {
|
|
419
809
|
const rating = data.action.details?.isPositive
|
|
420
810
|
? FeedbackRating.Positive
|
|
421
811
|
: FeedbackRating.Negative;
|
|
422
|
-
currentConversation.current?.exchanges?.createFeedback(
|
|
812
|
+
currentConversation.current?.exchanges?.createFeedback(exchangeId, {
|
|
423
813
|
rating,
|
|
424
814
|
comment,
|
|
425
815
|
});
|
|
@@ -431,68 +821,71 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
431
821
|
setFeedbackDialogOpen(false);
|
|
432
822
|
}, []);
|
|
433
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
|
+
}
|
|
434
840
|
pendingFeedback.current = null;
|
|
435
841
|
setFeedbackDialogOpen(false);
|
|
436
|
-
}, []);
|
|
437
|
-
// 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
|
|
438
844
|
useEffect(() => {
|
|
439
|
-
const initKey = `${agentId}-${folderId}-${existingConversationId ?? ""}`;
|
|
845
|
+
const initKey = `${agentId}-${folderId}-${existingConversationId ?? ""}-${externalUserId ?? ""}`;
|
|
440
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
|
|
441
850
|
initChat();
|
|
442
851
|
}
|
|
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.
|
|
852
|
+
}, [agentId, folderId, existingConversationId, externalUserId, initChat]);
|
|
449
853
|
useEffect(() => {
|
|
450
|
-
const instanceName = `agent-${agentId}-${folderId}`;
|
|
451
854
|
return () => {
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
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];
|
|
855
|
+
if (settingsRootRef.current) {
|
|
856
|
+
settingsRootRef.current.unmount();
|
|
857
|
+
settingsRootRef.current = null;
|
|
470
858
|
}
|
|
471
859
|
};
|
|
472
|
-
}, [
|
|
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]);
|
|
860
|
+
}, []);
|
|
493
861
|
useEffect(() => {
|
|
494
862
|
chatService?.setTheme(theme);
|
|
495
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]);
|
|
496
889
|
// Register event handlers after chatService is available
|
|
497
890
|
useEffect(() => {
|
|
498
891
|
if (!chatService)
|
|
@@ -501,24 +894,20 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
501
894
|
const unsubscribers = [];
|
|
502
895
|
const registerEvents = async () => {
|
|
503
896
|
try {
|
|
504
|
-
if (agentId
|
|
505
|
-
|
|
506
|
-
sort: SortOrder.Descending,
|
|
507
|
-
pageSize: 20,
|
|
508
|
-
});
|
|
897
|
+
if (agentId) {
|
|
898
|
+
await fetchFirstHistoryPage();
|
|
509
899
|
// only register handlers if the component is still mounted
|
|
510
900
|
if (cancelled)
|
|
511
901
|
return;
|
|
512
|
-
conversationsCursor.current = result.nextCursor;
|
|
513
|
-
pastConversations.current = result.items;
|
|
514
|
-
chatService.setHistory(getConversationHistoryDisplayItems(pastConversations.current), !result.hasNextPage);
|
|
515
902
|
}
|
|
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));
|
|
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
|
+
});
|
|
517
908
|
}
|
|
518
909
|
catch (err) {
|
|
519
|
-
const message = err instanceof Error
|
|
520
|
-
? err.message
|
|
521
|
-
: "Failed to load conversation history";
|
|
910
|
+
const message = err instanceof Error ? err.message : t("error_load_history");
|
|
522
911
|
setError(message);
|
|
523
912
|
}
|
|
524
913
|
};
|
|
@@ -528,16 +917,75 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
528
917
|
unsubscribers.forEach((unsub) => unsub());
|
|
529
918
|
};
|
|
530
919
|
}, [
|
|
920
|
+
agentId,
|
|
531
921
|
chatService,
|
|
922
|
+
fetchFirstHistoryPage,
|
|
923
|
+
folderId,
|
|
532
924
|
onClickDeleteConversation,
|
|
533
925
|
onClickOpenConversation,
|
|
534
926
|
onFeedback,
|
|
535
927
|
onHistoryLoadMore,
|
|
928
|
+
onHistorySearch,
|
|
536
929
|
onNewChat,
|
|
537
930
|
onSendMessage,
|
|
538
931
|
onSetAttachments,
|
|
539
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,
|
|
540
970
|
]);
|
|
541
|
-
return (_jsxs("div", { className: "uipath-conversational-agent-chat", children: [error &&
|
|
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 })] }));
|
|
542
990
|
};
|
|
543
991
|
//# sourceMappingURL=ConversationalAgentChat.js.map
|