@uipath/ui-widgets-conversational-agent-chat 1.1.8 → 1.1.9

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 (60) hide show
  1. package/dist/ConnectionsSection.stories.d.ts +30 -0
  2. package/dist/ConnectionsSection.stories.d.ts.map +1 -0
  3. package/dist/ConnectionsSection.stories.js +232 -0
  4. package/dist/ConnectionsSection.stories.js.map +1 -0
  5. package/dist/ConversationalAgentChat.css +53 -0
  6. package/dist/ConversationalAgentChat.d.ts.map +1 -1
  7. package/dist/ConversationalAgentChat.js +406 -23
  8. package/dist/ConversationalAgentChat.js.map +1 -1
  9. package/dist/ConversationalAgentChat.stories.d.ts +2 -2
  10. package/dist/components/ConnectionReadinessCard.d.ts +32 -0
  11. package/dist/components/ConnectionReadinessCard.d.ts.map +1 -0
  12. package/dist/components/ConnectionReadinessCard.js +269 -0
  13. package/dist/components/ConnectionReadinessCard.js.map +1 -0
  14. package/dist/components/ConnectionReadinessRenderer.d.ts +18 -0
  15. package/dist/components/ConnectionReadinessRenderer.d.ts.map +1 -0
  16. package/dist/components/ConnectionReadinessRenderer.js +32 -0
  17. package/dist/components/ConnectionReadinessRenderer.js.map +1 -0
  18. package/dist/components/PdfJsViewer.d.ts.map +1 -1
  19. package/dist/components/PdfJsViewer.js +16 -4
  20. package/dist/components/PdfJsViewer.js.map +1 -1
  21. package/dist/components/SettingsDialog/ConnectionsSection.d.ts +10 -0
  22. package/dist/components/SettingsDialog/ConnectionsSection.d.ts.map +1 -0
  23. package/dist/components/SettingsDialog/ConnectionsSection.js +289 -0
  24. package/dist/components/SettingsDialog/ConnectionsSection.js.map +1 -0
  25. package/dist/components/SettingsDialog/ProfileSection.d.ts.map +1 -1
  26. package/dist/components/SettingsDialog/ProfileSection.js +1 -1
  27. package/dist/components/SettingsDialog/ProfileSection.js.map +1 -1
  28. package/dist/components/SettingsDialog/SettingsDialog.d.ts +7 -1
  29. package/dist/components/SettingsDialog/SettingsDialog.d.ts.map +1 -1
  30. package/dist/components/SettingsDialog/SettingsDialog.js +3 -2
  31. package/dist/components/SettingsDialog/SettingsDialog.js.map +1 -1
  32. package/dist/constants/connectionStatus.d.ts +5 -0
  33. package/dist/constants/connectionStatus.d.ts.map +1 -0
  34. package/dist/constants/connectionStatus.js +16 -0
  35. package/dist/constants/connectionStatus.js.map +1 -0
  36. package/dist/i18n/locales/de/index.json +44 -1
  37. package/dist/i18n/locales/en/index.json +44 -1
  38. package/dist/i18n/locales/es/index.json +44 -1
  39. package/dist/i18n/locales/es-mx/index.json +44 -1
  40. package/dist/i18n/locales/fr/index.json +44 -1
  41. package/dist/i18n/locales/ja/index.json +44 -1
  42. package/dist/i18n/locales/keys/index.json +44 -1
  43. package/dist/i18n/locales/ko/index.json +44 -1
  44. package/dist/i18n/locales/pt/index.json +44 -1
  45. package/dist/i18n/locales/pt-br/index.json +44 -1
  46. package/dist/i18n/locales/ro/index.json +44 -1
  47. package/dist/i18n/locales/tr/index.json +44 -1
  48. package/dist/i18n/locales/zh-cn/index.json +44 -1
  49. package/dist/i18n/locales/zh-tw/index.json +44 -1
  50. package/dist/utils/spanTree.d.ts +21 -0
  51. package/dist/utils/spanTree.d.ts.map +1 -0
  52. package/dist/utils/spanTree.js +118 -0
  53. package/dist/utils/spanTree.js.map +1 -0
  54. package/dist/utils.d.ts +1 -1
  55. package/dist/utils.d.ts.map +1 -1
  56. package/dist/utils.js +2 -1
  57. package/dist/utils.js.map +1 -1
  58. package/dist/version.d.ts +1 -1
  59. package/dist/version.js +1 -1
  60. package/package.json +2 -2
@@ -1,8 +1,9 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import { ApChat, AutopilotChatEvent, AutopilotChatMode, AutopilotChatPreHookAction, AutopilotChatService, } from "@uipath/apollo-react/material/components";
3
3
  import { FontVariantToken } from "@uipath/apollo-core";
4
4
  import { Alert, AlertDescription, Button, Column, Dialog, DialogContent, DialogHeader, DialogTitle, PortalContainerProvider, Toaster, toast, } from "@uipath/apollo-wind";
5
- import { ConversationalAgent, FeedbackRating, SortOrder, } from "@uipath/uipath-typescript/conversational-agent";
5
+ import { ConversationalAgent, ConversationEndReason, ConnectionState, FeedbackRating, SortOrder, } from "@uipath/uipath-typescript/conversational-agent";
6
+ import { Traces } from "@uipath/uipath-typescript/traces";
6
7
  import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, } from "react";
7
8
  import { createRoot } from "react-dom/client";
8
9
  import { useWidgetTranslation } from "./i18n/useWidgetTranslation";
@@ -12,10 +13,12 @@ import { Loader } from "./components/Loader";
12
13
  import { SettingsDialog } from "./components/SettingsDialog";
