@uipath/ui-widgets-conversational-agent-chat 1.2.0-beta.0 → 1.2.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.
@@ -36,8 +36,26 @@ const EXCHANGES_PAGE_SIZE = 15;
36
36
  // `sessionStarted`, so if it never arrives, surface an error instead of
37
37
  // leaving the send silently pending.
38
38
  const SESSION_START_TIMEOUT_MS = 30000;
39
+ // How long a conversation create can take before we show an error.
40
+ const CONVERSATION_CREATE_TIMEOUT_MS = 30000;
39
41
  // Backend limit on ConversationSchema.label.
40
42
  const CONVERSATION_LABEL_MAX_LENGTH = 100;
43
+ // Thrown to anything still waiting on a conversation the user has left (New
44
+ // Chat, a switch, re-init, unmount). Callers ignore it.
45
+ class ConversationReplacedError extends Error {
46
+ }
47
+ function createDeferred() {
48
+ let resolve;
49
+ let reject;
50
+ const promise = new Promise((res, rej) => {
51
+ resolve = res;
52
+ reject = rej;
53
+ });
54
+ // Gates are rejected when replaced, even if nothing awaited them.
55
+ promise.catch(() => { });
56
+ return { promise, resolve, reject };
57
+ }
58
+ const hasRequiredInputs = (schema) => (schema?.required?.length ?? 0) > 0;
41
59
  // Map widget Locale to Apollo supported locale to allow for locales not supported by Apollo
42
60
  function toApolloSupportedLocale(widgetLocale) {
43
61
  return widgetLocale === "keys" ? "en" : widgetLocale;
@@ -62,7 +80,17 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
62
80
  surfaceName,
63
81
  surfaceVersion,
64
82
  }));
65
- const currentConversation = useRef(null);
83
+ // The active conversation. The state drives the session effect, and the ref
84
+ // is for Apollo's handlers, which are registered once. Each activation is a
85
+ // new object, so reopening a conversation restarts its session.
86
+ const [activation, setActivation] = useState({ conversation: null });
87
+ const activeConversationRef = useRef(null);
88
+ // The create in flight, shared by everything waiting on a conversation.
89
+ const pendingCreate = useRef(null);
90
+ // Whether this widget created the active conversation (see fetchFirstHistoryPage).
91
+ const activeCreatedHere = useRef(false);
92
+ // Bumped on each init and on unmount, so an outdated init stops at its next await.
93
+ const initRun = useRef(0);
66
94
  const initializedFor = useRef(null);
67
95
  const themeRef = useRef(theme);
68
96
  const modeRef = useRef(mode);
@@ -73,6 +101,9 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
73
101
  const initialConversationConsumed = useRef(false);
74
102
  const resolvedAgent = useRef(null);
75
103
  const folderIdRef = useRef(folderId);
104
+ // Read through a ref so a new object from the host doesn't re-run everything
105
+ // that depends on it.
106
+ const jobStartOverridesRef = useRef(jobStartOverrides);
76
107
  const toolConfirmationLabelsRef = useRef(null);
77
108
  // Per-instance so unmounting one widget doesn't tear down another's React roots.
78
109
  const toolConfirmationRenderer = useMemo(() => createToolConfirmationRenderer(), []);
@@ -88,6 +119,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
88
119
  disabledFeaturesRef.current = disabledFeatures;
89
120
  firstRunExperienceRef.current = firstRunExperience;
90
121
  folderIdRef.current = folderId;
122
+ jobStartOverridesRef.current = jobStartOverrides;
91
123
  onEvaluationSetClickedRef.current = onEvaluationSetClicked;
92
124
  onUserMessageSentRef.current = onUserMessageSent;
93
125
  citationPreviewRef.current = citationPreview;
@@ -108,13 +140,13 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
108
140
  onUserMessageSent,
109
141
  citationPreview,
110
142
  folderId,
143
+ jobStartOverrides,
111
144
  locale,
112
145
  t,
113
146
  ]);
114
147
  // Rebuild the SDK service when sdk or externalUserId change. Skip the first run because the
115
148
  // useRef initializer above already built it with the initial values. The chat is re-initialized
116
- // via initKey (which includes externalUserId) so dependent refs (session, currentConversation,
117
- // activeExchange) are reset by onNewChat / initChat downstream.
149
+ // via initKey (which includes externalUserId), and initChat resets the active conversation.
118
150
  const didMountAgentServiceRef = useRef(false);
