@hef2024/llmasaservice-ui 0.16.8 → 0.16.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 || "");
@@ -4148,15 +4242,17 @@ ${followOnPrompt}`;
4148
4242
  const panelClasses = ["ai-chat-panel", theme === "dark" ? "dark-theme" : ""].filter(Boolean).join(" ");
4149
4243
  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
4244
  const isLastEntry = index === Object.keys(history).length - 1;
4245
+ const isSystemMessage = prompt.startsWith("__system__:");
4151
4246
  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(
4247
+ const processedContent = processActions(cleanedText);
4248
+ 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
4249
  ReactMarkdown2,
4154
4250
  {
4155
4251
  remarkPlugins: [remarkGfm2],
4156
4252
  rehypePlugins: [rehypeRaw2],
4157
4253
  components: markdownComponents
4158
4254
  },
4159
- cleanedText
4255
+ processedContent
4160
4256
  ) : /* @__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
4257
  ReactMarkdown2,
4162
4258
  {
@@ -4164,7 +4260,7 @@ ${followOnPrompt}`;
4164
4260
  rehypePlugins: [rehypeRaw2],
4165
4261
  components: markdownComponents
4166
4262
  },
4167
- cleanedText
4263
+ processedContent
4168
4264
  ))), 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
4265
  Button,
4170
4266
  {
@@ -4239,8 +4335,7 @@ var AIChatPanel_default = React11.memo(AIChatPanel);
4239
4335
  // src/hooks/useAgentRegistry.ts
4240
4336
  import { useState as useState7, useEffect as useEffect8, useCallback as useCallback3, useMemo as useMemo3 } from "react";
4241
4337
  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}`;
4338
+ return `https://api.llmasaservice.io/agents/${agentId}`;
4244
4339
  };