13
14
  import { createToolConfirmationRenderer, } from "./components/ToolConfirmationRenderer";
14
15
  import { createClientSideToolRenderer, } from "./components/ClientSideToolRenderer";
16
+ import { createConnectionReadinessRenderer } from "./components/ConnectionReadinessRenderer";
15
17
  import { ALLOWED_ATTACHMENTS } from "./constants/attachments";
16
18
  import "./ConversationalAgentChat.css";
17
19
  import { TelemetryEvent, MessageWidget, TelemetryStatus, } from "./types";
18
20
  import { convertAttachmentToFile, createFileKey, getConversationHistoryDisplayItems, getFirstRunExperience, isFlowAgent, mapCitationSource, mapExchangesToChatMessages, normalizeInput, sortEvaluationSets, } from "./utils";
21
+ import { getToolCallTraces, mergeToolCallTraceMeta } from "./utils/spanTree";
19
22
  import { trackTelemetry } from "./utils/telemetryUtils";
20
23
  import { getI18n } from "./i18n";
21
24
  import { resolveAgent as fetchAgentRelease } from "./utils/resolveAgent";
@@ -24,6 +27,8 @@ import FilePreviewer from "./components/FilePreviewer";
24
27
  // host (Studio Web) may already own. See i18n/i18n.config.ts.
25
28
  const i18n = getI18n();
26
29
  const TOOL_CONFIRMATION_WIDGET_ID_PREFIX = "confirmation-";
30
+ const CONNECTION_READINESS_CARD = "cas-connection-readiness";
31
+ const CONNECTION_READINESS_CARD_ID = "connection-readiness-card";
27
32
  // Exchanges per page when lazily loading a conversation's history. Pages are
28
33
  // fetched newest-first and prepended as the user scrolls toward the top.
29
34
  const EXCHANGES_PAGE_SIZE = 15;
@@ -71,6 +76,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
71
76
  // Per-instance so unmounting one widget doesn't tear down another's React roots.
72
77
  const toolConfirmationRenderer = useMemo(() => createToolConfirmationRenderer(), []);
73
78
  const clientSideToolRenderer = useMemo(() => createClientSideToolRenderer(), []);
79
+ const connectionReadinessRenderer = useMemo(() => createConnectionReadinessRenderer(), []);
74
80
  // useLayoutEffect is ok here because the work is minimal enough that the cost is essentially zero
75
81
  // needed because React 19 doesn't support ref writes on render
76
82
  useLayoutEffect(() => {
@@ -99,6 +105,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
99
105
  onUserMessageSent,
100
106
  citationPreview,
101
107
  folderId,
108
+ locale,
102
109
  t,
103
110
  ]);
104
111
  // Rebuild the SDK service when sdk or externalUserId change. Skip the first run because the
@@ -117,13 +124,24 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
117
124
  const pastConversations = useRef([]);
118
125
  const uploadedAttachments = useRef(new Map());
119
126
  const conversationsCursor = useRef(undefined);
127
+ // Why the active conversation ended, or null while it's open. A ref so the
128
+ // send handler reads the current value without re-registering.
129
+ const endReasonRef = useRef(null);
120
130
  // Cursor for the active conversation's exchange history. Reset whenever a
121
131
  // conversation is opened/started; undefined means no older pages remain.
122
132
  const exchangesCursor = useRef(undefined);
123
133
  const agentIdRef = useRef(undefined);
124
134
  const agentKeyRef = useRef(undefined);
135
+ const toolDisplayModeRef = useRef(undefined);
125
136
  const isFlowAgentRef = useRef(false);
126
137
  const searchTextRef = useRef("");
138
+ // Latest spans for the active conversation's trace, polled only in FullTrace mode
139
+ const traceSpansRef = useRef([]);
140
+ // toolCallId -> JSON of the last-sent meta, so unchanged tool calls aren't re-sent each poll.
141
+ const sentToolCallMetaJsonRef = useRef(new Map());
142
+ const tracePollIntervalRef = useRef(null);
143
+ const tracePollInFlightRef = useRef(null);
144
+ const isMountedRef = useRef(false);
127
145
  const [chatService, setChatService] = useState();
128
146
  const [error, setError] = useState(null);
129
147
  const [inputSchemaState, setInputSchemaState] = useState(null);
@@ -139,11 +157,13 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
139
157
  const [citationPreviewData, setCitationPreviewData] = useState(null);
140
158
  const citationPreviewRef = useRef(citationPreview);
141
159
  const [hasMessages, setHasMessages] = useState(false);
160
+ const [connectionReadiness, setConnectionReadiness] = useState(null);
142
161
  const [themeRoot, setThemeRoot] = useState(null);
143
162
  const onEvaluationSetClickedRef = useRef(onEvaluationSetClicked);
144
163
  const onUserMessageSentRef = useRef(onUserMessageSent);
145
164
  const chatServiceRef = useRef(null);
146
165
  const settingsRootRef = useRef(null);
166
+ const autoBindTimeoutRef = useRef(null);
147
167
  // Last-applied agent inputs for the active conversation. Pre-populates the
148
168
  // settings inputs form when reopened; cleared on New Chat.
149
169
  const storedAgentInputs = useRef({});
@@ -153,6 +173,96 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
153
173
  useLayoutEffect(() => {
154
174
  inputSchemaStateRef.current = inputSchemaState;
155
175
  }, [inputSchemaState]);