119
151
  useLayoutEffect(() => {
120
152
  if (!didMountAgentServiceRef.current) {
@@ -124,6 +156,12 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
124
156
  agentService.current = new ConversationalAgent(sdk, externalUserId ? { externalUserId } : undefined);
125
157
  }, [sdk, externalUserId]);
126
158
  const session = useRef(null);
159
+ // Resolves with the active conversation's session once it starts. Replaced
160
+ // when the conversation changes, so a send never goes to one the user left.
161
+ const sessionReady = useRef(createDeferred());
162
+ // Set when the session failed to start; the next send tries again.
163
+ const sessionNeedsRestart = useRef(false);
164
+ const [sessionAttempt, setSessionAttempt] = useState(0);
127
165
  const pastConversations = useRef([]);
128
166
  const uploadedAttachments = useRef(new Map());
129
167
  const conversationsCursor = useRef(undefined);
@@ -215,7 +253,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
215
253
  try {
216
254
  const spans = await new Traces(sdk).getById(traceId);
217
255
  if (!isMountedRef.current ||
218
- currentConversation.current?.traceId !== traceId) {
256
+ activeConversationRef.current?.traceId !== traceId) {
219
257
  return;
220
258
  }
221
259
  applyTraceSpans(spans);
@@ -228,7 +266,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
228
266
  const startTracePolling = useCallback(() => {
229
267
  if (toolDisplayModeRef.current !== "FullTrace")
230
268
  return;
231
- const traceId = currentConversation.current?.traceId;
269
+ const traceId = activeConversationRef.current?.traceId;
232
270
  if (!traceId || tracePollIntervalRef.current)
233
271
  return;
234
272
  const tick = async () => {
@@ -251,7 +289,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
251
289
  return;
252
290
  clearInterval(tracePollIntervalRef.current);
253
291
  tracePollIntervalRef.current = null;
254
- const traceId = currentConversation.current?.traceId;
292
+ const traceId = activeConversationRef.current?.traceId;
255
293
  if (!finalFetch || !traceId)
256
294
  return;
257
295
  const pendingPoll = tracePollInFlightRef.current;
@@ -535,19 +573,34 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
535
573
  setHasMessages(true);
536
574
  });
537
575
  }, [chatService, startTracePolling, stopTracePolling, t]);
576
+ // Makes `conversation` the active one (or none). Anything still waiting on
577
+ // the previous one is rejected.
578
+ const activateConversation = useCallback((conversation) => {
579
+ pendingCreate.current = null;
580
+ activeCreatedHere.current = false;
581
+ sessionReady.current.reject(new ConversationReplacedError());
582
+ sessionReady.current = createDeferred();
583
+ sessionNeedsRestart.current = false;
584
+ activeConversationRef.current = conversation;
585
+ setActivation({ conversation });
586
+ }, []);
538
587
  const resolveAgent = useCallback(async () => {
588
+ // Only the init run that started this lookup may cache the result.
589
+ const run = initRun.current;
539
590
  let effectiveAgentId = agentId;
540
591
  let effectiveFolderId = folderIdRef.current;
541
592
  // When the host passes only existingConversationId, derive the agent from
542
593
  // the conversation so the header title + FRE still render for empty replays.
543
594
  if (effectiveAgentId == null && existingConversationId) {
544
- if (!currentConversation.current &&
595
+ if (!activeConversationRef.current &&
545
596
  !initialConversationConsumed.current) {
546
597
  const existing = await agentService.current.conversations.getById(existingConversationId);
547
- currentConversation.current = existing;
598
+ if (initRun.current !== run)
599
+ return undefined;
600
+ activateConversation(existing);
548
601
  initialConversationConsumed.current = true;
549
602
  }
550
- const conv = currentConversation.current;
603
+ const conv = activeConversationRef.current;
551
604
  if (conv?.agentId != null) {
552
605
  effectiveAgentId = conv.agentId;
553
606
  effectiveFolderId = conv.folderId;
@@ -564,45 +617,100 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
564
617
  const release = await fetchAgentRelease(sdk, effectiveAgentId, effectiveFolderId, { externalUserId });
565
618
  if (!release)
566
619
  return undefined;
567
- resolvedAgent.current = release;
568
- folderIdRef.current = release.folderId;
569
- return release;
570
- }, [agentId, existingConversationId, sdk, externalUserId]);
571
- const setConversationHistory = useCallback((next, allLoaded) => {
572
- pastConversations.current = next;
573
- if (!chatService)
574
- return;
575
- chatService.setHistory(getConversationHistoryDisplayItems(next, t("new_chat")), allLoaded);
576
- }, [chatService, t]);
577
- const getConversation = useCallback(async () => {
578
- if (currentConversation.current) {
579
- return currentConversation.current;
580
- }
581
- // Only load the existing conversation on first call to getConversation
582
- if (existingConversationId && !initialConversationConsumed.current) {
583
- const existing = await agentService.current.conversations.getById(existingConversationId);
584
- currentConversation.current = existing;
585
- initialConversationConsumed.current = true;
586
- return existing;
587
- }
588
- const agent = await resolveAgent();
589
- if (!agent) {
590
- throw new Error(t("error_missing_conversation_params"));
620
+ if (initRun.current === run) {
621
+ resolvedAgent.current = release;
622
+ folderIdRef.current = release.folderId;
591
623
  }
592
- const newConversation = await agent.conversations.create(jobStartOverrides ? { jobStartOverrides } : undefined);
593
- currentConversation.current = newConversation;
594
- // Show the new conversation in the sidebar immediately so its label
595
- // (auto-generated by the service after the first exchange) can refresh
596
- // in place via onLabelUpdated rather than waiting for a history reload.
597
- setConversationHistory([newConversation, ...pastConversations.current]);
598
- return newConversation;
624
+ return release;
599
625
  }, [
626
+ activateConversation,
627
+ agentId,
600
628
  existingConversationId,
601
- jobStartOverrides,
602
- resolveAgent,
603
- setConversationHistory,
604
- t,
629
+ sdk,
630
+ externalUserId,
605
631
  ]);
632
+ const setConversationHistory = useCallback((next, allLoaded) => {
633
+ pastConversations.current = next;
634
+ // Through the ref: a create during init can finish before `chatService` is set.
635
+ chatServiceRef.current?.setHistory(getConversationHistoryDisplayItems(next, t("new_chat")), allLoaded);
636
+ }, [t]);
637
+ // The only place a conversation is created. Callers share the create in flight.
638
+ const startConversation = useCallback((agentInput) => {
639
+ const inFlight = pendingCreate.current;
640
+ if (inFlight) {
641
+ if (!agentInput)
642
+ return inFlight;
643
+ // A create without inputs is already running: attach these to it.
644
+ return inFlight.then(async (conversation) => {
645
+ await agentService.current.conversations.updateById(conversation.id, {
646
+ agentInput: { inline: agentInput },
647
+ });
648
+ return conversation;
649
+ });
650
+ }
651
+ let timer;
652
+ const timeout = new Promise((_, reject) => {
653
+ timer = setTimeout(() => reject(new Error(t("error_initialize_chat"))), CONVERSATION_CREATE_TIMEOUT_MS);
654
+ });
655
+ const create = (async () => {
656
+ const agent = await resolveAgent();
657
+ if (!agent) {
658
+ throw new Error(t("error_missing_conversation_params"));
659
+ }
660
+ const jobStartOverrides = jobStartOverridesRef.current;
661
+ const options = {
662
+ ...(jobStartOverrides ? { jobStartOverrides } : {}),
663
+ ...(agentInput ? { agentInput: { inline: agentInput } } : {}),
664
+ };
665
+ return agent.conversations.create(Object.keys(options).length > 0
666
+ ? options
667
+ : undefined);
668
+ })();
669
+ const pending = Promise.race([
670
+ create,
671
+ timeout,
672
+ ])
673
+ .then((conversation) => {
674
+ if (pendingCreate.current !== pending) {
675
+ throw new ConversationReplacedError();
676
+ }
677
+ activateConversation(conversation);
678
+ activeCreatedHere.current = true;
679
+ // Add it to the sidebar now, so the label generated after the
680
+ // first reply updates it in place.
681
+ setConversationHistory([
682
+ conversation,
683
+ ...pastConversations.current,
684
+ ]);
685
+ return conversation;
686
+ }, (err) => {
687
+ if (pendingCreate.current !== pending) {
688
+ throw new ConversationReplacedError();
689
+ }
690
+ throw err;
691
+ })
692
+ .finally(() => {
693
+ clearTimeout(timer);
694
+ if (pendingCreate.current === pending)
695
+ pendingCreate.current = null;
696
+ });
697
+ pendingCreate.current = pending;
698
+ return pending;
699
+ }, [activateConversation, resolveAgent, setConversationHistory, t]);
700
+ const ensureConversation = useCallback(async () => {
701
+ return activeConversationRef.current ?? startConversation();
702
+ }, [startConversation]);
703
+ // For creates nobody awaits (load, New Chat): a failure shows a banner, and
704
+ // the next send tries again.
705
+ const startConversationInBackground = useCallback(() => {
706
+ startConversation().catch((err) => {
707
+ if (err instanceof ConversationReplacedError)
708
+ return;
709
+ chatServiceRef.current?.setError(t("error_initialize_chat"));
710
+ });
711
+ }, [startConversation, t]);
712
+ // Whether load and New Chat create the conversation right away.
713
+ const shouldCreateUpfront = useCallback((agent, requiredInputs) => !!agent && !requiredInputs && !readOnly && !isDebugMode, [isDebugMode, readOnly]);
606
714
  const showEndedBanner = useCallback((reason) => {
607
715
  const message = reason === ConversationEndReason.Failed
608
716
  ? t("conversation_ended_failed")
@@ -623,51 +731,75 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
623
731
  endReasonRef.current = null;
624
732
  chatServiceRef.current?.clearError();
625
733
  }, []);
626
- const getSessionHelper = useCallback(async () => {
627
- if (session.current) {
628
- return session.current;
734
+ // Read by the session handlers, so a locale change or a new callback doesn't
735
+ // restart the session.
736
+ const sessionCallbacksRef = useRef({
737
+ applyEndedState,
738
+ setConversationHistory,
739
+ t,
740
+ });
741
+ useLayoutEffect(() => {
742
+ sessionCallbacksRef.current = {
743
+ applyEndedState,
744
+ setConversationHistory,
745
+ t,
746
+ };
747
+ }, [applyEndedState, setConversationHistory, t]);
748
+ // Starts a session for the active conversation once the chat is up, and ends
749
+ // it when the conversation changes or the widget unmounts. Ended and
750
+ // read-only conversations get no session. A reply in progress keeps running
751
+ // if the user switches away.
752
+ useEffect(() => {
753
+ const conversation = activation.conversation;
754
+ // A conversation that ended while open is only marked on the ref, so check it too.
755
+ const latest = activeConversationRef.current;
756
+ const ended = !!conversation?.endedTime ||
757
+ (latest?.id === conversation?.id && !!latest?.endedTime);
758
+ if (!chatService || !conversation || ended || readOnly) {
759
+ return;
629
760
  }
630
- const conversation = await getConversation();
631
- const sessionHelper = agentService.current.conversations.startSession(conversation.id, { echo: false });
632
- // Mark active before registering handlers so a synchronous sessionStarted
633
- // can't lose the `session.current === sessionHelper` guard race below.
761
+ const conversationId = conversation.id;
762
+ const ready = sessionReady.current;
763
+ // A new session replaces a failed one.
764
+ sessionNeedsRestart.current = false;
765
+ const sessionHelper = agentService.current.conversations.startSession(conversationId, { echo: false });
766
+ // Set before registering handlers, which check it.
634
767
  session.current = sessionHelper;
635
- // Refresh the sidebar label when the service auto-generates one (or the
636
- // label is updated via the API). Bind to this session's conversation id
637
- // so a stale event from an orphaned session can't mislabel the active one.
768
+ // Refresh the sidebar label when the service generates or updates it.
769
+ // Uses this session's conversation id so an old session can't relabel
770
+ // the active one.
638
771
  sessionHelper.onLabelUpdated(({ label }) => {
639
- setConversationHistory(pastConversations.current.map((c) => c.id === conversation.id ? { ...c, label } : c));
772
+ sessionCallbacksRef.current.setConversationHistory(pastConversations.current.map((c) => c.id === conversationId ? { ...c, label } : c));
640
773
  });
641
774
  sessionHelper.onConversationEnd(({ reason }) => {
642
775
  const endReason = reason ?? ConversationEndReason.Completed;
643
776
  const endedTime = new Date().toISOString();
644
777
  // Mark it ended in the history list so reopening it later shows the ended state.
645
- setConversationHistory(pastConversations.current.map((c) => c.id === conversation.id ? { ...c, endedTime, endReason } : c));
646
- if (currentConversation.current?.id !== conversation.id)
778
+ sessionCallbacksRef.current.setConversationHistory(pastConversations.current.map((c) => c.id === conversationId ? { ...c, endedTime, endReason } : c));
779
+ const active = activeConversationRef.current;
780
+ if (active?.id !== conversationId)
647
781
  return;
648
- currentConversation.current = {
649
- ...currentConversation.current,
650
- endedTime,
651
- endReason,
652
- };
653
- applyEndedState(endReason);
782
+ // Only update the ref: the session stays open so the current reply can
783
+ // finish. The ended state blocks new sends.
784
+ activeConversationRef.current = { ...active, endedTime, endReason };
785
+ sessionCallbacksRef.current.applyEndedState(endReason);
654
786
  });
655
- // Buffer outgoing events until the server confirms the session is started,
656
- // then flush — so a send never blocks on the sessionStarted round-trip.
657
- // Combined with ending the session on switch (see endActiveSession), a
658
- // reopened conversation starts fresh and its buffered send flushes as soon
659
- // as the fresh sessionStarted arrives.
660
- sessionHelper.pauseEmits();
661
- const startTimeout = setTimeout(() => {
662
- // Ignore a session abandoned by a switch/unmount so it can't error on the
663
- // now-active conversation. If the active session never started, nothing
664
- // flushes the buffer — surface an error and clear it so a retry can build
665
- // a fresh session rather than reusing this permanently-paused one.
787
+ // On a failed start, show the error and reset the gate. The next send starts
788
+ // a new session.
789
+ const failSession = (message) => {
666
790
  if (session.current !== sessionHelper)
667
791
  return;
792
+ session.current = null;
793
+ sessionReady.current = createDeferred();
794
+ sessionNeedsRestart.current = true;
795
+ chatService.setError(message);
796
+ };
797
+ // Buffer outgoing events until the session has started, then send them.
798
+ sessionHelper.pauseEmits();
799
+ const startTimeout = setTimeout(() => {
668
800
  if (sessionHelper.isEmitPaused) {
669
- session.current = null;
670
- chatService?.setError(t("error_session_start_timeout"));
801
+ const { t } = sessionCallbacksRef.current;
802
+ failSession(t("error_session_start_timeout"));
671
803
  }
672
804
  }, SESSION_START_TIMEOUT_MS);
673
805
  sessionHelper.onSessionStarted(() => {
@@ -678,33 +810,28 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
678
810
  });
679
811
  sessionHelper.onErrorStart((error) => {
680
812
  clearTimeout(startTimeout);
681
- if (session.current !== sessionHelper)
682
- return;
683
- session.current = null;
684
- chatService?.setError(error.message || t("error_generic"));
813
+ const { t } = sessionCallbacksRef.current;
814
+ failSession(error.message || t("error_generic"));
685
815
  });
686
- return sessionHelper;
687
- }, [
688
- applyEndedState,
689
- chatService,
690
- getConversation,
691
- setConversationHistory,
692
- t,
693
- ]);
694
- // End the session on conversation switch/unmount so a reopen starts fresh and
695
- // gets a new `sessionStarted` — reusing a stale session hangs the send. The
696
- // in-flight exchange is left running (ending it is reserved for onStopResponse),
697
- // so switching away from a busy conversation and reopening resumes its turn.
698
- const endActiveSession = useCallback(() => {
699
- try {
700
- session.current?.sendSessionEnd();
701
- }
702
- catch {
703
- /* session already closed */
704
- }
705
- activeExchange.current = null;
706
- session.current = null;
707
- }, []);
816
+ ready.resolve(sessionHelper);
817
+ return () => {
818
+ clearTimeout(startTimeout);
819
+ try {
820
+ sessionHelper.sendSessionEnd();
821
+ }
822
+ catch {
823
+ /* session already closed */
824
+ }
825
+ if (session.current === sessionHelper)
826
+ session.current = null;
827
+ // Reset the gate if nothing else did, so restarting the same conversation
828
+ // (e.g. readOnly toggled) doesn't send on this ended session.
829
+ if (sessionReady.current === ready) {
830
+ sessionReady.current = createDeferred();
831
+ }
832
+ activeExchange.current = null;
833
+ };
834
+ }, [activation, chatService, readOnly, sessionAttempt]);
708
835
  // Shared helper: fetch connection readiness and update state.
709
836
  const fetchConnectionReadiness = useCallback(() => {
710
837
  const capturedAgentId = agentIdRef.current;
@@ -749,33 +876,42 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
749
876
  setConnectionReadiness(null);
750
877
  });
751
878
  }, []);
752
- const onNewChat = useCallback(() => {
753
- endActiveSession();
879
+ // Leaves the active conversation and drops any create in flight. Used by
880
+ // New Chat and init.
881
+ const resetConversation = useCallback(() => {
754
882
  clearEndedState();
755
- currentConversation.current = null;
756
- session.current = null;
883
+ activateConversation(null);
757
884
  activeExchange.current = null;
758
885
  exchangesCursor.current = undefined;
759
886
  storedAgentInputs.current = {};
760
887
  resetTraceState();
761
888
  setHasMessages(false);
762
889
  connectionReadinessRenderer.unmountAll();
763
- // Re-show the InputsPage with a cleared form when the agent's schema has
764
- // required inputs. Bumping the counter forces an unmount/remount via the
765
- // key on <InputsPage>, which resets internal form state.
766
- if ((inputSchemaState?.required?.length ?? 0) > 0) {
890
+ }, [
891
+ activateConversation,
892
+ clearEndedState,
893
+ connectionReadinessRenderer,
894
+ resetTraceState,
895
+ ]);
896
+ const onNewChat = useCallback(() => {
897
+ resetConversation();
898
+ if (hasRequiredInputs(inputSchemaState)) {
899
+ // Show the inputs form again, cleared (the key change remounts it). The
900
+ // conversation is created on submit.
767
901
  setInputsInstance((n) => n + 1);
768
902
  setShowInputPage(true);
769
903
  }
904
+ else if (shouldCreateUpfront(resolvedAgent.current, false)) {
905
+ startConversationInBackground();
906
+ }
770
907
  fetchConnectionReadiness();
771
908
  trackTelemetry(TelemetryEvent.NewChat, TelemetryStatus.Success);
772
909
  }, [
773
- clearEndedState,
774
- endActiveSession,
775
910
  fetchConnectionReadiness,
776
911
  inputSchemaState,
777
- connectionReadinessRenderer,
778
- resetTraceState,
912
+ resetConversation,
913
+ shouldCreateUpfront,
914
+ startConversationInBackground,
779
915
  ]);
780
916
  const buildHistoryFilterOptions = useCallback(() => {
781
917
  // The SDK's URL builder calls value.toString() without a null check, so
@@ -798,7 +934,16 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
798
934
  ...buildHistoryFilterOptions(),
799
935
  });
800
936
  conversationsCursor.current = result.nextCursor;
801
- setConversationHistory(result.items, !result.hasNextPage);
937
+ // A conversation we just created may not be on this page yet. Keep it at
938
+ // the top (unless searching), using the sidebar's copy so its label is current.
939
+ const active = activeConversationRef.current;
940
+ const kept = active &&
941
+ activeCreatedHere.current &&
942
+ !searchTextRef.current &&
943
+ !result.items.some((c) => c.id === active.id)
944
+ ? (pastConversations.current.find((c) => c.id === active.id) ?? active)
945
+ : null;
946
+ setConversationHistory(kept ? [kept, ...result.items] : result.items, !result.hasNextPage);
802
947
  }, [buildHistoryFilterOptions, chatService, setConversationHistory]);
803
948
  const onHistoryLoadMore = useCallback(async () => {
804
949
  if (!chatService)
@@ -826,7 +971,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
826
971
  return;
827
972
  await agentService.current.conversations.deleteById(id);
828
973
  setConversationHistory(pastConversations.current.filter((c) => c.id !== id));
829
- if (currentConversation.current?.id === id) {
974
+ if (activeConversationRef.current?.id === id) {
830
975
  onNewChat();
831
976
  }
832
977
  }, [chatService, onNewChat, setConversationHistory]);
@@ -861,7 +1006,13 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
861
1006
  chatService?.clearError();
862
1007
  setHasMessages(true);
863
1008
  setConnectionReadiness(null);
864
- const sessionHelper = await getSessionHelper();
1009
+ // Uses the create in flight, or starts one (debug mode, or after a failed create).
1010
+ await ensureConversation();
1011
+ if (sessionNeedsRestart.current) {
1012
+ sessionNeedsRestart.current = false;
1013
+ setSessionAttempt((n) => n + 1);
1014
+ }
1015
+ const sessionHelper = await sessionReady.current.promise;
865
1016
  const exchange = sessionHelper.startExchange();
866
1017
  chatService?.setWaiting(true);
867
1018
  chatService?.setShowLoading(true);
@@ -890,20 +1041,29 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
890
1041
  trackTelemetry(TelemetryEvent.SendMessage, TelemetryStatus.Success);
891
1042
  }
892
1043
  catch (err) {
1044
+ // The user left the conversation this send was waiting on.
1045
+ if (err instanceof ConversationReplacedError)
1046
+ return;
893
1047
  const errorMessage = err instanceof Error ? err.message : String(err);
894
1048
  trackTelemetry(TelemetryEvent.SendMessage, TelemetryStatus.Error, {
895
1049
  error: errorMessage,
896
1050
  });
897
1051
  chatService?.setError(t("error_send_message", { errorMessage }));
898
1052
  }
899
- }, [chatService, getSessionHelper, setupExchangeHandlers, showEndedBanner, t]);
1053
+ }, [
1054
+ chatService,
1055
+ ensureConversation,
1056
+ setupExchangeHandlers,
1057
+ showEndedBanner,
1058
+ t,
1059
+ ]);
900
1060
  const processAttachmentsInBatch = useCallback(async (attachmentBatch) => {
901
1061
  if (!chatService)
902
1062
  return;
903
1063
  const batchPromises = attachmentBatch.map(async (attachment) => {
904
1064
  try {
905
1065
  const file = convertAttachmentToFile(attachment);
906
- const conversation = await getConversation();
1066
+ const conversation = await ensureConversation();
907
1067
  const attachmentOutput = await agentService.current.conversations.uploadAttachment(conversation.id, file);
908
1068
  const key = createFileKey(attachment);
909
1069
  uploadedAttachments.current.set(key, attachmentOutput);
@@ -918,7 +1078,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
918
1078
  }
919
1079
  });
920
1080
  return await Promise.all(batchPromises);
921
- }, [chatService, getConversation]);
1081
+ }, [chatService, ensureConversation]);
922
1082
  const onSetAttachments = useCallback(async ({ added }) => {
923
1083
  if (!chatService)
924
1084
  return;
@@ -943,6 +1103,14 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
943
1103
  ...attachment,
944
1104
  loading: false,
945
1105
  })));