4245
4340
  function useAgentRegistry(agentIds, options = {}) {
4246
4341
  const { url = "https://chat.llmasaservice.io", autoFetch = true, localOverrides = {} } = options;
@@ -4445,6 +4540,7 @@ var MessageIcon = () => /* @__PURE__ */ React12.createElement("svg", { width: "1
4445
4540
  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
4541
  var LoadingDotIcon = () => /* @__PURE__ */ React12.createElement("span", { className: "ai-agent-panel__loading-dot" });
4447
4542
  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" }));
4543
+ 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
4544
  var normalizeConversationListPayload = (payload) => {
4449
4545
  if (!payload) return [];
4450
4546
  const conversations = Array.isArray(payload) ? payload : payload.conversations || [];
@@ -4562,7 +4658,8 @@ var ChatPanelWrapper = ({
4562
4658
  contextSections,
4563
4659
  totalContextTokens,
4564
4660
  maxContextTokens,
4565
- enableContextDetailView
4661
+ enableContextDetailView,
4662
+ onConversationCreated
4566
4663
  }) => {
4567
4664
  var _a, _b;
4568
4665
  const convAgentProfile = getAgent(activeConv.agentId);
@@ -4580,6 +4677,12 @@ var ChatPanelWrapper = ({
4580
4677
  },
4581
4678
  [handleLoadingChange, activeConv.conversationId]
4582
4679
  );
4680
+ const conversationCreatedCallback = useCallback4(
4681
+ (realConversationId) => {
4682
+ onConversationCreated(activeConv.conversationId, realConversationId);
4683
+ },
4684
+ [onConversationCreated, activeConv.conversationId]
4685
+ );
4583
4686
  const agentStatus = convAgentProfile == null ? void 0 : convAgentProfile.status;
4584
4687
  const promptsString = (convAgentMetadata == null ? void 0 : convAgentMetadata.displayFollowOnPrompts) || "";
4585
4688
  let effectiveFollowOnQuestions;
@@ -4638,7 +4741,8 @@ var ChatPanelWrapper = ({
4638
4741
  contextSections,
4639
4742
  totalContextTokens,
4640
4743
  maxContextTokens,
4641
- enableContextDetailView
4744
+ enableContextDetailView,
4745
+ onConversationCreated: conversationCreatedCallback
4642
4746
  }
4643
4747
  )
4644
4748
  );
@@ -4678,9 +4782,10 @@ var AIAgentPanel = ({
4678
4782
  actions = [],
4679
4783
  followOnQuestions = [],
4680
4784
  followOnPrompt = "",
4681
- historyListLimit = 50
4785
+ historyListLimit = 50,
4786
+ showConversationHistory = true
4682
4787
  }) => {
4683
- var _a, _b;
4788
+ var _a, _b, _c, _d;
4684
4789
  const [isCollapsed, setIsCollapsed] = useState8(defaultCollapsed);
4685
4790
  const [isHistoryCollapsed, setIsHistoryCollapsed] = useState8(() => {
4686
4791
  if (typeof window !== "undefined") {
@@ -4705,6 +4810,7 @@ var AIAgentPanel = ({
4705
4810
  const [showSearch, setShowSearch] = useState8(false);
4706
4811
  const [showHandoffDialog, setShowHandoffDialog] = useState8(false);
4707
4812
  const [suggestedAgent, setSuggestedAgent] = useState8(null);
4813
+ const [handoffSource, setHandoffSource] = useState8("agent");
4708
4814
  const panelRef = useRef6(null);
4709
4815
  const resizeRef = useRef6(null);
4710
4816
  const { agentIds, localOverrides } = useMemo4(() => {
@@ -4760,6 +4866,10 @@ var AIAgentPanel = ({
4760
4866
  activeConversationsRef.current = activeConversations;
4761
4867
  const currentConversationIdRef = useRef6(currentConversationId);
4762
4868
  currentConversationIdRef.current = currentConversationId;
4869
+ const [showContextNotification, setShowContextNotification] = useState8(false);
4870
+ const prevContextRef = useRef6(null);
4871
+ const contextNotificationTimeoutRef = useRef6(null);
4872
+ const prevDefaultAgentRef = useRef6(null);
4763
4873
  const fetchFirstPrompt = useCallback4((conversationId, agentIdForConversation) => __async(void 0, null, function* () {
4764
4874
  var _a2, _b2;
4765
4875
  if (checkedPromptsRef.current.has(conversationId)) {
@@ -4860,6 +4970,9 @@ var AIAgentPanel = ({
4860
4970
  fetchInProgressRef.current = true;
4861
4971
  setConversationsLoading(true);
4862
4972
  setConversationsError(null);
4973
+ console.log("projectId", projectId);
4974
+ console.log("customerId", customerId);
4975
+ console.log("apiKey", apiKey);
4863
4976
  try {
4864
4977
  console.log("fetchConversations - customerId:", customerId);
4865
4978
  const url2 = `https://api.llmasaservice.io/conversations?customer_id=${customerId}`;
@@ -4979,6 +5092,8 @@ var AIAgentPanel = ({
4979
5092
  const next = new Map(prev);
4980
5093
  next.set(conversationId, {
4981
5094
  conversationId,
5095
+ stableKey: conversationId,
5096
+ // Use real ID as stable key when loading from API
4982
5097
  agentId: agentIdToUse,
4983
5098
  history,
4984
5099
  isLoading: false,
@@ -5002,6 +5117,7 @@ var AIAgentPanel = ({
5002
5117
  }, [currentAgentId, fetchConversations]);
5003
5118
  useEffect9(() => {
5004
5119
  var _a2;
5120
+ if (!showConversationHistory) return;
5005
5121
  if (!agentsLoading && currentAgentId && apiKey) {
5006
5122
  const agentProfile = getAgent(currentAgentId);
5007
5123
  const projectId = (_a2 = agentProfile == null ? void 0 : agentProfile.metadata) == null ? void 0 : _a2.projectId;
@@ -5010,13 +5126,15 @@ var AIAgentPanel = ({
5010
5126
  fetchConversations(currentAgentId);
5011
5127
  }
5012
5128
  }
5013
- }, [agentsLoading, currentAgentId, apiKey, fetchConversations, getAgent]);
5129
+ }, [agentsLoading, currentAgentId, apiKey, fetchConversations, getAgent, showConversationHistory]);
5014
5130
  const handleNewConversation = useCallback4(() => {
5015
5131
  const tempId = `new-${Date.now()}`;
5016
5132
  setActiveConversations((prev) => {
5017
5133
  const next = new Map(prev);
5018
5134
  next.set(tempId, {
5019
5135
  conversationId: tempId,
5136
+ stableKey: tempId,
5137
+ // Stable key never changes even when conversationId updates
5020
5138
  agentId: currentAgentId,
5021
5139
  history: {},
5022
5140
  isLoading: false,
@@ -5166,6 +5284,80 @@ var AIAgentPanel = ({
5166
5284
  totalTokens
5167
5285
  };
5168
5286
  }, [context, sharedContextSections, pageContextSections, contextDataSources]);
5287
+ useEffect9(() => {
5288
+ const contextString = JSON.stringify(mergedContext.sections.map((s) => ({ id: s.id, data: s.data })));
5289
+ if (prevContextRef.current === null) {
5290
+ prevContextRef.current = contextString;
5291
+ return;
5292
+ }
5293
+ if (prevContextRef.current !== contextString) {
5294
+ console.log("AIAgentPanel - Context changed, showing notification");
5295
+ prevContextRef.current = contextString;
5296
+ if (contextNotificationTimeoutRef.current) {
5297
+ clearTimeout(contextNotificationTimeoutRef.current);
5298
+ contextNotificationTimeoutRef.current = null;
5299
+ }
5300
+ setShowContextNotification(true);
5301
+ contextNotificationTimeoutRef.current = setTimeout(() => {
5302
+ setShowContextNotification(false);
5303
+ contextNotificationTimeoutRef.current = null;
5304
+ }, 3e3);
5305
+ }
5306
+ }, [mergedContext.sections]);
5307
+ useEffect9(() => {
5308
+ return () => {
5309
+ if (contextNotificationTimeoutRef.current) {
5310
+ clearTimeout(contextNotificationTimeoutRef.current);
5311
+ }
5312
+ };
5313
+ }, []);
5314
+ useEffect9(() => {
5315
+ var _a2, _b2;
5316
+ let foundDefaultAgent = null;
5317
+ for (const section of pageContextSections) {
5318
+ if (section.data && typeof section.data === "object" && "defaultAgent" in section.data) {
5319
+ const defaultAgentValue = section.data.defaultAgent;
5320
+ if (typeof defaultAgentValue === "string" && defaultAgentValue) {
5321
+ foundDefaultAgent = defaultAgentValue;
5322
+ break;
5323
+ }
5324
+ }
5325
+ }
5326
+ if (!foundDefaultAgent || foundDefaultAgent === prevDefaultAgentRef.current) {
5327
+ return;
5328
+ }
5329
+ if (foundDefaultAgent === currentAgentId) {
5330
+ prevDefaultAgentRef.current = foundDefaultAgent;
5331
+ return;
5332
+ }
5333
+ const isAvailable = agentIds.includes(foundDefaultAgent);
5334
+ const agentProfile = getAgent(foundDefaultAgent);
5335
+ const isReady = (agentProfile == null ? void 0 : agentProfile.status) === "ready";
5336
+ if (isAvailable && isReady && currentConversationIdRef.current) {
5337
+ const agentName = ((_a2 = agentProfile == null ? void 0 : agentProfile.metadata) == null ? void 0 : _a2.displayTitle) || ((_b2 = localOverrides[foundDefaultAgent]) == null ? void 0 : _b2.localName) || foundDefaultAgent;
5338
+ const suggestionMessage = `This page recommends a different agent for better assistance.
5339
+
5340
+ [SUGGEST_AGENT:${foundDefaultAgent}|${agentName}|Recommended for this page]`;
5341
+ const syntheticKey = `__system__:page_suggestion_${foundDefaultAgent}_${Date.now()}`;
5342
+ prevDefaultAgentRef.current = foundDefaultAgent;
5343
+ setActiveConversations((prev) => {
5344
+ const conversationId = currentConversationIdRef.current;
5345
+ if (!conversationId) return prev;
5346
+ const existing = prev.get(conversationId);
5347
+ if (!existing) return prev;
5348
+ const next = new Map(prev);
5349
+ next.set(conversationId, __spreadProps(__spreadValues({}, existing), {
5350
+ history: __spreadProps(__spreadValues({}, existing.history), {
5351
+ [syntheticKey]: {
5352
+ content: suggestionMessage,
5353
+ callId: `page-suggestion-${Date.now()}`
5354
+ }
5355
+ })
5356
+ }));
5357
+ return next;
5358
+ });
5359
+ }
5360
+ }, [pageContextSections, currentAgentId, agentIds, getAgent, localOverrides]);
5169
5361
  const chatPanelData = useMemo4(() => {
5170
5362
  const contextData = mergedContext.sections.map((section) => ({
5171
5363
  key: section.id,
@@ -5268,6 +5460,7 @@ var AIAgentPanel = ({
5268
5460
  const suggestedId = handoffMatch[1];
5269
5461
  if (suggestedId && suggestedId !== currentAgentId && agents.includes(suggestedId)) {
5270
5462
  setSuggestedAgent(suggestedId);
5463
+ setHandoffSource("agent");
5271
5464
  setShowHandoffDialog(true);
5272
5465
  }
5273
5466
  }
@@ -5304,11 +5497,34 @@ var AIAgentPanel = ({
5304
5497
  }
5305
5498
  setShowHandoffDialog(false);
5306
5499
  setSuggestedAgent(null);
5500
+ setHandoffSource("agent");
5307
5501
  }, [suggestedAgent, handleAgentSwitch]);
5308
5502
  const handleHandoffCancel = useCallback4(() => {
5309
5503
  setShowHandoffDialog(false);
5310
5504
  setSuggestedAgent(null);
5505
+ setHandoffSource("agent");
5311
5506
  }, []);
5507
+ const handleConversationCreated = useCallback4((tempId, realId) => {
5508
+ console.log("Conversation created:", tempId, "->", realId);
5509
+ setActiveConversations((prev) => {
5510
+ const existing = prev.get(tempId);
5511
+ if (existing) {
5512
+ const next = new Map(prev);
5513
+ next.delete(tempId);
5514
+ next.set(realId, __spreadProps(__spreadValues({}, existing), {
5515
+ conversationId: realId
5516
+ }));
5517
+ return next;
5518
+ }
5519
+ return prev;
5520
+ });
5521
+ if (currentConversationIdRef.current === tempId) {
5522
+ setCurrentConversationId(realId);
5523
+ if (onConversationChange) {
5524
+ onConversationChange(realId);
5525
+ }
5526
+ }
5527
+ }, [onConversationChange]);
5312
5528
  const toggleCollapse = useCallback4(() => {
5313
5529
  setIsCollapsed((prev) => !prev);
5314
5530
  }, []);
@@ -5324,7 +5540,8 @@ var AIAgentPanel = ({
5324
5540
  theme === "dark" ? "dark-theme" : "",
5325
5541
  isCollapsed ? "ai-agent-panel--collapsed" : "",
5326
5542
  position === "left" ? "ai-agent-panel--left" : "ai-agent-panel--right",
5327
- sidebarPosition === "right" ? "ai-agent-panel--sidebar-right" : "ai-agent-panel--sidebar-left"
5543
+ sidebarPosition === "right" ? "ai-agent-panel--sidebar-right" : "ai-agent-panel--sidebar-left",
5544
+ !showConversationHistory ? "ai-agent-panel--no-history" : ""
5328
5545
  ].filter(Boolean).join(" ");
5329
5546
  if (isCollapsed) {
5330
5547
  return /* @__PURE__ */ React12.createElement("div", { className: panelClasses, ref: panelRef }, /* @__PURE__ */ React12.createElement(
@@ -5340,7 +5557,7 @@ var AIAgentPanel = ({
5340
5557
  },
5341
5558
  /* @__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
5559
  /* @__PURE__ */ React12.createElement("div", { className: "ai-agent-panel__collapsed-divider" }),
5343
- /* @__PURE__ */ React12.createElement(Tooltip, { content: "Search", side: "left" }, /* @__PURE__ */ React12.createElement(
5560
+ showConversationHistory && /* @__PURE__ */ React12.createElement(Tooltip, { content: "Search", side: "left" }, /* @__PURE__ */ React12.createElement(
5344
5561
  Button,
5345
5562
  {
5346
5563
  variant: "ghost",
@@ -5389,6 +5606,8 @@ var AIAgentPanel = ({
5389
5606
  const next = new Map(prev);
5390
5607
  next.set(tempId, {
5391
5608
  conversationId: tempId,
5609
+ stableKey: tempId,
5610
+ // Stable key never changes
5392
5611
  agentId: agent.id,
5393
5612
  history: {},
5394
5613
  isLoading: false,
@@ -5435,7 +5654,7 @@ var AIAgentPanel = ({
5435
5654
  tabIndex: 0
5436
5655
  }
5437
5656
  ),
5438
- /* @__PURE__ */ React12.createElement("div", { className: `ai-agent-panel__sidebar ${isHistoryCollapsed ? "ai-agent-panel__sidebar--collapsed" : ""}` }, isHistoryCollapsed ? (
5657
+ showConversationHistory && /* @__PURE__ */ React12.createElement("div", { className: `ai-agent-panel__sidebar ${isHistoryCollapsed ? "ai-agent-panel__sidebar--collapsed" : ""}` }, isHistoryCollapsed ? (
5439
5658
  // Collapsed history bar
5440
5659
  /* @__PURE__ */ React12.createElement(
5441
5660
  "div",
@@ -5491,6 +5710,8 @@ var AIAgentPanel = ({
5491
5710
  const next = new Map(prev);
5492
5711
  next.set(tempId, {
5493
5712
  conversationId: tempId,
5713
+ stableKey: tempId,
5714
+ // Stable key never changes
5494
5715
  agentId: agent.id,
5495
5716
  history: {},
5496
5717
  isLoading: false,
@@ -5548,7 +5769,7 @@ var AIAgentPanel = ({
5548
5769
  ))), /* @__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
5770
  "div",
5550
5771
  {
5551
- key: activeConv.conversationId,
5772
+ key: activeConv.stableKey,
5552
5773
  className: `ai-agent-panel__conversation ai-agent-panel__conversation--active-item ${currentConversationId === activeConv.conversationId ? "ai-agent-panel__conversation--current" : ""}`,
5553
5774
  onClick: () => {
5554
5775
  setCurrentConversationId(activeConv.conversationId);
@@ -5587,10 +5808,10 @@ var AIAgentPanel = ({
5587
5808
  /* @__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
5809
  );
5589
5810
  }))))))),
5590
- /* @__PURE__ */ React12.createElement("div", { className: "ai-agent-panel__chat" }, activeConversationsList.map((activeConv) => /* @__PURE__ */ React12.createElement(
5811
+ /* @__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
5812
  ChatPanelWrapper,
5592
5813
  {
5593
- key: `${activeConv.conversationId}-${activeConv.agentId}`,
5814
+ key: `${activeConv.stableKey}-${activeConv.agentId}`,
5594
5815
  activeConv,
5595
5816
  currentConversationId,
5596
5817
  getAgent,
@@ -5614,7 +5835,8 @@ var AIAgentPanel = ({
5614
5835
  contextSections: mergedContext.sections,
5615
5836
  totalContextTokens: mergedContext.totalTokens || 0,
5616
5837
  maxContextTokens,
5617
- enableContextDetailView
5838
+ enableContextDetailView,
5839
+ onConversationCreated: handleConversationCreated
5618
5840
  }
5619
5841
  )), 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
5842
  /* @__PURE__ */ React12.createElement(
@@ -5623,7 +5845,7 @@ var AIAgentPanel = ({
5623
5845
  isOpen: showHandoffDialog,
5624
5846
  onClose: handleHandoffCancel,
5625
5847
  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"}.`
5848
+ 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
5849
  },
5628
5850
  /* @__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
5851
  )