176
+ // Merge the trace's "conversationToolCall" spans into their tool call messages (keyed by toolCallId)
177
+ const applyTraceSpans = useCallback((spans) => {
178
+ // Only FullTrace renders the span tree; other modes use the SDK's tool call events alone.
179
+ if (toolDisplayModeRef.current !== "FullTrace")
180
+ return;
181
+ const chat = chatServiceRef.current;
182
+ if (!chat)
183
+ return;
184
+ traceSpansRef.current = spans;
185
+ const conversation = chat.getConversation() ?? [];
186
+ for (const trace of getToolCallTraces(spans)) {
187
+ // The trace only enriches tool call messages the SDK or history already
188
+ // created, so it can't show a tool call before its deferred spinner
189
+ // (e.g. while a confirmation is pending).
190
+ const existing = conversation.find((m) => m.id === trace.toolCallId);
191
+ if (!existing)
192
+ continue;
193
+ const meta = mergeToolCallTraceMeta(trace, existing.meta, toolDisplayModeRef.current);
194
+ const metaJson = JSON.stringify(meta);
195
+ if (sentToolCallMetaJsonRef.current.get(trace.toolCallId) === metaJson) {
196
+ continue;
197
+ }
198
+ chat.sendResponse({
199
+ ...existing,
200
+ id: trace.toolCallId,
201
+ content: t("performing_action_message", {
202
+ action: meta.toolName ?? "",
203
+ }),
204
+ created_at: existing.created_at ?? trace.startTime,
205
+ widget: MessageWidget.ApolloAgentsToolCall,
206
+ meta,
207
+ });
208
+ sentToolCallMetaJsonRef.current.set(trace.toolCallId, metaJson);
209
+ }
210
+ }, [t]);
211
+ const fetchAndApplyTrace = useCallback(async (traceId) => {
212
+ try {
213
+ const spans = await new Traces(sdk).getById(traceId);
214
+ if (!isMountedRef.current ||
215
+ currentConversation.current?.traceId !== traceId) {
216
+ return;
217
+ }
218
+ applyTraceSpans(spans);
219
+ }
220
+ catch {
221
+ // Transient errors: the next poll tick (or reopening) retries.
222
+ }
223
+ }, [sdk, applyTraceSpans]);
224
+ // Live polling on FullTrace mode only.
225
+ const startTracePolling = useCallback(() => {
226
+ if (toolDisplayModeRef.current !== "FullTrace")
227
+ return;
228
+ const traceId = currentConversation.current?.traceId;
229
+ if (!traceId || tracePollIntervalRef.current)
230
+ return;
231
+ const tick = async () => {
232
+ if (tracePollInFlightRef.current)
233
+ return;
234
+ const poll = fetchAndApplyTrace(traceId);
235
+ tracePollInFlightRef.current = poll;
236
+ try {
237
+ await poll;
238
+ }
239
+ finally {
240
+ tracePollInFlightRef.current = null;
241
+ }
242
+ };
243
+ void tick();
244
+ tracePollIntervalRef.current = setInterval(tick, 1000);
245
+ }, [fetchAndApplyTrace]);
246
+ const stopTracePolling = useCallback((finalFetch) => {
247
+ if (!tracePollIntervalRef.current)
248
+ return;
249
+ clearInterval(tracePollIntervalRef.current);
250
+ tracePollIntervalRef.current = null;
251
+ const traceId = currentConversation.current?.traceId;
252
+ if (!finalFetch || !traceId)
253
+ return;
254
+ const pendingPoll = tracePollInFlightRef.current;
255
+ void (async () => {
256
+ await pendingPoll;
257
+ await fetchAndApplyTrace(traceId);
258
+ })();
259
+ }, [fetchAndApplyTrace]);
260
+ // On leaving a conversation, stop polling
261
+ const resetTraceState = useCallback(() => {
262
+ stopTracePolling(false);
263
+ traceSpansRef.current = [];
264
+ sentToolCallMetaJsonRef.current = new Map();
265
+ }, [stopTracePolling]);
156
266
  const setupExchangeHandlers = useCallback((exchange) => {
157
267
  if (!chatService)
158
268
  return;
@@ -164,6 +274,10 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
164
274
  });
165
275
  exchange.onMessageStart((message) => {
166
276
  if (message.startEvent.role === "assistant") {
277
+ if (toolDisplayModeRef.current === "FullTrace") {
278
+ startTracePolling();
279
+ message.onMessageEnd(() => stopTracePolling(true));
280
+ }
167
281
  const messageId = message.messageId;
168
282
  const messageTimestamp = message.startEvent.timestamp;
169
283
  const exchangeId = exchange.exchangeId;
@@ -215,6 +329,17 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
215
329
  });
216
330
  // Track tool calls so we can defer the spinner when an interrupt arrives
217
331
  const pendingToolCalls = new Map();
332
+ // In FullTrace the SDK's tool call events still render the tool call,
333
+ // so it appears and completes even if trace fetches fail
334
+ const withTraceSpan = (toolCallId, meta) => {
335
+ if (toolDisplayModeRef.current !== "FullTrace")
336
+ return meta;
337
+ sentToolCallMetaJsonRef.current.delete(toolCallId);
338
+ const span = chatService
339
+ .getConversation()
340
+ ?.find((m) => m.id === toolCallId)?.meta?.span;
341
+ return span ? { ...meta, span } : meta;
342
+ };
218
343
  const sendToolCallSpinner = (toolCallId) => {
219
344
  const pending = pendingToolCalls.get(toolCallId);
220
345
  if (!pending || pending.spinnerSent)
@@ -227,11 +352,12 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
227
352
  }),
228
353
  created_at: pending.startTimeIso,
229
354
  widget: MessageWidget.ApolloAgentsToolCall,
