@inkeep/agents-ui 0.15.16 → 0.15.18

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.
@@ -1,3 +1,3 @@
1
- "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ne=require("@ai-sdk/react"),Oe=require("ai"),t=require("react"),Pe=require("../modal/modal-provider.cjs"),_e=require("../../providers/chat-bubble-provider.cjs"),Fe=require("../../providers/sidebar-chat-provider.cjs"),Be=require("../../providers/config-provider.cjs"),De=require("./use-captcha.cjs"),Ue=require("../../hooks/use-media-query.cjs"),Le=require("../../hooks/use-anonymous-session.cjs"),He=require("../../hooks/use-conversation-loader.cjs"),H=require("../../utils/generate-uid.cjs"),$e=require("../../providers/base-events-provider.cjs"),ze=require("../../providers/chat-form-provider.cjs"),We=require("../../providers/widget-provider.cjs"),Ke=require("@radix-ui/react-use-controllable-state"),je=require("../../hooks/use-streaming-events.cjs"),Ge=require("../../hooks/use-inkeep-api-client.cjs");function Je(f){const l=f.message??"";let r=Number(f.code)||Number(f.statusCode);if(Number.isNaN(r))try{r=Number(JSON.parse(l).status)}catch{}const d=Ge.parseAuthError(r,{detail:l});return d!==null?d:r===401?"session":null}const $=`Hmm..
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Pe=require("@ai-sdk/react"),Ne=require("ai"),t=require("react"),Oe=require("../modal/modal-provider.cjs"),_e=require("../../providers/chat-bubble-provider.cjs"),Fe=require("../../providers/sidebar-chat-provider.cjs"),Ue=require("../../providers/config-provider.cjs"),Be=require("./use-captcha.cjs"),De=require("../../hooks/use-media-query.cjs"),Le=require("../../hooks/use-anonymous-session.cjs"),He=require("../../hooks/use-conversation-loader.cjs"),w=require("../../utils/generate-uid.cjs"),$e=require("../../providers/base-events-provider.cjs"),ze=require("../../providers/chat-form-provider.cjs"),We=require("../../providers/widget-provider.cjs"),Ke=require("@radix-ui/react-use-controllable-state"),je=require("../../hooks/use-streaming-events.cjs"),Ge=require("../../hooks/use-inkeep-api-client.cjs");function Je(g){const l=g.message??"";let r=Number(g.code)||Number(g.statusCode);if(Number.isNaN(r))try{r=Number(JSON.parse(l).status)}catch{}const d=Ge.parseAuthError(r,{detail:l});return d!==null?d:r===401?"session":null}const $=`Hmm..
2
2
 
3
- It seems I might be having some issues right now. Please clear the chat and try again.`,Qe=()=>{const{baseSettings:f,aiChatSettings:l}=Be.useInkeepConfig(),[r="",d]=Ke.useControllableState({prop:l.conversationId,defaultProp:l.conversationId??""}),ce=Pe.useModal(),ue=_e.useOptionalChatBubble(),le=Fe.useOptionalSidebarChat(),{logEvent:h}=$e.useBaseEvents(),{setConversationId:de,emitToParent:C}=je.useStreamingEvents(),[v,k]=t.useState(""),pe=e=>k(e.target.value),{shouldBypassCaptcha:z,filters:W,privacyPreferences:fe}=f,{onInputMessageChange:ge,filters:K,baseUrl:S,agentUrl:me,context:j,headers:G,appId:y,apiKey:p}=l,he=ce?.isOpen??ue?.isOpen??le?.isOpen??!0,{getCaptchaHeader:b,invalidate:u}=De.useCaptcha({baseUrl:S,shouldBypassCaptcha:z||!!p,shouldMakeInitialRequest:he}),J=t.useRef(b);J.current=b;const Q=me||`${S}/run/api/chat`,{sessionToken:q,refreshSession:w}=Le.useAnonymousSession({baseUrl:S,appId:y,getCaptchaHeader:b,invalidateCaptcha:u,optOutAllAnalytics:fe?.optOutAllAnalytics}),{loadConversation:V}=He.useConversationLoader({baseUrl:S,appId:y,authToken:p??q,getCaptchaHeader:b,invalidateCaptcha:u,refreshSession:p?void 0:w}),[ve,Z]=t.useState(!1),R=t.useRef(null);R.current=q;const g=t.useRef(0),X=t.useRef(null),x=t.useRef(null),Y=t.useRef(G);Y.current=G;const T=t.useRef(void 0);T.current=W||K?JSON.stringify({...W,...K}):void 0;const ye=e=>{switch(e.code){case 400:return e.message;case 403:return`There seems to be a configuration error. Please contact ${f.organizationDisplayName??"Administrator"}`;default:return $}},[be,I]=t.useState([]),[Ce,N]=t.useState(null),Se=t.useMemo(()=>new Oe.DefaultChatTransport({api:Q,headers:()=>({"x-inkeep-client-timezone":Intl.DateTimeFormat().resolvedOptions().timeZone,"x-inkeep-client-timestamp":new Date().toISOString(),...y?{"x-inkeep-app-id":y}:{},...R.current?{Authorization:`Bearer ${R.current}`}:{},...p?{Authorization:`Bearer ${p}`}:{},...T.current?{"inkeep-filters":T.current}:{},...Y.current}),prepareSendMessagesRequest:async e=>{const s=await J.current();return{body:{...e.body,id:e.id,messages:e.messages,trigger:e.trigger,messageId:e.messageId},headers:{...e.headers,...s}}},body:{requestContext:j}}),[Q,j,y,p]),{messages:A,sendMessage:O,addToolApprovalResponse:P,status:ee,setMessages:m,stop:te,error:_}=Ne.useChat({transport:Se,onData(e){C(e.type,e.data)},async onFinish(){C("completion",{conversationId:r}),await h({eventName:"assistant_message_received",properties:{conversationId:r}}),h({eventName:"assistant_answer_displayed",properties:{conversationId:r}})},onError(e){console.error("onError",{code:e.code,message:e.message});const s=z||p?null:Je(e);if(s!==null&&g.current<1){g.current++;const i=x.current,a=X.current;(async()=>{if(s==="session"){const o=await w();o&&(R.current=o)}else u();if(i){P(i);return}a&&(m(o=>{let n=[...o];return n.at(-1)?.role==="assistant"&&(n=n.slice(0,-1)),n.at(-1)?.role==="user"&&(n=n.slice(0,-1)),n}),O({text:a.content},{body:a.body}))})().catch(()=>{g.current=0,u(),m(o=>{const n=[...o],L=n[n.length-1];if(!L)return n;const ie=$;return L.role==="user"?n.push({id:H.generateUid(16),role:"assistant",parts:[{type:"text",text:ie}]}):L.parts=[{type:"text",text:ie}],n})});return}g.current=0,s!==null&&u(),h({eventName:"chat_error",properties:{conversationId:r,error:e.message}}),m(i=>{const a=[...i],c=a[a.length-1];if(c){const o=ye(e);c.role==="user"?a.push({id:H.generateUid(16),role:"assistant",parts:[{type:"text",text:o}]}):c.parts=[{type:"text",text:o}]}return a})}}),se=ee==="submitted",F=ee==="streaming",Re=t.useMemo(()=>{const e=c=>{if(!c||typeof c!="object")return!1;const o=c;return typeof o.type=="string"&&o.type.startsWith("tool-")},i=[...A??[]].reverse().find(c=>c.role==="assistant");if(!i)return!1;const a=i.parts?.at(-1);return!(!e(a)||a.state!=="output-available"||!a.approval?.id||F)},[A,F]),re=F||Re,ne=se||re,Ie=A.length===0,B=!v.trim()||ne,Ae=Ue.useMediaQuery("(max-width: 768px)"),[Ee,E]=t.useState(null);t.useEffect(()=>{_&&E(_)},[_]);const Me=()=>E(null),ae=t.useRef(null);t.useEffect(()=>{ge?.(v)},[v]);const ke=e=>{e.key==="Enter"&&!e.shiftKey&&!B&&!e.nativeEvent.isComposing&&(e.preventDefault(),D())},D=async(e=v)=>{if(B&&(!e||e.trim().length===0))return;I([]),k(""),g.current=0,x.current=null,await h({eventName:"user_message_submitted",properties:{conversationId:r}});let s=r;s||(s=`conv_${H.generateUid(16)}`,d(s)),de(s),X.current={content:e,body:{conversationId:s}},O({text:e},{body:{conversationId:s}})},qe=t.useCallback(e=>{g.current=0,x.current=e,P(e)},[P]),U=t.useCallback(()=>{te().then(()=>{C("aborted",{conversationId:r})})},[te,r,C]),oe=()=>{Me(),m([]),d(""),I([]),N(null),u(),h({eventName:"chat_clear_button_clicked",properties:{conversationId:r}})},M=t.useCallback((e,s)=>{E(null),m(s),d(e),I([]),N(null),u()},[m,d,u]),we=t.useCallback(async(e,s)=>{U(),M(e,[]),Z(!0);try{const i=await V(e,s);i!==null&&M(e,i)}finally{s?.aborted||Z(!1)}},[M,V,U]),{openForm:xe}=ze.useChatForm(),Te=We.useWidget();return t.useImperativeHandle(l.chatFunctionsRef,()=>({submitMessage:D,updateInputMessage(e){k(e)},clearChat:oe,openForm:e=>{Te?.setView("chat"),xe(e,void 0)},focusInput:()=>{ae.current?.focus()}})),{messages:A,sendMessage:O,addToolApprovalResponse:qe,isLoading:se,isStreaming:re,isBusy:ne,error:Ee,setError:E,isSubmitDisabled:B,input:v,handleInputChange:pe,handleInputKeyDown:ke,handleSubmit:D,stop:U,clear:oe,inputRef:ae,isMobile:Ae,messageAttachments:be,setMessageAttachments:I,selectedWorkflow:Ce,setSelectedWorkflow:N,isNewChat:Ie,conversationId:r,restoreSession:M,loadAndRestoreSession:we,isSessionLoading:ve,sessionToken:q,refreshSession:w,getCaptchaHeader:b,invalidateCaptcha:u}};exports.DEFAULT_ERROR_MESSAGE=$;exports.useInkeepChat=Qe;
3
+ It seems I might be having some issues right now. Please clear the chat and try again.`,Qe=()=>{const{baseSettings:g,aiChatSettings:l}=Ue.useInkeepConfig(),[r="",d]=Ke.useControllableState({prop:l.conversationId,defaultProp:l.conversationId??""}),ce=Oe.useModal(),ue=_e.useOptionalChatBubble(),le=Fe.useOptionalSidebarChat(),{logEvent:m}=$e.useBaseEvents(),{setConversationId:de,emitToParent:C}=je.useStreamingEvents(),[v,k]=t.useState(""),pe=e=>k(e.target.value),{shouldBypassCaptcha:z,filters:W,privacyPreferences:ge}=g,{onInputMessageChange:fe,filters:K,baseUrl:S,agentUrl:he,context:j,headers:G,appId:y,apiKey:p}=l,me=ce?.isOpen??ue?.isOpen??le?.isOpen??!0,{getCaptchaHeader:b,invalidate:u}=Be.useCaptcha({baseUrl:S,shouldBypassCaptcha:z||!!p,shouldMakeInitialRequest:me}),J=t.useRef(b);J.current=b;const Q=he||`${S}/run/api/chat`,{sessionToken:q,refreshSession:x}=Le.useAnonymousSession({baseUrl:S,appId:y,getCaptchaHeader:b,invalidateCaptcha:u,optOutAllAnalytics:ge?.optOutAllAnalytics}),{loadConversation:V}=He.useConversationLoader({baseUrl:S,appId:y,authToken:p??q,getCaptchaHeader:b,invalidateCaptcha:u,refreshSession:p?void 0:x}),[ve,Z]=t.useState(!1),R=t.useRef(null);R.current=q;const f=t.useRef(0),X=t.useRef(null),T=t.useRef(null),Y=t.useRef(G);Y.current=G;const P=t.useRef(void 0);P.current=W||K?JSON.stringify({...W,...K}):void 0;const ye=e=>{switch(e.code){case 400:return e.message;case 403:return`There seems to be a configuration error. Please contact ${g.organizationDisplayName??"Administrator"}`;default:return $}},[be,I]=t.useState([]),[Ce,N]=t.useState(null),Se=t.useMemo(()=>new Ne.DefaultChatTransport({api:Q,headers:()=>({"x-inkeep-client-timezone":Intl.DateTimeFormat().resolvedOptions().timeZone,"x-inkeep-client-timestamp":new Date().toISOString(),...y?{"x-inkeep-app-id":y}:{},...R.current?{Authorization:`Bearer ${R.current}`}:{},...p?{Authorization:`Bearer ${p}`}:{},...P.current?{"inkeep-filters":P.current}:{},...Y.current}),prepareSendMessagesRequest:async e=>{const s=await J.current();return{body:{...e.body,id:e.id,messages:e.messages,trigger:e.trigger,messageId:e.messageId},headers:{...e.headers,...s}}},body:{requestContext:j}}),[Q,j,y,p]),{messages:A,sendMessage:O,addToolApprovalResponse:_,status:ee,setMessages:h,stop:te,error:F}=Pe.useChat({transport:Se,onData(e){C(e.type,e.data)},async onFinish(){C("completion",{conversationId:r}),await m({eventName:"assistant_message_received",properties:{conversationId:r}}),m({eventName:"assistant_answer_displayed",properties:{conversationId:r}})},onError(e){console.error("onError",{code:e.code,message:e.message});const s=z||p?null:Je(e);if(s!==null&&f.current<1){f.current++;const a=T.current,n=X.current;(async()=>{if(s==="session"){const c=await x();c&&(R.current=c)}else u();if(a){_(a);return}n&&(h(c=>{let i=[...c];return i.at(-1)?.role==="assistant"&&(i=i.slice(0,-1)),i.at(-1)?.role==="user"&&(i=i.slice(0,-1)),i}),O({text:n.content},{body:n.body}))})().catch(()=>{f.current=0,u(),h(c=>{const i=[...c],H=i[i.length-1];if(!H)return i;const ie=$;return H.role==="user"?i.push({id:w.generateUid(16),role:"assistant",parts:[{type:"text",text:ie}]}):H.parts=[{type:"text",text:ie}],i})});return}f.current=0,s!==null&&u(),m({eventName:"chat_error",properties:{conversationId:r,error:e.message}}),h(a=>{const n=[...a],o=n[n.length-1];if(o){const c=ye(e);o.role==="user"?n.push({id:w.generateUid(16),role:"assistant",parts:[{type:"text",text:c}]}):o.parts=[{type:"text",text:c}]}return n})}}),se=ee==="submitted",U=ee==="streaming",Re=t.useMemo(()=>{const e=o=>{if(!o||typeof o!="object")return!1;const c=o;return typeof c.type=="string"&&c.type.startsWith("tool-")},a=[...A??[]].reverse().find(o=>o.role==="assistant");if(!a)return!1;const n=a.parts?.at(-1);return!(!e(n)||n.state!=="output-available"||!n.approval?.id||U)},[A,U]),re=U||Re,ne=se||re,Ie=A.length===0,B=!v.trim()||ne,Ae=De.useMediaQuery("(max-width: 768px)"),[Ee,E]=t.useState(null);t.useEffect(()=>{F&&E(F)},[F]);const Me=()=>E(null),ae=t.useRef(null);t.useEffect(()=>{fe?.(v)},[v]);const we=e=>{e.key==="Enter"&&!e.shiftKey&&!B&&!e.nativeEvent.isComposing&&(e.preventDefault(),D())},D=async(e=v)=>{if(B&&(!e||e.trim().length===0))return;I([]),k(""),f.current=0,T.current=null,await m({eventName:"user_message_submitted",properties:{conversationId:r}});let s=r;s||(s=`conv_${w.generateUid(16)}`,d(s)),de(s),X.current={content:e,body:{conversationId:s}},O({text:e},{body:{conversationId:s}})},ke=t.useCallback(e=>{f.current=0,T.current=e,_(e)},[_]),L=t.useCallback(()=>{te().then(()=>{C("aborted",{conversationId:r})})},[te,r,C]),oe=()=>{Me(),h([]),d(""),I([]),N(null),u(),m({eventName:"chat_clear_button_clicked",properties:{conversationId:r}})},M=t.useCallback((e,s)=>{E(null),h(s),d(e),I([]),N(null),u()},[h,d,u]),qe=t.useCallback(async(e,s)=>{L(),M(e,[]),Z(!0);try{const a=await V(e,s),n=a?.[a.length-1],o=a!==null&&n?.role==="user"?[...a,{id:w.generateUid(16),role:"assistant",parts:[{type:"text",text:"This session was interrupted. Please check back in a few minutes or start a new conversation."}]}]:a;o!==null&&M(e,o)}finally{s?.aborted||Z(!1)}},[M,V,L]),{openForm:xe}=ze.useChatForm(),Te=We.useWidget();return t.useImperativeHandle(l.chatFunctionsRef,()=>({submitMessage:D,updateInputMessage(e){k(e)},clearChat:oe,openForm:e=>{Te?.setView("chat"),xe(e,void 0)},focusInput:()=>{ae.current?.focus()}})),{messages:A,sendMessage:O,addToolApprovalResponse:ke,isLoading:se,isStreaming:re,isBusy:ne,error:Ee,setError:E,isSubmitDisabled:B,input:v,handleInputChange:pe,handleInputKeyDown:we,handleSubmit:D,stop:L,clear:oe,inputRef:ae,isMobile:Ae,messageAttachments:be,setMessageAttachments:I,selectedWorkflow:Ce,setSelectedWorkflow:N,isNewChat:Ie,conversationId:r,restoreSession:M,loadAndRestoreSession:qe,isSessionLoading:ve,sessionToken:q,refreshSession:x,getCaptchaHeader:b,invalidateCaptcha:u}};exports.DEFAULT_ERROR_MESSAGE=$;exports.useInkeepChat=Qe;
@@ -1,7 +1,7 @@
1
1
  "use client";
2
2
  import { useChat as De } from "@ai-sdk/react";
3
3
  import { DefaultChatTransport as Pe } from "ai";
4
- import { useState as C, useRef as l, useMemo as le, useEffect as ue, useCallback as x, useImperativeHandle as He } from "react";
4
+ import { useState as C, useRef as l, useMemo as le, useEffect as ue, useCallback as E, useImperativeHandle as He } from "react";
5
5
  import { useModal as Le } from "../modal/modal-provider.js";
6
6
  import { useOptionalChatBubble as Ue } from "../../providers/chat-bubble-provider.js";
7
7
  import { useOptionalSidebarChat as $e } from "../../providers/sidebar-chat-provider.js";
@@ -10,7 +10,7 @@ import { useCaptcha as We } from "./use-captcha.js";
10
10
  import { useMediaQuery as qe } from "../../hooks/use-media-query.js";
11
11
  import { useAnonymousSession as Ke } from "../../hooks/use-anonymous-session.js";
12
12
  import { useConversationLoader as Je } from "../../hooks/use-conversation-loader.js";
13
- import { generateUid as W } from "../../utils/generate-uid.js";
13
+ import { generateUid as k } from "../../utils/generate-uid.js";
14
14
  import { useBaseEvents as je } from "../../providers/base-events-provider.js";
15
15
  import { useChatForm as Ge } from "../../providers/chat-form-provider.js";
16
16
  import { useWidget as Qe } from "../../providers/widget-provider.js";
@@ -34,7 +34,7 @@ It seems I might be having some issues right now. Please clear the chat and try
34
34
  const { baseSettings: d, aiChatSettings: u } = ze(), [s = "", p] = Ve({
35
35
  prop: u.conversationId,
36
36
  defaultProp: u.conversationId ?? ""
37
- }), me = Le(), de = Ue(), fe = $e(), { logEvent: h } = je(), { setConversationId: ge, emitToParent: S } = Ze(), [y, k] = C(""), he = (e) => k(e.target.value), { shouldBypassCaptcha: q, filters: K, privacyPreferences: ye } = d, {
37
+ }), me = Le(), de = Ue(), fe = $e(), { logEvent: h } = je(), { setConversationId: ge, emitToParent: S } = Ze(), [y, N] = C(""), he = (e) => N(e.target.value), { shouldBypassCaptcha: q, filters: K, privacyPreferences: ye } = d, {
38
38
  onInputMessageChange: ve,
39
39
  filters: J,
40
40
  baseUrl: I,
@@ -49,7 +49,7 @@ It seems I might be having some issues right now. Please clear the chat and try
49
49
  shouldMakeInitialRequest: Ce
50
50
  }), Q = l(b);
51
51
  Q.current = b;
52
- const V = be || `${I}/run/api/chat`, { sessionToken: N, refreshSession: T } = Ke({
52
+ const V = be || `${I}/run/api/chat`, { sessionToken: T, refreshSession: O } = Ke({
53
53
  baseUrl: I,
54
54
  appId: v,
55
55
  getCaptchaHeader: b,
@@ -58,17 +58,17 @@ It seems I might be having some issues right now. Please clear the chat and try
58
58
  }), { loadConversation: Z } = Je({
59
59
  baseUrl: I,
60
60
  appId: v,
61
- authToken: m ?? N,
61
+ authToken: m ?? T,
62
62
  getCaptchaHeader: b,
63
63
  invalidateCaptcha: c,
64
64
  // Only pass refreshSession for anonymous-session flows; API key auth has no token to refresh.
65
- refreshSession: m ? void 0 : T
66
- }), [Se, X] = C(!1), A = l(null);
67
- A.current = N;
68
- const f = l(0), Y = l(null), O = l(null), ee = l(G);
65
+ refreshSession: m ? void 0 : O
66
+ }), [Se, X] = C(!1), w = l(null);
67
+ w.current = T;
68
+ const f = l(0), Y = l(null), _ = l(null), ee = l(G);
69
69
  ee.current = G;
70
- const _ = l(void 0);
71
- _.current = K || J ? JSON.stringify({ ...K, ...J }) : void 0;
70
+ const F = l(void 0);
71
+ F.current = K || J ? JSON.stringify({ ...K, ...J }) : void 0;
72
72
  const Ie = (e) => {
73
73
  switch (e.code) {
74
74
  case 400:
@@ -78,16 +78,16 @@ It seems I might be having some issues right now. Please clear the chat and try
78
78
  default:
79
79
  return pe;
80
80
  }
81
- }, [Ae, R] = C([]), [Re, F] = C(null), we = le(
81
+ }, [we, A] = C([]), [Ae, B] = C(null), Me = le(
82
82
  () => new Pe({
83
83
  api: V,
84
84
  headers: () => ({
85
85
  "x-inkeep-client-timezone": Intl.DateTimeFormat().resolvedOptions().timeZone,
86
86
  "x-inkeep-client-timestamp": (/* @__PURE__ */ new Date()).toISOString(),
87
87
  ...v ? { "x-inkeep-app-id": v } : {},
88
- ...A.current ? { Authorization: `Bearer ${A.current}` } : {},
88
+ ...w.current ? { Authorization: `Bearer ${w.current}` } : {},
89
89
  ...m ? { Authorization: `Bearer ${m}` } : {},
90
- ..._.current ? { "inkeep-filters": _.current } : {},
90
+ ...F.current ? { "inkeep-filters": F.current } : {},
91
91
  ...ee.current
92
92
  }),
93
93
  prepareSendMessagesRequest: async (e) => {
@@ -112,15 +112,15 @@ It seems I might be having some issues right now. Please clear the chat and try
112
112
  }),
113
113
  [V, j, v, m]
114
114
  ), {
115
- messages: w,
116
- sendMessage: B,
117
- addToolApprovalResponse: D,
115
+ messages: M,
116
+ sendMessage: D,
117
+ addToolApprovalResponse: P,
118
118
  status: te,
119
119
  setMessages: g,
120
120
  stop: se,
121
- error: P
121
+ error: H
122
122
  } = De({
123
- transport: we,
123
+ transport: Me,
124
124
  onData(e) {
125
125
  S(e.type, e.data);
126
126
  },
@@ -142,31 +142,31 @@ It seems I might be having some issues right now. Please clear the chat and try
142
142
  const t = q || m ? null : Ye(e);
143
143
  if (t !== null && f.current < 1) {
144
144
  f.current++;
145
- const a = O.current, n = Y.current;
145
+ const n = _.current, r = Y.current;
146
146
  (async () => {
147
147
  if (t === "session") {
148
- const o = await T();
149
- o && (A.current = o);
148
+ const i = await O();
149
+ i && (w.current = i);
150
150
  } else
151
151
  c();
152
- if (a) {
153
- D(a);
152
+ if (n) {
153
+ P(n);
154
154
  return;
155
155
  }
156
- n && (g((o) => {
157
- let r = [...o];
158
- return r.at(-1)?.role === "assistant" && (r = r.slice(0, -1)), r.at(-1)?.role === "user" && (r = r.slice(0, -1)), r;
159
- }), B({ text: n.content }, { body: n.body }));
156
+ r && (g((i) => {
157
+ let a = [...i];
158
+ return a.at(-1)?.role === "assistant" && (a = a.slice(0, -1)), a.at(-1)?.role === "user" && (a = a.slice(0, -1)), a;
159
+ }), D({ text: r.content }, { body: r.body }));
160
160
  })().catch(() => {
161
- f.current = 0, c(), g((o) => {
162
- const r = [...o], z = r[r.length - 1];
163
- if (!z) return r;
161
+ f.current = 0, c(), g((i) => {
162
+ const a = [...i], W = a[a.length - 1];
163
+ if (!W) return a;
164
164
  const ce = pe;
165
- return z.role === "user" ? r.push({
166
- id: W(16),
165
+ return W.role === "user" ? a.push({
166
+ id: k(16),
167
167
  role: "assistant",
168
168
  parts: [{ type: "text", text: ce }]
169
- }) : z.parts = [{ type: "text", text: ce }], r;
169
+ }) : W.parts = [{ type: "text", text: ce }], a;
170
170
  });
171
171
  });
172
172
  return;
@@ -177,93 +177,97 @@ It seems I might be having some issues right now. Please clear the chat and try
177
177
  conversationId: s,
178
178
  error: e.message
179
179
  }
180
- }), g((a) => {
181
- const n = [...a], i = n[n.length - 1];
182
- if (i) {
183
- const o = Ie(e);
184
- i.role === "user" ? n.push({
185
- id: W(16),
180
+ }), g((n) => {
181
+ const r = [...n], o = r[r.length - 1];
182
+ if (o) {
183
+ const i = Ie(e);
184
+ o.role === "user" ? r.push({
185
+ id: k(16),
186
186
  role: "assistant",
187
- parts: [{ type: "text", text: o }]
188
- }) : i.parts = [{ type: "text", text: o }];
187
+ parts: [{ type: "text", text: i }]
188
+ }) : o.parts = [{ type: "text", text: i }];
189
189
  }
190
- return n;
190
+ return r;
191
191
  });
192
192
  }
193
- }), re = te === "submitted", H = te === "streaming", Me = le(() => {
194
- const e = (i) => {
195
- if (!i || typeof i != "object") return !1;
196
- const o = i;
197
- return typeof o.type == "string" && o.type.startsWith("tool-");
198
- }, a = [...w ?? []].reverse().find((i) => i.role === "assistant");
199
- if (!a) return !1;
200
- const n = a.parts?.at(-1);
201
- return !(!e(n) || n.state !== "output-available" || !n.approval?.id || H);
202
- }, [w, H]), ne = H || Me, oe = re || ne, Ee = w.length === 0, L = !y.trim() || oe, xe = qe("(max-width: 768px)"), [ke, M] = C(null);
193
+ }), re = te === "submitted", L = te === "streaming", Re = le(() => {
194
+ const e = (o) => {
195
+ if (!o || typeof o != "object") return !1;
196
+ const i = o;
197
+ return typeof i.type == "string" && i.type.startsWith("tool-");
198
+ }, n = [...M ?? []].reverse().find((o) => o.role === "assistant");
199
+ if (!n) return !1;
200
+ const r = n.parts?.at(-1);
201
+ return !(!e(r) || r.state !== "output-available" || !r.approval?.id || L);
202
+ }, [M, L]), ne = L || Re, oe = re || ne, xe = M.length === 0, U = !y.trim() || oe, Ee = qe("(max-width: 768px)"), [ke, R] = C(null);
203
203
  ue(() => {
204
- P && M(P);
205
- }, [P]);
206
- const Ne = () => M(null), ae = l(null);
204
+ H && R(H);
205
+ }, [H]);
206
+ const Ne = () => R(null), ae = l(null);
207
207
  ue(() => {
208
208
  ve?.(y);
209
209
  }, [y]);
210
210
  const Te = (e) => {
211
- e.key === "Enter" && !e.shiftKey && !L && !e.nativeEvent.isComposing && (e.preventDefault(), U());
212
- }, U = async (e = y) => {
213
- if (L && (!e || e.trim().length === 0)) return;
214
- R([]), k(""), f.current = 0, O.current = null, await h({
211
+ e.key === "Enter" && !e.shiftKey && !U && !e.nativeEvent.isComposing && (e.preventDefault(), $());
212
+ }, $ = async (e = y) => {
213
+ if (U && (!e || e.trim().length === 0)) return;
214
+ A([]), N(""), f.current = 0, _.current = null, await h({
215
215
  eventName: "user_message_submitted",
216
216
  properties: {
217
217
  conversationId: s
218
218
  }
219
219
  });
220
220
  let t = s;
221
- t || (t = `conv_${W(16)}`, p(t)), ge(t), Y.current = {
221
+ t || (t = `conv_${k(16)}`, p(t)), ge(t), Y.current = {
222
222
  content: e,
223
223
  body: { conversationId: t }
224
- }, B(
224
+ }, D(
225
225
  { text: e },
226
226
  {
227
227
  body: { conversationId: t }
228
228
  }
229
229
  );
230
- }, Oe = x(
230
+ }, Oe = E(
231
231
  (e) => {
232
- f.current = 0, O.current = e, D(e);
232
+ f.current = 0, _.current = e, P(e);
233
233
  },
234
- [D]
235
- ), $ = x(() => {
234
+ [P]
235
+ ), z = E(() => {
236
236
  se().then(() => {
237
237
  S("aborted", { conversationId: s });
238
238
  });
239
239
  }, [se, s, S]), ie = () => {
240
- Ne(), g([]), p(""), R([]), F(null), c(), h({
240
+ Ne(), g([]), p(""), A([]), B(null), c(), h({
241
241
  eventName: "chat_clear_button_clicked",
242
242
  properties: {
243
243
  conversationId: s
244
244
  }
245
245
  });
246
- }, E = x(
246
+ }, x = E(
247
247
  (e, t) => {
248
- M(null), g(t), p(e), R([]), F(null), c();
248
+ R(null), g(t), p(e), A([]), B(null), c();
249
249
  },
250
250
  [g, p, c]
251
- ), _e = x(
251
+ ), _e = E(
252
252
  async (e, t) => {
253
- $(), E(e, []), X(!0);
253
+ z(), x(e, []), X(!0);
254
254
  try {
255
- const a = await Z(e, t);
256
- a !== null && E(e, a);
255
+ const n = await Z(e, t), r = n?.[n.length - 1], o = n !== null && r?.role === "user" ? [...n, {
256
+ id: k(16),
257
+ role: "assistant",
258
+ parts: [{ type: "text", text: "This session was interrupted. Please check back in a few minutes or start a new conversation." }]
259
+ }] : n;
260
+ o !== null && x(e, o);
257
261
  } finally {
258
262
  t?.aborted || X(!1);
259
263
  }
260
264
  },
261
- [E, Z, $]
265
+ [x, Z, z]
262
266
  ), { openForm: Fe } = Ge(), Be = Qe();
263
267
  return He(u.chatFunctionsRef, () => ({
264
- submitMessage: U,
268
+ submitMessage: $,
265
269
  updateInputMessage(e) {
266
- k(e);
270
+ N(e);
267
271
  },
268
272
  clearChat: ie,
269
273
  openForm: (e) => {
@@ -273,35 +277,35 @@ It seems I might be having some issues right now. Please clear the chat and try
273
277
  ae.current?.focus();
274
278
  }
275
279
  })), {
276
- messages: w,
277
- sendMessage: B,
280
+ messages: M,
281
+ sendMessage: D,
278
282
  addToolApprovalResponse: Oe,
279
283
  isLoading: re,
280
284
  isStreaming: ne,
281
285
  isBusy: oe,
282
286
  error: ke,
283
- setError: M,
284
- isSubmitDisabled: L,
287
+ setError: R,
288
+ isSubmitDisabled: U,
285
289
  input: y,
286
290
  handleInputChange: he,
287
291
  handleInputKeyDown: Te,
288
- handleSubmit: U,
289
- stop: $,
292
+ handleSubmit: $,
293
+ stop: z,
290
294
  clear: ie,
291
295
  inputRef: ae,
292
- isMobile: xe,
296
+ isMobile: Ee,
293
297
  // Additional state for attachments and workflow
294
- messageAttachments: Ae,
295
- setMessageAttachments: R,
296
- selectedWorkflow: Re,
297
- setSelectedWorkflow: F,
298
- isNewChat: Ee,
298
+ messageAttachments: we,
299
+ setMessageAttachments: A,
300
+ selectedWorkflow: Ae,
301
+ setSelectedWorkflow: B,
302
+ isNewChat: xe,
299
303
  conversationId: s,
300
- restoreSession: E,
304
+ restoreSession: x,
301
305
  loadAndRestoreSession: _e,
302
306
  isSessionLoading: Se,
303
- sessionToken: N,
304
- refreshSession: T,
307
+ sessionToken: T,
308
+ refreshSession: O,
305
309
  getCaptchaHeader: b,
306
310
  invalidateCaptcha: c
307
311
  };
@@ -1 +1 @@
1
- "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react"),E=require("./use-local-storage.cjs"),T=require("./use-inkeep-api-client.cjs"),b=30*1e3,d=()=>{},g=async()=>({}),F=({baseUrl:o,appId:n,getCaptchaHeader:A,invalidateCaptcha:S,optOutAllAnalytics:m})=>{const p=n&&!m?`inkeep_session_${n}`:null,[u,f]=E.useLocalStorage(p),{fetchWithAuth:h}=T.useInkeepApiClient({appId:n,authToken:void 0,getCaptchaHeader:A??g,invalidateCaptcha:S??d}),i=e.useRef(o);i.current=o;const a=e.useRef(n);a.current=n;const y=e.useRef(f);y.current=f;const R=e.useRef(h);R.current=h;const s=e.useRef(null),c=e.useCallback(async t=>{if(!i.current||!a.current)return null;if(!t&&s.current)return s.current;const w=`${i.current}/run/auth/apps/${a.current}/anonymous-session`,k=(async()=>{try{const r=await R.current(w,{method:"POST",headers:{"Content-Type":"application/json"},signal:t});if(!r.ok)throw new Error(`Failed to fetch anonymous session: ${r.status}`);const l=await r.json();return y.current({token:l.token,expiresAt:l.expiresAt}),l.token}catch(r){return r instanceof Error&&r.name==="AbortError"||console.error("[useAnonymousSession]",r),null}finally{t||(s.current=null)}})();return t||(s.current=k),k},[]);e.useEffect(()=>{if(!o||!n||u&&new Date(u.expiresAt).getTime()-b>Date.now()||s.current)return;const t=new AbortController;return c(t.signal),()=>t.abort()},[o,n,u,c]);const C=e.useCallback(()=>c(),[c]);return{sessionToken:u?.token??null,refreshSession:C}};exports.useAnonymousSession=F;
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react"),b=require("./use-local-storage.cjs"),_=require("./use-inkeep-api-client.cjs"),M=30*1e3,$=2147483647,D=()=>{},F=async()=>({});function C(n){return new Date(n.expiresAt).getTime()-M<=Date.now()}const L=({baseUrl:n,appId:t,getCaptchaHeader:d,invalidateCaptcha:g,optOutAllAnalytics:p})=>{const w=t&&!p?`inkeep_session_${t}`:null,[u,R]=b.useLocalStorage(w),{fetchWithAuth:k}=_.useInkeepApiClient({appId:t,authToken:void 0,getCaptchaHeader:d??F,invalidateCaptcha:g??D}),l=e.useRef(n);l.current=n;const h=e.useRef(t);h.current=t;const c=e.useRef(u);c.current=u;const S=e.useRef(R);S.current=R;const T=e.useRef(k);T.current=k;const f=e.useRef(null),s=e.useCallback(async r=>{if(!l.current||!h.current)return null;if(!r&&f.current)return f.current;const o=`${l.current}/run/auth/apps/${h.current}/anonymous-session`,a=(async()=>{try{const i={"Content-Type":"application/json"},v=c.current?.token;v&&(i.Authorization=`Bearer ${v}`);const A=await T.current(o,{method:"POST",headers:i,signal:r});if(!A.ok)throw new Error(`Failed to fetch anonymous session: ${A.status}`);const y=await A.json();return S.current({token:y.token,expiresAt:y.expiresAt}),y.token}catch(i){return i instanceof Error&&i.name==="AbortError"||console.error("[anonymous-session] fetch failed",i),null}finally{r||(f.current=null)}})();return r||(f.current=a),a},[]),E=e.useRef(!1);e.useEffect(()=>{if(!n||!t)return;const r=!E.current;if(E.current=!0,!r&&c.current&&!C(c.current)||f.current)return;const o=new AbortController;return s(o.signal),()=>o.abort()},[n,t,s]),e.useEffect(()=>{if(!n||!t||!u?.expiresAt)return;const m=new Date(u.expiresAt).getTime()-M-Date.now();if(m<=0)return;const a=setTimeout(()=>s(),Math.min(m,$));return()=>clearTimeout(a)},[n,t,u?.expiresAt,s]),e.useEffect(()=>{if(!n||!t)return;const r=()=>{if(document.visibilityState!=="visible")return;const o=c.current;(!o||C(o))&&s()};return document.addEventListener("visibilitychange",r),()=>document.removeEventListener("visibilitychange",r)},[n,t,s]);const x=e.useCallback(()=>s(),[s]);return{sessionToken:u?.token??null,refreshSession:x}};exports.useAnonymousSession=L;
@@ -1,57 +1,82 @@
1
1
  "use client";
2
- import { useRef as o, useCallback as k, useEffect as F } from "react";
3
- import { useLocalStorage as T } from "./use-local-storage.js";
4
- import { useInkeepApiClient as x } from "./use-inkeep-api-client.js";
5
- const _ = 30 * 1e3, $ = () => {
6
- }, d = async () => ({}), D = ({
7
- baseUrl: s,
2
+ import { useRef as s, useCallback as E, useEffect as k } from "react";
3
+ import { useLocalStorage as D } from "./use-local-storage.js";
4
+ import { useInkeepApiClient as F } from "./use-inkeep-api-client.js";
5
+ const M = 30 * 1e3, b = 2147483647, L = () => {
6
+ }, j = async () => ({});
7
+ function w(t) {
8
+ return new Date(t.expiresAt).getTime() - M <= Date.now();
9
+ }
10
+ const X = ({
11
+ baseUrl: t,
8
12
  appId: e,
9
- getCaptchaHeader: A,
10
- invalidateCaptcha: R,
11
- optOutAllAnalytics: S
13
+ getCaptchaHeader: C,
14
+ invalidateCaptcha: d,
15
+ optOutAllAnalytics: g
12
16
  }) => {
13
- const w = e && !S ? `inkeep_session_${e}` : null, [c, l] = T(w), { fetchWithAuth: h } = x({
17
+ const _ = e && !g ? `inkeep_session_${e}` : null, [i, T] = D(_), { fetchWithAuth: R } = F({
14
18
  appId: e,
15
19
  authToken: void 0,
16
- getCaptchaHeader: A ?? d,
17
- invalidateCaptcha: R ?? $
18
- }), i = o(s);
19
- i.current = s;
20
- const a = o(e);
21
- a.current = e;
22
- const m = o(l);
23
- m.current = l;
24
- const p = o(h);
25
- p.current = h;
26
- const r = o(null), u = k(async (n) => {
27
- if (!i.current || !a.current) return null;
28
- if (!n && r.current) return r.current;
29
- const E = `${i.current}/run/auth/apps/${a.current}/anonymous-session`, y = (async () => {
20
+ getCaptchaHeader: C ?? j,
21
+ invalidateCaptcha: d ?? L
22
+ }), l = s(t);
23
+ l.current = t;
24
+ const h = s(e);
25
+ h.current = e;
26
+ const u = s(i);
27
+ u.current = i;
28
+ const S = s(T);
29
+ S.current = T;
30
+ const p = s(R);
31
+ p.current = R;
32
+ const f = s(null), r = E(async (n) => {
33
+ if (!l.current || !h.current) return null;
34
+ if (!n && f.current)
35
+ return f.current;
36
+ const o = `${l.current}/run/auth/apps/${h.current}/anonymous-session`, a = (async () => {
30
37
  try {
31
- const t = await p.current(E, {
38
+ const c = { "Content-Type": "application/json" }, x = u.current?.token;
39
+ x && (c.Authorization = `Bearer ${x}`);
40
+ const A = await p.current(o, {
32
41
  method: "POST",
33
- headers: { "Content-Type": "application/json" },
42
+ headers: c,
34
43
  signal: n
35
44
  });
36
- if (!t.ok) throw new Error(`Failed to fetch anonymous session: ${t.status}`);
37
- const f = await t.json();
38
- return m.current({ token: f.token, expiresAt: f.expiresAt }), f.token;
39
- } catch (t) {
40
- return t instanceof Error && t.name === "AbortError" || console.error("[useAnonymousSession]", t), null;
45
+ if (!A.ok) throw new Error(`Failed to fetch anonymous session: ${A.status}`);
46
+ const y = await A.json();
47
+ return S.current({ token: y.token, expiresAt: y.expiresAt }), y.token;
48
+ } catch (c) {
49
+ return c instanceof Error && c.name === "AbortError" || console.error("[anonymous-session] fetch failed", c), null;
41
50
  } finally {
42
- n || (r.current = null);
51
+ n || (f.current = null);
43
52
  }
44
53
  })();
45
- return n || (r.current = y), y;
46
- }, []);
47
- F(() => {
48
- if (!s || !e || c && new Date(c.expiresAt).getTime() - _ > Date.now() || r.current) return;
49
- const n = new AbortController();
50
- return u(n.signal), () => n.abort();
51
- }, [s, e, c, u]);
52
- const C = k(() => u(), [u]);
53
- return { sessionToken: c?.token ?? null, refreshSession: C };
54
+ return n || (f.current = a), a;
55
+ }, []), v = s(!1);
56
+ k(() => {
57
+ if (!t || !e) return;
58
+ const n = !v.current;
59
+ if (v.current = !0, !n && u.current && !w(u.current) || f.current) return;
60
+ const o = new AbortController();
61
+ return r(o.signal), () => o.abort();
62
+ }, [t, e, r]), k(() => {
63
+ if (!t || !e || !i?.expiresAt) return;
64
+ const m = new Date(i.expiresAt).getTime() - M - Date.now();
65
+ if (m <= 0) return;
66
+ const a = setTimeout(() => r(), Math.min(m, b));
67
+ return () => clearTimeout(a);
68
+ }, [t, e, i?.expiresAt, r]), k(() => {
69
+ if (!t || !e) return;
70
+ const n = () => {
71
+ if (document.visibilityState !== "visible") return;
72
+ const o = u.current;
73
+ (!o || w(o)) && r();
74
+ };
75
+ return document.addEventListener("visibilitychange", n), () => document.removeEventListener("visibilitychange", n);
76
+ }, [t, e, r]);
77
+ const $ = E(() => r(), [r]);
78
+ return { sessionToken: i?.token ?? null, refreshSession: $ };
54
79
  };
55
80
  export {
56
- D as useAnonymousSession
81
+ X as useAnonymousSession
57
82
  };
@@ -1 +1 @@
1
- "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const E=require("react/jsx-runtime"),t=require("react"),l=require("./config-provider.cjs"),a=t.createContext(void 0),p=({children:e})=>{const{baseSettings:s,componentType:n}=l.useInkeepConfig(),{tags:o,analyticsProperties:r}=s,i=t.useMemo(()=>({widgetLibraryVersion:"0.15.15",componentType:n,tags:o}),[n,o]),u={logEvent:t.useCallback(async c=>{const v={...i,...c.properties,...r},d={eventName:c.eventName,properties:v};return s.onEvent?.(d)},[s,i,r])};return E.jsx(a.Provider,{value:u,children:e})},g=()=>{const e=t.useContext(a);if(!e)throw new Error("useBaseEvents must be used within a BaseEventsProvider");return e};exports.BaseEventsProvider=p;exports.useBaseEvents=g;
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const E=require("react/jsx-runtime"),t=require("react"),l=require("./config-provider.cjs"),a=t.createContext(void 0),p=({children:e})=>{const{baseSettings:s,componentType:n}=l.useInkeepConfig(),{tags:o,analyticsProperties:r}=s,i=t.useMemo(()=>({widgetLibraryVersion:"0.15.18",componentType:n,tags:o}),[n,o]),u={logEvent:t.useCallback(async c=>{const v={...i,...c.properties,...r},d={eventName:c.eventName,properties:v};return s.onEvent?.(d)},[s,i,r])};return E.jsx(a.Provider,{value:u,children:e})},g=()=>{const e=t.useContext(a);if(!e)throw new Error("useBaseEvents must be used within a BaseEventsProvider");return e};exports.BaseEventsProvider=p;exports.useBaseEvents=g;
@@ -5,7 +5,7 @@ import { useInkeepConfig as g } from "./config-provider.js";
5
5
  const a = d(void 0), P = ({ children: e }) => {
6
6
  const { baseSettings: t, componentType: o } = g(), { tags: s, analyticsProperties: n } = t, r = u(
7
7
  () => ({
8
- widgetLibraryVersion: "0.15.15",
8
+ widgetLibraryVersion: "0.15.18",
9
9
  componentType: o,
10
10
  tags: s
11
11
  }),
@@ -1 +1 @@
1
- "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const X=require("react/jsx-runtime"),e=require("react"),Y=require("../components/embedded-chat/chat-provider.cjs"),N=require("./config-provider.cjs"),ee=require("../hooks/use-inkeep-api-client.cjs"),F=e.createContext(void 0),D=25;function te(t){const{stop:a,clear:c,conversationId:u,isStreaming:H,loadAndRestoreSession:P,sessionToken:f,refreshSession:W,getCaptchaHeader:G,invalidateCaptcha:K}=Y.useChat(),{aiChatSettings:U}=N.useInkeepConfig(),{baseUrl:h,appId:k,apiKey:Z}=U,r=!Z&&!!k,C=f,{fetchWithAuth:I}=ee.useInkeepApiClient({appId:k,authToken:C,getCaptchaHeader:G,invalidateCaptcha:K,refreshSession:W}),[p,S]=e.useState(!1),[R,E]=e.useState([]),[g,x]=e.useState(!1),[m,_]=e.useState(0),[v,z]=e.useState(!1),b=e.useRef(!1),q=e.useRef(null),j=e.useRef([]);j.current=R;const M=e.useRef(I);M.current=I;const o=e.useCallback(async(s,i=!1)=>{if(!(!h||!C||!r)){x(!0);try{const w=`${h}/run/v1/conversations?page=${s+1}&limit=${D}`,y=await M.current(w);if(!y.ok)throw new Error(`Failed to fetch conversations: ${y.status}`);const L=await y.json(),d=(L.data??[]).map(n=>({id:n.id,title:n.title??"",createdAt:new Date(n.createdAt),updatedAt:new Date(n.updatedAt)}));E(n=>{if(s===0&&!i)return d;if(s===0&&i){const l=new Set(d.map(A=>A.id));return[...d,...n.slice(D).filter(A=>!l.has(A.id))]}const V=new Set(n.map(l=>l.id));return[...n,...d.filter(l=>!V.has(l.id))]});const{page:O,pages:T}=L.pagination??{};z(O!=null&&T!=null?O<T:!1),i||_(s)}catch(w){console.error("[useChatHistory] Failed to load conversations:",w)}finally{x(!1)}}},[h,C,r]);e.useEffect(()=>{!p||!f||!r||(t==="stack"?(E([]),o(0)):b.current||(b.current=!0,o(0)))},[p,f,r,t,o]);const $=e.useRef("");e.useEffect(()=>{r&&t==="sidepane"&&(!u||!H||b.current&&$.current!==u&&(j.current.some(s=>s.id===u)||($.current=u,o(0,!0))))},[u,r,t,o,H]);const B=e.useCallback(()=>{!g&&v&&o(m+1)},[g,v,m,o]),J=e.useCallback(()=>{a(),c(),t!=="sidepane"&&S(!1)},[t,a,c]),Q=e.useCallback(async s=>{q.current?.abort();const i=new AbortController;q.current=i,await P(s,i.signal),!i.signal.aborted&&t!=="sidepane"&&S(!1)},[t,P]);return{isEnabled:r,isOpen:p,setIsOpen:S,sessions:R,isLoading:g,hasMore:v,loadMore:B,startNewConversation:J,loadSession:Q}}const se=({layout:t,children:a})=>{const c=te(t);return X.jsx(F.Provider,{value:c,children:typeof a=="function"?a(c):a})},ne=()=>{const t=e.useContext(F);if(!t)throw new Error("useChatHistory must be used within a ChatHistoryProvider");return t};exports.ChatHistoryProvider=se;exports.useChatHistory=ne;
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const X=require("react/jsx-runtime"),e=require("react"),Y=require("../components/embedded-chat/chat-provider.cjs"),N=require("./config-provider.cjs"),ee=require("../hooks/use-inkeep-api-client.cjs"),D=e.createContext(void 0),T=25;function te(t){const{stop:a,clear:c,conversationId:u,isStreaming:H,loadAndRestoreSession:P,sessionToken:f,refreshSession:F,getCaptchaHeader:W,invalidateCaptcha:G}=Y.useChat(),{aiChatSettings:K}=N.useInkeepConfig(),{baseUrl:h,appId:k,apiKey:U}=K,o=!U&&!!k,C=f,{fetchWithAuth:I}=ee.useInkeepApiClient({appId:k,authToken:C,getCaptchaHeader:W,invalidateCaptcha:G,refreshSession:F}),[p,S]=e.useState(!1),[R,Z]=e.useState([]),[g,E]=e.useState(!1),[x,_]=e.useState(0),[v,z]=e.useState(!1),b=e.useRef(!1),m=e.useRef(null),q=e.useRef([]);q.current=R;const j=e.useRef(I);j.current=I;const i=e.useCallback(async(s,n=!1)=>{if(!(!h||!C||!o)){n||E(!0);try{const w=`${h}/run/v1/conversations?page=${s+1}&limit=${T}`,y=await j.current(w);if(!y.ok)throw new Error(`Failed to fetch conversations: ${y.status}`);const $=await y.json(),d=($.data??[]).map(r=>({id:r.id,title:r.title??"",createdAt:new Date(r.createdAt),updatedAt:new Date(r.updatedAt)}));Z(r=>{if(s===0&&!n)return d;if(s===0&&n){const l=new Set(d.map(A=>A.id));return[...d,...r.slice(T).filter(A=>!l.has(A.id))]}const V=new Set(r.map(l=>l.id));return[...r,...d.filter(l=>!V.has(l.id))]});const{page:L,pages:O}=$.pagination??{};z(L!=null&&O!=null?L<O:!1),n||_(s)}catch(w){console.error("[useChatHistory] Failed to load conversations:",w)}finally{E(!1)}}},[h,C,o]);e.useEffect(()=>{!p||!f||!o||(t==="stack"?i(0):b.current||(b.current=!0,i(0)))},[p,f,o,t,i]);const M=e.useRef("");e.useEffect(()=>{o&&t==="sidepane"&&(!u||!H||b.current&&M.current!==u&&(q.current.some(s=>s.id===u)||(M.current=u,i(0,!0))))},[u,o,t,i,H]);const B=e.useCallback(()=>{!g&&v&&i(x+1)},[g,v,x,i]),J=e.useCallback(()=>{a(),c(),t!=="sidepane"&&S(!1)},[t,a,c]),Q=e.useCallback(async s=>{m.current?.abort();const n=new AbortController;m.current=n,await P(s,n.signal),!n.signal.aborted&&t!=="sidepane"&&S(!1)},[t,P]);return{isEnabled:o,isOpen:p,setIsOpen:S,sessions:R,isLoading:g,hasMore:v,loadMore:B,startNewConversation:J,loadSession:Q}}const se=({layout:t,children:a})=>{const c=te(t);return X.jsx(D.Provider,{value:c,children:typeof a=="function"?a(c):a})},ne=()=>{const t=e.useContext(D);if(!t)throw new Error("useChatHistory must be used within a ChatHistoryProvider");return t};exports.ChatHistoryProvider=se;exports.useChatHistory=ne;