1106
+ // The user left the conversation these were waiting on; drop the rest.
1107
+ if (batchResults?.some((result) => result.error instanceof ConversationReplacedError)) {
1108
+ chatService.setAttachmentsLoading(newAttachments.slice(i + BATCH_SIZE).map((attachment) => ({
1109
+ ...attachment,
1110
+ loading: false,
1111
+ })));
1112
+ return;
1113
+ }
946
1114
  }
947
1115
  // Handle any failed uploads
948
1116
  const failedUploads = results.filter((result) => !result.success);
@@ -989,11 +1157,14 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
989
1157
  const selectedConversation = pastConversations.current.find((c) => c.id === id);
990
1158
  if (!selectedConversation)
991
1159
  return;
992
- endActiveSession();
993
1160
  resetTraceState();
994
- currentConversation.current = selectedConversation;
995
- session.current = null;
1161
+ activateConversation(selectedConversation);
996
1162
  exchangesCursor.current = undefined;
1163
+ // Set before the transcript loads: an ended conversation has no session,
1164
+ // so a send in the meantime must be blocked.
1165
+ endReasonRef.current = selectedConversation.endedTime
1166
+ ? (selectedConversation.endReason ?? ConversationEndReason.Completed)
1167
+ : null;
997
1168
  connectionReadinessRenderer.unmountAll();