230
- meta: {
355
+ meta: withTraceSpan(toolCallId, {
231
356
  toolName: pending.toolName,
232
357
  input: pending.toolInput,
233
358
  startTime: pending.startTimeIso,
234
- },
359
+ displayMode: toolDisplayModeRef.current,
360
+ }),
235
361
  });
236
362
  };
237
363
  // Caller supplies the approve/reject channel.
@@ -303,7 +429,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
303
429
  }),
304
430
  created_at: endTimeIso,
305
431
  widget: MessageWidget.ApolloAgentsToolCall,
306
- meta: {
432
+ meta: withTraceSpan(toolCall.toolCallId, {
307
433
  toolName: startEvent.toolName,
308
434
  input: toolInput,
309
435
  startTime: startTimeIso,
@@ -311,7 +437,8 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
311
437
  endTime: endTimeIso,
312
438
  isError,
313
439
  ...(cancelled && { cancelled: true }),
314
- },
440
+ displayMode: toolDisplayModeRef.current,
441
+ }),
315
442
  });
316
443
  pendingToolCalls.delete(toolCall.toolCallId);
317
444
  };
@@ -397,13 +524,14 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
397
524
  }
398
525
  });
399
526
  exchange.onExchangeEnd(() => {
527
+ stopTracePolling(true);
400
528
  activeExchange.current = null;
401
529
  chatService.sendOutputStreamEvent({ turnComplete: true });
402
530
  chatService.setShowLoading(false);
403
531
  chatService.setWaiting(false);
404
532
  setHasMessages(true);
405
533
  });
406
- }, [chatService, t]);
534
+ }, [chatService, startTracePolling, stopTracePolling, t]);
407
535
  const resolveAgent = useCallback(async () => {
408
536
  let effectiveAgentId = agentId;
409
537
  let effectiveFolderId = folderIdRef.current;
@@ -472,6 +600,26 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
472
600
  setConversationHistory,
473
601
  t,
474
602
  ]);
603
+ const showEndedBanner = useCallback((reason) => {
604
+ const message = reason === ConversationEndReason.Failed
605
+ ? t("conversation_ended_failed")
606
+ : reason === ConversationEndReason.Cancelled
607
+ ? t("conversation_ended_cancelled")
608
+ : t("conversation_ended_completed");
609
+ // Clearing also unmounts a dismissed banner; Apollo's alert keeps its hidden state otherwise.
610
+ chatServiceRef.current?.clearError();
611
+ chatServiceRef.current?.setError(message, reason === ConversationEndReason.Completed ? "warn" : "error");
612
+ }, [t]);
613
+ const applyEndedState = useCallback((reason) => {
614
+ endReasonRef.current = reason ?? ConversationEndReason.Completed;
615
+ showEndedBanner(endReasonRef.current);
616
+ }, [showEndedBanner]);
617
+ const clearEndedState = useCallback(() => {
618
+ if (!endReasonRef.current)
619
+ return;
620
+ endReasonRef.current = null;
621
+ chatServiceRef.current?.clearError();
622
+ }, []);
475
623
  const getSessionHelper = useCallback(async () => {
476
624
  if (session.current) {
477
625
  return session.current;
@@ -487,6 +635,20 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
487
635
  sessionHelper.onLabelUpdated(({ label }) => {
488
636
  setConversationHistory(pastConversations.current.map((c) => c.id === conversation.id ? { ...c, label } : c));
489
637
  });
638
+ sessionHelper.onConversationEnd(({ reason }) => {
639
+ const endReason = reason ?? ConversationEndReason.Completed;
640
+ const endedTime = new Date().toISOString();
641
+ // Mark it ended in the history list so reopening it later shows the ended state.
642
+ setConversationHistory(pastConversations.current.map((c) => c.id === conversation.id ? { ...c, endedTime, endReason } : c));
643
+ if (currentConversation.current?.id !== conversation.id)
644
+ return;
645
+ currentConversation.current = {
646
+ ...currentConversation.current,
647
+ endedTime,
648
+ endReason,
649
+ };
650
+ applyEndedState(endReason);
651
+ });
490
652
  // Buffer outgoing events until the server confirms the session is started,
491
653
  // then flush — so a send never blocks on the sessionStarted round-trip.
492
654
  // Combined with ending the session on switch (see endActiveSession), a
@@ -519,7 +681,13 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
519
681
  chatService?.setError(error.message || t("error_generic"));
520
682
  });
521
683
  return sessionHelper;
522
- }, [chatService, getConversation, setConversationHistory, t]);
684
+ }, [
685
+ applyEndedState,
686
+ chatService,
687
+ getConversation,
688
+ setConversationHistory,
689
+ t,
690
+ ]);
523
691
  // End the session on conversation switch/unmount so a reopen starts fresh and
524
692
  // gets a new `sessionStarted` — reusing a stale session hangs the send. The
525
693
  // in-flight exchange is left running (ending it is reserved for onStopResponse),
@@ -534,14 +702,61 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
534
702
  activeExchange.current = null;
535
703
  session.current = null;
536
704
  }, []);
