@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.js CHANGED
@@ -521,10 +521,7 @@ var ChatPanel = ({
521
521
  { key: "--userLanguage", data: browserInfo == null ? void 0 : browserInfo.userLanguage }
522
522
  ];
523
523
  };
524
- let publicAPIUrl = "https://api.llmasaservice.io";
525
- if (window.location.hostname === "localhost" || window.location.hostname === "dev.llmasaservice.io") {
526
- publicAPIUrl = "https://8ftw8droff.execute-api.us-east-1.amazonaws.com/dev";
527
- }
524
+ const publicAPIUrl = "https://api.llmasaservice.io";
528
525
  const [toolList, setToolList] = (0, import_react3.useState)([]);
529
526
  const [toolsLoading, setToolsLoading] = (0, import_react3.useState)(false);
530
527
  const [toolsFetchError, setToolsFetchError] = (0, import_react3.useState)(false);
@@ -2894,7 +2891,7 @@ var AgentPanel = ({
2894
2891
  (0, import_react4.useEffect)(() => {
2895
2892
  const fetchAgentData = () => __async(void 0, null, function* () {
2896
2893
  try {
2897
- const fetchUrl = url.endsWith("dev") ? `https://8ftw8droff.execute-api.us-east-1.amazonaws.com/dev/agents/${agent}` : `https://api.llmasaservice.io/agents/${agent}`;
2894
+ const fetchUrl = `https://api.llmasaservice.io/agents/${agent}`;
2898
2895
  const response = yield fetch(fetchUrl, {
2899
2896
  method: "GET",
2900
2897
  headers: {
@@ -3646,8 +3643,10 @@ var AIChatPanel = ({
3646
3643
  contextSections = [],
3647
3644
  totalContextTokens = 0,
3648
3645
  maxContextTokens = 8e3,
3649
- enableContextDetailView = false
3646
+ enableContextDetailView = false,
3647
+ onConversationCreated
3650
3648
  }) => {
3649
+ const publicAPIUrl = "https://api.llmasaservice.io";
3651
3650
  const [lastController, setLastController] = (0, import_react11.useState)(new AbortController());
3652
3651
  const [lastMessages, setLastMessages] = (0, import_react11.useState)([]);
3653
3652
  const [history, setHistory] = (0, import_react11.useState)(initialHistory);
@@ -3670,6 +3669,24 @@ var AIChatPanel = ({
3670
3669
  const prevIdleRef = (0, import_react11.useRef)(true);
3671
3670
  const hasNotifiedCompletionRef = (0, import_react11.useRef)(true);
3672
3671
  const latestHistoryRef = (0, import_react11.useRef)(initialHistory);
3672
+ (0, import_react11.useEffect)(() => {
3673
+ if (!initialHistory) return;
3674
+ setHistory((prev) => {
3675
+ const currentKeys = Object.keys(prev);
3676
+ const newEntries = {};
3677
+ let hasNewEntries = false;
3678
+ for (const [key, value] of Object.entries(initialHistory)) {
3679
+ if (!currentKeys.includes(key)) {
3680
+ newEntries[key] = value;
3681
+ hasNewEntries = true;
3682
+ }
3683
+ }
3684
+ if (hasNewEntries) {
3685
+ return __spreadValues(__spreadValues({}, prev), newEntries);
3686
+ }
3687
+ return prev;
3688
+ });
3689
+ }, [initialHistory]);
3673
3690
  const llmResult = (0, import_llmasaservice_client2.useLLM)(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
3674
3691
  project_id,
3675
3692
  customer
@@ -3709,6 +3726,60 @@ var AIChatPanel = ({
3709
3726
  userLanguage: navigator.language
3710
3727
  };
3711
3728
  }, []);
3729
+ const ensureConversation = (0, import_react11.useCallback)(() => {
3730
+ var _a, _b;
3731
+ console.log("ensureConversation - called with:", {
3732
+ currentConversation,
3733
+ createConversationOnFirstChat,
3734
+ project_id,
3735
+ publicAPIUrl
3736
+ });
3737
+ if ((!currentConversation || currentConversation === "") && createConversationOnFirstChat) {
3738
+ if (!project_id) {
3739
+ console.error("ensureConversation - Cannot create conversation without project_id");
3740
+ return Promise.resolve("");
3741
+ }
3742
+ const requestBody = {
3743
+ project_id,
3744
+ agentId: agent,
3745
+ customerId: (_a = customer == null ? void 0 : customer.customer_id) != null ? _a : null,
3746
+ customerEmail: (_b = customer == null ? void 0 : customer.customer_user_email) != null ? _b : null,
3747
+ timezone: browserInfo == null ? void 0 : browserInfo.userTimezone,
3748
+ language: browserInfo == null ? void 0 : browserInfo.userLanguage
3749
+ };
3750
+ console.log("ensureConversation - Creating conversation with:", requestBody);
3751
+ console.log("ensureConversation - API URL:", `${publicAPIUrl}/conversations`);
3752
+ return fetch(`${publicAPIUrl}/conversations`, {
3753
+ method: "POST",
3754
+ headers: {
3755
+ "Content-Type": "application/json"
3756
+ },
3757
+ body: JSON.stringify(requestBody)
3758
+ }).then((res) => __async(void 0, null, function* () {
3759
+ if (!res.ok) {
3760
+ const errorText = yield res.text();
3761
+ throw new Error(
3762
+ `HTTP error! status: ${res.status}, message: ${errorText}`
3763
+ );
3764
+ }
3765
+ return res.json();
3766
+ })).then((newConvo) => {
3767
+ console.log("ensureConversation - API response:", newConvo);
3768
+ if (newConvo == null ? void 0 : newConvo.id) {
3769
+ console.log("ensureConversation - New conversation ID:", newConvo.id);
3770
+ setCurrentConversation(newConvo.id);
3771
+ return newConvo.id;
3772
+ }
3773
+ console.warn("ensureConversation - No ID in response");
3774
+ return "";
3775
+ }).catch((error) => {
3776
+ console.error("Error creating new conversation", error);
3777
+ return "";
3778
+ });
3779
+ }
3780
+ console.log("ensureConversation - using existing conversation:", currentConversation);
3781
+ return Promise.resolve(currentConversation);
3782
+ }, [currentConversation, createConversationOnFirstChat, publicAPIUrl, project_id, agent, customer, browserInfo]);
3712
3783
  const dataWithExtras = (0, import_react11.useCallback)(() => {
3713
3784
  var _a, _b, _c, _d, _e, _f, _g, _h;
3714
3785
  return [
@@ -3822,6 +3893,7 @@ var AIChatPanel = ({
3822
3893
  lastScrollTimeRef.current = now;
3823
3894
  }, []);
3824
3895
  const continueChat = (0, import_react11.useCallback)((promptText) => {
3896
+ console.log("AIChatPanel.continueChat called with:", promptText);
3825
3897
  setThinkingBlocks([]);
3826
3898
  setCurrentThinkingIndex(0);
3827
3899
  setUserHasScrolled(false);
@@ -3841,58 +3913,68 @@ var AIChatPanel = ({
3841
3913
  const promptToSend = promptText;
3842
3914
  if (!promptToSend || !promptToSend.trim()) return;
3843
3915
  setIsLoading(true);
3844
- const messagesAndHistory = [];
3845
- Object.entries(history).forEach(([historyPrompt, historyEntry]) => {
3846
- let promptForHistory = historyPrompt;
3847
- const isoTimestampRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z:/;
3848
- if (isoTimestampRegex.test(historyPrompt)) {
3849
- const colonIndex = historyPrompt.indexOf(":", 19);
3850
- promptForHistory = historyPrompt.substring(colonIndex + 1);
3851
- } else if (/^\d+:/.test(historyPrompt)) {
3852
- const colonIndex = historyPrompt.indexOf(":");
3853
- promptForHistory = historyPrompt.substring(colonIndex + 1);
3916
+ console.log("AIChatPanel.continueChat - about to call ensureConversation");
3917
+ ensureConversation().then((convId) => {
3918
+ console.log("AIChatPanel.continueChat - ensureConversation resolved with:", convId);
3919
+ const messagesAndHistory = [];
3920
+ Object.entries(history).forEach(([historyPrompt, historyEntry]) => {
3921
+ let promptForHistory = historyPrompt;
3922
+ const isoTimestampRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z:/;
3923
+ if (isoTimestampRegex.test(historyPrompt)) {
3924
+ const colonIndex = historyPrompt.indexOf(":", 19);
3925
+ promptForHistory = historyPrompt.substring(colonIndex + 1);
3926
+ } else if (/^\d+:/.test(historyPrompt)) {
3927
+ const colonIndex = historyPrompt.indexOf(":");
3928
+ promptForHistory = historyPrompt.substring(colonIndex + 1);
3929
+ }
3930
+ messagesAndHistory.push({ role: "user", content: promptForHistory });
3931
+ messagesAndHistory.push({ role: "assistant", content: historyEntry.content });
3932
+ });
3933
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
3934
+ const promptKey = `${timestamp}:${promptToSend.trim()}`;
3935
+ setHistory((prevHistory) => __spreadProps(__spreadValues({}, prevHistory), {
3936
+ [promptKey]: { content: "", callId: "" }
3937
+ }));
3938
+ let fullPromptToSend = promptToSend.trim();
3939
+ if (Object.keys(history).length === 0 && promptTemplate) {
3940
+ fullPromptToSend = promptTemplate.replace("{{prompt}}", fullPromptToSend);
3854
3941
  }
3855
- messagesAndHistory.push({ role: "user", content: promptForHistory });
3856
- messagesAndHistory.push({ role: "assistant", content: historyEntry.content });
3857
- });
3858
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
3859
- const promptKey = `${timestamp}:${promptToSend.trim()}`;
3860
- setHistory((prevHistory) => __spreadProps(__spreadValues({}, prevHistory), {
3861
- [promptKey]: { content: "", callId: "" }
3862
- }));
3863
- let fullPromptToSend = promptToSend.trim();
3864
- if (Object.keys(history).length === 0 && promptTemplate) {
3865
- fullPromptToSend = promptTemplate.replace("{{prompt}}", fullPromptToSend);
3866
- }
3867
- if (followOnPrompt) {
3868
- fullPromptToSend += `
3942
+ if (followOnPrompt) {
3943
+ fullPromptToSend += `
3869
3944
 
3870
3945
  ${followOnPrompt}`;
3871
- }
3872
- const newController = new AbortController();
3873
- setLastController(newController);
3874
- send(
3875
- fullPromptToSend,
3876
- messagesAndHistory,
3877
- [
3878
- ...dataWithExtras(),
3879
- { key: "--messages", data: messagesAndHistory.length.toString() }
3880
- ],
3881
- true,
3882
- // stream
3883
- true,
3884
- // includeHistory
3885
- service,
3886
- // group_id from agent config
3887
- currentConversation,
3888
- newController
3889
- );
3890
- setLastPrompt(promptToSend.trim());
3891
- setLastMessages(messagesAndHistory);
3892
- setLastKey(promptKey);
3893
- setTimeout(() => {
3894
- scrollToBottom();
3895
- }, 0);
3946
+ }
3947
+ const newController = new AbortController();
3948
+ setLastController(newController);
3949
+ send(
3950
+ fullPromptToSend,
3951
+ messagesAndHistory,
3952
+ [
3953
+ ...dataWithExtras(),
3954
+ { key: "--messages", data: messagesAndHistory.length.toString() }
3955
+ ],
3956
+ true,
3957
+ // stream
3958
+ true,
3959
+ // includeHistory
3960
+ service,
3961
+ // group_id from agent config
3962
+ convId,
3963
+ // Use the conversation ID from ensureConversation
3964
+ newController
3965
+ );
3966
+ setLastPrompt(promptToSend.trim());
3967
+ setLastMessages(messagesAndHistory);
3968
+ setLastKey(promptKey);
3969
+ if (convId && onConversationCreated) {
3970
+ setTimeout(() => {
3971
+ onConversationCreated(convId);
3972
+ }, 100);
3973
+ }
3974
+ setTimeout(() => {
3975
+ scrollToBottom();
3976
+ }, 0);
3977
+ });
3896
3978
  }, [
3897
3979
  idle,
3898
3980
  stop,
@@ -3907,9 +3989,10 @@ ${followOnPrompt}`;
3907
3989
  followOnPrompt,
3908
3990
  send,
3909
3991
  service,
3910
- currentConversation,
3992
+ ensureConversation,
3911
3993
  dataWithExtras,
3912
- scrollToBottom
3994
+ scrollToBottom,
3995
+ onConversationCreated
3913
3996
  ]);
3914
3997
  const handleSuggestionClick = (0, import_react11.useCallback)((question) => {
3915
3998
  continueChat(question);
@@ -3951,18 +4034,18 @@ ${followOnPrompt}`;
3951
4034
  (0, import_react11.useEffect)(() => {
3952
4035
  if (!response || !lastKey || justReset) return;
3953
4036
  const { cleanedText, blocks } = processThinkingTags(response);
3954
- const processedContent = processActions(cleanedText);
3955
4037
  setThinkingBlocks(blocks);
3956
4038
  setHistory((prev) => {
3957
4039
  const newHistory = __spreadValues({}, prev);
3958
4040
  newHistory[lastKey] = {
3959
- content: processedContent,
4041
+ content: cleanedText,
4042
+ // Store raw content, not processed
3960
4043
  callId: lastCallId || ""
3961
4044
  };
3962
4045
  latestHistoryRef.current = newHistory;
3963
4046
  return newHistory;
3964
4047
  });
3965
- }, [response, lastKey, lastCallId, processThinkingTags, processActions, justReset]);
4048
+ }, [response, lastKey, lastCallId, processThinkingTags, justReset]);
3966
4049
  (0, import_react11.useEffect)(() => {
3967
4050
  const wasStreaming = !prevIdleRef.current;
3968
4051
  const isNowIdle = idle;
@@ -4046,38 +4129,49 @@ ${followOnPrompt}`;
4046
4129
  }, []);
4047
4130
  (0, import_react11.useEffect)(() => {
4048
4131
  const hasLoadedHistory = initialHistory && Object.keys(initialHistory).length > 0;
4132
+ if (!project_id) {
4133
+ return;
4134
+ }
4049
4135
  if (initialPrompt && initialPrompt !== "" && initialPrompt !== lastPrompt && !hasLoadedHistory) {
4050
4136
  setIsLoading(true);
4051
4137
  setThinkingBlocks([]);
4052
4138
  setCurrentThinkingIndex(0);
4053
4139
  setUserHasScrolled(false);
4054
- const controller = new AbortController();
4055
- setLastController(controller);
4056
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
4057
- const promptKey = `${timestamp}:${initialPrompt}`;
4058
- setHistory({ [promptKey]: { content: "", callId: "" } });
4059
- let fullPrompt = initialPrompt;
4060
- if (promptTemplate) {
4061
- fullPrompt = promptTemplate.replace("{{prompt}}", initialPrompt);
4062
- }
4063
- send(
4064
- fullPrompt,
4065
- [],
4066
- [
4067
- ...dataWithExtras(),
4068
- { key: "--messages", data: "0" }
4069
- ],
4070
- true,
4071
- true,
4072
- service,
4073
- currentConversation,
4074
- controller
4075
- );
4076
- setLastPrompt(initialPrompt);
4077
- setLastMessages([]);
4078
- setLastKey(promptKey);
4140
+ ensureConversation().then((convId) => {
4141
+ const controller = new AbortController();
4142
+ setLastController(controller);
4143
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
4144
+ const promptKey = `${timestamp}:${initialPrompt}`;
4145
+ setHistory({ [promptKey]: { content: "", callId: "" } });
4146
+ let fullPrompt = initialPrompt;
4147
+ if (promptTemplate) {
4148
+ fullPrompt = promptTemplate.replace("{{prompt}}", initialPrompt);
4149
+ }
4150
+ send(
4151
+ fullPrompt,
4152
+ [],
4153
+ [
4154
+ ...dataWithExtras(),
4155
+ { key: "--messages", data: "0" }
4156
+ ],
4157
+ true,
4158
+ true,
4159
+ service,
4160
+ convId,
4161
+ // Use conversation ID from ensureConversation
4162
+ controller
4163
+ );
4164
+ setLastPrompt(initialPrompt);
4165
+ setLastMessages([]);
4166
+ setLastKey(promptKey);
4167
+ if (convId && onConversationCreated) {
4168
+ setTimeout(() => {
4169
+ onConversationCreated(convId);
4170
+ }, 100);
4171
+ }
4172
+ });
4079
4173
  }
4080
- }, [initialPrompt, initialHistory]);
4174
+ }, [initialPrompt, initialHistory, ensureConversation, promptTemplate, send, dataWithExtras, service, lastPrompt, project_id, onConversationCreated]);
4081
4175
  const CodeBlock = (0, import_react11.useCallback)((_a) => {
4082
4176
  var _b = _a, { node, inline, className, children } = _b, props = __objRest(_b, ["node", "inline", "className", "children"]);
4083
4177
  const match = /language-(\w+)/.exec(className || "");
@@ -4181,15 +4275,17 @@ ${followOnPrompt}`;
4181
4275
  const panelClasses = ["ai-chat-panel", theme === "dark" ? "dark-theme" : ""].filter(Boolean).join(" ");
4182
4276
  return /* @__PURE__ */ import_react11.default.createElement("div", { className: panelClasses }, title && /* @__PURE__ */ import_react11.default.createElement("div", { className: "ai-chat-panel__title" }, title), /* @__PURE__ */ import_react11.default.createElement(ScrollArea, { className: "ai-chat-panel__messages", ref: responseAreaRef }, initialMessage && /* @__PURE__ */ import_react11.default.createElement("div", { className: "ai-chat-message ai-chat-message--assistant" }, /* @__PURE__ */ import_react11.default.createElement("div", { className: "ai-chat-message__content" }, /* @__PURE__ */ import_react11.default.createElement(import_react_markdown2.default, { remarkPlugins: [import_remark_gfm2.default], rehypePlugins: [import_rehype_raw2.default] }, initialMessage))), Object.entries(history).map(([prompt, entry], index) => {
4183
4277
  const isLastEntry = index === Object.keys(history).length - 1;
4278
+ const isSystemMessage = prompt.startsWith("__system__:");
4184
4279
  const { cleanedText } = processThinkingTags(entry.content);
4185
- return /* @__PURE__ */ import_react11.default.createElement("div", { key: index, className: "ai-chat-entry" }, !(hideInitialPrompt && index === 0) && /* @__PURE__ */ import_react11.default.createElement("div", { className: "ai-chat-message ai-chat-message--user" }, /* @__PURE__ */ import_react11.default.createElement("div", { className: "ai-chat-message__content" }, formatPromptForDisplay(prompt))), /* @__PURE__ */ import_react11.default.createElement("div", { className: "ai-chat-message ai-chat-message--assistant" }, /* @__PURE__ */ import_react11.default.createElement("div", { className: "ai-chat-message__content" }, isLastEntry && (isLoading || !idle) && !justReset ? /* @__PURE__ */ import_react11.default.createElement("div", { className: "ai-chat-streaming" }, thinkingBlocks.length > 0 && renderThinkingBlocks(), cleanedText ? /* @__PURE__ */ import_react11.default.createElement(
4280
+ const processedContent = processActions(cleanedText);
4281
+ return /* @__PURE__ */ import_react11.default.createElement("div", { key: index, className: "ai-chat-entry" }, !(hideInitialPrompt && index === 0) && !isSystemMessage && /* @__PURE__ */ import_react11.default.createElement("div", { className: "ai-chat-message ai-chat-message--user" }, /* @__PURE__ */ import_react11.default.createElement("div", { className: "ai-chat-message__content" }, formatPromptForDisplay(prompt))), /* @__PURE__ */ import_react11.default.createElement("div", { className: "ai-chat-message ai-chat-message--assistant" }, /* @__PURE__ */ import_react11.default.createElement("div", { className: "ai-chat-message__content" }, isLastEntry && (isLoading || !idle) && !justReset ? /* @__PURE__ */ import_react11.default.createElement("div", { className: "ai-chat-streaming" }, thinkingBlocks.length > 0 && renderThinkingBlocks(), processedContent ? /* @__PURE__ */ import_react11.default.createElement(
4186
4282
  import_react_markdown2.default,
4187
4283
  {
4188
4284
  remarkPlugins: [import_remark_gfm2.default],
4189
4285
  rehypePlugins: [import_rehype_raw2.default],
4190
4286
  components: markdownComponents
4191
4287
  },
4192
- cleanedText
4288
+ processedContent
4193
4289
  ) : /* @__PURE__ */ import_react11.default.createElement("div", { className: "ai-chat-loading" }, /* @__PURE__ */ import_react11.default.createElement("span", null, "Thinking"), /* @__PURE__ */ import_react11.default.createElement("span", { className: "ai-chat-loading__dots" }, /* @__PURE__ */ import_react11.default.createElement("span", { className: "ai-chat-loading__dot" }), /* @__PURE__ */ import_react11.default.createElement("span", { className: "ai-chat-loading__dot" }), /* @__PURE__ */ import_react11.default.createElement("span", { className: "ai-chat-loading__dot" })))) : /* @__PURE__ */ import_react11.default.createElement(import_react11.default.Fragment, null, isLastEntry && thinkingBlocks.length > 0 && renderThinkingBlocks(), /* @__PURE__ */ import_react11.default.createElement(
4194
4290
  import_react_markdown2.default,
4195
4291
  {
@@ -4197,7 +4293,7 @@ ${followOnPrompt}`;
4197
4293
  rehypePlugins: [import_rehype_raw2.default],
4198
4294
  components: markdownComponents
4199
4295
  },
4200
- cleanedText
4296
+ processedContent
4201
4297
  ))), idle && !isLoading && /* @__PURE__ */ import_react11.default.createElement("div", { className: "ai-chat-message__actions" }, /* @__PURE__ */ import_react11.default.createElement(Tooltip, { content: copiedCallId === entry.callId ? "Copied!" : "Copy" }, /* @__PURE__ */ import_react11.default.createElement(
4202
4298
  Button,
4203
4299
  {
@@ -4272,8 +4368,7 @@ var AIChatPanel_default = import_react11.default.memo(AIChatPanel);
4272
4368
  // src/hooks/useAgentRegistry.ts
4273
4369
  var import_react12 = require("react");
4274
4370
  var resolveApiEndpoint = (baseUrl, agentId) => {
4275
- const apiRoot = baseUrl.endsWith("dev") ? "https://8ftw8droff.execute-api.us-east-1.amazonaws.com/dev" : "https://api.llmasaservice.io";
4276
- return `${apiRoot}/agents/${agentId}`;
4371
+ return `https://api.llmasaservice.io/agents/${agentId}`;
4277
4372
  };
4278
4373
  function useAgentRegistry(agentIds, options = {}) {
4279
4374
  const { url = "https://chat.llmasaservice.io", autoFetch = true, localOverrides = {} } = options;
@@ -4478,6 +4573,7 @@ var MessageIcon = () => /* @__PURE__ */ import_react13.default.createElement("sv
4478
4573
  var CloseIcon = () => /* @__PURE__ */ import_react13.default.createElement("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, /* @__PURE__ */ import_react13.default.createElement("path", { d: "M9 3L3 9M3 3l6 6", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round" }));
4479
4574
  var LoadingDotIcon = () => /* @__PURE__ */ import_react13.default.createElement("span", { className: "ai-agent-panel__loading-dot" });
4480
4575
  var SidebarIcon = () => /* @__PURE__ */ import_react13.default.createElement("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, /* @__PURE__ */ import_react13.default.createElement("rect", { x: "2", y: "2", width: "12", height: "12", rx: "2", stroke: "currentColor", strokeWidth: "1.5" }), /* @__PURE__ */ import_react13.default.createElement("path", { d: "M6 2v12", stroke: "currentColor", strokeWidth: "1.5" }));
4576
+ var SparkleIcon = () => /* @__PURE__ */ import_react13.default.createElement("svg", { width: "14", height: "14", viewBox: "0 0 16 16", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, /* @__PURE__ */ import_react13.default.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__ */ import_react13.default.createElement("circle", { cx: "8", cy: "8", r: "2", fill: "currentColor" }));
4481
4577
  var normalizeConversationListPayload = (payload) => {
4482
4578
  if (!payload) return [];
4483
4579
  const conversations = Array.isArray(payload) ? payload : payload.conversations || [];
@@ -4595,7 +4691,8 @@ var ChatPanelWrapper = ({
4595
4691
  contextSections,
4596
4692
  totalContextTokens,
4597
4693
  maxContextTokens,
4598
- enableContextDetailView
4694
+ enableContextDetailView,
4695
+ onConversationCreated
4599
4696
  }) => {
4600
4697
  var _a, _b;
4601
4698
  const convAgentProfile = getAgent(activeConv.agentId);
@@ -4613,6 +4710,12 @@ var ChatPanelWrapper = ({
4613
4710
  },
4614
4711
  [handleLoadingChange, activeConv.conversationId]
4615
4712
  );
4713
+ const conversationCreatedCallback = (0, import_react13.useCallback)(
4714
+ (realConversationId) => {
4715
+ onConversationCreated(activeConv.conversationId, realConversationId);
4716
+ },
4717
+ [onConversationCreated, activeConv.conversationId]
4718
+ );
4616
4719
  const agentStatus = convAgentProfile == null ? void 0 : convAgentProfile.status;
4617
4720
  const promptsString = (convAgentMetadata == null ? void 0 : convAgentMetadata.displayFollowOnPrompts) || "";
4618
4721
  let effectiveFollowOnQuestions;
@@ -4671,7 +4774,8 @@ var ChatPanelWrapper = ({
4671
4774
  contextSections,
4672
4775
  totalContextTokens,
4673
4776
  maxContextTokens,
4674
- enableContextDetailView
4777
+ enableContextDetailView,
4778
+ onConversationCreated: conversationCreatedCallback
4675
4779
  }
4676
4780
  )
4677
4781
  );
@@ -4711,9 +4815,10 @@ var AIAgentPanel = ({
4711
4815
  actions = [],
4712
4816
  followOnQuestions = [],
4713
4817
  followOnPrompt = "",
4714
- historyListLimit = 50
4818
+ historyListLimit = 50,
4819
+ showConversationHistory = true
4715
4820
  }) => {
4716
- var _a, _b;
4821
+ var _a, _b, _c, _d;
4717
4822
  const [isCollapsed, setIsCollapsed] = (0, import_react13.useState)(defaultCollapsed);
4718
4823
  const [isHistoryCollapsed, setIsHistoryCollapsed] = (0, import_react13.useState)(() => {
4719
4824
  if (typeof window !== "undefined") {
@@ -4738,6 +4843,7 @@ var AIAgentPanel = ({
4738
4843
  const [showSearch, setShowSearch] = (0, import_react13.useState)(false);
4739
4844
  const [showHandoffDialog, setShowHandoffDialog] = (0, import_react13.useState)(false);
4740
4845
  const [suggestedAgent, setSuggestedAgent] = (0, import_react13.useState)(null);
4846
+ const [handoffSource, setHandoffSource] = (0, import_react13.useState)("agent");
4741
4847
  const panelRef = (0, import_react13.useRef)(null);
4742
4848
  const resizeRef = (0, import_react13.useRef)(null);
4743
4849
  const { agentIds, localOverrides } = (0, import_react13.useMemo)(() => {
@@ -4793,6 +4899,10 @@ var AIAgentPanel = ({
4793
4899
  activeConversationsRef.current = activeConversations;
4794
4900
  const currentConversationIdRef = (0, import_react13.useRef)(currentConversationId);
4795
4901
  currentConversationIdRef.current = currentConversationId;
4902
+ const [showContextNotification, setShowContextNotification] = (0, import_react13.useState)(false);
4903
+ const prevContextRef = (0, import_react13.useRef)(null);
4904
+ const contextNotificationTimeoutRef = (0, import_react13.useRef)(null);
4905
+ const prevDefaultAgentRef = (0, import_react13.useRef)(null);
4796
4906
  const fetchFirstPrompt = (0, import_react13.useCallback)((conversationId, agentIdForConversation) => __async(void 0, null, function* () {
4797
4907
  var _a2, _b2;
4798
4908
  if (checkedPromptsRef.current.has(conversationId)) {
@@ -4893,6 +5003,9 @@ var AIAgentPanel = ({
4893
5003
  fetchInProgressRef.current = true;
4894
5004
  setConversationsLoading(true);
4895
5005
  setConversationsError(null);
5006
+ console.log("projectId", projectId);
5007
+ console.log("customerId", customerId);
5008
+ console.log("apiKey", apiKey);
4896
5009
  try {
4897
5010
  console.log("fetchConversations - customerId:", customerId);
4898
5011
  const url2 = `https://api.llmasaservice.io/conversations?customer_id=${customerId}`;
@@ -5012,6 +5125,8 @@ var AIAgentPanel = ({
5012
5125
  const next = new Map(prev);
5013
5126
  next.set(conversationId, {
5014
5127
  conversationId,
5128
+ stableKey: conversationId,
5129
+ // Use real ID as stable key when loading from API
5015
5130
  agentId: agentIdToUse,
5016
5131
  history,
5017
5132
  isLoading: false,
@@ -5035,6 +5150,7 @@ var AIAgentPanel = ({
5035
5150
  }, [currentAgentId, fetchConversations]);
5036
5151
  (0, import_react13.useEffect)(() => {
5037
5152
  var _a2;
5153
+ if (!showConversationHistory) return;
5038
5154
  if (!agentsLoading && currentAgentId && apiKey) {
5039
5155
  const agentProfile = getAgent(currentAgentId);
5040
5156
  const projectId = (_a2 = agentProfile == null ? void 0 : agentProfile.metadata) == null ? void 0 : _a2.projectId;
@@ -5043,13 +5159,15 @@ var AIAgentPanel = ({
5043
5159
  fetchConversations(currentAgentId);
5044
5160
  }
5045
5161
  }
5046
- }, [agentsLoading, currentAgentId, apiKey, fetchConversations, getAgent]);
5162
+ }, [agentsLoading, currentAgentId, apiKey, fetchConversations, getAgent, showConversationHistory]);
5047
5163
  const handleNewConversation = (0, import_react13.useCallback)(() => {
5048
5164
  const tempId = `new-${Date.now()}`;
5049
5165
  setActiveConversations((prev) => {
5050
5166
  const next = new Map(prev);
5051
5167
  next.set(tempId, {
5052
5168
  conversationId: tempId,
5169
+ stableKey: tempId,
5170
+ // Stable key never changes even when conversationId updates
5053
5171
  agentId: currentAgentId,
5054
5172
  history: {},
5055
5173
  isLoading: false,
@@ -5199,6 +5317,80 @@ var AIAgentPanel = ({
5199
5317
  totalTokens
5200
5318
  };
5201
5319
  }, [context, sharedContextSections, pageContextSections, contextDataSources]);
5320
+ (0, import_react13.useEffect)(() => {
5321
+ const contextString = JSON.stringify(mergedContext.sections.map((s) => ({ id: s.id, data: s.data })));
5322
+ if (prevContextRef.current === null) {
5323
+ prevContextRef.current = contextString;
5324
+ return;
5325
+ }
5326
+ if (prevContextRef.current !== contextString) {
5327
+ console.log("AIAgentPanel - Context changed, showing notification");
5328
+ prevContextRef.current = contextString;
5329
+ if (contextNotificationTimeoutRef.current) {
5330
+ clearTimeout(contextNotificationTimeoutRef.current);
5331
+ contextNotificationTimeoutRef.current = null;
5332
+ }
5333
+ setShowContextNotification(true);
5334
+ contextNotificationTimeoutRef.current = setTimeout(() => {
5335
+ setShowContextNotification(false);
5336
+ contextNotificationTimeoutRef.current = null;
5337
+ }, 3e3);
5338
+ }
5339
+ }, [mergedContext.sections]);
5340
+ (0, import_react13.useEffect)(() => {
5341
+ return () => {
5342
+ if (contextNotificationTimeoutRef.current) {
5343
+ clearTimeout(contextNotificationTimeoutRef.current);
5344
+ }
5345
+ };
5346
+ }, []);
5347
+ (0, import_react13.useEffect)(() => {
5348
+ var _a2, _b2;
5349
+ let foundDefaultAgent = null;
5350
+ for (const section of pageContextSections) {
5351
+ if (section.data && typeof section.data === "object" && "defaultAgent" in section.data) {
5352
+ const defaultAgentValue = section.data.defaultAgent;
5353
+ if (typeof defaultAgentValue === "string" && defaultAgentValue) {
5354
+ foundDefaultAgent = defaultAgentValue;
5355
+ break;
5356
+ }
5357
+ }
5358
+ }
5359
+ if (!foundDefaultAgent || foundDefaultAgent === prevDefaultAgentRef.current) {
5360
+ return;
5361
+ }
5362
+ if (foundDefaultAgent === currentAgentId) {
5363
+ prevDefaultAgentRef.current = foundDefaultAgent;
5364
+ return;
5365
+ }
5366
+ const isAvailable = agentIds.includes(foundDefaultAgent);
5367
+ const agentProfile = getAgent(foundDefaultAgent);
5368
+ const isReady = (agentProfile == null ? void 0 : agentProfile.status) === "ready";
5369
+ if (isAvailable && isReady && currentConversationIdRef.current) {
5370
+ const agentName = ((_a2 = agentProfile == null ? void 0 : agentProfile.metadata) == null ? void 0 : _a2.displayTitle) || ((_b2 = localOverrides[foundDefaultAgent]) == null ? void 0 : _b2.localName) || foundDefaultAgent;
5371
+ const suggestionMessage = `This page recommends a different agent for better assistance.
5372
+
5373
+ [SUGGEST_AGENT:${foundDefaultAgent}|${agentName}|Recommended for this page]`;
5374
+ const syntheticKey = `__system__:page_suggestion_${foundDefaultAgent}_${Date.now()}`;
5375
+ prevDefaultAgentRef.current = foundDefaultAgent;
5376
+ setActiveConversations((prev) => {
5377
+ const conversationId = currentConversationIdRef.current;
5378
+ if (!conversationId) return prev;
5379
+ const existing = prev.get(conversationId);
5380
+ if (!existing) return prev;
5381
+ const next = new Map(prev);
5382
+ next.set(conversationId, __spreadProps(__spreadValues({}, existing), {
5383
+ history: __spreadProps(__spreadValues({}, existing.history), {
5384
+ [syntheticKey]: {
5385
+ content: suggestionMessage,
5386
+ callId: `page-suggestion-${Date.now()}`
5387
+ }
5388
+ })
5389
+ }));
5390
+ return next;
5391
+ });
5392
+ }
5393
+ }, [pageContextSections, currentAgentId, agentIds, getAgent, localOverrides]);
5202
5394
  const chatPanelData = (0, import_react13.useMemo)(() => {
5203
5395
  const contextData = mergedContext.sections.map((section) => ({
5204
5396
  key: section.id,
@@ -5301,6 +5493,7 @@ var AIAgentPanel = ({
5301
5493
  const suggestedId = handoffMatch[1];
5302
5494
  if (suggestedId && suggestedId !== currentAgentId && agents.includes(suggestedId)) {
5303
5495
  setSuggestedAgent(suggestedId);
5496
+ setHandoffSource("agent");
5304
5497
  setShowHandoffDialog(true);
5305
5498
  }
5306
5499
  }
@@ -5337,11 +5530,34 @@ var AIAgentPanel = ({
5337
5530
  }
5338
5531
  setShowHandoffDialog(false);
5339
5532
  setSuggestedAgent(null);
5533
+ setHandoffSource("agent");
5340
5534
  }, [suggestedAgent, handleAgentSwitch]);
5341
5535
  const handleHandoffCancel = (0, import_react13.useCallback)(() => {
5342
5536
  setShowHandoffDialog(false);
5343
5537
  setSuggestedAgent(null);
5538
+ setHandoffSource("agent");
5344
5539
  }, []);
5540
+ const handleConversationCreated = (0, import_react13.useCallback)((tempId, realId) => {
5541
+ console.log("Conversation created:", tempId, "->", realId);
5542
+ setActiveConversations((prev) => {
5543
+ const existing = prev.get(tempId);
5544
+ if (existing) {
5545
+ const next = new Map(prev);
5546
+ next.delete(tempId);
5547
+ next.set(realId, __spreadProps(__spreadValues({}, existing), {
5548
+ conversationId: realId
5549
+ }));
5550
+ return next;
5551
+ }
5552
+ return prev;
5553
+ });
5554
+ if (currentConversationIdRef.current === tempId) {
5555
+ setCurrentConversationId(realId);
5556
+ if (onConversationChange) {
5557
+ onConversationChange(realId);
5558
+ }
5559
+ }
5560
+ }, [onConversationChange]);
5345
5561
  const toggleCollapse = (0, import_react13.useCallback)(() => {
5346
5562
  setIsCollapsed((prev) => !prev);
5347
5563
  }, []);
@@ -5357,7 +5573,8 @@ var AIAgentPanel = ({
5357
5573
  theme === "dark" ? "dark-theme" : "",
5358
5574
  isCollapsed ? "ai-agent-panel--collapsed" : "",
5359
5575
  position === "left" ? "ai-agent-panel--left" : "ai-agent-panel--right",
5360
- sidebarPosition === "right" ? "ai-agent-panel--sidebar-right" : "ai-agent-panel--sidebar-left"
5576
+ sidebarPosition === "right" ? "ai-agent-panel--sidebar-right" : "ai-agent-panel--sidebar-left",
5577
+ !showConversationHistory ? "ai-agent-panel--no-history" : ""
5361
5578
  ].filter(Boolean).join(" ");
5362
5579
  if (isCollapsed) {
5363
5580
  return /* @__PURE__ */ import_react13.default.createElement("div", { className: panelClasses, ref: panelRef }, /* @__PURE__ */ import_react13.default.createElement(
@@ -5373,7 +5590,7 @@ var AIAgentPanel = ({
5373
5590
  },
5374
5591
  /* @__PURE__ */ import_react13.default.createElement(Tooltip, { content: "Expand Panel", side: "left" }, /* @__PURE__ */ import_react13.default.createElement(Button, { variant: "ghost", size: "icon", onClick: toggleCollapse }, position === "right" ? /* @__PURE__ */ import_react13.default.createElement(ChevronLeftIcon, null) : /* @__PURE__ */ import_react13.default.createElement(ChevronRightIcon, null))),
5375
5592
  /* @__PURE__ */ import_react13.default.createElement("div", { className: "ai-agent-panel__collapsed-divider" }),
5376
- /* @__PURE__ */ import_react13.default.createElement(Tooltip, { content: "Search", side: "left" }, /* @__PURE__ */ import_react13.default.createElement(
5593
+ showConversationHistory && /* @__PURE__ */ import_react13.default.createElement(Tooltip, { content: "Search", side: "left" }, /* @__PURE__ */ import_react13.default.createElement(
5377
5594
  Button,
5378
5595
  {
5379
5596
  variant: "ghost",
@@ -5422,6 +5639,8 @@ var AIAgentPanel = ({
5422
5639
  const next = new Map(prev);
5423
5640
  next.set(tempId, {
5424
5641
  conversationId: tempId,
5642
+ stableKey: tempId,
5643
+ // Stable key never changes
5425
5644
  agentId: agent.id,
5426
5645
  history: {},
5427
5646
  isLoading: false,
@@ -5468,7 +5687,7 @@ var AIAgentPanel = ({
5468
5687
  tabIndex: 0
5469
5688
  }
5470
5689
  ),
5471
- /* @__PURE__ */ import_react13.default.createElement("div", { className: `ai-agent-panel__sidebar ${isHistoryCollapsed ? "ai-agent-panel__sidebar--collapsed" : ""}` }, isHistoryCollapsed ? (
5690
+ showConversationHistory && /* @__PURE__ */ import_react13.default.createElement("div", { className: `ai-agent-panel__sidebar ${isHistoryCollapsed ? "ai-agent-panel__sidebar--collapsed" : ""}` }, isHistoryCollapsed ? (
5472
5691
  // Collapsed history bar
5473
5692
  /* @__PURE__ */ import_react13.default.createElement(
5474
5693
  "div",
@@ -5524,6 +5743,8 @@ var AIAgentPanel = ({
5524
5743
  const next = new Map(prev);
5525
5744
  next.set(tempId, {
5526
5745
  conversationId: tempId,
5746
+ stableKey: tempId,
5747
+ // Stable key never changes
5527
5748
  agentId: agent.id,
5528
5749
  history: {},
5529
5750
  isLoading: false,
@@ -5581,7 +5802,7 @@ var AIAgentPanel = ({
5581
5802
  ))), /* @__PURE__ */ import_react13.default.createElement(Tooltip, { content: "Collapse History", side: "bottom" }, /* @__PURE__ */ import_react13.default.createElement(Button, { variant: "ghost", size: "icon", onClick: toggleHistoryCollapse }, /* @__PURE__ */ import_react13.default.createElement(SidebarIcon, null))), /* @__PURE__ */ import_react13.default.createElement(Button, { variant: "ghost", size: "icon", onClick: toggleCollapse }, position === "right" ? /* @__PURE__ */ import_react13.default.createElement(ChevronRightIcon, null) : /* @__PURE__ */ import_react13.default.createElement(ChevronLeftIcon, null))), /* @__PURE__ */ import_react13.default.createElement(ScrollArea, { className: "ai-agent-panel__conversations" }, activeConversationsList.length > 0 && /* @__PURE__ */ import_react13.default.createElement("div", { className: "ai-agent-panel__group ai-agent-panel__group--active" }, /* @__PURE__ */ import_react13.default.createElement("div", { className: "ai-agent-panel__group-label" }, /* @__PURE__ */ import_react13.default.createElement("span", null, "Active (", activeConversationsList.length, ")")), activeConversationsList.map((activeConv) => /* @__PURE__ */ import_react13.default.createElement(
5582
5803
  "div",
5583
5804
  {
5584
- key: activeConv.conversationId,
5805
+ key: activeConv.stableKey,
5585
5806
  className: `ai-agent-panel__conversation ai-agent-panel__conversation--active-item ${currentConversationId === activeConv.conversationId ? "ai-agent-panel__conversation--current" : ""}`,
5586
5807
  onClick: () => {
5587
5808
  setCurrentConversationId(activeConv.conversationId);
@@ -5620,10 +5841,10 @@ var AIAgentPanel = ({
5620
5841
  /* @__PURE__ */ import_react13.default.createElement("div", { className: "ai-agent-panel__conversation-content" }, /* @__PURE__ */ import_react13.default.createElement("div", { className: "ai-agent-panel__conversation-title" }, isActive && /* @__PURE__ */ import_react13.default.createElement("span", { className: "ai-agent-panel__active-badge" }, "\u25CF"), conversationFirstPrompts[conv.conversationId] || conv.title))
5621
5842
  );
5622
5843
  }))))))),
5623
- /* @__PURE__ */ import_react13.default.createElement("div", { className: "ai-agent-panel__chat" }, activeConversationsList.map((activeConv) => /* @__PURE__ */ import_react13.default.createElement(
5844
+ /* @__PURE__ */ import_react13.default.createElement("div", { className: "ai-agent-panel__chat" }, showContextNotification && /* @__PURE__ */ import_react13.default.createElement("div", { className: "ai-agent-panel__context-notification" }, /* @__PURE__ */ import_react13.default.createElement(SparkleIcon, null), /* @__PURE__ */ import_react13.default.createElement("span", null, "Agent now has new context")), activeConversationsList.map((activeConv) => /* @__PURE__ */ import_react13.default.createElement(
5624
5845
  ChatPanelWrapper,
5625
5846
  {
5626
- key: `${activeConv.conversationId}-${activeConv.agentId}`,
5847
+ key: `${activeConv.stableKey}-${activeConv.agentId}`,
5627
5848
  activeConv,
5628
5849
  currentConversationId,
5629
5850
  getAgent,
@@ -5647,7 +5868,8 @@ var AIAgentPanel = ({
5647
5868
  contextSections: mergedContext.sections,
5648
5869
  totalContextTokens: mergedContext.totalTokens || 0,
5649
5870
  maxContextTokens,
5650
- enableContextDetailView
5871
+ enableContextDetailView,
5872
+ onConversationCreated: handleConversationCreated
5651
5873
  }
5652
5874
  )), loadingConversationId && /* @__PURE__ */ import_react13.default.createElement("div", { className: "ai-agent-panel__conversation-loading-overlay" }, /* @__PURE__ */ import_react13.default.createElement("div", { className: "ai-agent-panel__loading-spinner" }), /* @__PURE__ */ import_react13.default.createElement("p", null, "Loading conversation...")), currentAgentMetadata && activeConversationsList.length === 0 && !loadingConversationId && /* @__PURE__ */ import_react13.default.createElement("div", { className: "ai-agent-panel__empty-chat" }, /* @__PURE__ */ import_react13.default.createElement(MessageIcon, null), /* @__PURE__ */ import_react13.default.createElement("p", null, "Select a conversation or start a new one"), /* @__PURE__ */ import_react13.default.createElement(Button, { variant: "default", size: "sm", onClick: handleNewConversation }, "New Conversation")), agentsLoading && !currentAgentMetadata && /* @__PURE__ */ import_react13.default.createElement("div", { className: "ai-agent-panel__loading" }, /* @__PURE__ */ import_react13.default.createElement("div", { className: "ai-agent-panel__loading-spinner" }), /* @__PURE__ */ import_react13.default.createElement("p", null, "Loading agent..."))),
5653
5875
  /* @__PURE__ */ import_react13.default.createElement(
@@ -5656,7 +5878,7 @@ var AIAgentPanel = ({
5656
5878
  isOpen: showHandoffDialog,
5657
5879
  onClose: handleHandoffCancel,
5658
5880
  title: "Switch Agent?",
5659
- 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"}.`
5881
+ 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"}.`
5660
5882
  },
5661
5883
  /* @__PURE__ */ import_react13.default.createElement(DialogFooter, null, /* @__PURE__ */ import_react13.default.createElement(Button, { variant: "outline", onClick: handleHandoffCancel }, "Stay with current agent"), /* @__PURE__ */ import_react13.default.createElement(Button, { onClick: handleHandoffConfirm }, "Switch agent"))
5662
5884
  )