@inkeep/agents-ui 0.0.0-dev-20260721222136 → 0.0.0-dev-20260721224224

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 o=require("../../hooks/use-inkeep-api-client.cjs");function s(t){const e=Number(t.code)||Number(t.statusCode);if(e&&!Number.isNaN(e))return e;try{const r=Number(JSON.parse(t.message??"").status);return r&&!Number.isNaN(r)?r:null}catch{return null}}function a(t){const e=s(t),r=o.parseAuthError(e??0,{detail:t.message??""});return r!==null?r:e===401?"session":e===403?"captcha":null}function E(t){const e=s(t);return e===400||e===413||e===429}function i(t){if(s(t)!==null)return!1;const e=(t.message??"").toLowerCase();return e.includes("failed to fetch")||e.includes("load failed")||e.includes("networkerror")||e.includes("network request failed")}const u="Something went wrong sending your message. Check your connection and try again.",c=`Hmm..
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("../../hooks/use-inkeep-api-client.cjs");function n(t){const e=Number(t.code)||Number(t.statusCode);if(e&&!Number.isNaN(e))return e;try{const r=Number(JSON.parse(t.message??"").status);return r&&!Number.isNaN(r)?r:null}catch{return null}}function E(t){const e=n(t),r=o.parseAuthError(e??0,{detail:t.message??""});return r!==null?r:e===401?"session":e===403?"captcha":null}function a(t){const e=n(t);return e===400||e===413||e===429}function i(t){if(n(t)!==null)return!1;const e=(t.message??"").toLowerCase();return e.includes("failed to fetch")||e.includes("load failed")||e.includes("networkerror")||e.includes("network request failed")}const u="Something went wrong sending your message. Check your connection and try again.",c="Your message could not be sent. If you attached large files, try removing one. Otherwise, check your connection and try again.",_=`Hmm..
2
2
 
3
- It seems I might be having some issues right now. Please clear the chat and try again.`,l="Please try again.",A="You're sending requests too quickly. Please wait a moment and try again.",S="Your message or attachments are too large. Remove a file or shorten your message and try again.",_=43e5,n=4/3;function R(t){return new TextEncoder().encode(t.text).length+Math.ceil(t.rawFileBytes*n)+t.encodedPartsBytes}const d=8e3;exports.BASE64_SIZE_FACTOR=n;exports.DEFAULT_ERROR_MESSAGE=c;exports.MAX_REQUEST_BODY_BYTES=_;exports.NETWORK_ERROR_MESSAGE=u;exports.PAYLOAD_TOO_LARGE_MESSAGE=S;exports.RATE_LIMIT_MESSAGE=A;exports.RECOVERABLE_FALLBACK_MESSAGE=l;exports.RECOVERABLE_NOTIFICATION_DURATION_MS=d;exports.estimateRequestBodyBytes=R;exports.isNetworkError=i;exports.isRecoverableError=E;exports.resolveHttpStatusCode=s;exports.resolveStreamingAuthError=a;
3
+ It seems I might be having some issues right now. Please clear the chat and try again.`,l="Please try again.",R="You're sending requests too quickly. Please wait a moment and try again.",A="Your message or attachments are too large. Remove a file or shorten your message and try again.",S=43e5,s=4/3;function d(t){return new TextEncoder().encode(t.text).length+Math.ceil(t.rawFileBytes*s)+t.encodedPartsBytes}const O=8e3;exports.BASE64_SIZE_FACTOR=s;exports.DEFAULT_ERROR_MESSAGE=_;exports.MAX_REQUEST_BODY_BYTES=S;exports.NETWORK_ERROR_MESSAGE=u;exports.NETWORK_ERROR_WITH_FILES_MESSAGE=c;exports.PAYLOAD_TOO_LARGE_MESSAGE=A;exports.RATE_LIMIT_MESSAGE=R;exports.RECOVERABLE_FALLBACK_MESSAGE=l;exports.RECOVERABLE_NOTIFICATION_DURATION_MS=O;exports.estimateRequestBodyBytes=d;exports.isNetworkError=i;exports.isRecoverableError=a;exports.resolveHttpStatusCode=n;exports.resolveStreamingAuthError=E;
@@ -41,6 +41,7 @@ export declare function isRecoverableError(error: Error): boolean;
41
41
  */
42
42
  export declare function isNetworkError(error: Error): boolean;
43
43
  export declare const NETWORK_ERROR_MESSAGE = "Something went wrong sending your message. Check your connection and try again.";
44
+ export declare const NETWORK_ERROR_WITH_FILES_MESSAGE = "Your message could not be sent. If you attached large files, try removing one. Otherwise, check your connection and try again.";
44
45
  export declare const DEFAULT_ERROR_MESSAGE = "Hmm.. \n\nIt seems I might be having some issues right now. Please clear the chat and try again.";
45
46
  export declare const RECOVERABLE_FALLBACK_MESSAGE = "Please try again.";
46
47
  export declare const RATE_LIMIT_MESSAGE = "You're sending requests too quickly. Please wait a moment and try again.";
@@ -10,11 +10,11 @@ function s(t) {
10
10
  return null;
11
11
  }
12
12
  }