705
+ // Shared helper: fetch connection readiness and update state.
706
+ const fetchConnectionReadiness = useCallback(() => {
707
+ const capturedAgentId = agentIdRef.current;
708
+ const capturedFolderId = folderIdRef.current;
709
+ if (capturedAgentId == null || capturedFolderId == null)
710
+ return;
711
+ const capturedInitKey = initializedFor.current;
712
+ const applyReadiness = (items) => {
713
+ if (initializedFor.current !== capturedInitKey)
714
+ return;
715
+ if (items.length === 0) {
716
+ setConnectionReadiness(null);
717
+ return;
718
+ }
719
+ const readiness = items.map((item) => {
720
+ const selectedConn = item.currentConnectionId
721
+ ? item.connections?.find((c) => c.id === item.currentConnectionId)
722
+ : undefined;
723
+ return {
724
+ connectorKey: item.connectorKey,
725
+ connectorName: item.connectorName ?? item.connectorKey,
726
+ connectorImage: item.connectorImage,
727
+ isConfigurable: item.isConfigurable !== false,
728
+ currentConnectionId: item.currentConnectionId,
729
+ currentConnectionName: item.currentConnectionName,
730
+ currentConnectionState: selectedConn?.state ??
731
+ (item.currentConnectionId ? ConnectionState.Expired : undefined),
732
+ connectionsUrl: item.connectionsUrl,
733
+ };
734
+ });
735
+ const hasUnresolved = readiness.some((c) => c.isConfigurable &&
736
+ (!c.currentConnectionId ||
737
+ c.currentConnectionState !== ConnectionState.Enabled));
738
+ setConnectionReadiness(hasUnresolved ? readiness : null);
739
+ };
740
+ agentService.current
741
+ .getAvailableConnections(capturedAgentId, capturedFolderId)
742
+ .then(applyReadiness)
743
+ .catch(() => {
744
+ if (initializedFor.current !== capturedInitKey)
745
+ return;
746
+ setConnectionReadiness(null);
747
+ });
748
+ }, []);
537
749
  const onNewChat = useCallback(() => {
538
750
  endActiveSession();
751
+ clearEndedState();
539
752
  currentConversation.current = null;
540
753
  session.current = null;
541
754
  activeExchange.current = null;
542
755
  exchangesCursor.current = undefined;
543
756
  storedAgentInputs.current = {};
757
+ resetTraceState();
544
758
  setHasMessages(false);
759
+ connectionReadinessRenderer.unmountAll();
545
760
  // Re-show the InputsPage with a cleared form when the agent's schema has
546
761
  // required inputs. Bumping the counter forces an unmount/remount via the
547
762
  // key on <InputsPage>, which resets internal form state.
@@ -549,8 +764,16 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
549
764
  setInputsInstance((n) => n + 1);
550
765
  setShowInputPage(true);
551
766
  }
767
+ fetchConnectionReadiness();
552
768
  trackTelemetry(TelemetryEvent.NewChat, TelemetryStatus.Success);
553
- }, [endActiveSession, inputSchemaState]);
769
+ }, [
770
+ clearEndedState,
771
+ endActiveSession,
772
+ fetchConnectionReadiness,
773
+ inputSchemaState,
774
+ connectionReadinessRenderer,
775
+ resetTraceState,
776
+ ]);
554
777
  const buildHistoryFilterOptions = useCallback(() => {
555
778
  // The SDK's URL builder calls value.toString() without a null check, so
556
779
  // omit any param that is undefined/empty rather than passing it as such.
@@ -620,9 +843,21 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
620
843
  }
621
844
  }, [chatService, setConversationHistory, t, toasterId]);
622
845
  const onSendMessage = useCallback(async (data) => {
846
+ // An ended conversation accepts no input. Apollo has already added the
847
+ // request bubble and loading state before this runs, and has no pre-hook
848
+ // for sends, so re-show the banner and undo the loading state.
849
+ if (endReasonRef.current) {
850
+ showEndedBanner(endReasonRef.current);
851
+ chatService?.stopResponse();
852
+ return;
853
+ }
623
854
  try {
624
855
  // required for debug-mode hosts that need to gate agent execution on the first user message
625
856
  onUserMessageSentRef.current?.({ content: data.content });
857
+ // Clearing also unmounts a dismissed banner; Apollo's alert keeps its hidden state otherwise.
858
+ chatService?.clearError();
859
+ setHasMessages(true);
860
+ setConnectionReadiness(null);
626
861
  const sessionHelper = await getSessionHelper();
627
862
  const exchange = sessionHelper.startExchange();
628
863
  chatService?.setWaiting(true);
@@ -658,7 +893,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
658
893
  });
659
894
  chatService?.setError(t("error_send_message", { errorMessage }));
660
895
  }
661
- }, [chatService, getSessionHelper, setupExchangeHandlers, t]);
896
+ }, [chatService, getSessionHelper, setupExchangeHandlers, showEndedBanner, t]);
662
897
  const processAttachmentsInBatch = useCallback(async (attachmentBatch) => {
663
898
  if (!chatService)
664
899
  return;
@@ -752,13 +987,26 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
752
987
  if (!selectedConversation)
753
988
  return;
754
989
  endActiveSession();
990
+ resetTraceState();
755
991
  currentConversation.current = selectedConversation;
756
992
  session.current = null;
757
993
  exchangesCursor.current = undefined;
994
+ connectionReadinessRenderer.unmountAll();
758
995
  const { exchanges } = await fetchExchanges(selectedConversation.id);
759
- const messages = mapExchangesToChatMessages(exchanges);
996
+ const messages = mapExchangesToChatMessages(exchanges, toolDisplayModeRef.current);
760
997
  chatService.setConversation(messages);
761
998
  setHasMessages(messages.length > 0);
999
+ if (selectedConversation.endedTime) {
1000
+ applyEndedState(selectedConversation.endReason);
1001
+ }
1002
+ else {
1003
+ endReasonRef.current = null;
1004
+ }
1005
+ fetchConnectionReadiness();
1006
+ if (toolDisplayModeRef.current === "FullTrace" &&
1007
+ selectedConversation.traceId) {
1008
+ void fetchAndApplyTrace(selectedConversation.traceId);
1009
+ }
762
1010
  trackTelemetry(TelemetryEvent.OpenConversation, TelemetryStatus.Success, {
763
1011
  conversationId: id,
764
1012
  });
@@ -771,7 +1019,17 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
771
1019
  });
