@hef2024/llmasaservice-ui 0.16.8 → 0.16.10

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/dist/index.mjs CHANGED
@@ -482,10 +482,7 @@ var ChatPanel = ({
482
482
  { key: "--userLanguage", data: browserInfo == null ? void 0 : browserInfo.userLanguage }
483
483
  ];
484
484
  };
485
- let publicAPIUrl = "https://api.llmasaservice.io";
486
- if (window.location.hostname === "localhost" || window.location.hostname === "dev.llmasaservice.io") {
487
- publicAPIUrl = "https://8ftw8droff.execute-api.us-east-1.amazonaws.com/dev";
488
- }
485
+ const publicAPIUrl = "https://api.llmasaservice.io";
489
486
  const [toolList, setToolList] = useState2([]);
490
487
  const [toolsLoading, setToolsLoading] = useState2(false);
491
488
  const [toolsFetchError, setToolsFetchError] = useState2(false);
@@ -2855,7 +2852,7 @@ var AgentPanel = ({
2855
2852
  useEffect3(() => {
2856
2853
  const fetchAgentData = () => __async(void 0, null, function* () {
2857
2854
  try {
2858
- const fetchUrl = url.endsWith("dev") ? `https://8ftw8droff.execute-api.us-east-1.amazonaws.com/dev/agents/${agent}` : `https://api.llmasaservice.io/agents/${agent}`;
2855
+ const fetchUrl = `https://api.llmasaservice.io/agents/${agent}`;
2859
2856
  const response = yield fetch(fetchUrl, {
2860
2857
  method: "GET",
2861
2858
  headers: {
@@ -2963,7 +2960,7 @@ var AgentPanel = ({
2963
2960
  var AgentPanel_default = AgentPanel;
2964
2961
 
2965
2962
  // src/AIAgentPanel.tsx
2966
- import React12, { useState as useState8, useCallback as useCallback4, useMemo as useMemo4, useRef as useRef6, useEffect as useEffect9 } from "react";
2963
+ import React12, { useCallback as useCallback4, useEffect as useEffect9, useMemo as useMemo4, useRef as useRef6, useState as useState8 } from "react";
2967
2964
 
2968
2965
  // src/AIChatPanel.tsx
2969
2966
  import React11, {
@@ -3613,8 +3610,10 @@ var AIChatPanel = ({
3613
3610
  contextSections = [],
3614
3611
  totalContextTokens = 0,
3615
3612
  maxContextTokens = 8e3,
3616
- enableContextDetailView = false
3613
+ enableContextDetailView = false,
3614
+ onConversationCreated
3617
3615
  }) => {
3616
+ const publicAPIUrl = "https://api.llmasaservice.io";
3618
3617
  const [lastController, setLastController] = useState6(new AbortController());
3619
3618
  const [lastMessages, setLastMessages] = useState6([]);
3620
3619
  const [history, setHistory] = useState6(initialHistory);
@@ -3637,6 +3636,24 @@ var AIChatPanel = ({
3637
3636
  const prevIdleRef = useRef5(true);
3638
3637
  const hasNotifiedCompletionRef = useRef5(true);
3639
3638
  const latestHistoryRef = useRef5(initialHistory);
3639
+ useEffect7(() => {
3640
+ if (!initialHistory) return;
3641
+ setHistory((prev) => {
3642
+ const currentKeys = Object.keys(prev);
3643
+ const newEntries = {};
3644
+ let hasNewEntries = false;
3645
+ for (const [key, value] of Object.entries(initialHistory)) {
3646
+ if (!currentKeys.includes(key)) {
3647
+ newEntries[key] = value;
3648
+ hasNewEntries = true;
3649
+ }
3650
+ }
3651
+ if (hasNewEntries) {
3652
+ return __spreadValues(__spreadValues({}, prev), newEntries);
3653
+ }
3654
+ return prev;
3655
+ });
3656
+ }, [initialHistory]);
3640
3657
  const llmResult = useLLM2(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
3641
3658
  project_id,
3642
3659
  customer
@@ -3676,6 +3693,60 @@ var AIChatPanel = ({
3676
3693
  userLanguage: navigator.language
3677
3694
  };
3678
3695
  }, []);
3696
+ const ensureConversation = useCallback2(() => {
3697
+ var _a, _b;
3698
+ console.log("ensureConversation - called with:", {
3699
+ currentConversation,
3700
+ createConversationOnFirstChat,
3701
+ project_id,
3702
+ publicAPIUrl
3703
+ });
3704
+ if ((!currentConversation || currentConversation === "") && createConversationOnFirstChat) {
3705
+ if (!project_id) {
3706
+ console.error("ensureConversation - Cannot create conversation without project_id");
3707
+ return Promise.resolve("");
3708
+ }
3709
+ const requestBody = {
3710
+ project_id,
3711
+ agentId: agent,
3712
+ customerId: (_a = customer == null ? void 0 : customer.customer_id) != null ? _a : null,
3713
+ customerEmail: (_b = customer == null ? void 0 : customer.customer_user_email) != null ? _b : null,
3714
+ timezone: browserInfo == null ? void 0 : browserInfo.userTimezone,
3715
+ language: browserInfo == null ? void 0 : browserInfo.userLanguage
3716
+ };
3717
+ console.log("ensureConversation - Creating conversation with:", requestBody);
3718
+ console.log("ensureConversation - API URL:", `${publicAPIUrl}/conversations`);
3719
+ return fetch(`${publicAPIUrl}/conversations`, {
3720
+ method: "POST",
3721
+ headers: {
3722
+ "Content-Type": "application/json"
3723
+ },
3724
+ body: JSON.stringify(requestBody)
3725
+ }).then((res) => __async(void 0, null, function* () {
3726
+ if (!res.ok) {
3727
+ const errorText = yield res.text();
3728
+ throw new Error(
3729
+ `HTTP error! status: ${res.status}, message: ${errorText}`
3730
+ );
3731
+ }
3732
+ return res.json();
3733
+ })).then((newConvo) => {
3734
+ console.log("ensureConversation - API response:", newConvo);
3735
+ if (newConvo == null ? void 0 : newConvo.id) {
3736
+ console.log("ensureConversation - New conversation ID:", newConvo.id);
3737
+ setCurrentConversation(newConvo.id);
3738
+ return newConvo.id;
3739
+ }
3740
+ console.warn("ensureConversation - No ID in response");
3741
+ return "";
3742
+ }).catch((error) => {
3743
+ console.error("Error creating new conversation", error);
3744
+ return "";
3745
+ });
3746
+ }
3747
+ console.log("ensureConversation - using existing conversation:", currentConversation);
3748
+ return Promise.resolve(currentConversation);
3749
+ }, [currentConversation, createConversationOnFirstChat, publicAPIUrl, project_id, agent, customer, browserInfo]);
3679
3750
  const dataWithExtras = useCallback2(() => {
3680
3751
  var _a, _b, _c, _d, _e, _f, _g, _h;
3681
3752
  return [
@@ -3789,6 +3860,7 @@ var AIChatPanel = ({
3789
3860
  lastScrollTimeRef.current = now;
3790
3861
  }, []);
3791
3862
  const continueChat = useCallback2((promptText) => {
3863
+ console.log("AIChatPanel.continueChat called with:", promptText);
3792
3864
  setThinkingBlocks([]);
3793
3865
  setCurrentThinkingIndex(0);
3794
3866
  setUserHasScrolled(false);
@@ -3808,58 +3880,68 @@ var AIChatPanel = ({
3808
3880
  const promptToSend = promptText;
3809
3881
  if (!promptToSend || !promptToSend.trim()) return;
3810
3882
  setIsLoading(true);
3811
- const messagesAndHistory = [];
3812
- Object.entries(history).forEach(([historyPrompt, historyEntry]) => {
3813
- let promptForHistory = historyPrompt;
3814
- const isoTimestampRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z:/;
3815
- if (isoTimestampRegex.test(historyPrompt)) {
3816
- const colonIndex = historyPrompt.indexOf(":", 19);
3817
- promptForHistory = historyPrompt.substring(colonIndex + 1);
3818
- } else if (/^\d+:/.test(historyPrompt)) {
3819
- const colonIndex = historyPrompt.indexOf(":");
3820
- promptForHistory = historyPrompt.substring(colonIndex + 1);
3883
+ console.log("AIChatPanel.continueChat - about to call ensureConversation");
3884
+ ensureConversation().then((convId) => {
3885
+ console.log("AIChatPanel.continueChat - ensureConversation resolved with:", convId);
3886
+ const messagesAndHistory = [];
3887
+ Object.entries(history).forEach(([historyPrompt, historyEntry]) => {
3888
+ let promptForHistory = historyPrompt;
3889
+ const isoTimestampRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z:/;
3890
+ if (isoTimestampRegex.test(historyPrompt)) {
3891
+ const colonIndex = historyPrompt.indexOf(":", 19);
3892
+ promptForHistory = historyPrompt.substring(colonIndex + 1);
3893
+ } else if (/^\d+:/.test(historyPrompt)) {
3894
+ const colonIndex = historyPrompt.indexOf(":");
3895
+ promptForHistory = historyPrompt.substring(colonIndex + 1);
3896
+ }
3897
+ messagesAndHistory.push({ role: "user", content: promptForHistory });
3898
+ messagesAndHistory.push({ role: "assistant", content: historyEntry.content });
3899
+ });
3900
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
3901
+ const promptKey = `${timestamp}:${promptToSend.trim()}`;
3902
+ setHistory((prevHistory) => __spreadProps(__spreadValues({}, prevHistory), {
3903
+ [promptKey]: { content: "", callId: "" }
3904
+ }));
3905
+ let fullPromptToSend = promptToSend.trim();
3906
+ if (Object.keys(history).length === 0 && promptTemplate) {
3907
+ fullPromptToSend = promptTemplate.replace("{{prompt}}", fullPromptToSend);
3821
3908
  }
3822
- messagesAndHistory.push({ role: "user", content: promptForHistory });
3823
- messagesAndHistory.push({ role: "assistant", content: historyEntry.content });
3824
- });
3825
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
3826
- const promptKey = `${timestamp}:${promptToSend.trim()}`;
3827
- setHistory((prevHistory) => __spreadProps(__spreadValues({}, prevHistory), {
3828
- [promptKey]: { content: "", callId: "" }
3829
- }));
3830
- let fullPromptToSend = promptToSend.trim();
3831
- if (Object.keys(history).length === 0 && promptTemplate) {
3832
- fullPromptToSend = promptTemplate.replace("{{prompt}}", fullPromptToSend);
3833
- }
3834
- if (followOnPrompt) {
3835
- fullPromptToSend += `
3909
+ if (followOnPrompt) {
3910
+ fullPromptToSend += `
3836
3911
 
3837
3912
  ${followOnPrompt}`;
3838
- }
3839
- const newController = new AbortController();
3840
- setLastController(newController);
3841
- send(
3842
- fullPromptToSend,
3843
- messagesAndHistory,
3844
- [
3845
- ...dataWithExtras(),
3846
- { key: "--messages", data: messagesAndHistory.length.toString() }
3847
- ],
3848
- true,
3849
- // stream
3850
- true,
3851
- // includeHistory
3852
- service,
3853
- // group_id from agent config
3854
- currentConversation,
3855
- newController
3856
- );
3857
- setLastPrompt(promptToSend.trim());
3858
- setLastMessages(messagesAndHistory);
3859
- setLastKey(promptKey);
3860
- setTimeout(() => {
3861
- scrollToBottom();
3862
- }, 0);
3913
+ }
3914
+ const newController = new AbortController();
3915
+ setLastController(newController);
3916
+ send(
3917
+ fullPromptToSend,
3918
+ messagesAndHistory,
3919
+ [
3920
+ ...dataWithExtras(),
3921
+ { key: "--messages", data: messagesAndHistory.length.toString() }
3922
+ ],
3923
+ true,
3924
+ // stream
3925
+ true,
3926
+ // includeHistory
3927
+ service,
3928
+ // group_id from agent config
3929
+ convId,
3930
+ // Use the conversation ID from ensureConversation
3931
+ newController
3932
+ );
3933
+ setLastPrompt(promptToSend.trim());
3934
+ setLastMessages(messagesAndHistory);
3935
+ setLastKey(promptKey);
3936
+ if (convId && onConversationCreated) {
3937
+ setTimeout(() => {
3938
+ onConversationCreated(convId);
3939
+ }, 100);
3940
+ }
3941
+ setTimeout(() => {
3942
+ scrollToBottom();
3943
+ }, 0);
3944
+ });
3863
3945
  }, [
3864
3946
  idle,
3865
3947
  stop,
@@ -3874,9 +3956,10 @@ ${followOnPrompt}`;
3874
3956
  followOnPrompt,
3875
3957
  send,
3876
3958
  service,
3877
- currentConversation,
3959
+ ensureConversation,
3878
3960
  dataWithExtras,
3879
- scrollToBottom
3961
+ scrollToBottom,
3962
+ onConversationCreated
3880
3963
  ]);
3881
3964
  const handleSuggestionClick = useCallback2((question) => {
3882
3965
  continueChat(question);
@@ -3918,18 +4001,18 @@ ${followOnPrompt}`;
3918
4001
  useEffect7(() => {
3919
4002
  if (!response || !lastKey || justReset) return;
3920
4003
  const { cleanedText, blocks } = processThinkingTags(response);
3921
- const processedContent = processActions(cleanedText);
3922
4004
  setThinkingBlocks(blocks);
3923
4005
  setHistory((prev) => {
3924
4006
  const newHistory = __spreadValues({}, prev);
3925
4007
  newHistory[lastKey] = {
3926
- content: processedContent,
4008
+ content: cleanedText,
4009
+ // Store raw content, not processed
3927
4010
  callId: lastCallId || ""
3928
4011
  };
3929
4012
  latestHistoryRef.current = newHistory;
3930
4013
  return newHistory;
3931
4014
  });
3932
- }, [response, lastKey, lastCallId, processThinkingTags, processActions, justReset]);
4015
+ }, [response, lastKey, lastCallId, processThinkingTags, justReset]);
3933
4016
  useEffect7(() => {
3934
4017
  const wasStreaming = !prevIdleRef.current;
3935
4018
  const isNowIdle = idle;
@@ -4013,38 +4096,49 @@ ${followOnPrompt}`;
4013
4096
  }, []);
4014
4097
  useEffect7(() => {
4015
4098
  const hasLoadedHistory = initialHistory && Object.keys(initialHistory).length > 0;
4099
+ if (!project_id) {
4100
+ return;
4101
+ }
4016
4102
  if (initialPrompt && initialPrompt !== "" && initialPrompt !== lastPrompt && !hasLoadedHistory) {
4017
4103
  setIsLoading(true);
4018
4104
  setThinkingBlocks([]);
4019
4105
  setCurrentThinkingIndex(0);
4020
4106
  setUserHasScrolled(false);
4021
- const controller = new AbortController();
4022
- setLastController(controller);
4023
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
4024
- const promptKey = `${timestamp}:${initialPrompt}`;
4025
- setHistory({ [promptKey]: { content: "", callId: "" } });
4026
- let fullPrompt = initialPrompt;
4027
- if (promptTemplate) {
4028
- fullPrompt = promptTemplate.replace("{{prompt}}", initialPrompt);
4029
- }
4030
- send(
4031
- fullPrompt,
4032
- [],
4033
- [
4034
- ...dataWithExtras(),
4035
- { key: "--messages", data: "0" }
4036
- ],
4037
- true,
4038
- true,
4039
- service,
4040
- currentConversation,
4041
- controller
4042
- );
4043
- setLastPrompt(initialPrompt);
4044
- setLastMessages([]);
4045
- setLastKey(promptKey);
4107
+ ensureConversation().then((convId) => {
4108
+ const controller = new AbortController();
4109
+ setLastController(controller);
4110
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
4111
+ const promptKey = `${timestamp}:${initialPrompt}`;
4112
+ setHistory({ [promptKey]: { content: "", callId: "" } });
4113
+ let fullPrompt = initialPrompt;
4114
+ if (promptTemplate) {
4115
+ fullPrompt = promptTemplate.replace("{{prompt}}", initialPrompt);
4116
+ }
4117
+ send(
4118
+ fullPrompt,
4119
+ [],
4120
+ [
4121
+ ...dataWithExtras(),
4122
+ { key: "--messages", data: "0" }
4123
+ ],
4124
+ true,
4125
+ true,
4126
+ service,
4127
+ convId,
4128
+ // Use conversation ID from ensureConversation
4129
+ controller
4130
+ );
4131
+ setLastPrompt(initialPrompt);
4132
+ setLastMessages([]);
4133
+ setLastKey(promptKey);
4134
+ if (convId && onConversationCreated) {
4135
+ setTimeout(() => {
4136
+ onConversationCreated(convId);
4137
+ }, 100);
4138
+ }
4139
+ });
4046
4140
  }
4047
- }, [initialPrompt, initialHistory]);
4141
+ }, [initialPrompt, initialHistory, ensureConversation, promptTemplate, send, dataWithExtras, service, lastPrompt, project_id, onConversationCreated]);
4048
4142
  const CodeBlock = useCallback2((_a) => {
4049
4143
  var _b = _a, { node, inline, className, children } = _b, props = __objRest(_b, ["node", "inline", "className", "children"]);
4050
4144
  const match = /language-(\w+)/.exec(className || "");
@@ -4099,7 +4193,13 @@ ${followOnPrompt}`;
4099
4193
  variant: "default",
4100
4194
  size: "sm",
4101
4195
  className: "ai-chat-agent-suggestion__button",
4102
- onClick: () => onAgentChange(agentId)
4196
+ onClick: () => {
4197
+ onAgentChange(agentId);
4198
+ setTimeout(() => {
4199
+ var _a;
4200
+ (_a = bottomRef.current) == null ? void 0 : _a.scrollIntoView({ behavior: "auto" });
4201
+ }, 50);
4202
+ }
4103
4203
  },
4104
4204
  "Switch"
4105
4205
  ));
@@ -4148,15 +4248,17 @@ ${followOnPrompt}`;
4148
4248
  const panelClasses = ["ai-chat-panel", theme === "dark" ? "dark-theme" : ""].filter(Boolean).join(" ");
4149
4249
  return /* @__PURE__ */ React11.createElement("div", { className: panelClasses }, title && /* @__PURE__ */ React11.createElement("div", { className: "ai-chat-panel__title" }, title), /* @__PURE__ */ React11.createElement(ScrollArea, { className: "ai-chat-panel__messages", ref: responseAreaRef }, initialMessage && /* @__PURE__ */ React11.createElement("div", { className: "ai-chat-message ai-chat-message--assistant" }, /* @__PURE__ */ React11.createElement("div", { className: "ai-chat-message__content" }, /* @__PURE__ */ React11.createElement(ReactMarkdown2, { remarkPlugins: [remarkGfm2], rehypePlugins: [rehypeRaw2] }, initialMessage))), Object.entries(history).map(([prompt, entry], index) => {
4150
4250
  const isLastEntry = index === Object.keys(history).length - 1;
4251
+ const isSystemMessage = prompt.startsWith("__system__:");
4151
4252
  const { cleanedText } = processThinkingTags(entry.content);
4152
- return /* @__PURE__ */ React11.createElement("div", { key: index, className: "ai-chat-entry" }, !(hideInitialPrompt && index === 0) && /* @__PURE__ */ React11.createElement("div", { className: "ai-chat-message ai-chat-message--user" }, /* @__PURE__ */ React11.createElement("div", { className: "ai-chat-message__content" }, formatPromptForDisplay(prompt))), /* @__PURE__ */ React11.createElement("div", { className: "ai-chat-message ai-chat-message--assistant" }, /* @__PURE__ */ React11.createElement("div", { className: "ai-chat-message__content" }, isLastEntry && (isLoading || !idle) && !justReset ? /* @__PURE__ */ React11.createElement("div", { className: "ai-chat-streaming" }, thinkingBlocks.length > 0 && renderThinkingBlocks(), cleanedText ? /* @__PURE__ */ React11.createElement(
4253
+ const processedContent = processActions(cleanedText);
4254
+ return /* @__PURE__ */ React11.createElement("div", { key: index, className: "ai-chat-entry" }, !(hideInitialPrompt && index === 0) && !isSystemMessage && /* @__PURE__ */ React11.createElement("div", { className: "ai-chat-message ai-chat-message--user" }, /* @__PURE__ */ React11.createElement("div", { className: "ai-chat-message__content" }, formatPromptForDisplay(prompt))), /* @__PURE__ */ React11.createElement("div", { className: "ai-chat-message ai-chat-message--assistant" }, /* @__PURE__ */ React11.createElement("div", { className: "ai-chat-message__content" }, isLastEntry && (isLoading || !idle) && !justReset ? /* @__PURE__ */ React11.createElement("div", { className: "ai-chat-streaming" }, thinkingBlocks.length > 0 && renderThinkingBlocks(), processedContent ? /* @__PURE__ */ React11.createElement(
4153
4255
  ReactMarkdown2,
4154
4256
  {
4155
4257
  remarkPlugins: [remarkGfm2],
4156
4258
  rehypePlugins: [rehypeRaw2],
4157
4259
  components: markdownComponents
4158
4260
  },
4159
- cleanedText
4261
+ processedContent
4160
4262
  ) : /* @__PURE__ */ React11.createElement("div", { className: "ai-chat-loading" }, /* @__PURE__ */ React11.createElement("span", null, "Thinking"), /* @__PURE__ */ React11.createElement("span", { className: "ai-chat-loading__dots" }, /* @__PURE__ */ React11.createElement("span", { className: "ai-chat-loading__dot" }), /* @__PURE__ */ React11.createElement("span", { className: "ai-chat-loading__dot" }), /* @__PURE__ */ React11.createElement("span", { className: "ai-chat-loading__dot" })))) : /* @__PURE__ */ React11.createElement(React11.Fragment, null, isLastEntry && thinkingBlocks.length > 0 && renderThinkingBlocks(), /* @__PURE__ */ React11.createElement(
4161
4263
  ReactMarkdown2,
4162
4264
  {
@@ -4164,7 +4266,7 @@ ${followOnPrompt}`;
4164
4266
  rehypePlugins: [rehypeRaw2],
4165
4267
  components: markdownComponents
4166
4268
  },
4167
- cleanedText
4269
+ processedContent
4168
4270
  ))), idle && !isLoading && /* @__PURE__ */ React11.createElement("div", { className: "ai-chat-message__actions" }, /* @__PURE__ */ React11.createElement(Tooltip, { content: copiedCallId === entry.callId ? "Copied!" : "Copy" }, /* @__PURE__ */ React11.createElement(
4169
4271
  Button,
4170
4272
  {
@@ -4239,8 +4341,7 @@ var AIChatPanel_default = React11.memo(AIChatPanel);
4239
4341
  // src/hooks/useAgentRegistry.ts
4240
4342
  import { useState as useState7, useEffect as useEffect8, useCallback as useCallback3, useMemo as useMemo3 } from "react";
4241
4343
  var resolveApiEndpoint = (baseUrl, agentId) => {
4242
- const apiRoot = baseUrl.endsWith("dev") ? "https://8ftw8droff.execute-api.us-east-1.amazonaws.com/dev" : "https://api.llmasaservice.io";
4243
- return `${apiRoot}/agents/${agentId}`;
4344
+ return `https://api.llmasaservice.io/agents/${agentId}`;
4244
4345
  };
4245
4346
  function useAgentRegistry(agentIds, options = {}) {
4246
4347
  const { url = "https://chat.llmasaservice.io", autoFetch = true, localOverrides = {} } = options;
@@ -4445,6 +4546,7 @@ var MessageIcon = () => /* @__PURE__ */ React12.createElement("svg", { width: "1
4445
4546
  var CloseIcon = () => /* @__PURE__ */ React12.createElement("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, /* @__PURE__ */ React12.createElement("path", { d: "M9 3L3 9M3 3l6 6", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round" }));
4446
4547
  var LoadingDotIcon = () => /* @__PURE__ */ React12.createElement("span", { className: "ai-agent-panel__loading-dot" });
4447
4548
  var SidebarIcon = () => /* @__PURE__ */ React12.createElement("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, /* @__PURE__ */ React12.createElement("rect", { x: "2", y: "2", width: "12", height: "12", rx: "2", stroke: "currentColor", strokeWidth: "1.5" }), /* @__PURE__ */ React12.createElement("path", { d: "M6 2v12", stroke: "currentColor", strokeWidth: "1.5" }));
4549
+ var SparkleIcon = () => /* @__PURE__ */ React12.createElement("svg", { width: "14", height: "14", viewBox: "0 0 16 16", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, /* @__PURE__ */ React12.createElement("path", { d: "M8 1v3M8 12v3M3 8H0M16 8h-3M12.95 3.05l-2.12 2.12M5.17 10.83l-2.12 2.12M12.95 12.95l-2.12-2.12M5.17 5.17L3.05 3.05", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round" }), /* @__PURE__ */ React12.createElement("circle", { cx: "8", cy: "8", r: "2", fill: "currentColor" }));
4448
4550
  var normalizeConversationListPayload = (payload) => {
4449
4551
  if (!payload) return [];
4450
4552
  const conversations = Array.isArray(payload) ? payload : payload.conversations || [];
@@ -4562,7 +4664,8 @@ var ChatPanelWrapper = ({
4562
4664
  contextSections,
4563
4665
  totalContextTokens,
4564
4666
  maxContextTokens,
4565
- enableContextDetailView
4667
+ enableContextDetailView,
4668
+ onConversationCreated
4566
4669
  }) => {
4567
4670
  var _a, _b;
4568
4671
  const convAgentProfile = getAgent(activeConv.agentId);
@@ -4580,6 +4683,12 @@ var ChatPanelWrapper = ({
4580
4683
  },
4581
4684
  [handleLoadingChange, activeConv.conversationId]
4582
4685
  );
4686
+ const conversationCreatedCallback = useCallback4(
4687
+ (realConversationId) => {
4688
+ onConversationCreated(activeConv.conversationId, realConversationId);
4689
+ },
4690
+ [onConversationCreated, activeConv.conversationId]
4691
+ );
4583
4692
  const agentStatus = convAgentProfile == null ? void 0 : convAgentProfile.status;
4584
4693
  const promptsString = (convAgentMetadata == null ? void 0 : convAgentMetadata.displayFollowOnPrompts) || "";
4585
4694
  let effectiveFollowOnQuestions;
@@ -4638,7 +4747,8 @@ var ChatPanelWrapper = ({
4638
4747
  contextSections,
4639
4748
  totalContextTokens,
4640
4749
  maxContextTokens,
4641
- enableContextDetailView
4750
+ enableContextDetailView,
4751
+ onConversationCreated: conversationCreatedCallback
4642
4752
  }
4643
4753
  )
4644
4754
  );
@@ -4678,9 +4788,10 @@ var AIAgentPanel = ({
4678
4788
  actions = [],
4679
4789
  followOnQuestions = [],
4680
4790
  followOnPrompt = "",
4681
- historyListLimit = 50
4791
+ historyListLimit = 50,
4792
+ showConversationHistory = true
4682
4793
  }) => {
4683
- var _a, _b;
4794
+ var _a, _b, _c, _d;
4684
4795
  const [isCollapsed, setIsCollapsed] = useState8(defaultCollapsed);
4685
4796
  const [isHistoryCollapsed, setIsHistoryCollapsed] = useState8(() => {
4686
4797
  if (typeof window !== "undefined") {
@@ -4705,6 +4816,7 @@ var AIAgentPanel = ({
4705
4816
  const [showSearch, setShowSearch] = useState8(false);
4706
4817
  const [showHandoffDialog, setShowHandoffDialog] = useState8(false);
4707
4818
  const [suggestedAgent, setSuggestedAgent] = useState8(null);
4819
+ const [handoffSource, setHandoffSource] = useState8("agent");
4708
4820
  const panelRef = useRef6(null);
4709
4821
  const resizeRef = useRef6(null);
4710
4822
  const { agentIds, localOverrides } = useMemo4(() => {
@@ -4760,6 +4872,10 @@ var AIAgentPanel = ({
4760
4872
  activeConversationsRef.current = activeConversations;
4761
4873
  const currentConversationIdRef = useRef6(currentConversationId);
4762
4874
  currentConversationIdRef.current = currentConversationId;
4875
+ const [showContextNotification, setShowContextNotification] = useState8(false);
4876
+ const prevContextRef = useRef6(null);
4877
+ const contextNotificationTimeoutRef = useRef6(null);
4878
+ const prevDefaultAgentRef = useRef6(null);
4763
4879
  const fetchFirstPrompt = useCallback4((conversationId, agentIdForConversation) => __async(void 0, null, function* () {
4764
4880
  var _a2, _b2;
4765
4881
  if (checkedPromptsRef.current.has(conversationId)) {
@@ -4860,6 +4976,9 @@ var AIAgentPanel = ({
4860
4976
  fetchInProgressRef.current = true;
4861
4977
  setConversationsLoading(true);
4862
4978
  setConversationsError(null);
4979
+ console.log("projectId", projectId);
4980
+ console.log("customerId", customerId);
4981
+ console.log("apiKey", apiKey);
4863
4982
  try {
4864
4983
  console.log("fetchConversations - customerId:", customerId);
4865
4984
  const url2 = `https://api.llmasaservice.io/conversations?customer_id=${customerId}`;
@@ -4979,6 +5098,8 @@ var AIAgentPanel = ({
4979
5098
  const next = new Map(prev);
4980
5099
  next.set(conversationId, {
4981
5100
  conversationId,
5101
+ stableKey: conversationId,
5102
+ // Use real ID as stable key when loading from API
4982
5103
  agentId: agentIdToUse,
4983
5104
  history,
4984
5105
  isLoading: false,
@@ -5002,6 +5123,7 @@ var AIAgentPanel = ({
5002
5123
  }, [currentAgentId, fetchConversations]);
5003
5124
  useEffect9(() => {
5004
5125
  var _a2;
5126
+ if (!showConversationHistory) return;
5005
5127
  if (!agentsLoading && currentAgentId && apiKey) {
5006
5128
  const agentProfile = getAgent(currentAgentId);
5007
5129
  const projectId = (_a2 = agentProfile == null ? void 0 : agentProfile.metadata) == null ? void 0 : _a2.projectId;
@@ -5010,13 +5132,15 @@ var AIAgentPanel = ({
5010
5132
  fetchConversations(currentAgentId);
5011
5133
  }
5012
5134
  }
5013
- }, [agentsLoading, currentAgentId, apiKey, fetchConversations, getAgent]);
5135
+ }, [agentsLoading, currentAgentId, apiKey, fetchConversations, getAgent, showConversationHistory]);
5014
5136
  const handleNewConversation = useCallback4(() => {
5015
5137
  const tempId = `new-${Date.now()}`;
5016
5138
  setActiveConversations((prev) => {
5017
5139
  const next = new Map(prev);
5018
5140
  next.set(tempId, {
5019
5141
  conversationId: tempId,
5142
+ stableKey: tempId,
5143
+ // Stable key never changes even when conversationId updates
5020
5144
  agentId: currentAgentId,
5021
5145
  history: {},
5022
5146
  isLoading: false,
@@ -5166,6 +5290,80 @@ var AIAgentPanel = ({
5166
5290
  totalTokens
5167
5291
  };
5168
5292
  }, [context, sharedContextSections, pageContextSections, contextDataSources]);
5293
+ useEffect9(() => {
5294
+ const contextString = JSON.stringify(mergedContext.sections.map((s) => ({ id: s.id, data: s.data })));
5295
+ if (prevContextRef.current === null) {
5296
+ prevContextRef.current = contextString;
5297
+ return;
5298
+ }
5299
+ if (prevContextRef.current !== contextString) {
5300
+ console.log("AIAgentPanel - Context changed, showing notification");
5301
+ prevContextRef.current = contextString;
5302
+ if (contextNotificationTimeoutRef.current) {
5303
+ clearTimeout(contextNotificationTimeoutRef.current);
5304
+ contextNotificationTimeoutRef.current = null;
5305
+ }
5306
+ setShowContextNotification(true);
5307
+ contextNotificationTimeoutRef.current = setTimeout(() => {
5308
+ setShowContextNotification(false);
5309
+ contextNotificationTimeoutRef.current = null;
5310
+ }, 3e3);
5311
+ }
5312
+ }, [mergedContext.sections]);
5313
+ useEffect9(() => {
5314
+ return () => {
5315
+ if (contextNotificationTimeoutRef.current) {
5316
+ clearTimeout(contextNotificationTimeoutRef.current);
5317
+ }
5318
+ };
5319
+ }, []);
5320
+ useEffect9(() => {
5321
+ var _a2, _b2;
5322
+ let foundDefaultAgent = null;
5323
+ for (const section of pageContextSections) {
5324
+ if (section.data && typeof section.data === "object" && "defaultAgent" in section.data) {
5325
+ const defaultAgentValue = section.data.defaultAgent;
5326
+ if (typeof defaultAgentValue === "string" && defaultAgentValue) {
5327
+ foundDefaultAgent = defaultAgentValue;
5328
+ break;
5329
+ }
5330
+ }
5331
+ }
5332
+ if (!foundDefaultAgent || foundDefaultAgent === prevDefaultAgentRef.current) {
5333
+ return;
5334
+ }
5335
+ if (foundDefaultAgent === currentAgentId) {
5336
+ prevDefaultAgentRef.current = foundDefaultAgent;
5337
+ return;
5338
+ }
5339
+ const isAvailable = agentIds.includes(foundDefaultAgent);
5340
+ const agentProfile = getAgent(foundDefaultAgent);
5341
+ const isReady = (agentProfile == null ? void 0 : agentProfile.status) === "ready";
5342
+ if (isAvailable && isReady && currentConversationIdRef.current) {
5343
+ const agentName = ((_a2 = agentProfile == null ? void 0 : agentProfile.metadata) == null ? void 0 : _a2.displayTitle) || ((_b2 = localOverrides[foundDefaultAgent]) == null ? void 0 : _b2.localName) || foundDefaultAgent;
5344
+ const suggestionMessage = `This page recommends a different agent for better assistance.
5345
+
5346
+ [SUGGEST_AGENT:${foundDefaultAgent}|${agentName}|Recommended for this page]`;
5347
+ const syntheticKey = `__system__:page_suggestion_${foundDefaultAgent}_${Date.now()}`;
5348
+ prevDefaultAgentRef.current = foundDefaultAgent;
5349
+ setActiveConversations((prev) => {
5350
+ const conversationId = currentConversationIdRef.current;
5351
+ if (!conversationId) return prev;
5352
+ const existing = prev.get(conversationId);
5353
+ if (!existing) return prev;
5354
+ const next = new Map(prev);
5355
+ next.set(conversationId, __spreadProps(__spreadValues({}, existing), {
5356
+ history: __spreadProps(__spreadValues({}, existing.history), {
5357
+ [syntheticKey]: {
5358
+ content: suggestionMessage,
5359
+ callId: `page-suggestion-${Date.now()}`
5360
+ }
5361
+ })
5362
+ }));
5363
+ return next;
5364
+ });
5365
+ }
5366
+ }, [pageContextSections, currentAgentId, agentIds, getAgent, localOverrides]);
5169
5367
  const chatPanelData = useMemo4(() => {
5170
5368
  const contextData = mergedContext.sections.map((section) => ({
5171
5369
  key: section.id,
@@ -5268,6 +5466,7 @@ var AIAgentPanel = ({
5268
5466
  const suggestedId = handoffMatch[1];
5269
5467
  if (suggestedId && suggestedId !== currentAgentId && agents.includes(suggestedId)) {
5270
5468
  setSuggestedAgent(suggestedId);
5469
+ setHandoffSource("agent");
5271
5470
  setShowHandoffDialog(true);
5272
5471
  }
5273
5472
  }
@@ -5304,11 +5503,34 @@ var AIAgentPanel = ({
5304
5503
  }
5305
5504
  setShowHandoffDialog(false);
5306
5505
  setSuggestedAgent(null);
5506
+ setHandoffSource("agent");
5307
5507
  }, [suggestedAgent, handleAgentSwitch]);
5308
5508
  const handleHandoffCancel = useCallback4(() => {
5309
5509
  setShowHandoffDialog(false);
5310
5510
  setSuggestedAgent(null);
5511
+ setHandoffSource("agent");
5311
5512
  }, []);
5513
+ const handleConversationCreated = useCallback4((tempId, realId) => {
5514
+ console.log("Conversation created:", tempId, "->", realId);
5515
+ setActiveConversations((prev) => {
5516
+ const existing = prev.get(tempId);
5517
+ if (existing) {
5518
+ const next = new Map(prev);
5519
+ next.delete(tempId);
5520
+ next.set(realId, __spreadProps(__spreadValues({}, existing), {
5521
+ conversationId: realId
5522
+ }));
5523
+ return next;
5524
+ }
5525
+ return prev;
5526
+ });
5527
+ if (currentConversationIdRef.current === tempId) {
5528
+ setCurrentConversationId(realId);
5529
+ if (onConversationChange) {
5530
+ onConversationChange(realId);
5531
+ }
5532
+ }
5533
+ }, [onConversationChange]);
5312
5534
  const toggleCollapse = useCallback4(() => {
5313
5535
  setIsCollapsed((prev) => !prev);
5314
5536
  }, []);
@@ -5324,7 +5546,8 @@ var AIAgentPanel = ({
5324
5546
  theme === "dark" ? "dark-theme" : "",
5325
5547
  isCollapsed ? "ai-agent-panel--collapsed" : "",
5326
5548
  position === "left" ? "ai-agent-panel--left" : "ai-agent-panel--right",
5327
- sidebarPosition === "right" ? "ai-agent-panel--sidebar-right" : "ai-agent-panel--sidebar-left"
5549
+ sidebarPosition === "right" ? "ai-agent-panel--sidebar-right" : "ai-agent-panel--sidebar-left",
5550
+ !showConversationHistory ? "ai-agent-panel--no-history" : ""
5328
5551
  ].filter(Boolean).join(" ");
5329
5552
  if (isCollapsed) {
5330
5553
  return /* @__PURE__ */ React12.createElement("div", { className: panelClasses, ref: panelRef }, /* @__PURE__ */ React12.createElement(
@@ -5340,7 +5563,7 @@ var AIAgentPanel = ({
5340
5563
  },
5341
5564
  /* @__PURE__ */ React12.createElement(Tooltip, { content: "Expand Panel", side: "left" }, /* @__PURE__ */ React12.createElement(Button, { variant: "ghost", size: "icon", onClick: toggleCollapse }, position === "right" ? /* @__PURE__ */ React12.createElement(ChevronLeftIcon, null) : /* @__PURE__ */ React12.createElement(ChevronRightIcon, null))),
5342
5565
  /* @__PURE__ */ React12.createElement("div", { className: "ai-agent-panel__collapsed-divider" }),
5343
- /* @__PURE__ */ React12.createElement(Tooltip, { content: "Search", side: "left" }, /* @__PURE__ */ React12.createElement(
5566
+ showConversationHistory && /* @__PURE__ */ React12.createElement(Tooltip, { content: "Search", side: "left" }, /* @__PURE__ */ React12.createElement(
5344
5567
  Button,
5345
5568
  {
5346
5569
  variant: "ghost",
@@ -5389,6 +5612,8 @@ var AIAgentPanel = ({
5389
5612
  const next = new Map(prev);
5390
5613
  next.set(tempId, {
5391
5614
  conversationId: tempId,
5615
+ stableKey: tempId,
5616
+ // Stable key never changes
5392
5617
  agentId: agent.id,
5393
5618
  history: {},
5394
5619
  isLoading: false,
@@ -5435,7 +5660,7 @@ var AIAgentPanel = ({
5435
5660
  tabIndex: 0
5436
5661
  }
5437
5662
  ),
5438
- /* @__PURE__ */ React12.createElement("div", { className: `ai-agent-panel__sidebar ${isHistoryCollapsed ? "ai-agent-panel__sidebar--collapsed" : ""}` }, isHistoryCollapsed ? (
5663
+ showConversationHistory && /* @__PURE__ */ React12.createElement("div", { className: `ai-agent-panel__sidebar ${isHistoryCollapsed ? "ai-agent-panel__sidebar--collapsed" : ""}` }, isHistoryCollapsed ? (
5439
5664
  // Collapsed history bar
5440
5665
  /* @__PURE__ */ React12.createElement(
5441
5666
  "div",
@@ -5491,6 +5716,8 @@ var AIAgentPanel = ({
5491
5716
  const next = new Map(prev);
5492
5717
  next.set(tempId, {
5493
5718
  conversationId: tempId,
5719
+ stableKey: tempId,
5720
+ // Stable key never changes
5494
5721
  agentId: agent.id,
5495
5722
  history: {},
5496
5723
  isLoading: false,
@@ -5548,7 +5775,7 @@ var AIAgentPanel = ({
5548
5775
  ))), /* @__PURE__ */ React12.createElement(Tooltip, { content: "Collapse History", side: "bottom" }, /* @__PURE__ */ React12.createElement(Button, { variant: "ghost", size: "icon", onClick: toggleHistoryCollapse }, /* @__PURE__ */ React12.createElement(SidebarIcon, null))), /* @__PURE__ */ React12.createElement(Button, { variant: "ghost", size: "icon", onClick: toggleCollapse }, position === "right" ? /* @__PURE__ */ React12.createElement(ChevronRightIcon, null) : /* @__PURE__ */ React12.createElement(ChevronLeftIcon, null))), /* @__PURE__ */ React12.createElement(ScrollArea, { className: "ai-agent-panel__conversations" }, activeConversationsList.length > 0 && /* @__PURE__ */ React12.createElement("div", { className: "ai-agent-panel__group ai-agent-panel__group--active" }, /* @__PURE__ */ React12.createElement("div", { className: "ai-agent-panel__group-label" }, /* @__PURE__ */ React12.createElement("span", null, "Active (", activeConversationsList.length, ")")), activeConversationsList.map((activeConv) => /* @__PURE__ */ React12.createElement(
5549
5776
  "div",
5550
5777
  {
5551
- key: activeConv.conversationId,
5778
+ key: activeConv.stableKey,
5552
5779
  className: `ai-agent-panel__conversation ai-agent-panel__conversation--active-item ${currentConversationId === activeConv.conversationId ? "ai-agent-panel__conversation--current" : ""}`,
5553
5780
  onClick: () => {
5554
5781
  setCurrentConversationId(activeConv.conversationId);
@@ -5587,10 +5814,10 @@ var AIAgentPanel = ({
5587
5814
  /* @__PURE__ */ React12.createElement("div", { className: "ai-agent-panel__conversation-content" }, /* @__PURE__ */ React12.createElement("div", { className: "ai-agent-panel__conversation-title" }, isActive && /* @__PURE__ */ React12.createElement("span", { className: "ai-agent-panel__active-badge" }, "\u25CF"), conversationFirstPrompts[conv.conversationId] || conv.title))
5588
5815
  );
5589
5816
  }))))))),
5590
- /* @__PURE__ */ React12.createElement("div", { className: "ai-agent-panel__chat" }, activeConversationsList.map((activeConv) => /* @__PURE__ */ React12.createElement(
5817
+ /* @__PURE__ */ React12.createElement("div", { className: "ai-agent-panel__chat" }, showContextNotification && /* @__PURE__ */ React12.createElement("div", { className: "ai-agent-panel__context-notification" }, /* @__PURE__ */ React12.createElement(SparkleIcon, null), /* @__PURE__ */ React12.createElement("span", null, "Agent now has new context")), activeConversationsList.map((activeConv) => /* @__PURE__ */ React12.createElement(
5591
5818
  ChatPanelWrapper,
5592
5819
  {
5593
- key: `${activeConv.conversationId}-${activeConv.agentId}`,
5820
+ key: `${activeConv.stableKey}-${activeConv.agentId}`,
5594
5821
  activeConv,
5595
5822
  currentConversationId,
5596
5823
  getAgent,
@@ -5614,7 +5841,8 @@ var AIAgentPanel = ({
5614
5841
  contextSections: mergedContext.sections,
5615
5842
  totalContextTokens: mergedContext.totalTokens || 0,
5616
5843
  maxContextTokens,
5617
- enableContextDetailView
5844
+ enableContextDetailView,
5845
+ onConversationCreated: handleConversationCreated
5618
5846
  }
5619
5847
  )), loadingConversationId && /* @__PURE__ */ React12.createElement("div", { className: "ai-agent-panel__conversation-loading-overlay" }, /* @__PURE__ */ React12.createElement("div", { className: "ai-agent-panel__loading-spinner" }), /* @__PURE__ */ React12.createElement("p", null, "Loading conversation...")), currentAgentMetadata && activeConversationsList.length === 0 && !loadingConversationId && /* @__PURE__ */ React12.createElement("div", { className: "ai-agent-panel__empty-chat" }, /* @__PURE__ */ React12.createElement(MessageIcon, null), /* @__PURE__ */ React12.createElement("p", null, "Select a conversation or start a new one"), /* @__PURE__ */ React12.createElement(Button, { variant: "default", size: "sm", onClick: handleNewConversation }, "New Conversation")), agentsLoading && !currentAgentMetadata && /* @__PURE__ */ React12.createElement("div", { className: "ai-agent-panel__loading" }, /* @__PURE__ */ React12.createElement("div", { className: "ai-agent-panel__loading-spinner" }), /* @__PURE__ */ React12.createElement("p", null, "Loading agent..."))),
5620
5848
  /* @__PURE__ */ React12.createElement(
@@ -5623,7 +5851,7 @@ var AIAgentPanel = ({
5623
5851
  isOpen: showHandoffDialog,
5624
5852
  onClose: handleHandoffCancel,
5625
5853
  title: "Switch Agent?",
5626
- description: `The current agent suggests transferring this conversation to ${suggestedAgent ? ((_b = (_a = getAgent(suggestedAgent)) == null ? void 0 : _a.metadata) == null ? void 0 : _b.displayTitle) || suggestedAgent : "another agent"}.`
5854
+ description: handoffSource === "page" ? `This page has a recommended agent: ${suggestedAgent ? ((_b = (_a = getAgent(suggestedAgent)) == null ? void 0 : _a.metadata) == null ? void 0 : _b.displayTitle) || suggestedAgent : "another agent"}. Would you like to switch?` : `The current agent suggests transferring this conversation to ${suggestedAgent ? ((_d = (_c = getAgent(suggestedAgent)) == null ? void 0 : _c.metadata) == null ? void 0 : _d.displayTitle) || suggestedAgent : "another agent"}.`
5627
5855
  },
5628
5856
  /* @__PURE__ */ React12.createElement(DialogFooter, null, /* @__PURE__ */ React12.createElement(Button, { variant: "outline", onClick: handleHandoffCancel }, "Stay with current agent"), /* @__PURE__ */ React12.createElement(Button, { onClick: handleHandoffConfirm }, "Switch agent"))
5629
5857
  )