13
- function i(t) {
13
+ function c(t) {
14
14
  const e = s(t), n = r(e ?? 0, { detail: t.message ?? "" });
15
15
  return n !== null ? n : e === 401 ? "session" : e === 403 ? "captcha" : null;
16
16
  }
17
- function c(t) {
17
+ function i(t) {
18
18
  const e = s(t);
19
19
  return e === 400 || e === 413 || e === 429;
20
20
  }
@@ -26,25 +26,26 @@ function u(t) {
26
26
  e.includes("networkerror") || // Firefox
27
27
  e.includes("network request failed");
28
28
  }
29
- const l = "Something went wrong sending your message. Check your connection and try again.", E = `Hmm..
29
+ const l = "Something went wrong sending your message. Check your connection and try again.", E = "Your message could not be sent. If you attached large files, try removing one. Otherwise, check your connection and try again.", d = `Hmm..
30
30
 
31
- It seems I might be having some issues right now. Please clear the chat and try again.`, m = "Please try again.", d = "You're sending requests too quickly. Please wait a moment and try again.", g = "Your message or attachments are too large. Remove a file or shorten your message and try again.", A = 43e5, o = 4 / 3;
32
- function f(t) {
31
+ It seems I might be having some issues right now. Please clear the chat and try again.`, m = "Please try again.", g = "You're sending requests too quickly. Please wait a moment and try again.", R = "Your message or attachments are too large. Remove a file or shorten your message and try again.", _ = 43e5, o = 4 / 3;
32
+ function A(t) {
33
33
  return new TextEncoder().encode(t.text).length + Math.ceil(t.rawFileBytes * o) + t.encodedPartsBytes;
34
34
  }
35
- const R = 8e3;
35
+ const S = 8e3;
36
36
  export {
37
37
  o as BASE64_SIZE_FACTOR,
38
- E as DEFAULT_ERROR_MESSAGE,
39
- A as MAX_REQUEST_BODY_BYTES,
38
+ d as DEFAULT_ERROR_MESSAGE,
39
+ _ as MAX_REQUEST_BODY_BYTES,
40
40
  l as NETWORK_ERROR_MESSAGE,
41
- g as PAYLOAD_TOO_LARGE_MESSAGE,
42
- d as RATE_LIMIT_MESSAGE,
41
+ E as NETWORK_ERROR_WITH_FILES_MESSAGE,
42
+ R as PAYLOAD_TOO_LARGE_MESSAGE,
43
+ g as RATE_LIMIT_MESSAGE,
43
44
  m as RECOVERABLE_FALLBACK_MESSAGE,
44
- R as RECOVERABLE_NOTIFICATION_DURATION_MS,
45
- f as estimateRequestBodyBytes,
45
+ S as RECOVERABLE_NOTIFICATION_DURATION_MS,
46
+ A as estimateRequestBodyBytes,
46
47
  u as isNetworkError,
47
- c as isRecoverableError,
48
+ i as isRecoverableError,
48
49
  s as resolveHttpStatusCode,
49
- i as resolveStreamingAuthError
50
+ c as resolveStreamingAuthError
50
51
  };
@@ -1,2 +1,2 @@
1
- "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Xe=require("@ai-sdk/react"),Ze=require("./file-upload-input.cjs"),et=require("ai"),t=require("react"),tt=require("../../providers/config-provider.cjs"),st=require("../../providers/chat-auth-provider.cjs"),rt=require("../../hooks/use-media-query.cjs"),nt=require("../../hooks/use-conversation-loader.cjs"),at=require("../../hooks/use-initial-conversation.cjs"),O=require("../../utils/generate-uid.cjs"),ot=require("../../providers/base-events-provider.cjs"),it=require("../../providers/chat-form-provider.cjs"),ct=require("../../providers/widget-provider.cjs"),ut=require("@radix-ui/react-use-controllable-state"),lt=require("../../hooks/use-streaming-events.cjs"),dt=require("../../hooks/use-input-notification.cjs"),r=require("./chat-error-helpers.cjs"),ft=()=>{const{baseSettings:se,aiChatSettings:E}=tt.useInkeepConfig(),[u="",R]=ut.useControllableState({prop:E.conversationIdOverride,defaultProp:E.conversationIdOverride??""}),{logEvent:m}=ot.useBaseEvents(),{setConversationId:we,emitToParent:k}=lt.useStreamingEvents(),re=t.useRef(u);t.useEffect(()=>{const e=re.current;re.current=u,e!==u&&m({eventName:"chat_conversation_changed",properties:{conversationId:u,previousConversationId:e}})},[u,m]);const[I,_]=t.useState(""),Oe=e=>_(e.target.value),{shouldBypassCaptcha:ke,filters:ne,userProperties:B,analyticsProperties:D}=se,{authToken:ae,isAuthenticated:y,isAuthConfigured:oe,refreshAuthToken:ie,sessionToken:ce,refreshSession:ue,getCaptchaHeader:F,invalidateCaptcha:f,effectiveAuthToken:le,applicableRefreshSession:Fe}=st.useChatAuth(),{onInputMessageChange:Le,filters:de,baseUrl:fe,agentUrl:Pe,context:pe,headers:ge,appId:L,apiKey:U,files:T}=E,he=t.useRef(F);he.current=F;const me=Pe||`${fe}/run/api/chat`,{loadConversation:ve}=nt.useConversationLoader({baseUrl:fe,appId:L,authToken:le,getCaptchaHeader:F,invalidateCaptcha:f,refreshSession:Fe}),[Ne,Ee]=t.useState(!1),G=t.useRef(null);G.current=ce;const $=t.useRef(null);$.current=ae;const K=t.useRef(void 0);K.current=B&&Object.keys(B).length>0?B:void 0;const z=t.useRef(void 0);z.current=D&&Object.keys(D).length>0?D:void 0;const A=t.useRef(0),P=t.useRef(null),H=t.useRef(null),v=t.useRef(void 0),xe=T?.map(e=>`${e.filename??""}:${e.mediaType}:${e.url.length}:${e.url.slice(0,64)}:${e.url.slice(-32)}`).join(`
2
- `)??"";t.useEffect(()=>{v.current=T?.length?T:void 0},[xe]);const Re=t.useRef(ge);Re.current=ge;const Y=t.useRef(void 0);Y.current=ne||de?JSON.stringify({...ne,...de}):void 0;const qe=e=>{if(r.isNetworkError(e))return P.current?.files?.length?r.PAYLOAD_TOO_LARGE_MESSAGE:r.NETWORK_ERROR_MESSAGE;switch(r.resolveHttpStatusCode(e)){case 400:try{const s=JSON.parse(e.message??"");return s.detail??s.error?.message??r.RECOVERABLE_FALLBACK_MESSAGE}catch{return e.message?.trim()||r.RECOVERABLE_FALLBACK_MESSAGE}case 401:return oe?"Authentication failed. Please try again.":r.DEFAULT_ERROR_MESSAGE;case 403:return`There seems to be a configuration error. Please contact ${se.organizationDisplayName??"Administrator"}`;case 413:return r.PAYLOAD_TOO_LARGE_MESSAGE;case 429:return r.RATE_LIMIT_MESSAGE;default:return r.DEFAULT_ERROR_MESSAGE}},[S,V]=t.useState([]),Be=t.useMemo(()=>new et.DefaultChatTransport({api:me,headers:()=>{const e=U??$.current??G.current;return{"x-inkeep-client-timezone":Intl.DateTimeFormat().resolvedOptions().timeZone,"x-inkeep-client-timestamp":new Date().toISOString(),"x-inkeep-invocation-type":"chat_widget",...L?{"x-inkeep-app-id":L}:{},...e?{Authorization:`Bearer ${e}`}:{},...Y.current?{"inkeep-filters":Y.current}:{},...Re.current}},prepareSendMessagesRequest:async e=>{const l=await he.current(),s=e.messages[e.messages.length-1];return s||console.warn("[useInkeepChat] prepareSendMessagesRequest called with empty messages array"),{body:{...e.body,id:e.id,messages:s?[s]:[],trigger:e.trigger,messageId:e.messageId,...K.current?{userProperties:K.current}:{},...z.current?{properties:z.current}:{}},headers:{...e.headers,...l}}},body:{requestContext:pe}}),[me,pe,L,U]),{messages:M,sendMessage:j,addToolApprovalResponse:Q,status:ye,setMessages:h,stop:N,error:x}=Xe.useChat({transport:Be,onData(e){k(e.type,e.data)},async onFinish({message:e}){k("completion",{conversationId:u}),await m({eventName:"assistant_message_received",properties:{conversationId:u,messageId:e.id}}),m({eventName:"assistant_answer_displayed",properties:{conversationId:u,messageId:e.id}})},onError(e){console.error("onError",{code:e.code,message:e.message});const l=ke||U?null:r.resolveStreamingAuthError(e);if(l!==null&&A.current<1){A.current++;const i=H.current,n=P.current;(async()=>{if(l==="session"&&oe){const a=await ie();if(!a)throw new Error("Auth token refresh failed");$.current=a}else if(l==="session"){const a=await ue();a&&(G.current=a)}else f();if(i){Q(i);return}n&&(h(a=>{let c=[...a];return c.at(-1)?.role==="assistant"&&(c=c.slice(0,-1)),c.at(-1)?.role==="user"&&(c=c.slice(0,-1)),c}),j({id:n.messageId,parts:[...n.content.trim()?[{type:"text",text:n.content}]:[],...n.files??[]]},{body:n.body}))})().catch(()=>{A.current=0,f(),h(a=>{const c=[...a],g=c[c.length-1];if(!g)return c;const d=r.DEFAULT_ERROR_MESSAGE;return g.role==="user"?c.push({id:O.generateUid(16),role:"assistant",parts:[{type:"text",text:d}]}):g.parts=[{type:"text",text:d}],c})});return}A.current=0,l!==null&&f();const s=r.isRecoverableError(e)||r.isNetworkError(e),o=qe(e);if(m({eventName:"chat_error",properties:{conversationId:u,messageId:M.at(-1)?.id,error:e.message}}),s){const i=o===r.PAYLOAD_TOO_LARGE_MESSAGE?"Message too large":o===r.RATE_LIMIT_MESSAGE?"Rate limit reached":"Request failed";q({title:i,message:o},r.RECOVERABLE_NOTIFICATION_DURATION_MS),h(p=>{let a=[...p];return a.at(-1)?.role==="assistant"&&(a=a.slice(0,-1)),a.at(-1)?.role==="user"&&(a=a.slice(0,-1)),a});const n=P.current?.content;n&&_(n),Z.current=e;return}h(i=>{const n=[...i],p=n[n.length-1];return p&&(p.role==="user"?n.push({id:O.generateUid(16),role:"assistant",parts:[{type:"text",text:o}]}):p.parts=[{type:"text",text:o}]),n})}}),Ae=t.useRef(y);t.useEffect(()=>{const e=Ae.current;Ae.current=y,e!==y&&(N(),b(null),h([]),R(""),_(""),V([]),f())},[y,N,h,R,f]);const Se=ye==="submitted",W=ye==="streaming",De=t.useMemo(()=>{const e=i=>{if(!i||typeof i!="object")return!1;const n=i;return typeof n.type=="string"&&n.type.startsWith("tool-")},s=[...M??[]].reverse().find(i=>i.role==="assistant");if(!s)return!1;const o=s.parts?.at(-1);return!(!e(o)||o.state!=="output-available"||!o.approval?.id||W)},[M,W]),[Ue,J]=t.useState(!1),Ce=W||De&&!Ue,Ie=Se||Ce,Ge=M.length===0,X=!I.trim()&&S.length===0||Ie,$e=rt.useMediaQuery("(max-width: 768px)"),[Ke,b]=t.useState(null),Z=t.useRef(null);t.useEffect(()=>{if(x){if(Z.current===x){Z.current=null;return}b(x)}},[x]);const ze=()=>b(null),{inputNotification:He,showInputNotification:q,clearInputNotification:Ye}=dt.useInputNotification(),_e=t.useRef(null);t.useEffect(()=>{Le?.(I)},[I]);const Ve=e=>{e.key==="Enter"&&!e.shiftKey&&!X&&!e.nativeEvent.isComposing&&(e.preventDefault(),ee())},ee=async(e=I)=>{if(X&&(!e||e.trim().length===0)&&S.length===0||!e.trim()&&!S.length&&!v.current?.length)return;if(r.estimateRequestBodyBytes({text:e,rawFileBytes:S.reduce((g,d)=>g+d.size,0),encodedPartsBytes:(v.current??[]).reduce((g,d)=>g+d.url.length,0)})>r.MAX_REQUEST_BODY_BYTES){q({title:"Message too large",message:r.PAYLOAD_TOO_LARGE_MESSAGE},r.RECOVERABLE_NOTIFICATION_DURATION_MS);return}const s=S;V([]),_(""),A.current=0,H.current=null,J(!1);let o=u;o||(o=`conv_${O.generateUid(16)}`,R(o));const i=O.generateUid(21);we(o),await m({eventName:"user_message_submitted",properties:{conversationId:o,messageId:i}});const n=v.current;v.current=void 0;let p=[];if(s.length>0)try{p=await Promise.all(s.map(g=>{const d=Ze.normalizeFileType(g);return new Promise((Je,be)=>{const w=new FileReader;w.onload=()=>{if(typeof w.result!="string"){be(new Error(`Failed to read file "${d.name}"`));return}Je({type:"file",url:w.result,mediaType:d.type,filename:d.name})},w.onerror=()=>be(new Error(`Failed to read file "${d.name}"`)),w.readAsDataURL(d)})}))}catch{q({title:"Failed to attach files",message:"Could not read one or more files. Please try again."});return}const a=p.length||n?.length?[...p,...n??[]]:void 0,c=[...e.trim()?[{type:"text",text:e}]:[],...a??[]];P.current={content:e,messageId:i,body:{conversationId:o},files:a},j({id:i,parts:c},{body:{conversationId:o}})},je=t.useCallback(e=>{A.current=0,H.current=e,J(!1),Q(e)},[Q]),te=t.useCallback(()=>{J(!0),N().then(()=>{k("aborted",{conversationId:u})})},[N,u,k]),Te=()=>{ze(),h([]),R(""),f(),v.current=T?.length?T:void 0,m({eventName:"chat_clear_button_clicked",properties:{conversationId:u}})},C=t.useCallback((e,l)=>{b(null),h(l),R(e),f(),v.current=void 0},[h,R,f]),Me=t.useCallback(async(e,l)=>{te(),C(e,[]),Ee(!0);try{const s=await ve(e,l);if(s===null)return!1;const i=s[s.length-1]?.role==="user"?[...s,{id:O.generateUid(16),role:"assistant",parts:[{type:"text",text:"This session was interrupted. Please check back in a few minutes or start a new conversation."}]}]:s;return C(e,i),!0}finally{l?.aborted||Ee(!1)}},[C,ve,te]);at.useInitialConversation({conversationId:E.conversationId,fetchedConversation:E.fetchedConversation,effectiveAuthToken:le,restoreSession:C,loadAndRestoreSession:Me,onLoadFailed:()=>C("",[])});const{openForm:Qe}=it.useChatForm(),We=ct.useWidget();return t.useImperativeHandle(E.chatFunctionsRef,()=>({submitMessage:ee,updateInputMessage(e){_(e)},clearChat:Te,openForm:e=>{We?.setView("chat"),Qe(e,void 0)},focusInput:()=>{_e.current?.focus()}})),{messages:M,sendMessage:j,addToolApprovalResponse:je,isLoading:Se,isStreaming:Ce,isBusy:Ie,error:Ke,setError:b,isSubmitDisabled:X,input:I,handleInputChange:Oe,handleInputKeyDown:Ve,handleSubmit:ee,stop:te,clear:Te,inputRef:_e,isMobile:$e,files:S,setFiles:V,isNewChat:Ge,conversationId:u,restoreSession:C,loadAndRestoreSession:Me,isSessionLoading:Ne,authToken:y?ae:ce,refreshSession:y?ie:ue,getCaptchaHeader:F,invalidateCaptcha:f,inputNotification:He,showInputNotification:q,clearInputNotification:Ye}};exports.useInkeepChat=ft;
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Xe=require("@ai-sdk/react"),Ze=require("./file-upload-input.cjs"),et=require("ai"),t=require("react"),tt=require("../../providers/config-provider.cjs"),st=require("../../providers/chat-auth-provider.cjs"),rt=require("../../hooks/use-media-query.cjs"),nt=require("../../hooks/use-conversation-loader.cjs"),at=require("../../hooks/use-initial-conversation.cjs"),O=require("../../utils/generate-uid.cjs"),ot=require("../../providers/base-events-provider.cjs"),it=require("../../providers/chat-form-provider.cjs"),ct=require("../../providers/widget-provider.cjs"),ut=require("@radix-ui/react-use-controllable-state"),lt=require("../../hooks/use-streaming-events.cjs"),dt=require("../../hooks/use-input-notification.cjs"),s=require("./chat-error-helpers.cjs"),ft=()=>{const{baseSettings:se,aiChatSettings:R}=tt.useInkeepConfig(),[u="",v]=ut.useControllableState({prop:R.conversationIdOverride,defaultProp:R.conversationIdOverride??""}),{logEvent:m}=ot.useBaseEvents(),{setConversationId:we,emitToParent:k}=lt.useStreamingEvents(),re=t.useRef(u);t.useEffect(()=>{const e=re.current;re.current=u,e!==u&&m({eventName:"chat_conversation_changed",properties:{conversationId:u,previousConversationId:e}})},[u,m]);const[_,C]=t.useState(""),Oe=e=>C(e.target.value),{shouldBypassCaptcha:ke,filters:ne,userProperties:B,analyticsProperties:D}=se,{authToken:ae,isAuthenticated:S,isAuthConfigured:oe,refreshAuthToken:ie,sessionToken:ce,refreshSession:ue,getCaptchaHeader:F,invalidateCaptcha:f,effectiveAuthToken:le,applicableRefreshSession:Fe}=st.useChatAuth(),{onInputMessageChange:Le,filters:de,baseUrl:fe,agentUrl:Ne,context:pe,headers:ge,appId:L,apiKey:U,files:T}=R,he=t.useRef(F);he.current=F;const me=Ne||`${fe}/run/api/chat`,{loadConversation:Ee}=nt.useConversationLoader({baseUrl:fe,appId:L,authToken:le,getCaptchaHeader:F,invalidateCaptcha:f,refreshSession:Fe}),[Pe,Re]=t.useState(!1),G=t.useRef(null);G.current=ce;const $=t.useRef(null);$.current=ae;const K=t.useRef(void 0);K.current=B&&Object.keys(B).length>0?B:void 0;const H=t.useRef(void 0);H.current=D&&Object.keys(D).length>0?D:void 0;const y=t.useRef(0),N=t.useRef(null),W=t.useRef(null),E=t.useRef(void 0),xe=T?.map(e=>`${e.filename??""}:${e.mediaType}:${e.url.length}:${e.url.slice(0,64)}:${e.url.slice(-32)}`).join(`
2
+ `)??"";t.useEffect(()=>{E.current=T?.length?T:void 0},[xe]);const ve=t.useRef(ge);ve.current=ge;const z=t.useRef(void 0);z.current=ne||de?JSON.stringify({...ne,...de}):void 0;const qe=e=>{if(s.isNetworkError(e))return N.current?.files?.length?s.NETWORK_ERROR_WITH_FILES_MESSAGE:s.NETWORK_ERROR_MESSAGE;switch(s.resolveHttpStatusCode(e)){case 400:try{const r=JSON.parse(e.message??"");return r.detail??r.error?.message??s.RECOVERABLE_FALLBACK_MESSAGE}catch{return e.message?.trim()||s.RECOVERABLE_FALLBACK_MESSAGE}case 401:return oe?"Authentication failed. Please try again.":s.DEFAULT_ERROR_MESSAGE;case 403:return`There seems to be a configuration error. Please contact ${se.organizationDisplayName??"Administrator"}`;case 413:return s.PAYLOAD_TOO_LARGE_MESSAGE;case 429:return s.RATE_LIMIT_MESSAGE;default:return s.DEFAULT_ERROR_MESSAGE}},[A,V]=t.useState([]),Be=t.useMemo(()=>new et.DefaultChatTransport({api:me,headers:()=>{const e=U??$.current??G.current;return{"x-inkeep-client-timezone":Intl.DateTimeFormat().resolvedOptions().timeZone,"x-inkeep-client-timestamp":new Date().toISOString(),"x-inkeep-invocation-type":"chat_widget",...L?{"x-inkeep-app-id":L}:{},...e?{Authorization:`Bearer ${e}`}:{},...z.current?{"inkeep-filters":z.current}:{},...ve.current}},prepareSendMessagesRequest:async e=>{const l=await he.current(),r=e.messages[e.messages.length-1];return r||console.warn("[useInkeepChat] prepareSendMessagesRequest called with empty messages array"),{body:{...e.body,id:e.id,messages:r?[r]:[],trigger:e.trigger,messageId:e.messageId,...K.current?{userProperties:K.current}:{},...H.current?{properties:H.current}:{}},headers:{...e.headers,...l}}},body:{requestContext:pe}}),[me,pe,L,U]),{messages:M,sendMessage:Y,addToolApprovalResponse:j,status:Se,setMessages:h,stop:P,error:x}=Xe.useChat({transport:Be,onData(e){k(e.type,e.data)},async onFinish({message:e}){k("completion",{conversationId:u}),await m({eventName:"assistant_message_received",properties:{conversationId:u,messageId:e.id}}),m({eventName:"assistant_answer_displayed",properties:{conversationId:u,messageId:e.id}})},onError(e){console.error("onError",{code:e.code,message:e.message});const l=ke||U?null:s.resolveStreamingAuthError(e);if(l!==null&&y.current<1){y.current++;const i=W.current,a=N.current;(async()=>{if(l==="session"&&oe){const o=await ie();if(!o)throw new Error("Auth token refresh failed");$.current=o}else if(l==="session"){const o=await ue();o&&(G.current=o)}else f();if(i){j(i);return}a&&(h(o=>{let c=[...o];return c.at(-1)?.role==="assistant"&&(c=c.slice(0,-1)),c.at(-1)?.role==="user"&&(c=c.slice(0,-1)),c}),Y({id:a.messageId,parts:[...a.content.trim()?[{type:"text",text:a.content}]:[],...a.files??[]]},{body:a.body}))})().catch(()=>{y.current=0,f(),h(o=>{const c=[...o],g=c[c.length-1];if(!g)return c;const d=s.DEFAULT_ERROR_MESSAGE;return g.role==="user"?c.push({id:O.generateUid(16),role:"assistant",parts:[{type:"text",text:d}]}):g.parts=[{type:"text",text:d}],c})});return}y.current=0,l!==null&&f();const r=s.isRecoverableError(e)||s.isNetworkError(e),n=qe(e);if(m({eventName:"chat_error",properties:{conversationId:u,messageId:M.at(-1)?.id,error:e.message}}),r){const i=n===s.PAYLOAD_TOO_LARGE_MESSAGE?"Message too large":n===s.RATE_LIMIT_MESSAGE?"Rate limit reached":n===s.NETWORK_ERROR_MESSAGE||n===s.NETWORK_ERROR_WITH_FILES_MESSAGE?"Connection error":"Request failed";q({title:i,message:n},s.RECOVERABLE_NOTIFICATION_DURATION_MS),h(p=>{let o=[...p];return o.at(-1)?.role==="assistant"&&(o=o.slice(0,-1)),o.at(-1)?.role==="user"&&(o=o.slice(0,-1)),o});const a=N.current?.content;a&&C(a),Z.current=e;return}h(i=>{const a=[...i],p=a[a.length-1];return p&&(p.role==="user"?a.push({id:O.generateUid(16),role:"assistant",parts:[{type:"text",text:n}]}):p.parts=[{type:"text",text:n}]),a})}}),ye=t.useRef(S);t.useEffect(()=>{const e=ye.current;ye.current=S,e!==S&&(P(),b(null),h([]),v(""),C(""),V([]),f())},[S,P,h,v,f]);const Ae=Se==="submitted",Q=Se==="streaming",De=t.useMemo(()=>{const e=i=>{if(!i||typeof i!="object")return!1;const a=i;return typeof a.type=="string"&&a.type.startsWith("tool-")},r=[...M??[]].reverse().find(i=>i.role==="assistant");if(!r)return!1;const n=r.parts?.at(-1);return!(!e(n)||n.state!=="output-available"||!n.approval?.id||Q)},[M,Q]),[Ue,J]=t.useState(!1),Ie=Q||De&&!Ue,_e=Ae||Ie,Ge=M.length===0,X=!_.trim()&&A.length===0||_e,$e=rt.useMediaQuery("(max-width: 768px)"),[Ke,b]=t.useState(null),Z=t.useRef(null);t.useEffect(()=>{if(x){if(Z.current===x){Z.current=null;return}b(x)}},[x]);const He=()=>b(null),{inputNotification:We,showInputNotification:q,clearInputNotification:ze}=dt.useInputNotification(),Ce=t.useRef(null);t.useEffect(()=>{Le?.(_)},[_]);const Ve=e=>{e.key==="Enter"&&!e.shiftKey&&!X&&!e.nativeEvent.isComposing&&(e.preventDefault(),ee())},ee=async(e=_)=>{if(X&&(!e||e.trim().length===0)&&A.length===0||!e.trim()&&!A.length&&!E.current?.length)return;if(s.estimateRequestBodyBytes({text:e,rawFileBytes:A.reduce((g,d)=>g+d.size,0),encodedPartsBytes:(E.current??[]).reduce((g,d)=>g+d.url.length,0)})>s.MAX_REQUEST_BODY_BYTES){q({title:"Message too large",message:s.PAYLOAD_TOO_LARGE_MESSAGE},s.RECOVERABLE_NOTIFICATION_DURATION_MS);return}const r=A;V([]),C(""),y.current=0,W.current=null,J(!1);let n=u;n||(n=`conv_${O.generateUid(16)}`,v(n));const i=O.generateUid(21);we(n),await m({eventName:"user_message_submitted",properties:{conversationId:n,messageId:i}});const a=E.current;E.current=void 0;let p=[];if(r.length>0)try{p=await Promise.all(r.map(g=>{const d=Ze.normalizeFileType(g);return new Promise((Je,be)=>{const w=new FileReader;w.onload=()=>{if(typeof w.result!="string"){be(new Error(`Failed to read file "${d.name}"`));return}Je({type:"file",url:w.result,mediaType:d.type,filename:d.name})},w.onerror=()=>be(new Error(`Failed to read file "${d.name}"`)),w.readAsDataURL(d)})}))}catch{q({title:"Failed to attach files",message:"Could not read one or more files. Please try again."});return}const o=p.length||a?.length?[...p,...a??[]]:void 0,c=[...e.trim()?[{type:"text",text:e}]:[],...o??[]];N.current={content:e,messageId:i,body:{conversationId:n},files:o},Y({id:i,parts:c},{body:{conversationId:n}})},Ye=t.useCallback(e=>{y.current=0,W.current=e,J(!1),j(e)},[j]),te=t.useCallback(()=>{J(!0),P().then(()=>{k("aborted",{conversationId:u})})},[P,u,k]),Te=()=>{He(),h([]),v(""),f(),E.current=T?.length?T:void 0,m({eventName:"chat_clear_button_clicked",properties:{conversationId:u}})},I=t.useCallback((e,l)=>{b(null),h(l),v(e),f(),E.current=void 0},[h,v,f]),Me=t.useCallback(async(e,l)=>{te(),I(e,[]),Re(!0);try{const r=await Ee(e,l);if(r===null)return!1;const i=r[r.length-1]?.role==="user"?[...r,{id:O.generateUid(16),role:"assistant",parts:[{type:"text",text:"This session was interrupted. Please check back in a few minutes or start a new conversation."}]}]:r;return I(e,i),!0}finally{l?.aborted||Re(!1)}},[I,Ee,te]);at.useInitialConversation({conversationId:R.conversationId,fetchedConversation:R.fetchedConversation,effectiveAuthToken:le,restoreSession:I,loadAndRestoreSession:Me,onLoadFailed:()=>I("",[])});const{openForm:je}=it.useChatForm(),Qe=ct.useWidget();return t.useImperativeHandle(R.chatFunctionsRef,()=>({submitMessage:ee,updateInputMessage(e){C(e)},clearChat:Te,openForm:e=>{Qe?.setView("chat"),je(e,void 0)},focusInput:()=>{Ce.current?.focus()}})),{messages:M,sendMessage:Y,addToolApprovalResponse:Ye,isLoading:Ae,isStreaming:Ie,isBusy:_e,error:Ke,setError:b,isSubmitDisabled:X,input:_,handleInputChange:Oe,handleInputKeyDown:Ve,handleSubmit:ee,stop:te,clear:Te,inputRef:Ce,isMobile:$e,files:A,setFiles:V,isNewChat:Ge,conversationId:u,restoreSession:I,loadAndRestoreSession:Me,isSessionLoading:Pe,authToken:S?ae:ce,refreshSession:S?ie:ue,getCaptchaHeader:F,invalidateCaptcha:f,inputNotification:We,showInputNotification:q,clearInputNotification:ze}};exports.useInkeepChat=ft;
@@ -1,26 +1,26 @@
1
1
  "use client";
2
- import { useChat as it } from "@ai-sdk/react";
3
- import { normalizeFileType as ct } from "./file-upload-input.js";
4
- import { DefaultChatTransport as lt } from "ai";
5
- import { useRef as i, useEffect as _, useState as k, useMemo as Oe, useCallback as $, useImperativeHandle as ut } from "react";
6
- import { useInkeepConfig as dt } from "../../providers/config-provider.js";
7
- import { useChatAuth as pt } from "../../providers/chat-auth-provider.js";
8
- import { useMediaQuery as ft } from "../../hooks/use-media-query.js";
9
- import { useConversationLoader as mt } from "../../hooks/use-conversation-loader.js";
10
- import { useInitialConversation as gt } from "../../hooks/use-initial-conversation.js";
2
+ import { useChat as lt } from "@ai-sdk/react";
3
+ import { normalizeFileType as ut } from "./file-upload-input.js";
4
+ import { DefaultChatTransport as dt } from "ai";
5
+ import { useRef as i, useEffect as _, useState as k, useMemo as Oe, useCallback as $, useImperativeHandle as pt } from "react";
6
+ import { useInkeepConfig as ft } from "../../providers/config-provider.js";
7
+ import { useChatAuth as mt } from "../../providers/chat-auth-provider.js";
8
+ import { useMediaQuery as gt } from "../../hooks/use-media-query.js";
9
+ import { useConversationLoader as ht } from "../../hooks/use-conversation-loader.js";
10
+ import { useInitialConversation as vt } from "../../hooks/use-initial-conversation.js";
11
11
  import { generateUid as F } from "../../utils/generate-uid.js";
12
- import { useBaseEvents as ht } from "../../providers/base-events-provider.js";
13
- import { useChatForm as vt } from "../../providers/chat-form-provider.js";
14
- import { useWidget as yt } from "../../providers/widget-provider.js";
15
- import { useControllableState as Rt } from "@radix-ui/react-use-controllable-state";
16
- import { useStreamingEvents as It } from "../../hooks/use-streaming-events.js";
12
+ import { useBaseEvents as yt } from "../../providers/base-events-provider.js";
13
+ import { useChatForm as Rt } from "../../providers/chat-form-provider.js";
14
+ import { useWidget as Et } from "../../providers/widget-provider.js";
15
+ import { useControllableState as It } from "@radix-ui/react-use-controllable-state";
16
+ import { useStreamingEvents as St } from "../../hooks/use-streaming-events.js";
17
17
  import { useInputNotification as Ct } from "../../hooks/use-input-notification.js";
18
- import { resolveStreamingAuthError as Et, DEFAULT_ERROR_MESSAGE as oe, isRecoverableError as St, isNetworkError as Ne, RECOVERABLE_NOTIFICATION_DURATION_MS as Pe, PAYLOAD_TOO_LARGE_MESSAGE as U, RATE_LIMIT_MESSAGE as Be, NETWORK_ERROR_MESSAGE as At, resolveHttpStatusCode as wt, RECOVERABLE_FALLBACK_MESSAGE as De, estimateRequestBodyBytes as Tt, MAX_REQUEST_BODY_BYTES as bt } from "./chat-error-helpers.js";
19
- const Ht = () => {
20
- const { baseSettings: ae, aiChatSettings: v } = dt(), [c = "", y] = Rt({
18
+ import { resolveStreamingAuthError as At, DEFAULT_ERROR_MESSAGE as ne, isRecoverableError as Tt, isNetworkError as Ne, RECOVERABLE_NOTIFICATION_DURATION_MS as Pe, PAYLOAD_TOO_LARGE_MESSAGE as oe, RATE_LIMIT_MESSAGE as Be, NETWORK_ERROR_MESSAGE as De, NETWORK_ERROR_WITH_FILES_MESSAGE as Le, resolveHttpStatusCode as wt, RECOVERABLE_FALLBACK_MESSAGE as $e, estimateRequestBodyBytes as bt, MAX_REQUEST_BODY_BYTES as Mt } from "./chat-error-helpers.js";
19
+ const Wt = () => {
20
+ const { baseSettings: ae, aiChatSettings: v } = ft(), [c = "", y] = It({
21
21
  prop: v.conversationIdOverride,
22
22
  defaultProp: v.conversationIdOverride ?? ""
23
- }), { logEvent: g } = ht(), { setConversationId: Le, emitToParent: x } = It(), ie = i(c);
23
+ }), { logEvent: g } = yt(), { setConversationId: Ue, emitToParent: x } = St(), ie = i(c);
24
24
  _(() => {
25
25
  const e = ie.current;
26
26
  ie.current = c, e !== c && g({
@@ -31,10 +31,10 @@ const Ht = () => {
31
31
  }
32
32
  });
33
33
  }, [c, g]);
34
- const [S, A] = k(""), $e = (e) => A(e.target.value), {
35
- shouldBypassCaptcha: Ue,
34
+ const [C, A] = k(""), Ge = (e) => A(e.target.value), {
35
+ shouldBypassCaptcha: Ke,
36
36
  filters: ce,
37
- userProperties: z,
37
+ userProperties: U,
38
38
  analyticsProperties: G
39
39
  } = ae, {
40
40
  authToken: le,
@@ -47,79 +47,79 @@ const Ht = () => {
47
47
  invalidateCaptcha: d,
48
48
  effectiveAuthToken: me,
49
49
  applicableRefreshSession: ze
50
- } = pt(), {
51
- onInputMessageChange: Ge,
50
+ } = mt(), {
51
+ onInputMessageChange: He,
52
52
  filters: ge,
53
53
  baseUrl: he,
54
- agentUrl: Ke,
54
+ agentUrl: qe,
55
55
  context: ve,
56
56
  headers: ye,
57
57
  appId: N,
58
58
  apiKey: K,
59
- files: w
59
+ files: T
60
60
  } = v, Re = i(O);
61
61
  Re.current = O;
62
- const Ie = Ke || `${he}/run/api/chat`, { loadConversation: Ce } = mt({
62
+ const Ee = qe || `${he}/run/api/chat`, { loadConversation: Ie } = ht({
63
63
  baseUrl: he,
64
64
  appId: N,
65
65
  authToken: me,
66
66
  getCaptchaHeader: O,
67
67
  invalidateCaptcha: d,
68
68
  refreshSession: ze
69
- }), [qe, Ee] = k(!1), q = i(null);
70
- q.current = pe;
69
+ }), [We, Se] = k(!1), z = i(null);
70
+ z.current = pe;
71
71
  const H = i(null);
72
72
  H.current = le;
73
- const j = i(void 0);
74
- j.current = z && Object.keys(z).length > 0 ? z : void 0;
75
- const V = i(void 0);
76
- V.current = G && Object.keys(G).length > 0 ? G : void 0;
77
- const I = i(0), P = i(null), W = i(null), h = i(void 0), He = w?.map(
73
+ const q = i(void 0);
74
+ q.current = U && Object.keys(U).length > 0 ? U : void 0;
75
+ const W = i(void 0);
76
+ W.current = G && Object.keys(G).length > 0 ? G : void 0;
77
+ const E = i(0), P = i(null), j = i(null), h = i(void 0), je = T?.map(
78
78
  (e) => `${e.filename ?? ""}:${e.mediaType}:${e.url.length}:${e.url.slice(0, 64)}:${e.url.slice(-32)}`
79
79
  ).join(`
80
80
  `) ?? "";
81
81
  _(() => {
82
- h.current = w?.length ? w : void 0;
83
- }, [He]);
84
- const Se = i(ye);
85
- Se.current = ye;
86
- const Y = i(void 0);
87
- Y.current = ce || ge ? JSON.stringify({ ...ce, ...ge }) : void 0;
88
- const je = (e) => {
82
+ h.current = T?.length ? T : void 0;
83
+ }, [je]);
84
+ const Ce = i(ye);
85
+ Ce.current = ye;
86
+ const V = i(void 0);
87
+ V.current = ce || ge ? JSON.stringify({ ...ce, ...ge }) : void 0;
88
+ const Ve = (e) => {
89
89
  if (Ne(e))
90
- return P.current?.files?.length ? U : At;
90
+ return P.current?.files?.length ? Le : De;
91
91
  switch (wt(e)) {
92
92
  case 400:
93
93
  try {
94
94
  const t = JSON.parse(e.message ?? "");
95
- return t.detail ?? t.error?.message ?? De;
95
+ return t.detail ?? t.error?.message ?? $e;
96
96
  } catch {
97
- return e.message?.trim() || De;
97
+ return e.message?.trim() || $e;
98
98
  }
99
99
  case 401:
100
- return ue ? "Authentication failed. Please try again." : oe;
100
+ return ue ? "Authentication failed. Please try again." : ne;
101
101
  case 403:
102
102
  return `There seems to be a configuration error. Please contact ${ae.organizationDisplayName ?? "Administrator"}`;
103
103
  case 413:
104
- return U;
104
+ return oe;
105
105
  case 429:
106
106
  return Be;
107
107
  default:
108
- return oe;
108
+ return ne;
109
109
  }
110
- }, [C, J] = k([]), Ve = Oe(
111
- () => new lt({
112
- api: Ie,
110
+ }, [I, Y] = k([]), Ye = Oe(
111
+ () => new dt({
112
+ api: Ee,
113
113
  headers: () => {
114
- const e = K ?? H.current ?? q.current;
114
+ const e = K ?? H.current ?? z.current;
115
115
  return {
116
116
  "x-inkeep-client-timezone": Intl.DateTimeFormat().resolvedOptions().timeZone,
117
117
  "x-inkeep-client-timestamp": (/* @__PURE__ */ new Date()).toISOString(),
118
118
  "x-inkeep-invocation-type": "chat_widget",
119
119
  ...N ? { "x-inkeep-app-id": N } : {},
120
120
  ...e ? { Authorization: `Bearer ${e}` } : {},
121
- ...Y.current ? { "inkeep-filters": Y.current } : {},
122
- ...Se.current
121
+ ...V.current ? { "inkeep-filters": V.current } : {},
122
+ ...Ce.current
123
123
  };
124
124
  },
125
125
  prepareSendMessagesRequest: async (e) => {
@@ -133,8 +133,8 @@ const Ht = () => {
133
133
  messages: t ? [t] : [],
134
134
  trigger: e.trigger,
135
135
  messageId: e.messageId,
136
- ...j.current ? { userProperties: j.current } : {},
137
- ...V.current ? { properties: V.current } : {}
136
+ ...q.current ? { userProperties: q.current } : {},
137
+ ...W.current ? { properties: W.current } : {}
138
138
  },
139
139
  headers: {
140
140
  ...e.headers,
@@ -146,17 +146,17 @@ const Ht = () => {
146
146
  requestContext: ve
147
147
  }
148
148
  }),
149
- [Ie, ve, N, K]
149
+ [Ee, ve, N, K]
150
150
  ), {
151
- messages: T,
152
- sendMessage: Q,
153
- addToolApprovalResponse: X,
151
+ messages: w,
152
+ sendMessage: J,
153
+ addToolApprovalResponse: Q,
154
154
  status: Ae,
155
155
  setMessages: m,
156
156
  stop: B,
157
157
  error: D
158
- } = it({
159
- transport: Ve,
158
+ } = lt({
159
+ transport: Ye,
160
160
  onData(e) {
161
161
  x(e.type, e.data);
162
162
  },
@@ -177,42 +177,42 @@ const Ht = () => {
177
177
  },
178
178
  onError(e) {
179
179
  console.error("onError", { code: e.code, message: e.message });
180
- const l = Ue || K ? null : Et(e);
181
- if (l !== null && I.current < 1) {
182
- I.current++;
183
- const o = W.current, s = P.current;
180
+ const l = Ke || K ? null : At(e);
181
+ if (l !== null && E.current < 1) {
182
+ E.current++;
183
+ const o = j.current, r = P.current;
184
184
  (async () => {
185
185
  if (l === "session" && ue) {
186
- const r = await de();
187
- if (!r) throw new Error("Auth token refresh failed");
188
- H.current = r;
186
+ const n = await de();
187
+ if (!n) throw new Error("Auth token refresh failed");
188
+ H.current = n;
189
189
  } else if (l === "session") {
190
- const r = await fe();
191
- r && (q.current = r);
190
+ const n = await fe();
191
+ n && (z.current = n);
192
192
  } else
193
193
  d();
194
194
  if (o) {
195
- X(o);
195
+ Q(o);
196
196
  return;
197
197
  }
198
- s && (m((r) => {
199
- let a = [...r];
198
+ r && (m((n) => {
199
+ let a = [...n];
200
200
  return a.at(-1)?.role === "assistant" && (a = a.slice(0, -1)), a.at(-1)?.role === "user" && (a = a.slice(0, -1)), a;
201
- }), Q(
201
+ }), J(
202
202
  {
203
- id: s.messageId,
203
+ id: r.messageId,
204
204
  parts: [
205
- ...s.content.trim() ? [{ type: "text", text: s.content }] : [],
206
- ...s.files ?? []
205
+ ...r.content.trim() ? [{ type: "text", text: r.content }] : [],
206
+ ...r.files ?? []
207
207
  ]
208
208
  },
209
- { body: s.body }
209
+ { body: r.body }
210
210
  ));
211
211
  })().catch(() => {
212
- I.current = 0, d(), m((r) => {
213
- const a = [...r], f = a[a.length - 1];
212
+ E.current = 0, d(), m((n) => {
213
+ const a = [...n], f = a[a.length - 1];
214
214
  if (!f) return a;
215
- const u = oe;
215
+ const u = ne;
216
216
  return f.role === "user" ? a.push({
217
217
  id: F(16),
218
218
  role: "assistant",
@@ -222,111 +222,111 @@ const Ht = () => {
222
222
  });
223
223
  return;
224
224
  }
225
- I.current = 0, l !== null && d();
226
- const t = St(e) || Ne(e), n = je(e);
225
+ E.current = 0, l !== null && d();
226
+ const t = Tt(e) || Ne(e), s = Ve(e);
227
227
  if (g({
228
228
  eventName: "chat_error",
229
229
  properties: {
230
230
  conversationId: c,
231
- messageId: T.at(-1)?.id,
231
+ messageId: w.at(-1)?.id,
232
232
  error: e.message
233
233
  }
234
234
  }), t) {
235
235
  L(
236
- { title: n === U ? "Message too large" : n === Be ? "Rate limit reached" : "Request failed", message: n },
236
+ { title: s === oe ? "Message too large" : s === Be ? "Rate limit reached" : s === De || s === Le ? "Connection error" : "Request failed", message: s },
237
237
  Pe
238
238
  ), m((p) => {
239
- let r = [...p];
240
- return r.at(-1)?.role === "assistant" && (r = r.slice(0, -1)), r.at(-1)?.role === "user" && (r = r.slice(0, -1)), r;
239
+ let n = [...p];
240
+ return n.at(-1)?.role === "assistant" && (n = n.slice(0, -1)), n.at(-1)?.role === "user" && (n = n.slice(0, -1)), n;
241
241
  });
242
- const s = P.current?.content;
243
- s && A(s), se.current = e;
242
+ const r = P.current?.content;
243
+ r && A(r), te.current = e;
244
244
  return;
245
245
  }
246
246
  m((o) => {
247
- const s = [...o], p = s[s.length - 1];
248
- return p && (p.role === "user" ? s.push({
247
+ const r = [...o], p = r[r.length - 1];
248
+ return p && (p.role === "user" ? r.push({
249
249
  id: F(16),
250
250
  role: "assistant",
251
- parts: [{ type: "text", text: n }]
252
- }) : p.parts = [{ type: "text", text: n }]), s;
251
+ parts: [{ type: "text", text: s }]
252
+ }) : p.parts = [{ type: "text", text: s }]), r;
253
253
  });
254
254
  }
255
- }), we = i(R);
255
+ }), Te = i(R);
256
256
  _(() => {
257
- const e = we.current;
258
- we.current = R, e !== R && (B(), b(null), m([]), y(""), A(""), J([]), d());
257
+ const e = Te.current;
258
+ Te.current = R, e !== R && (B(), b(null), m([]), y(""), A(""), Y([]), d());
259
259
  }, [R, B, m, y, d]);
260
- const Te = Ae === "submitted", Z = Ae === "streaming", We = Oe(() => {
260
+ const we = Ae === "submitted", X = Ae === "streaming", Je = Oe(() => {
261
261
  const e = (o) => {
262
262
  if (!o || typeof o != "object") return !1;
263
- const s = o;
264
- return typeof s.type == "string" && s.type.startsWith("tool-");
265
- }, t = [...T ?? []].reverse().find((o) => o.role === "assistant");
263
+ const r = o;
264
+ return typeof r.type == "string" && r.type.startsWith("tool-");
265
+ }, t = [...w ?? []].reverse().find((o) => o.role === "assistant");
266
266
  if (!t) return !1;
267
- const n = t.parts?.at(-1);
268
- return !(!e(n) || n.state !== "output-available" || !n.approval?.id || Z);
269
- }, [T, Z]), [Ye, ee] = k(!1), be = Z || We && !Ye, Me = Te || be, Je = T.length === 0, te = !S.trim() && C.length === 0 || Me, Qe = ft("(max-width: 768px)"), [Xe, b] = k(null), se = i(null);
267
+ const s = t.parts?.at(-1);
268
+ return !(!e(s) || s.state !== "output-available" || !s.approval?.id || X);
269
+ }, [w, X]), [Qe, Z] = k(!1), be = X || Je && !Qe, Me = we || be, Xe = w.length === 0, ee = !C.trim() && I.length === 0 || Me, Ze = gt("(max-width: 768px)"), [et, b] = k(null), te = i(null);
270
270
  _(() => {
271
271
  if (D) {
272
- if (se.current === D) {
273
- se.current = null;
272
+ if (te.current === D) {
273
+ te.current = null;
274
274
  return;
275
275
  }
276
276
  b(D);
277
277
  }
278
278
  }, [D]);
279
- const Ze = () => b(null), { inputNotification: et, showInputNotification: L, clearInputNotification: tt } = Ct(), _e = i(null);
279
+ const tt = () => b(null), { inputNotification: st, showInputNotification: L, clearInputNotification: rt } = Ct(), _e = i(null);
280
280
  _(() => {
281
- Ge?.(S);
282
- }, [S]);
283
- const st = (e) => {
284
- e.key === "Enter" && !e.shiftKey && !te && !e.nativeEvent.isComposing && (e.preventDefault(), re());
285
- }, re = async (e = S) => {
286
- if (te && (!e || e.trim().length === 0) && C.length === 0 || !e.trim() && !C.length && !h.current?.length)
281
+ He?.(C);
282
+ }, [C]);
283
+ const nt = (e) => {
284
+ e.key === "Enter" && !e.shiftKey && !ee && !e.nativeEvent.isComposing && (e.preventDefault(), se());
285
+ }, se = async (e = C) => {
286
+ if (ee && (!e || e.trim().length === 0) && I.length === 0 || !e.trim() && !I.length && !h.current?.length)
287
287
  return;
288
- if (Tt({
288
+ if (bt({
289
289
  text: e,
290
- rawFileBytes: C.reduce((f, u) => f + u.size, 0),
290
+ rawFileBytes: I.reduce((f, u) => f + u.size, 0),
291
291
  encodedPartsBytes: (h.current ?? []).reduce(
292
292
  (f, u) => f + u.url.length,
293
293
  0
294
294
  )
295
- }) > bt) {
295
+ }) > Mt) {
296
296
  L(
297
- { title: "Message too large", message: U },
297
+ { title: "Message too large", message: oe },
298
298
  Pe
299
299
  );
300
300
  return;
301
301
  }
302
- const t = C;
303
- J([]), A(""), I.current = 0, W.current = null, ee(!1);
304
- let n = c;
305
- n || (n = `conv_${F(16)}`, y(n));
302
+ const t = I;
303
+ Y([]), A(""), E.current = 0, j.current = null, Z(!1);
304
+ let s = c;
305
+ s || (s = `conv_${F(16)}`, y(s));
306
306
  const o = F(21);
307
- Le(n), await g({
307
+ Ue(s), await g({
308
308
  eventName: "user_message_submitted",
309
309
  properties: {
310
- conversationId: n,
310
+ conversationId: s,
311
311
  messageId: o
312
312
  }
313
313
  });
314
- const s = h.current;
314
+ const r = h.current;
315
315
  h.current = void 0;
316
316
  let p = [];
317
317
  if (t.length > 0)
318
318
  try {
319
319
  p = await Promise.all(
320
320
  t.map((f) => {
321
- const u = ct(f);
322
- return new Promise((at, xe) => {
321
+ const u = ut(f);
322
+ return new Promise((ct, xe) => {
323
323
  const M = new FileReader();
324
324
  M.onload = () => {
325
325
  if (typeof M.result != "string") {
326
326
  xe(new Error(`Failed to read file "${u.name}"`));
327
327
  return;
328
328
  }
329
- at({
329
+ ct({
330
330
  type: "file",
331
331
  url: M.result,
332
332
  mediaType: u.type,
@@ -343,42 +343,42 @@ const Ht = () => {
343
343
  });
344
344
  return;
345
345
  }
346
- const r = p.length || s?.length ? [...p, ...s ?? []] : void 0, a = [
346
+ const n = p.length || r?.length ? [...p, ...r ?? []] : void 0, a = [
347
347
  ...e.trim() ? [{ type: "text", text: e }] : [],
348
- ...r ?? []
348
+ ...n ?? []
349
349
  ];
350
350
  P.current = {
351
351
  content: e,
352
352
  messageId: o,
353
- body: { conversationId: n },
354
- files: r
355
- }, Q({ id: o, parts: a }, { body: { conversationId: n } });
356
- }, rt = $(
353
+ body: { conversationId: s },
354
+ files: n
355
+ }, J({ id: o, parts: a }, { body: { conversationId: s } });
356
+ }, ot = $(
357
357
  (e) => {
358
- I.current = 0, W.current = e, ee(!1), X(e);
358
+ E.current = 0, j.current = e, Z(!1), Q(e);
359
359
  },
360
- [X]
361
- ), ne = $(() => {
362
- ee(!0), B().then(() => {
360
+ [Q]
361
+ ), re = $(() => {
362
+ Z(!0), B().then(() => {
363
363
  x("aborted", { conversationId: c });
364
364
  });
365
365
  }, [B, c, x]), ke = () => {
366
- Ze(), m([]), y(""), d(), h.current = w?.length ? w : void 0, g({
366
+ tt(), m([]), y(""), d(), h.current = T?.length ? T : void 0, g({
367
367
  eventName: "chat_clear_button_clicked",
368
368
  properties: {
369
369
  conversationId: c
370
370
  }
371
371
  });
372
- }, E = $(
372
+ }, S = $(
373
373
  (e, l) => {
374
374
  b(null), m(l), y(e), d(), h.current = void 0;
375
375
  },
376
376
  [m, y, d]
377
377
  ), Fe = $(
378
378
  async (e, l) => {
379
- ne(), E(e, []), Ee(!0);
379
+ re(), S(e, []), Se(!0);
380
380
  try {
381
- const t = await Ce(e, l);
381
+ const t = await Ie(e, l);
382
382
  if (t === null) return !1;
383
383
  const o = t[t.length - 1]?.role === "user" ? [
384
384
  ...t,
@@ -393,68 +393,68 @@ const Ht = () => {
393
393
  ]
394
394
  }
395
395
  ] : t;
396
- return E(e, o), !0;
396
+ return S(e, o), !0;
397
397
  } finally {
398
- l?.aborted || Ee(!1);
398
+ l?.aborted || Se(!1);
399
399
  }
400
400
  },
401
- [E, Ce, ne]
401
+ [S, Ie, re]
402
402
  );
403
- gt({
403
+ vt({
404
404
  conversationId: v.conversationId,
405
405
  fetchedConversation: v.fetchedConversation,
406
406
  effectiveAuthToken: me,
407
- restoreSession: E,
407
+ restoreSession: S,
408
408
  loadAndRestoreSession: Fe,
409
- onLoadFailed: () => E("", [])
409
+ onLoadFailed: () => S("", [])
410
410
  });
411
- const { openForm: nt } = vt(), ot = yt();
412
- return ut(v.chatFunctionsRef, () => ({
413
- submitMessage: re,
411
+ const { openForm: at } = Rt(), it = Et();
412
+ return pt(v.chatFunctionsRef, () => ({
413
+ submitMessage: se,
414
414
  updateInputMessage(e) {
415
415
  A(e);
416
416
  },
417
417
  clearChat: ke,
418
418
  openForm: (e) => {
419
- ot?.setView("chat"), nt(e, void 0);
419
+ it?.setView("chat"), at(e, void 0);
420
420
  },
421
421
  focusInput: () => {
422
422
  _e.current?.focus();
423
423
  }
424
424
  })), {
425
- messages: T,
426
- sendMessage: Q,
427
- addToolApprovalResponse: rt,
428
- isLoading: Te,
425
+ messages: w,
426
+ sendMessage: J,
427
+ addToolApprovalResponse: ot,
428
+ isLoading: we,
429
429
  isStreaming: be,
430
430
  isBusy: Me,
431
- error: Xe,
431
+ error: et,
432
432
  setError: b,
433
- isSubmitDisabled: te,
434
- input: S,
435
- handleInputChange: $e,
436
- handleInputKeyDown: st,
437
- handleSubmit: re,
438
- stop: ne,
433
+ isSubmitDisabled: ee,
434
+ input: C,
435
+ handleInputChange: Ge,
436
+ handleInputKeyDown: nt,
437
+ handleSubmit: se,
438
+ stop: re,
439
439
  clear: ke,
440
440
  inputRef: _e,
441
- isMobile: Qe,
442
- files: C,
443
- setFiles: J,
444
- isNewChat: Je,
441
+ isMobile: Ze,
442
+ files: I,
443
+ setFiles: Y,
444
+ isNewChat: Xe,
445
445
  conversationId: c,
446
- restoreSession: E,
446
+ restoreSession: S,
447
447
  loadAndRestoreSession: Fe,
448
- isSessionLoading: qe,
448
+ isSessionLoading: We,
449
449
  authToken: R ? le : pe,
450
450
  refreshSession: R ? de : fe,
451
451
  getCaptchaHeader: O,
452
452
  invalidateCaptcha: d,
453
- inputNotification: et,
453
+ inputNotification: st,
454
454
  showInputNotification: L,
455
- clearInputNotification: tt
455
+ clearInputNotification: rt
456
456
  };
457
457
  };
458
458
  export {
459
- Ht as useInkeepChat
459
+ Wt as useInkeepChat
460
460
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inkeep/agents-ui",
3
- "version": "0.0.0-dev-20260721222136",
3
+ "version": "0.0.0-dev-20260721224224",
4
4
  "description": "",
5
5
  "homepage": "",
6
6
  "repository": {