772
1020
  chatService.setError(t("error_open_conversation", { errorMessage }));
773
1021
  }
774
- }, [chatService, endActiveSession, fetchExchanges, t]);
1022
+ }, [
1023
+ applyEndedState,
1024
+ chatService,
1025
+ connectionReadinessRenderer,
1026
+ endActiveSession,
1027
+ fetchAndApplyTrace,
1028
+ fetchConnectionReadiness,
1029
+ fetchExchanges,
1030
+ resetTraceState,
1031
+ t,
1032
+ ]);
775
1033
  // Apollo fires this when the user scrolls to the top of the message list.
776
1034
  // Prepend the next older page; signal `done` (no more pages) so Apollo stops
777
1035
  // requesting once the cursor is exhausted.
@@ -785,7 +1043,8 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
785
1043
  }
786
1044
  try {
787
1045
  const { exchanges, hasNextPage } = await fetchExchanges(conversationId, exchangesCursor.current);
788
- chatService.prependOlderMessages(mapExchangesToChatMessages(exchanges), !hasNextPage);
1046
+ chatService.prependOlderMessages(mapExchangesToChatMessages(exchanges, toolDisplayModeRef.current), !hasNextPage);
1047
+ applyTraceSpans(traceSpansRef.current);
789
1048
  }
790
1049
  catch (err) {
791
1050
  chatService.prependOlderMessages([], true);
@@ -795,14 +1054,22 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
795
1054
  error: errorMessage,
796
1055
  });
797
1056
  }
