@uipath/ui-widgets-conversational-agent-chat 1.2.0-beta.1 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -9
- package/dist/ConversationalAgentChat.css +67 -4
- package/dist/ConversationalAgentChat.d.ts +1 -1
- package/dist/ConversationalAgentChat.d.ts.map +1 -1
- package/dist/ConversationalAgentChat.js +384 -170
- package/dist/ConversationalAgentChat.js.map +1 -1
- package/dist/ConversationalAgentChat.stories.d.ts +6 -0
- package/dist/ConversationalAgentChat.stories.d.ts.map +1 -1
- package/dist/ConversationalAgentChat.stories.js +5 -0
- package/dist/ConversationalAgentChat.stories.js.map +1 -1
- package/dist/types.d.ts +5 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.d.ts.map +1 -1
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/package.json +6 -6
|
@@ -36,13 +36,52 @@ 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;
|
|
44
62
|
}
|
|
45
|
-
|
|
63
|
+
// Apollo's ApChat defaults message text to fontSizeM (14px); the deprecated
|
|
64
|
+
// portal-shell chat used a larger size, so bump primary text and markdown body
|
|
65
|
+
// tokens to fontSizeL (16px) to match. Compact mode keeps Apollo's own smaller
|
|
66
|
+
// compact tokens instead.
|
|
67
|
+
const getChatSpacing = (compactMode) => compactMode
|
|
68
|
+
? { compactMode: true }
|
|
69
|
+
: {
|
|
70
|
+
primaryFontToken: FontVariantToken.fontSizeL,
|
|
71
|
+
primaryBoldFontToken: FontVariantToken.fontSizeLBold,
|
|
72
|
+
suggestionFontToken: FontVariantToken.fontSizeL,
|
|
73
|
+
markdownTokens: {
|
|
74
|
+
p: FontVariantToken.fontSizeL,
|
|
75
|
+
li: FontVariantToken.fontSizeL,
|
|
76
|
+
th: FontVariantToken.fontSizeL,
|
|
77
|
+
td: FontVariantToken.fontSizeL,
|
|
78
|
+
em: FontVariantToken.fontSizeL,
|
|
79
|
+
del: FontVariantToken.fontSizeL,
|
|
80
|
+
strong: FontVariantToken.fontSizeLBold,
|
|
81
|
+
link: FontVariantToken.fontSizeL,
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConversationId, externalUserId, inputSchema: inputSchemaProp, locale = "en", theme: themeProp, mode = AutopilotChatMode.Embedded, renderer = "material", compactMode = false, readOnly = false, overrideLabels, firstRunExperience, disabledFeatures, citationPreview = true, usePdfJsViewer = true, jobStartOverrides, isDebugMode = false, evaluationSets, addToEvalButtonLabel, onEvaluationSetClicked, onUserMessageSent, surfaceName, surfaceVersion, }) => {
|
|
46
85
|
// `inputSchema` is an internal debug-only override. In normal usage the
|
|
47
86
|
// schema is resolved from the agent release, so accepting it outside debug
|
|
48
87
|
// mode would only confuse callers — reject the combination loudly.
|
|
@@ -62,17 +101,31 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
62
101
|
surfaceName,
|
|
63
102
|
surfaceVersion,
|
|
64
103
|
}));
|
|
65
|
-
|
|
104
|
+
// The active conversation. The state drives the session effect, and the ref
|
|
105
|
+
// is for Apollo's handlers, which are registered once. Each activation is a
|
|
106
|
+
// new object, so reopening a conversation restarts its session.
|
|
107
|
+
const [activation, setActivation] = useState({ conversation: null });
|
|
108
|
+
const activeConversationRef = useRef(null);
|
|
109
|
+
// The create in flight, shared by everything waiting on a conversation.
|
|
110
|
+
const pendingCreate = useRef(null);
|
|
111
|
+
// Whether this widget created the active conversation (see fetchFirstHistoryPage).
|
|
112
|
+
const activeCreatedHere = useRef(false);
|
|
113
|
+
// Bumped on each init and on unmount, so an outdated init stops at its next await.
|
|
114
|
+
const initRun = useRef(0);
|
|
66
115
|
const initializedFor = useRef(null);
|
|
67
116
|
const themeRef = useRef(theme);
|
|
68
117
|
const modeRef = useRef(mode);
|
|
69
118
|
const rendererRef = useRef(renderer);
|
|
119
|
+
const compactModeRef = useRef(compactMode);
|
|
70
120
|
const overrideLabelsRef = useRef(overrideLabels);
|
|
71
121
|
const disabledFeaturesRef = useRef(disabledFeatures);
|
|
72
122
|
const firstRunExperienceRef = useRef(firstRunExperience);
|
|
73
123
|
const initialConversationConsumed = useRef(false);
|
|
74
124
|
const resolvedAgent = useRef(null);
|
|
75
125
|
const folderIdRef = useRef(folderId);
|
|
126
|
+
// Read through a ref so a new object from the host doesn't re-run everything
|
|
127
|
+
// that depends on it.
|
|
128
|
+
const jobStartOverridesRef = useRef(jobStartOverrides);
|
|
76
129
|
const toolConfirmationLabelsRef = useRef(null);
|
|
77
130
|
// Per-instance so unmounting one widget doesn't tear down another's React roots.
|
|
78
131
|
const toolConfirmationRenderer = useMemo(() => createToolConfirmationRenderer(), []);
|
|
@@ -84,10 +137,12 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
84
137
|
themeRef.current = theme;
|
|
85
138
|
modeRef.current = mode;
|
|
86
139
|
rendererRef.current = renderer;
|
|
140
|
+
compactModeRef.current = compactMode;
|
|
87
141
|
overrideLabelsRef.current = overrideLabels;
|
|
88
142
|
disabledFeaturesRef.current = disabledFeatures;
|
|
89
143
|
firstRunExperienceRef.current = firstRunExperience;
|
|
90
144
|
folderIdRef.current = folderId;
|
|
145
|
+
jobStartOverridesRef.current = jobStartOverrides;
|
|
91
146
|
onEvaluationSetClickedRef.current = onEvaluationSetClicked;
|
|
92
147
|
onUserMessageSentRef.current = onUserMessageSent;
|
|
93
148
|
citationPreviewRef.current = citationPreview;
|
|
@@ -101,6 +156,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
101
156
|
theme,
|
|
102
157
|
mode,
|
|
103
158
|
renderer,
|
|
159
|
+
compactMode,
|
|
104
160
|
overrideLabels,
|
|
105
161
|
disabledFeatures,
|
|
106
162
|
firstRunExperience,
|
|
@@ -108,13 +164,13 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
108
164
|
onUserMessageSent,
|
|
109
165
|
citationPreview,
|
|
110
166
|
folderId,
|
|
167
|
+
jobStartOverrides,
|
|
111
168
|
locale,
|
|
112
169
|
t,
|
|
113
170
|
]);
|
|
114
171
|
// Rebuild the SDK service when sdk or externalUserId change. Skip the first run because the
|
|
115
172
|
// useRef initializer above already built it with the initial values. The chat is re-initialized
|
|
116
|
-
// via initKey (which includes externalUserId)
|
|
117
|
-
// activeExchange) are reset by onNewChat / initChat downstream.
|
|
173
|
+
// via initKey (which includes externalUserId), and initChat resets the active conversation.
|
|
118
174
|
const didMountAgentServiceRef = useRef(false);
|
|
119
175
|
useLayoutEffect(() => {
|
|
120
176
|
if (!didMountAgentServiceRef.current) {
|
|
@@ -124,6 +180,12 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
124
180
|
agentService.current = new ConversationalAgent(sdk, externalUserId ? { externalUserId } : undefined);
|
|
125
181
|
}, [sdk, externalUserId]);
|
|
126
182
|
const session = useRef(null);
|
|
183
|
+
// Resolves with the active conversation's session once it starts. Replaced
|
|
184
|
+
// when the conversation changes, so a send never goes to one the user left.
|
|
185
|
+
const sessionReady = useRef(createDeferred());
|
|
186
|
+
// Set when the session failed to start; the next send tries again.
|
|
187
|
+
const sessionNeedsRestart = useRef(false);
|
|
188
|
+
const [sessionAttempt, setSessionAttempt] = useState(0);
|
|
127
189
|
const pastConversations = useRef([]);
|
|
128
190
|
const uploadedAttachments = useRef(new Map());
|
|
129
191
|
const conversationsCursor = useRef(undefined);
|
|
@@ -215,7 +277,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
215
277
|
try {
|
|
216
278
|
const spans = await new Traces(sdk).getById(traceId);
|
|
217
279
|
if (!isMountedRef.current ||
|
|
218
|
-
|
|
280
|
+
activeConversationRef.current?.traceId !== traceId) {
|
|
219
281
|
return;
|
|
220
282
|
}
|
|
221
283
|
applyTraceSpans(spans);
|
|
@@ -228,7 +290,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
228
290
|
const startTracePolling = useCallback(() => {
|
|
229
291
|
if (toolDisplayModeRef.current !== "FullTrace")
|
|
230
292
|
return;
|
|
231
|
-
const traceId =
|
|
293
|
+
const traceId = activeConversationRef.current?.traceId;
|
|
232
294
|
if (!traceId || tracePollIntervalRef.current)
|
|
233
295
|
return;
|
|
234
296
|
const tick = async () => {
|
|
@@ -251,7 +313,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
251
313
|
return;
|
|
252
314
|
clearInterval(tracePollIntervalRef.current);
|
|
253
315
|
tracePollIntervalRef.current = null;
|
|
254
|
-
const traceId =
|
|
316
|
+
const traceId = activeConversationRef.current?.traceId;
|
|
255
317
|
if (!finalFetch || !traceId)
|
|
256
318
|
return;
|
|
257
319
|
const pendingPoll = tracePollInFlightRef.current;
|
|
@@ -535,19 +597,34 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
535
597
|
setHasMessages(true);
|
|
536
598
|
});
|
|
537
599
|
}, [chatService, startTracePolling, stopTracePolling, t]);
|
|
600
|
+
// Makes `conversation` the active one (or none). Anything still waiting on
|
|
601
|
+
// the previous one is rejected.
|
|
602
|
+
const activateConversation = useCallback((conversation) => {
|
|
603
|
+
pendingCreate.current = null;
|
|
604
|
+
activeCreatedHere.current = false;
|
|
605
|
+
sessionReady.current.reject(new ConversationReplacedError());
|
|
606
|
+
sessionReady.current = createDeferred();
|
|
607
|
+
sessionNeedsRestart.current = false;
|
|
608
|
+
activeConversationRef.current = conversation;
|
|
609
|
+
setActivation({ conversation });
|
|
610
|
+
}, []);
|
|
538
611
|
const resolveAgent = useCallback(async () => {
|
|
612
|
+
// Only the init run that started this lookup may cache the result.
|
|
613
|
+
const run = initRun.current;
|
|
539
614
|
let effectiveAgentId = agentId;
|
|
540
615
|
let effectiveFolderId = folderIdRef.current;
|
|
541
616
|
// When the host passes only existingConversationId, derive the agent from
|
|
542
617
|
// the conversation so the header title + FRE still render for empty replays.
|
|
543
618
|
if (effectiveAgentId == null && existingConversationId) {
|
|
544
|
-
if (!
|
|
619
|
+
if (!activeConversationRef.current &&
|
|
545
620
|
!initialConversationConsumed.current) {
|
|
546
621
|
const existing = await agentService.current.conversations.getById(existingConversationId);
|
|
547
|
-
|
|
622
|
+
if (initRun.current !== run)
|
|
623
|
+
return undefined;
|
|
624
|
+
activateConversation(existing);
|
|
548
625
|
initialConversationConsumed.current = true;
|
|
549
626
|
}
|
|
550
|
-
const conv =
|
|
627
|
+
const conv = activeConversationRef.current;
|
|
551
628
|
if (conv?.agentId != null) {
|
|
552
629
|
effectiveAgentId = conv.agentId;
|
|
553
630
|
effectiveFolderId = conv.folderId;
|
|
@@ -564,45 +641,100 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
564
641
|
const release = await fetchAgentRelease(sdk, effectiveAgentId, effectiveFolderId, { externalUserId });
|
|
565
642
|
if (!release)
|
|
566
643
|
return undefined;
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
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"));
|
|
644
|
+
if (initRun.current === run) {
|
|
645
|
+
resolvedAgent.current = release;
|
|
646
|
+
folderIdRef.current = release.folderId;
|
|
591
647
|
}
|
|
592
|
-
|
|
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;
|
|
648
|
+
return release;
|
|
599
649
|
}, [
|
|
650
|
+
activateConversation,
|
|
651
|
+
agentId,
|
|
600
652
|
existingConversationId,
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
setConversationHistory,
|
|
604
|
-
t,
|
|
653
|
+
sdk,
|
|
654
|
+
externalUserId,
|
|
605
655
|
]);
|
|
656
|
+
const setConversationHistory = useCallback((next, allLoaded) => {
|
|
657
|
+
pastConversations.current = next;
|
|
658
|
+
// Through the ref: a create during init can finish before `chatService` is set.
|
|
659
|
+
chatServiceRef.current?.setHistory(getConversationHistoryDisplayItems(next, t("new_chat")), allLoaded);
|
|
660
|
+
}, [t]);
|
|
661
|
+
// The only place a conversation is created. Callers share the create in flight.
|
|
662
|
+
const startConversation = useCallback((agentInput) => {
|
|
663
|
+
const inFlight = pendingCreate.current;
|
|
664
|
+
if (inFlight) {
|
|
665
|
+
if (!agentInput)
|
|
666
|
+
return inFlight;
|
|
667
|
+
// A create without inputs is already running: attach these to it.
|
|
668
|
+
return inFlight.then(async (conversation) => {
|
|
669
|
+
await agentService.current.conversations.updateById(conversation.id, {
|
|
670
|
+
agentInput: { inline: agentInput },
|
|
671
|
+
});
|
|
672
|
+
return conversation;
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
let timer;
|
|
676
|
+
const timeout = new Promise((_, reject) => {
|
|
677
|
+
timer = setTimeout(() => reject(new Error(t("error_initialize_chat"))), CONVERSATION_CREATE_TIMEOUT_MS);
|
|
678
|
+
});
|
|
679
|
+
const create = (async () => {
|
|
680
|
+
const agent = await resolveAgent();
|
|
681
|
+
if (!agent) {
|
|
682
|
+
throw new Error(t("error_missing_conversation_params"));
|
|
683
|
+
}
|
|
684
|
+
const jobStartOverrides = jobStartOverridesRef.current;
|
|
685
|
+
const options = {
|
|
686
|
+
...(jobStartOverrides ? { jobStartOverrides } : {}),
|
|
687
|
+
...(agentInput ? { agentInput: { inline: agentInput } } : {}),
|
|
688
|
+
};
|
|
689
|
+
return agent.conversations.create(Object.keys(options).length > 0
|
|
690
|
+
? options
|
|
691
|
+
: undefined);
|
|
692
|
+
})();
|
|
693
|
+
const pending = Promise.race([
|
|
694
|
+
create,
|
|
695
|
+
timeout,
|
|
696
|
+
])
|
|
697
|
+
.then((conversation) => {
|
|
698
|
+
if (pendingCreate.current !== pending) {
|
|
699
|
+
throw new ConversationReplacedError();
|
|
700
|
+
}
|
|
701
|
+
activateConversation(conversation);
|
|
702
|
+
activeCreatedHere.current = true;
|
|
703
|
+
// Add it to the sidebar now, so the label generated after the
|
|
704
|
+
// first reply updates it in place.
|
|
705
|
+
setConversationHistory([
|
|
706
|
+
conversation,
|
|
707
|
+
...pastConversations.current,
|
|
708
|
+
]);
|
|
709
|
+
return conversation;
|
|
710
|
+
}, (err) => {
|
|
711
|
+
if (pendingCreate.current !== pending) {
|
|
712
|
+
throw new ConversationReplacedError();
|
|
713
|
+
}
|
|
714
|
+
throw err;
|
|
715
|
+
})
|
|
716
|
+
.finally(() => {
|
|
717
|
+
clearTimeout(timer);
|
|
718
|
+
if (pendingCreate.current === pending)
|
|
719
|
+
pendingCreate.current = null;
|
|
720
|
+
});
|
|
721
|
+
pendingCreate.current = pending;
|
|
722
|
+
return pending;
|
|
723
|
+
}, [activateConversation, resolveAgent, setConversationHistory, t]);
|
|
724
|
+
const ensureConversation = useCallback(async () => {
|
|
725
|
+
return activeConversationRef.current ?? startConversation();
|
|
726
|
+
}, [startConversation]);
|
|
727
|
+
// For creates nobody awaits (load, New Chat): a failure shows a banner, and
|
|
728
|
+
// the next send tries again.
|
|
729
|
+
const startConversationInBackground = useCallback(() => {
|
|
730
|
+
startConversation().catch((err) => {
|
|
731
|
+
if (err instanceof ConversationReplacedError)
|
|
732
|
+
return;
|
|
733
|
+
chatServiceRef.current?.setError(t("error_initialize_chat"));
|
|
734
|
+
});
|
|
735
|
+
}, [startConversation, t]);
|
|
736
|
+
// Whether load and New Chat create the conversation right away.
|
|
737
|
+
const shouldCreateUpfront = useCallback((agent, requiredInputs) => !!agent && !requiredInputs && !readOnly && !isDebugMode, [isDebugMode, readOnly]);
|
|
606
738
|
const showEndedBanner = useCallback((reason) => {
|
|
607
739
|
const message = reason === ConversationEndReason.Failed
|
|
608
740
|
? t("conversation_ended_failed")
|
|
@@ -623,51 +755,75 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
623
755
|
endReasonRef.current = null;
|
|
624
756
|
chatServiceRef.current?.clearError();
|
|
625
757
|
}, []);
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
758
|
+
// Read by the session handlers, so a locale change or a new callback doesn't
|
|
759
|
+
// restart the session.
|
|
760
|
+
const sessionCallbacksRef = useRef({
|
|
761
|
+
applyEndedState,
|
|
762
|
+
setConversationHistory,
|
|
763
|
+
t,
|
|
764
|
+
});
|
|
765
|
+
useLayoutEffect(() => {
|
|
766
|
+
sessionCallbacksRef.current = {
|
|
767
|
+
applyEndedState,
|
|
768
|
+
setConversationHistory,
|
|
769
|
+
t,
|
|
770
|
+
};
|
|
771
|
+
}, [applyEndedState, setConversationHistory, t]);
|
|
772
|
+
// Starts a session for the active conversation once the chat is up, and ends
|
|
773
|
+
// it when the conversation changes or the widget unmounts. Ended and
|
|
774
|
+
// read-only conversations get no session. A reply in progress keeps running
|
|
775
|
+
// if the user switches away.
|
|
776
|
+
useEffect(() => {
|
|
777
|
+
const conversation = activation.conversation;
|
|
778
|
+
// A conversation that ended while open is only marked on the ref, so check it too.
|
|
779
|
+
const latest = activeConversationRef.current;
|
|
780
|
+
const ended = !!conversation?.endedTime ||
|
|
781
|
+
(latest?.id === conversation?.id && !!latest?.endedTime);
|
|
782
|
+
if (!chatService || !conversation || ended || readOnly) {
|
|
783
|
+
return;
|
|
629
784
|
}
|
|
630
|
-
const
|
|
631
|
-
const
|
|
632
|
-
//
|
|
633
|
-
|
|
785
|
+
const conversationId = conversation.id;
|
|
786
|
+
const ready = sessionReady.current;
|
|
787
|
+
// A new session replaces a failed one.
|
|
788
|
+
sessionNeedsRestart.current = false;
|
|
789
|
+
const sessionHelper = agentService.current.conversations.startSession(conversationId, { echo: false });
|
|
790
|
+
// Set before registering handlers, which check it.
|
|
634
791
|
session.current = sessionHelper;
|
|
635
|
-
// Refresh the sidebar label when the service
|
|
636
|
-
//
|
|
637
|
-
//
|
|
792
|
+
// Refresh the sidebar label when the service generates or updates it.
|
|
793
|
+
// Uses this session's conversation id so an old session can't relabel
|
|
794
|
+
// the active one.
|
|
638
795
|
sessionHelper.onLabelUpdated(({ label }) => {
|
|
639
|
-
setConversationHistory(pastConversations.current.map((c) => c.id ===
|
|
796
|
+
sessionCallbacksRef.current.setConversationHistory(pastConversations.current.map((c) => c.id === conversationId ? { ...c, label } : c));
|
|
640
797
|
});
|
|
641
798
|
sessionHelper.onConversationEnd(({ reason }) => {
|
|
642
799
|
const endReason = reason ?? ConversationEndReason.Completed;
|
|
643
800
|
const endedTime = new Date().toISOString();
|
|
644
801
|
// Mark it ended in the history list so reopening it later shows the ended state.
|
|
645
|
-
setConversationHistory(pastConversations.current.map((c) => c.id ===
|
|
646
|
-
|
|
802
|
+
sessionCallbacksRef.current.setConversationHistory(pastConversations.current.map((c) => c.id === conversationId ? { ...c, endedTime, endReason } : c));
|
|
803
|
+
const active = activeConversationRef.current;
|
|
804
|
+
if (active?.id !== conversationId)
|
|
647
805
|
return;
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
};
|
|
653
|
-
applyEndedState(endReason);
|
|
806
|
+
// Only update the ref: the session stays open so the current reply can
|
|
807
|
+
// finish. The ended state blocks new sends.
|
|
808
|
+
activeConversationRef.current = { ...active, endedTime, endReason };
|
|
809
|
+
sessionCallbacksRef.current.applyEndedState(endReason);
|
|
654
810
|
});
|
|
655
|
-
//
|
|
656
|
-
//
|
|
657
|
-
|
|
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.
|
|
811
|
+
// On a failed start, show the error and reset the gate. The next send starts
|
|
812
|
+
// a new session.
|
|
813
|
+
const failSession = (message) => {
|
|
666
814
|
if (session.current !== sessionHelper)
|
|
667
815
|
return;
|
|
816
|
+
session.current = null;
|
|
817
|
+
sessionReady.current = createDeferred();
|
|
818
|
+
sessionNeedsRestart.current = true;
|
|
819
|
+
chatService.setError(message);
|
|
820
|
+
};
|
|
821
|
+
// Buffer outgoing events until the session has started, then send them.
|
|
822
|
+
sessionHelper.pauseEmits();
|
|
823
|
+
const startTimeout = setTimeout(() => {
|
|
668
824
|
if (sessionHelper.isEmitPaused) {
|
|
669
|
-
|
|
670
|
-
|
|
825
|
+
const { t } = sessionCallbacksRef.current;
|
|
826
|
+
failSession(t("error_session_start_timeout"));
|
|
671
827
|
}
|
|
672
828
|
}, SESSION_START_TIMEOUT_MS);
|
|
673
829
|
sessionHelper.onSessionStarted(() => {
|
|
@@ -678,33 +834,28 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
678
834
|
});
|
|
679
835
|
sessionHelper.onErrorStart((error) => {
|
|
680
836
|
clearTimeout(startTimeout);
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
session.current = null;
|
|
684
|
-
chatService?.setError(error.message || t("error_generic"));
|
|
837
|
+
const { t } = sessionCallbacksRef.current;
|
|
838
|
+
failSession(error.message || t("error_generic"));
|
|
685
839
|
});
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
activeExchange.current = null;
|
|
706
|
-
session.current = null;
|
|
707
|
-
}, []);
|
|
840
|
+
ready.resolve(sessionHelper);
|
|
841
|
+
return () => {
|
|
842
|
+
clearTimeout(startTimeout);
|
|
843
|
+
try {
|
|
844
|
+
sessionHelper.sendSessionEnd();
|
|
845
|
+
}
|
|
846
|
+
catch {
|
|
847
|
+
/* session already closed */
|
|
848
|
+
}
|
|
849
|
+
if (session.current === sessionHelper)
|
|
850
|
+
session.current = null;
|
|
851
|
+
// Reset the gate if nothing else did, so restarting the same conversation
|
|
852
|
+
// (e.g. readOnly toggled) doesn't send on this ended session.
|
|
853
|
+
if (sessionReady.current === ready) {
|
|
854
|
+
sessionReady.current = createDeferred();
|
|
855
|
+
}
|
|
856
|
+
activeExchange.current = null;
|
|
857
|
+
};
|
|
858
|
+
}, [activation, chatService, readOnly, sessionAttempt]);
|
|
708
859
|
// Shared helper: fetch connection readiness and update state.
|
|
709
860
|
const fetchConnectionReadiness = useCallback(() => {
|
|
710
861
|
const capturedAgentId = agentIdRef.current;
|
|
@@ -749,33 +900,42 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
749
900
|
setConnectionReadiness(null);
|
|
750
901
|
});
|
|
751
902
|
}, []);
|
|
752
|
-
|
|
753
|
-
|
|
903
|
+
// Leaves the active conversation and drops any create in flight. Used by
|
|
904
|
+
// New Chat and init.
|
|
905
|
+
const resetConversation = useCallback(() => {
|
|
754
906
|
clearEndedState();
|
|
755
|
-
|
|
756
|
-
session.current = null;
|
|
907
|
+
activateConversation(null);
|
|
757
908
|
activeExchange.current = null;
|
|
758
909
|
exchangesCursor.current = undefined;
|
|
759
910
|
storedAgentInputs.current = {};
|
|
760
911
|
resetTraceState();
|
|
761
912
|
setHasMessages(false);
|
|
762
913
|
connectionReadinessRenderer.unmountAll();
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
914
|
+
}, [
|
|
915
|
+
activateConversation,
|
|
916
|
+
clearEndedState,
|
|
917
|
+
connectionReadinessRenderer,
|
|
918
|
+
resetTraceState,
|
|
919
|
+
]);
|
|
920
|
+
const onNewChat = useCallback(() => {
|
|
921
|
+
resetConversation();
|
|
922
|
+
if (hasRequiredInputs(inputSchemaState)) {
|
|
923
|
+
// Show the inputs form again, cleared (the key change remounts it). The
|
|
924
|
+
// conversation is created on submit.
|
|
767
925
|
setInputsInstance((n) => n + 1);
|
|
768
926
|
setShowInputPage(true);
|
|
769
927
|
}
|
|
928
|
+
else if (shouldCreateUpfront(resolvedAgent.current, false)) {
|
|
929
|
+
startConversationInBackground();
|
|
930
|
+
}
|
|
770
931
|
fetchConnectionReadiness();
|
|
771
932
|
trackTelemetry(TelemetryEvent.NewChat, TelemetryStatus.Success);
|
|
772
933
|
}, [
|
|
773
|
-
clearEndedState,
|
|
774
|
-
endActiveSession,
|
|
775
934
|
fetchConnectionReadiness,
|
|
776
935
|
inputSchemaState,
|
|
777
|
-
|
|
778
|
-
|
|
936
|
+
resetConversation,
|
|
937
|
+
shouldCreateUpfront,
|
|
938
|
+
startConversationInBackground,
|
|
779
939
|
]);
|
|
780
940
|
const buildHistoryFilterOptions = useCallback(() => {
|
|
781
941
|
// The SDK's URL builder calls value.toString() without a null check, so
|
|
@@ -798,7 +958,16 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
798
958
|
...buildHistoryFilterOptions(),
|
|
799
959
|
});
|
|
800
960
|
conversationsCursor.current = result.nextCursor;
|
|
801
|
-
|
|
961
|
+
// A conversation we just created may not be on this page yet. Keep it at
|
|
962
|
+
// the top (unless searching), using the sidebar's copy so its label is current.
|
|
963
|
+
const active = activeConversationRef.current;
|
|
964
|
+
const kept = active &&
|
|
965
|
+
activeCreatedHere.current &&
|
|
966
|
+
!searchTextRef.current &&
|
|
967
|
+
!result.items.some((c) => c.id === active.id)
|
|
968
|
+
? (pastConversations.current.find((c) => c.id === active.id) ?? active)
|
|
969
|
+
: null;
|
|
970
|
+
setConversationHistory(kept ? [kept, ...result.items] : result.items, !result.hasNextPage);
|
|
802
971
|
}, [buildHistoryFilterOptions, chatService, setConversationHistory]);
|
|
803
972
|
const onHistoryLoadMore = useCallback(async () => {
|
|
804
973
|
if (!chatService)
|
|
@@ -826,7 +995,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
826
995
|
return;
|
|
827
996
|
await agentService.current.conversations.deleteById(id);
|
|
828
997
|
setConversationHistory(pastConversations.current.filter((c) => c.id !== id));
|
|
829
|
-
if (
|
|
998
|
+
if (activeConversationRef.current?.id === id) {
|
|
830
999
|
onNewChat();
|
|
831
1000
|
}
|
|
832
1001
|
}, [chatService, onNewChat, setConversationHistory]);
|
|
@@ -861,7 +1030,13 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
861
1030
|
chatService?.clearError();
|
|
862
1031
|
setHasMessages(true);
|
|
863
1032
|
setConnectionReadiness(null);
|
|
864
|
-
|
|
1033
|
+
// Uses the create in flight, or starts one (debug mode, or after a failed create).
|
|
1034
|
+
await ensureConversation();
|
|
1035
|
+
if (sessionNeedsRestart.current) {
|
|
1036
|
+
sessionNeedsRestart.current = false;
|
|
1037
|
+
setSessionAttempt((n) => n + 1);
|
|
1038
|
+
}
|
|
1039
|
+
const sessionHelper = await sessionReady.current.promise;
|
|
865
1040
|
const exchange = sessionHelper.startExchange();
|
|
866
1041
|
chatService?.setWaiting(true);
|
|
867
1042
|
chatService?.setShowLoading(true);
|
|
@@ -890,20 +1065,29 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
890
1065
|
trackTelemetry(TelemetryEvent.SendMessage, TelemetryStatus.Success);
|
|
891
1066
|
}
|
|
892
1067
|
catch (err) {
|
|
1068
|
+
// The user left the conversation this send was waiting on.
|
|
1069
|
+
if (err instanceof ConversationReplacedError)
|
|
1070
|
+
return;
|
|
893
1071
|
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
894
1072
|
trackTelemetry(TelemetryEvent.SendMessage, TelemetryStatus.Error, {
|
|
895
1073
|
error: errorMessage,
|
|
896
1074
|
});
|
|
897
1075
|
chatService?.setError(t("error_send_message", { errorMessage }));
|
|
898
1076
|
}
|
|
899
|
-
}, [
|
|
1077
|
+
}, [
|
|
1078
|
+
chatService,
|
|
1079
|
+
ensureConversation,
|
|
1080
|
+
setupExchangeHandlers,
|
|
1081
|
+
showEndedBanner,
|
|
1082
|
+
t,
|
|
1083
|
+
]);
|
|
900
1084
|
const processAttachmentsInBatch = useCallback(async (attachmentBatch) => {
|
|
901
1085
|
if (!chatService)
|
|
902
1086
|
return;
|
|
903
1087
|
const batchPromises = attachmentBatch.map(async (attachment) => {
|
|
904
1088
|
try {
|
|
905
1089
|
const file = convertAttachmentToFile(attachment);
|
|
906
|
-
const conversation = await
|
|
1090
|
+
const conversation = await ensureConversation();
|
|
907
1091
|
const attachmentOutput = await agentService.current.conversations.uploadAttachment(conversation.id, file);
|
|
908
1092
|
const key = createFileKey(attachment);
|
|
909
1093
|
uploadedAttachments.current.set(key, attachmentOutput);
|
|
@@ -918,7 +1102,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
918
1102
|
}
|
|
919
1103
|
});
|
|
920
1104
|
return await Promise.all(batchPromises);
|
|
921
|
-
}, [chatService,
|
|
1105
|
+
}, [chatService, ensureConversation]);
|
|
922
1106
|
const onSetAttachments = useCallback(async ({ added }) => {
|
|
923
1107
|
if (!chatService)
|
|
924
1108
|
return;
|
|
@@ -943,6 +1127,14 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
943
1127
|
...attachment,
|
|
944
1128
|
loading: false,
|
|
945
1129
|
})));
|
|
1130
|
+
// The user left the conversation these were waiting on; drop the rest.
|
|
1131
|
+
if (batchResults?.some((result) => result.error instanceof ConversationReplacedError)) {
|
|
1132
|
+
chatService.setAttachmentsLoading(newAttachments.slice(i + BATCH_SIZE).map((attachment) => ({
|
|
1133
|
+
...attachment,
|
|
1134
|
+
loading: false,
|
|
1135
|
+
})));
|
|
1136
|
+
return;
|
|
1137
|
+
}
|
|
946
1138
|
}
|
|
947
1139
|
// Handle any failed uploads
|
|
948
1140
|
const failedUploads = results.filter((result) => !result.success);
|
|
@@ -989,11 +1181,14 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
989
1181
|
const selectedConversation = pastConversations.current.find((c) => c.id === id);
|
|
990
1182
|
if (!selectedConversation)
|
|
991
1183
|
return;
|
|
992
|
-
endActiveSession();
|
|
993
1184
|
resetTraceState();
|
|
994
|
-
|
|
995
|
-
session.current = null;
|
|
1185
|
+
activateConversation(selectedConversation);
|
|
996
1186
|
exchangesCursor.current = undefined;
|
|
1187
|
+
// Set before the transcript loads: an ended conversation has no session,
|
|
1188
|
+
// so a send in the meantime must be blocked.
|
|
1189
|
+
endReasonRef.current = selectedConversation.endedTime
|
|
1190
|
+
? (selectedConversation.endReason ?? ConversationEndReason.Completed)
|
|
1191
|
+
: null;
|
|
997
1192
|
connectionReadinessRenderer.unmountAll();
|
|
998
1193
|
const { exchanges } = await fetchExchanges(selectedConversation.id);
|
|
999
1194
|
const messages = mapExchangesToChatMessages(exchanges, toolDisplayModeRef.current);
|
|
@@ -1002,9 +1197,6 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
1002
1197
|
if (selectedConversation.endedTime) {
|
|
1003
1198
|
applyEndedState(selectedConversation.endReason);
|
|
1004
1199
|
}
|
|
1005
|
-
else {
|
|
1006
|
-
endReasonRef.current = null;
|
|
1007
|
-
}
|
|
1008
1200
|
fetchConnectionReadiness();
|
|
1009
1201
|
if (toolDisplayModeRef.current === "FullTrace" &&
|
|
1010
1202
|
selectedConversation.traceId) {
|
|
@@ -1023,10 +1215,10 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
1023
1215
|
chatService.setError(t("error_open_conversation", { errorMessage }));
|
|
1024
1216
|
}
|
|
1025
1217
|
}, [
|
|
1218
|
+
activateConversation,
|
|
1026
1219
|
applyEndedState,
|
|
1027
1220
|
chatService,
|
|
1028
1221
|
connectionReadinessRenderer,
|
|
1029
|
-
endActiveSession,
|
|
1030
1222
|
fetchAndApplyTrace,
|
|
1031
1223
|
fetchConnectionReadiness,
|
|
1032
1224
|
fetchExchanges,
|
|
@@ -1039,7 +1231,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
1039
1231
|
const onConversationLoadMore = useCallback(async () => {
|
|
1040
1232
|
if (!chatService)
|
|
1041
1233
|
return;
|
|
1042
|
-
const conversationId =
|
|
1234
|
+
const conversationId = activeConversationRef.current?.id;
|
|
1043
1235
|
if (!conversationId || !exchangesCursor.current) {
|
|
1044
1236
|
chatService.prependOlderMessages([], true);
|
|
1045
1237
|
return;
|
|
@@ -1059,7 +1251,15 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
1059
1251
|
}
|
|
1060
1252
|
}, [applyTraceSpans, chatService, fetchExchanges]);
|
|
1061
1253
|
const initChat = useCallback(async () => {
|
|
1254
|
+
const run = ++initRun.current;
|
|
1062
1255
|
const initKey = `${agentId}-${folderId}-${existingConversationId ?? ""}-${externalUserId ?? ""}`;
|
|
1256
|
+
// A re-init (new agent, user or conversation) starts over.
|
|
1257
|
+
resetConversation();
|
|
1258
|
+
initialConversationConsumed.current = false;
|
|
1259
|
+
resolvedAgent.current = null;
|
|
1260
|
+
setChatService(undefined);
|
|
1261
|
+
setShowInputPage(false);
|
|
1262
|
+
setError(null);
|
|
1063
1263
|
try {
|
|
1064
1264
|
initializedFor.current = initKey;
|
|
1065
1265
|
setConnectionReadiness(null);
|
|
@@ -1068,6 +1268,8 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
1068
1268
|
autoBindTimeoutRef.current = null;
|
|
1069
1269
|
}
|
|
1070
1270
|
const agentRelease = await resolveAgent();
|
|
1271
|
+
if (initRun.current !== run)
|
|
1272
|
+
return;
|
|
1071
1273
|
agentIdRef.current = agentRelease?.id;
|
|
1072
1274
|
agentKeyRef.current = agentRelease?.releaseKey;
|
|
1073
1275
|
toolDisplayModeRef.current =
|
|
@@ -1089,11 +1291,11 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
1089
1291
|
// Skip when resuming an existing conversation — its inputs were already
|
|
1090
1292
|
// captured at creation time. The exception is debug mode, where the host
|
|
1091
1293
|
// opens an empty conversation up front, so inputs are still collected here.
|
|
1092
|
-
const
|
|
1294
|
+
const requiredInputs = hasRequiredInputs(inputSchema);
|
|
1093
1295
|
// Persist the schema regardless of `hasRequiredInputs` so the settings
|
|
1094
1296
|
// panel can render optional-input editing.
|
|
1095
1297
|
setInputSchemaState(inputSchema ?? null);
|
|
1096
|
-
if (
|
|
1298
|
+
if (requiredInputs && (!existingConversationId || isDebugMode)) {
|
|
1097
1299
|
setAgentNameState(agentName);
|
|
1098
1300
|
setShowInputPage(true);
|
|
1099
1301
|
}
|
|
@@ -1118,11 +1320,9 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
1118
1320
|
// updateConversation. Server-side this applies to all subsequent
|
|
1119
1321
|
// messages; we don't prepend per send.
|
|
1120
1322
|
const handleApplySettingsInputs = async (inputs) => {
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
}
|
|
1125
|
-
await agentService.current.conversations.updateById(conversationId, {
|
|
1323
|
+
// Waits for the create in flight, or starts one.
|
|
1324
|
+
const conversation = await ensureConversation();
|
|
1325
|
+
await agentService.current.conversations.updateById(conversation.id, {
|
|
1126
1326
|
agentInput: { inline: inputs },
|
|
1127
1327
|
});
|
|
1128
1328
|
storedAgentInputs.current = inputs;
|
|
@@ -1150,7 +1350,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
1150
1350
|
const profileResetKey = agentId != null && folderId != null
|
|
1151
1351
|
? `${agentId}-${folderId}`
|
|
1152
1352
|
: "no-agent";
|
|
1153
|
-
const conversationId =
|
|
1353
|
+
const conversationId = activeConversationRef.current?.id ?? "no-conv";
|
|
1154
1354
|
const inputsResetKey = `${profileResetKey}-${conversationId}`;
|
|
1155
1355
|
root.render(_jsx(PortalContainerProvider, { children: _jsx(SettingsDialog, { profileResetKey: profileResetKey, conversationalAgent: agentService.current, onClose: () => {
|
|
1156
1356
|
chatServiceRef.current?.toggleSettings(false);
|
|
@@ -1237,24 +1437,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
1237
1437
|
return false;
|
|
1238
1438
|
},
|
|
1239
1439
|
},
|
|
1240
|
-
|
|
1241
|
-
// deprecated portal-shell chat used a larger size, so bump primary
|
|
1242
|
-
// text and markdown body tokens to fontSizeL (16px) to match.
|
|
1243
|
-
spacing: {
|
|
1244
|
-
primaryFontToken: FontVariantToken.fontSizeL,
|
|
1245
|
-
primaryBoldFontToken: FontVariantToken.fontSizeLBold,
|
|
1246
|
-
suggestionFontToken: FontVariantToken.fontSizeL,
|
|
1247
|
-
markdownTokens: {
|
|
1248
|
-
p: FontVariantToken.fontSizeL,
|
|
1249
|
-
li: FontVariantToken.fontSizeL,
|
|
1250
|
-
th: FontVariantToken.fontSizeL,
|
|
1251
|
-
td: FontVariantToken.fontSizeL,
|
|
1252
|
-
em: FontVariantToken.fontSizeL,
|
|
1253
|
-
del: FontVariantToken.fontSizeL,
|
|
1254
|
-
strong: FontVariantToken.fontSizeLBold,
|
|
1255
|
-
link: FontVariantToken.fontSizeL,
|
|
1256
|
-
},
|
|
1257
|
-
},
|
|
1440
|
+
spacing: getChatSpacing(compactModeRef.current),
|
|
1258
1441
|
disabledFeatures: {
|
|
1259
1442
|
fullScreen: true,
|
|
1260
1443
|
preview: true,
|
|
@@ -1281,9 +1464,20 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
1281
1464
|
// Clean up any existing readiness roots before replacing the conversation
|
|
1282
1465
|
connectionReadinessRenderer.unmountAll();
|
|
1283
1466
|
if (existingConversationId) {
|
|
1284
|
-
|
|
1467
|
+
// Already fetched when the agent was derived from the conversation.
|
|
1468
|
+
let conversation = activeConversationRef.current;
|
|
1469
|
+
if (!conversation) {
|
|
1470
|
+
conversation = await agentService.current.conversations.getById(existingConversationId);
|
|
1471
|
+
if (initRun.current !== run)
|
|
1472
|
+
return;
|
|
1473
|
+
initialConversationConsumed.current = true;
|
|
1474
|
+
}
|
|
1285
1475
|
exchangesCursor.current = undefined;
|
|
1286
1476
|
const { exchanges } = await fetchExchanges(conversation.id);
|
|
1477
|
+
if (initRun.current !== run)
|
|
1478
|
+
return;
|
|
1479
|
+
// The session effect starts its session once the chat is up (none if ended).
|
|
1480
|
+
activateConversation(conversation);
|
|
1287
1481
|
const messages = mapExchangesToChatMessages(exchanges);
|
|
1288
1482
|
chatServiceInstance.setConversation(mapExchangesToChatMessages(exchanges, toolDisplayModeRef.current));
|
|
1289
1483
|
if (conversation.endedTime) {
|
|
@@ -1301,15 +1495,24 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
1301
1495
|
chatServiceInstance.setConversation([]);
|
|
1302
1496
|
}
|
|
1303
1497
|
setChatService(chatServiceInstance);
|
|
1498
|
+
// Created after the chat is shown; a send in the meantime waits for it.
|
|
1499
|
+
if (!existingConversationId &&
|
|
1500
|
+
shouldCreateUpfront(agentRelease, requiredInputs)) {
|
|
1501
|
+
startConversationInBackground();
|
|
1502
|
+
}
|
|
1304
1503
|
}
|
|
1305
1504
|
catch (err) {
|
|
1505
|
+
if (initRun.current !== run)
|
|
1506
|
+
return;
|
|
1306
1507
|
const message = err instanceof Error ? err.message : t("error_initialize_chat");
|
|
1307
1508
|
setError(message);
|
|
1308
1509
|
initializedFor.current = null;
|
|
1309
1510
|
}
|
|
1310
1511
|
}, [
|
|
1512
|
+
activateConversation,
|
|
1311
1513
|
agentId,
|
|
1312
1514
|
applyEndedState,
|
|
1515
|
+
ensureConversation,
|
|
1313
1516
|
fetchAndApplyTrace,
|
|
1314
1517
|
folderId,
|
|
1315
1518
|
existingConversationId,
|
|
@@ -1318,8 +1521,10 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
1318
1521
|
isDebugMode,
|
|
1319
1522
|
locale,
|
|
1320
1523
|
readOnly,
|
|
1524
|
+
resetConversation,
|
|
1321
1525
|
resolveAgent,
|
|
1322
|
-
|
|
1526
|
+
shouldCreateUpfront,
|
|
1527
|
+
startConversationInBackground,
|
|
1323
1528
|
fetchConnectionReadiness,
|
|
1324
1529
|
connectionReadinessRenderer,
|
|
1325
1530
|
fetchExchanges,
|
|
@@ -1369,7 +1574,7 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
1369
1574
|
const rating = data.action.details?.isPositive
|
|
1370
1575
|
? FeedbackRating.Positive
|
|
1371
1576
|
: FeedbackRating.Negative;
|
|
1372
|
-
|
|
1577
|
+
activeConversationRef.current?.exchanges?.createFeedback(exchangeId, {
|
|
1373
1578
|
rating,
|
|
1374
1579
|
comment,
|
|
1375
1580
|
});
|
|
@@ -1428,22 +1633,38 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
1428
1633
|
useEffect(() => {
|
|
1429
1634
|
chatService?.setRenderer(renderer);
|
|
1430
1635
|
}, [chatService, renderer]);
|
|
1636
|
+
useEffect(() => {
|
|
1637
|
+
chatService?.setSpacing(getChatSpacing(compactMode));
|
|
1638
|
+
}, [chatService, compactMode]);
|
|
1639
|
+
// The widget translates these labels itself (Apollo's own strings follow
|
|
1640
|
+
// `locale`), so re-send them when the locale or the host's labels change.
|
|
1641
|
+
const footerDisclaimerLabel = overrideLabels?.footerDisclaimer;
|
|
1642
|
+
const inputPlaceholderLabel = overrideLabels?.inputPlaceholder;
|
|
1643
|
+
useEffect(() => {
|
|
1644
|
+
chatService?.setOverrideLabels({
|
|
1645
|
+
footerDisclaimer: footerDisclaimerLabel ?? t("disclaimer_message"),
|
|
1646
|
+
inputPlaceholder: inputPlaceholderLabel ?? t("chat_input_placeholder"),
|
|
1647
|
+
});
|
|
1648
|
+
}, [chatService, footerDisclaimerLabel, inputPlaceholderLabel, t]);
|
|
1431
1649
|
useEffect(() => {
|
|
1432
1650
|
isMountedRef.current = true;
|
|
1433
1651
|
return () => {
|
|
1434
1652
|
isMountedRef.current = false;
|
|
1435
1653
|
};
|
|
1436
1654
|
}, []);
|
|
1437
|
-
//
|
|
1655
|
+
// On unmount, stop any init or create still running and stop trace polling.
|
|
1656
|
+
// Clearing initializedFor lets StrictMode's remount initialize again.
|
|
1438
1657
|
useEffect(() => {
|
|
1439
1658
|
return () => {
|
|
1440
|
-
|
|
1659
|
+
initRun.current += 1;
|
|
1660
|
+
initializedFor.current = null;
|
|
1661
|
+
pendingCreate.current = null;
|
|
1441
1662
|
if (tracePollIntervalRef.current) {
|
|
1442
1663
|
clearInterval(tracePollIntervalRef.current);
|
|
1443
1664
|
tracePollIntervalRef.current = null;
|
|
1444
1665
|
}
|
|
1445
1666
|
};
|
|
1446
|
-
}, [
|
|
1667
|
+
}, []);
|
|
1447
1668
|
// Release React state held by the imperative tool-confirmation and client-side tool roots.
|
|
1448
1669
|
useEffect(() => {
|
|
1449
1670
|
return () => {
|
|
@@ -1616,15 +1837,8 @@ export const ConversationalAgentChat = ({ sdk, agentId, folderId, existingConver
|
|
|
1616
1837
|
await agentService.current.conversations.updateById(existingConversationId, { agentInput: { inline: inputs } });
|
|
1617
1838
|
}
|
|
1618
1839
|
else {
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
throw new Error(t("error_missing_conversation_params"));
|
|
1622
|
-
}
|
|
1623
|
-
const conversation = await agent.conversations.create({
|
|
1624
|
-
...(jobStartOverrides ? { jobStartOverrides } : {}),
|
|
1625
|
-
agentInput: { inline: inputs },
|
|
1626
|
-
});
|
|
1627
|
-
currentConversation.current = conversation;
|
|
1840
|
+
// Awaited so a failure shows on the form and the inputs aren't lost.
|
|
1841
|
+
await startConversation(inputs);
|
|
1628
1842
|
}
|
|
1629
1843
|
storedAgentInputs.current = inputs;
|
|
1630
1844
|
setShowInputPage(false);
|