998
1169
  const { exchanges } = await fetchExchanges(selectedConversation.id);
999
1170
  const messages = mapExchangesToChatMessages(exchanges, toolDisplayModeRef.current);
@@ -1002,9 +1173,6 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
1002
1173
  if (selectedConversation.endedTime) {
1003
1174
  applyEndedState(selectedConversation.endReason);
1004
1175
  }
1005
- else {
1006
- endReasonRef.current = null;
1007
- }
1008
1176
  fetchConnectionReadiness();
1009
1177
  if (toolDisplayModeRef.current === "FullTrace" &&
1010
1178
  selectedConversation.traceId) {
@@ -1023,10 +1191,10 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
1023
1191
  chatService.setError(t("error_open_conversation", { errorMessage }));
1024
1192
  }
1025
1193
  }, [
1194
+ activateConversation,
1026
1195
  applyEndedState,
1027
1196
  chatService,
1028
1197
  connectionReadinessRenderer,
1029
- endActiveSession,
1030
1198
  fetchAndApplyTrace,
1031
1199
  fetchConnectionReadiness,
1032
1200
  fetchExchanges,
@@ -1039,7 +1207,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
1039
1207
  const onConversationLoadMore = useCallback(async () => {
1040
1208
  if (!chatService)
1041
1209
  return;
1042
- const conversationId = currentConversation.current?.id;
1210
+ const conversationId = activeConversationRef.current?.id;
1043
1211
  if (!conversationId || !exchangesCursor.current) {
1044
1212
  chatService.prependOlderMessages([], true);
1045
1213
  return;
@@ -1059,7 +1227,15 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
1059
1227
  }
1060
1228
  }, [applyTraceSpans, chatService, fetchExchanges]);
1061
1229
  const initChat = useCallback(async () => {
1230
+ const run = ++initRun.current;
1062
1231
  const initKey = `${agentId}-${folderId}-${existingConversationId ?? ""}-${externalUserId ?? ""}`;
1232
+ // A re-init (new agent, user or conversation) starts over.
1233
+ resetConversation();
1234
+ initialConversationConsumed.current = false;
1235
+ resolvedAgent.current = null;
1236
+ setChatService(undefined);
1237
+ setShowInputPage(false);
1238
+ setError(null);
1063
1239
  try {
1064
1240
  initializedFor.current = initKey;
1065
1241
  setConnectionReadiness(null);
@@ -1068,6 +1244,8 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
1068
1244
  autoBindTimeoutRef.current = null;
1069
1245
  }
1070
1246
  const agentRelease = await resolveAgent();
1247
+ if (initRun.current !== run)
1248
+ return;
1071
1249
  agentIdRef.current = agentRelease?.id;
1072
1250
  agentKeyRef.current = agentRelease?.releaseKey;
1073
1251
  toolDisplayModeRef.current =
@@ -1089,18 +1267,20 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
1089
1267
  // Skip when resuming an existing conversation — its inputs were already
1090
1268
  // captured at creation time. The exception is debug mode, where the host
1091
1269
  // opens an empty conversation up front, so inputs are still collected here.
1092
- const hasRequiredInputs = (inputSchema?.required?.length ?? 0) > 0;
1270
+ const requiredInputs = hasRequiredInputs(inputSchema);
1093
1271
  // Persist the schema regardless of `hasRequiredInputs` so the settings
1094
1272
  // panel can render optional-input editing.
1095
1273
  setInputSchemaState(inputSchema ?? null);
1096
- if (hasRequiredInputs && (!existingConversationId || isDebugMode)) {
1274
+ if (requiredInputs && (!existingConversationId || isDebugMode)) {
1097
1275
  setAgentNameState(agentName);
1098
1276
  setShowInputPage(true);
1099
1277
  }
1100
1278
  // Resolve the first-run experience: the host-provided config wins so
1101
1279
  // callers can override the welcome copy and starting prompts, falling
1102
- // back to the agent's own appearance.
1103
- const firstRunExperienceConfig = getFirstRunExperience(firstRunExperienceRef.current, agentRelease?.appearance);
1280
+ // back to the agent's own appearance. Full screen then falls back to the
1281
+ // agent's name, so it always opens on the centered first-run screen; the
1282
+ // other modes already show the name in their header.
1283
+ const firstRunExperienceConfig = getFirstRunExperience(firstRunExperienceRef.current, agentRelease?.appearance, modeRef.current === AutopilotChatMode.FullScreen ? agentName : "");
1104
1284
  // Fetch connection readiness (fire-and-forget; card is optional)
1105
1285
  if (agentRelease) {
1106
1286
  fetchConnectionReadiness();
@@ -1116,11 +1296,9 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
1116
1296
  // updateConversation. Server-side this applies to all subsequent
1117
1297
  // messages; we don't prepend per send.
1118
1298
  const handleApplySettingsInputs = async (inputs) => {
1119
- const conversationId = currentConversation.current?.id;
1120
- if (!conversationId) {
1121
- throw new Error(t("error_missing_conversation_params"));
1122
- }
1123
- await agentService.current.conversations.updateById(conversationId, {
1299
+ // Waits for the create in flight, or starts one.
1300
+ const conversation = await ensureConversation();
1301
+ await agentService.current.conversations.updateById(conversation.id, {
1124
1302
  agentInput: { inline: inputs },
1125
1303
  });
1126
1304
  storedAgentInputs.current = inputs;
@@ -1148,7 +1326,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
1148
1326
  const profileResetKey = agentId != null && folderId != null
1149
1327
  ? `${agentId}-${folderId}`
1150
1328
  : "no-agent";
1151
- const conversationId = currentConversation.current?.id ?? "no-conv";
1329
+ const conversationId = activeConversationRef.current?.id ?? "no-conv";
1152
1330
  const inputsResetKey = `${profileResetKey}-${conversationId}`;
1153
1331
  root.render(_jsx(PortalContainerProvider, { children: _jsx(SettingsDialog, { profileResetKey: profileResetKey, conversationalAgent: agentService.current, onClose: () => {
1154
1332
  chatServiceRef.current?.toggleSettings(false);
@@ -1279,9 +1457,20 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
1279
1457
  // Clean up any existing readiness roots before replacing the conversation
1280
1458
  connectionReadinessRenderer.unmountAll();
1281
1459
  if (existingConversationId) {
1282
- const conversation = await getConversation();
1460
+ // Already fetched when the agent was derived from the conversation.
1461
+ let conversation = activeConversationRef.current;
1462
+ if (!conversation) {
1463
+ conversation = await agentService.current.conversations.getById(existingConversationId);
1464
+ if (initRun.current !== run)
1465
+ return;
1466
+ initialConversationConsumed.current = true;
1467
+ }
1283
1468
  exchangesCursor.current = undefined;
1284
1469
  const { exchanges } = await fetchExchanges(conversation.id);
1470
+ if (initRun.current !== run)
1471
+ return;
1472
+ // The session effect starts its session once the chat is up (none if ended).
1473
+ activateConversation(conversation);
1285
1474
  const messages = mapExchangesToChatMessages(exchanges);
1286
1475
  chatServiceInstance.setConversation(mapExchangesToChatMessages(exchanges, toolDisplayModeRef.current));
1287
1476
  if (conversation.endedTime) {
@@ -1299,15 +1488,24 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
1299
1488
  chatServiceInstance.setConversation([]);
1300
1489
  }
1301
1490
  setChatService(chatServiceInstance);
1491
+ // Created after the chat is shown; a send in the meantime waits for it.
1492
+ if (!existingConversationId &&
1493
+ shouldCreateUpfront(agentRelease, requiredInputs)) {
1494
+ startConversationInBackground();
1495
+ }
1302
1496
  }
1303
1497
  catch (err) {
1498
+ if (initRun.current !== run)
1499
+ return;
1304
1500
  const message = err instanceof Error ? err.message : t("error_initialize_chat");
1305
1501
  setError(message);
1306
1502
  initializedFor.current = null;
1307
1503
  }
1308
1504
  }, [
1505
+ activateConversation,
1309
1506
  agentId,
1310
1507
  applyEndedState,
1508
+ ensureConversation,
1311
1509
  fetchAndApplyTrace,
1312
1510
  folderId,
1313
1511
  existingConversationId,
@@ -1316,8 +1514,10 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
1316
1514
  isDebugMode,
1317
1515
  locale,
1318
1516
  readOnly,
1517
+ resetConversation,
1319
1518
  resolveAgent,
1320
- getConversation,
1519
+ shouldCreateUpfront,
1520
+ startConversationInBackground,
1321
1521
  fetchConnectionReadiness,
1322
1522
  connectionReadinessRenderer,
1323
1523
  fetchExchanges,
@@ -1367,7 +1567,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
1367
1567
  const rating = data.action.details?.isPositive
1368
1568
  ? FeedbackRating.Positive
1369
1569
  : FeedbackRating.Negative;
1370
- currentConversation.current?.exchanges?.createFeedback(exchangeId, {
1570
+ activeConversationRef.current?.exchanges?.createFeedback(exchangeId, {
1371
1571
  rating,
1372
1572
  comment,
1373
1573
  });
@@ -1426,22 +1626,35 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
1426
1626
  useEffect(() => {
1427
1627
  chatService?.setRenderer(renderer);
1428
1628
  }, [chatService, renderer]);
1629
+ // The widget translates these labels itself (Apollo's own strings follow
1630
+ // `locale`), so re-send them when the locale or the host's labels change.
1631
+ const footerDisclaimerLabel = overrideLabels?.footerDisclaimer;
1632
+ const inputPlaceholderLabel = overrideLabels?.inputPlaceholder;
1633
+ useEffect(() => {
1634
+ chatService?.setOverrideLabels({
1635
+ footerDisclaimer: footerDisclaimerLabel ?? t("disclaimer_message"),
1636
+ inputPlaceholder: inputPlaceholderLabel ?? t("chat_input_placeholder"),
1637
+ });
1638
+ }, [chatService, footerDisclaimerLabel, inputPlaceholderLabel, t]);
1429
1639
  useEffect(() => {
1430
1640
  isMountedRef.current = true;
1431
1641
  return () => {
1432
1642
  isMountedRef.current = false;
1433
1643
  };
1434
1644
  }, []);
1435
- // Close the SDK session and stop trace polling on unmount so neither lingers
1645
+ // On unmount, stop any init or create still running and stop trace polling.
1646
+ // Clearing initializedFor lets StrictMode's remount initialize again.
1436
1647
  useEffect(() => {
1437
1648
  return () => {
1438
- endActiveSession();
1649
+ initRun.current += 1;
1650
+ initializedFor.current = null;
1651
+ pendingCreate.current = null;
1439
1652
  if (tracePollIntervalRef.current) {
1440
1653
  clearInterval(tracePollIntervalRef.current);
1441
1654
  tracePollIntervalRef.current = null;
1442
1655
  }
1443
1656
  };
1444
- }, [endActiveSession]);
1657
+ }, []);
1445
1658
  // Release React state held by the imperative tool-confirmation and client-side tool roots.
1446
1659
  useEffect(() => {
1447
1660
  return () => {
@@ -1614,15 +1827,8 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
1614
1827
  await agentService.current.conversations.updateById(existingConversationId, { agentInput: { inline: inputs } });
1615
1828
  }
1616
1829
  else {
1617
- const agent = await resolveAgent();
1618
- if (!agent) {
1619
- throw new Error(t("error_missing_conversation_params"));
1620
- }
1621
- const conversation = await agent.conversations.create({
1622
- ...(jobStartOverrides ? { jobStartOverrides } : {}),
1623
- agentInput: { inline: inputs },
1624
- });
1625
- currentConversation.current = conversation;
1830
+ // Awaited so a failure shows on the form and the inputs aren't lost.
1831
+ await startConversation(inputs);
1626
1832
  }
1627
1833
  storedAgentInputs.current = inputs;
1628
1834
  setShowInputPage(false);