798
- }, [chatService, fetchExchanges]);
1057
+ }, [applyTraceSpans, chatService, fetchExchanges]);
799
1058
  const initChat = useCallback(async () => {
800
1059
  const initKey = `${agentId}-${folderId}-${existingConversationId ?? ""}-${externalUserId ?? ""}`;
801
1060
  try {
802
1061
  initializedFor.current = initKey;
1062
+ setConnectionReadiness(null);
1063
+ if (autoBindTimeoutRef.current) {
1064
+ clearTimeout(autoBindTimeoutRef.current);
1065
+ autoBindTimeoutRef.current = null;
1066
+ }
803
1067
  const agentRelease = await resolveAgent();
804
1068
  agentIdRef.current = agentRelease?.id;
805
1069
  agentKeyRef.current = agentRelease?.releaseKey;
1070
+ toolDisplayModeRef.current =
1071
+ agentRelease?.appearance
1072
+ ?.displayMode ?? "InputsAndOutputs";
806
1073
  isFlowAgentRef.current = isFlowAgent(agentRelease);
807
1074
  const agentName = agentRelease?.name ?? "";
808
1075
  // In debug mode the agent (and its derived schema) may not be resolvable,
@@ -831,6 +1098,17 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
831
1098
  // callers can override the welcome copy and starting prompts, falling
832
1099
  // back to the agent's own appearance.
833
1100
  const firstRunExperienceConfig = getFirstRunExperience(firstRunExperienceRef.current, agentRelease?.appearance);
1101
+ // Fetch connection readiness (fire-and-forget; card is optional)
1102
+ if (agentRelease) {
1103
+ fetchConnectionReadiness();
1104
+ // Re-fetch after a delay to pick up server-side auto-bind results
1105
+ autoBindTimeoutRef.current = setTimeout(() => {
1106
+ autoBindTimeoutRef.current = null;
1107
+ if (initializedFor.current !== initKey)
1108
+ return;
1109
+ fetchConnectionReadiness();
1110
+ }, 1500);
1111
+ }
834
1112
  // Persists agent inputs against the active conversation via
835
1113
  // updateConversation. Server-side this applies to all subsequent
836
1114
  // messages; we don't prepend per send.
@@ -869,7 +1147,10 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
869
1147
  : "no-agent";
870
1148
  const conversationId = currentConversation.current?.id ?? "no-conv";
871
1149
  const inputsResetKey = `${profileResetKey}-${conversationId}`;
872
- root.render(_jsx(PortalContainerProvider, { children: _jsx(SettingsDialog, { profileResetKey: profileResetKey, conversationalAgent: agentService.current, onClose: () => chatServiceRef.current?.toggleSettings(false), inputSchema: inputSchemaStateRef.current, initialInputs: storedAgentInputs.current, onApplyInputs: handleApplySettingsInputs, inputsResetKey: inputsResetKey }) }));
1150
+ root.render(_jsx(PortalContainerProvider, { children: _jsx(SettingsDialog, { profileResetKey: profileResetKey, conversationalAgent: agentService.current, onClose: () => {
1151
+ chatServiceRef.current?.toggleSettings(false);
1152
+ fetchConnectionReadiness();
1153
+ }, inputSchema: inputSchemaStateRef.current, initialInputs: storedAgentInputs.current, onApplyInputs: handleApplySettingsInputs, inputsResetKey: inputsResetKey, agentId: agentIdRef.current, folderId: folderIdRef.current, onConnectionsChanged: fetchConnectionReadiness }) }));
873
1154
  };
874
1155
  const chatServiceInstance = AutopilotChatService.Instantiate({
875
1156
  instanceName: `agent-${agentId}-${folderId}`,
@@ -987,14 +1268,26 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
987
1268
  // Singleton keeps the previous conversation's unsent draft and error banner; drop both before the awaits.
988
1269
  chatServiceInstance.setPrompt("");
989
1270
  chatServiceInstance.clearError();
1271
+ endReasonRef.current = null;
990
1272
  if (!disabledFeaturesRef.current?.attachments) {
991
1273
  chatServiceInstance.setAllowedAttachments(ALLOWED_ATTACHMENTS);
992
1274
  }
1275
+ // Clean up any existing readiness roots before replacing the conversation
1276
+ connectionReadinessRenderer.unmountAll();
993
1277
  if (existingConversationId) {
994
1278
  const conversation = await getConversation();
995
1279
  exchangesCursor.current = undefined;
996
1280
  const { exchanges } = await fetchExchanges(conversation.id);
997
- chatServiceInstance.setConversation(mapExchangesToChatMessages(exchanges));
1281
+ const messages = mapExchangesToChatMessages(exchanges);
1282
+ chatServiceInstance.setConversation(mapExchangesToChatMessages(exchanges, toolDisplayModeRef.current));
1283
+ if (conversation.endedTime) {
1284
+ applyEndedState(conversation.endReason);
1285
+ }
1286
+ if (toolDisplayModeRef.current === "FullTrace" &&
1287
+ conversation.traceId) {
1288
+ void fetchAndApplyTrace(conversation.traceId);
1289
+ }
1290
+ setHasMessages(messages.length > 0);
998
1291
  }
999
1292
  else {
1000
1293
  // AutopilotChatService is a singleton, so it may still hold the
@@ -1010,6 +1303,8 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
1010
1303
  }
1011
1304
  }, [
1012
1305
  agentId,
1306
+ applyEndedState,
1307
+ fetchAndApplyTrace,
1013
1308
  folderId,
1014
1309
  existingConversationId,
1015
1310
  externalUserId,
@@ -1019,6 +1314,8 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
1019
1314
  readOnly,
1020
1315
  resolveAgent,
1021
1316
  getConversation,
1317
+ fetchConnectionReadiness,
1318
+ connectionReadinessRenderer,
1022
1319
  fetchExchanges,
1023
1320
  t,
1024
1321
  toasterId,
@@ -1032,18 +1329,20 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
1032
1329
  const onStopResponse = useCallback(() => {
1033
1330
  if (!chatService)
1034
1331
  return;
1332
+ stopTracePolling(true);
1035
1333
  if (activeExchange.current) {
1036
1334
  // Flows own their exchange; a client exchange end strands them. Switching
1037
1335
  // conversations still fires StopResponse.
1038
1336
  if (!isFlowAgentRef.current) {
1039
1337
  activeExchange.current.sendExchangeEnd();
1338
+ chatService.setError(t("response_stopped_message"), "warn");
1040
1339
  }
1041
1340
  activeExchange.current = null;
1042
1341
  }
1043
1342
  chatService.sendOutputStreamEvent({ turnComplete: true });
1044
1343
  chatService.setShowLoading(false);
1045
1344
  chatService.setWaiting(false);
1046
- }, [chatService]);
1345
+ }, [chatService, stopTracePolling, t]);
1047
1346
  const onCustomHeaderActionClicked = useCallback((action) => {
1048
1347
  if (action.id.startsWith("eval-")) {
1049
1348
  const evaluationSetId = action.id.replace("eval-", "");
@@ -1108,6 +1407,10 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
1108
1407
  settingsRootRef.current.unmount();
1109
1408
  settingsRootRef.current = null;
1110
1409
  }
1410
+ if (autoBindTimeoutRef.current) {
1411
+ clearTimeout(autoBindTimeoutRef.current);
1412
+ autoBindTimeoutRef.current = null;
1413
+ }
1111
1414
  };
1112
1415
  }, []);
1113
1416
  useEffect(() => {
@@ -1116,10 +1419,20 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
1116
1419
  useEffect(() => {
1117
1420
  chatService?.setChatMode(mode);
1118
1421
  }, [chatService, mode]);
1119
- // Close the SDK session on unmount so the WebSocket doesn't linger.
1422
+ useEffect(() => {
1423
+ isMountedRef.current = true;
1424
+ return () => {
1425
+ isMountedRef.current = false;
1426
+ };
1427
+ }, []);
1428
+ // Close the SDK session and stop trace polling on unmount so neither lingers
1120
1429
  useEffect(() => {
1121
1430
  return () => {
1122
1431
  endActiveSession();
1432
+ if (tracePollIntervalRef.current) {
1433
+ clearInterval(tracePollIntervalRef.current);
1434
+ tracePollIntervalRef.current = null;
1435
+ }
1123
1436
  };
1124
1437
  }, [endActiveSession]);
1125
1438
  // Release React state held by the imperative tool-confirmation and client-side tool roots.
@@ -1127,8 +1440,13 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
1127
1440
  return () => {
1128
1441
  toolConfirmationRenderer.unmountAll();
1129
1442
  clientSideToolRenderer.unmountAll();
1443
+ connectionReadinessRenderer.unmountAll();
1130
1444
  };
1131
- }, [toolConfirmationRenderer, clientSideToolRenderer]);
1445
+ }, [
1446
+ toolConfirmationRenderer,
1447
+ clientSideToolRenderer,
1448
+ connectionReadinessRenderer,
1449
+ ]);
1132
1450
  // Register event handlers after chatService is available
1133
1451
  useEffect(() => {
1134
1452
  if (!chatService)
@@ -1152,6 +1470,15 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
1152
1470
  name: MessageWidget.ClientSideToolInput,
1153
1471
  render: (container, message) => clientSideToolRenderer.render(container, message),
1154
1472
  });
1473
+ chatService.injectMessageRenderer({
1474
+ name: CONNECTION_READINESS_CARD,
1475
+ render: (container, message) => connectionReadinessRenderer.render(container, message, {
1476
+ conversationalAgent: agentService.current,
1477
+ onAllConnected: () => setConnectionReadiness(null),
1478
+ onOpenSettings: () => chatServiceRef.current?.toggleSettings(true),
1479
+ onConnectionsChanged: fetchConnectionReadiness,
1480
+ }),
1481
+ });
1155
1482
  }
1156
1483
  catch (err) {
1157
1484
  const message = err instanceof Error ? err.message : t("error_load_history");
@@ -1182,6 +1509,62 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
1182
1509
  t,
1183
1510
  toolConfirmationRenderer,
1184
1511
  clientSideToolRenderer,
1512
+ connectionReadinessRenderer,
1513
+ fetchConnectionReadiness,
1514
+ ]);
1515
+ // Inject/update/remove the connection readiness card as a message in the
1516
+ // conversation — matching CAS positioning inside the scroll area.
1517
+ useEffect(() => {
1518
+ if (!chatService)
1519
+ return;
1520
+ const conversation = chatService.getConversation() ?? [];
1521
+ const existingIndex = conversation.findIndex(
1522
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1523
+ (m) => m.id === CONNECTION_READINESS_CARD_ID);
1524
+ if (connectionReadiness) {
1525
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1526
+ const cardMessage = {
1527
+ id: CONNECTION_READINESS_CARD_ID,
1528
+ content: " ",
1529
+ created_at: new Date().toISOString(),
1530
+ role: "assistant",
1531
+ widget: CONNECTION_READINESS_CARD,
1532
+ done: true,
1533
+ disableActions: true,
1534
+ meta: {
1535
+ connectors: connectionReadiness,
1536
+ agentId: agentIdRef.current,
1537
+ folderId: folderIdRef.current,
1538
+ defaultCollapsed: hasMessages,
1539
+ },
1540
+ };
1541
+ if (existingIndex >= 0) {
1542
+ const updated = [...conversation];
1543
+ updated[existingIndex] = cardMessage;
1544
+ chatService.setConversation(updated);
1545
+ }
1546
+ else if (hasMessages) {
1547
+ // Append so the card appears near the bottom where the user is
1548
+ chatService.setConversation([...conversation, cardMessage]);
1549
+ }
1550
+ else {
1551
+ // Fresh conversation — card goes first, before welcome message
1552
+ chatService.setConversation([cardMessage, ...conversation]);
1553
+ }
1554
+ }
1555
+ else if (existingIndex >= 0) {
1556
+ // Defer unmount — the card's onAllConnected effect may still be
1557
+ // executing inside this root's React tree when this runs.
1558
+ queueMicrotask(() => connectionReadinessRenderer.unmountAll());
1559
+ chatService.setConversation(
1560
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1561
+ conversation.filter((m) => m.id !== CONNECTION_READINESS_CARD_ID));
1562
+ }
1563
+ }, [
1564
+ chatService,
1565
+ connectionReadiness,
1566
+ hasMessages,
1567
+ connectionReadinessRenderer,
1185
1568
  ]);
1186
1569
  useEffect(() => {
1187
1570
  if (!chatService ||
@@ -1236,10 +1619,10 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
1236
1619
  }
1237
1620
  storedAgentInputs.current = inputs;
1238
1621
  setShowInputPage(false);
1239
- } }, `${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,
1240
- // Keep Apollo's tooltips, menus and history popover inside the
1241
- // themed wrapper; portalled to <body> they'd lose the theme tokens.
1242
- portalContainer: themeRoot ?? undefined }, locale)), _jsx(FeedbackDialog, { open: feedbackDialogOpen, isPositive: feedbackIsPositive, onOpenChange: setFeedbackDialogOpen, onSubmit: onFeedbackSubmit, onCancel: onFeedbackCancel }), _jsx(Dialog, { open: !!citationPreviewData, onOpenChange: (open) => {
1622
+ } }, `${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(_Fragment, { children: _jsx(ApChat, { chatServiceInstance: chatService, locale: toApolloSupportedLocale(locale), theme: theme, enableInternalThemeProvider: true,
1623
+ // Keep Apollo's tooltips, menus and history popover inside the
1624
+ // themed wrapper; portalled to <body> they'd lose the theme tokens.
1625
+ portalContainer: themeRoot ?? undefined }, locale) })), _jsx(FeedbackDialog, { open: feedbackDialogOpen, isPositive: feedbackIsPositive, onOpenChange: setFeedbackDialogOpen, onSubmit: onFeedbackSubmit, onCancel: onFeedbackCancel }), _jsx(Dialog, { open: !!citationPreviewData, onOpenChange: (open) => {
1243
1626
  if (!open)
1244
1627
  setCitationPreviewData(null);
1245
1628
  }, children: citationPreviewData && (_jsxs(DialogContent, { className: "sm:max-w-4xl", children: [_jsx(DialogHeader, { children: _jsx(DialogTitle, { children: citationPreviewData.title }) }), citationPreviewData.error ? (_jsx(Column, { w: "full", align: "center", justify: "center", style: { height: "60vh", maxHeight: "600px" }, children: t("file_preview_error") })) : (_jsx(FilePreviewer, { file: citationPreviewData.file, usePdfJs: usePdfJsViewer, pageNumber: citationPreviewData.pageNumber, iframeParams: `#page=${citationPreviewData.pageNumber}` }))] })) }), _jsx(Toaster, { id: toasterId, position: "top-right", richColors: true })] }) }) }));