@inkeep/agents-ui 0.0.0-dev-20260721212136 → 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"),k=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"),a=require("./chat-error-helpers.cjs"),ft=()=>{const{baseSettings:se,aiChatSettings:R}=tt.useInkeepConfig(),[u="",E]=ut.useControllableState({prop:R.conversationIdOverride,defaultProp:R.conversationIdOverride??""}),{logEvent:m}=ot.useBaseEvents(),{setConversationId:we,emitToParent:O}=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(""),ke=e=>_(e.target.value),{shouldBypassCaptcha:Oe,filters:ne,userProperties:B,analyticsProperties:D}=se,{authToken:ae,isAuthenticated:y,isAuthConfigured:oe,refreshAuthToken:ie,sessionToken:ce,refreshSession:ue,getCaptchaHeader:F,invalidateCaptcha:p,effectiveAuthToken:le,applicableRefreshSession:Fe}=st.useChatAuth(),{onInputMessageChange:Pe,filters:de,baseUrl:fe,agentUrl:Le,context:pe,headers:ge,appId:P,apiKey:U,files:T}=R,he=t.useRef(F);he.current=F;const me=Le||`${fe}/run/api/chat`,{loadConversation:ve}=nt.useConversationLoader({baseUrl:fe,appId:P,authToken:le,getCaptchaHeader:F,invalidateCaptcha:p,refreshSession:Fe}),[Ne,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 z=t.useRef(void 0);z.current=D&&Object.keys(D).length>0?D:void 0;const S=t.useRef(0),L=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 Ee=t.useRef(ge);Ee.current=ge;const V=t.useRef(void 0);V.current=ne||de?JSON.stringify({...ne,...de}):void 0;const qe=e=>{if(a.isNetworkError(e))return L.current?.files?.length?a.PAYLOAD_TOO_LARGE_MESSAGE:a.NETWORK_ERROR_MESSAGE;switch(a.resolveHttpStatusCode(e)){case 400:try{const s=JSON.parse(e.message??"");return s.detail??s.error?.message??a.RECOVERABLE_FALLBACK_MESSAGE}catch{return e.message?.trim()||a.RECOVERABLE_FALLBACK_MESSAGE}case 401:return oe?"Authentication failed. Please try again.":a.DEFAULT_ERROR_MESSAGE;case 403:return`There seems to be a configuration error. Please contact ${se.organizationDisplayName??"Administrator"}`;case 413:return a.PAYLOAD_TOO_LARGE_MESSAGE;case 429:return a.RATE_LIMIT_MESSAGE;default:return a.DEFAULT_ERROR_MESSAGE}},[A,Y]=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",...P?{"x-inkeep-app-id":P}:{},...e?{Authorization:`Bearer ${e}`}:{},...V.current?{"inkeep-filters":V.current}:{},...Ee.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,P,U]),{messages:b,sendMessage:j,addToolApprovalResponse:Q,status:ye,setMessages:h,stop:N,error:x}=Xe.useChat({transport:Be,onData(e){O(e.type,e.data)},async onFinish({message:e}){O("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=Oe||U?null:a.resolveStreamingAuthError(e);if(l!==null&&S.current<1){S.current++;const r=H.current,n=L.current;(async()=>{if(l==="session"&&oe){const d=await ie();if(!d)throw new Error("Auth token refresh failed");$.current=d}else if(l==="session"){const d=await ue();d&&(G.current=d)}else p();if(r){Q(r);return}n&&(h(d=>{let c=[...d];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(()=>{S.current=0,p(),h(d=>{const c=[...d],g=c[c.length-1];if(!g)return c;const f=a.DEFAULT_ERROR_MESSAGE;return g.role==="user"?c.push({id:k.generateUid(16),role:"assistant",parts:[{type:"text",text:f}]}):g.parts=[{type:"text",text:f}],c})});return}S.current=0,l!==null&&p();const s=a.isRecoverableError(e)||a.isNetworkError(e),o=qe(e);if(m({eventName:"chat_error",properties:{conversationId:u,messageId:b.at(-1)?.id,error:e.message}}),s){q({title:"Request failed",message:o},a.RECOVERABLE_NOTIFICATION_DURATION_MS),h(n=>{let i=[...n];return i.at(-1)?.role==="assistant"&&(i=i.slice(0,-1)),i.at(-1)?.role==="user"&&(i=i.slice(0,-1)),i});const r=L.current?.content;r&&_(r),Z.current=e;return}h(r=>{const n=[...r],i=n[n.length-1];return i&&(i.role==="user"?n.push({id:k.generateUid(16),role:"assistant",parts:[{type:"text",text:o}]}):i.parts=[{type:"text",text:o}]),n})}}),Se=t.useRef(y);t.useEffect(()=>{const e=Se.current;Se.current=y,e!==y&&(N(),M(null),h([]),E(""),_(""),Y([]),p())},[y,N,h,E,p]);const Ae=ye==="submitted",W=ye==="streaming",De=t.useMemo(()=>{const e=r=>{if(!r||typeof r!="object")return!1;const n=r;return typeof n.type=="string"&&n.type.startsWith("tool-")},s=[...b??[]].reverse().find(r=>r.role==="assistant");if(!s)return!1;const o=s.parts?.at(-1);return!(!e(o)||o.state!=="output-available"||!o.approval?.id||W)},[b,W]),[Ue,J]=t.useState(!1),Ce=W||De&&!Ue,Ie=Ae||Ce,Ge=b.length===0,X=!I.trim()&&A.length===0||Ie,$e=rt.useMediaQuery("(max-width: 768px)"),[Ke,M]=t.useState(null),Z=t.useRef(null);t.useEffect(()=>{if(x){if(Z.current===x){Z.current=null;return}M(x)}},[x]);const ze=()=>M(null),{inputNotification:He,showInputNotification:q,clearInputNotification:Ve}=dt.useInputNotification(),_e=t.useRef(null);t.useEffect(()=>{Pe?.(I)},[I]);const Ye=e=>{e.key==="Enter"&&!e.shiftKey&&!X&&!e.nativeEvent.isComposing&&(e.preventDefault(),ee())},ee=async(e=I)=>{if(X&&(!e||e.trim().length===0)&&A.length===0||!e.trim()&&!A.length&&!v.current?.length)return;if(a.estimateRequestBodyBytes({text:e,rawFileBytes:A.reduce((g,f)=>g+f.size,0),encodedPartsBytes:(v.current??[]).reduce((g,f)=>g+f.url.length,0)})>a.MAX_REQUEST_BODY_BYTES){q({title:"Message too large",message:a.PAYLOAD_TOO_LARGE_MESSAGE},a.RECOVERABLE_NOTIFICATION_DURATION_MS);return}const s=A;Y([]),_(""),S.current=0,H.current=null,J(!1);let o=u;o||(o=`conv_${k.generateUid(16)}`,E(o));const r=k.generateUid(21);we(o),await m({eventName:"user_message_submitted",properties:{conversationId:o,messageId:r}});const n=v.current;v.current=void 0;let i=[];if(s.length>0)try{i=await Promise.all(s.map(g=>{const f=Ze.normalizeFileType(g);return new Promise((Je,Me)=>{const w=new FileReader;w.onload=()=>{if(typeof w.result!="string"){Me(new Error(`Failed to read file "${f.name}"`));return}Je({type:"file",url:w.result,mediaType:f.type,filename:f.name})},w.onerror=()=>Me(new Error(`Failed to read file "${f.name}"`)),w.readAsDataURL(f)})}))}catch{q({title:"Failed to attach files",message:"Could not read one or more files. Please try again."});return}const d=i.length||n?.length?[...i,...n??[]]:void 0,c=[...e.trim()?[{type:"text",text:e}]:[],...d??[]];L.current={content:e,messageId:r,body:{conversationId:o},files:d},j({id:r,parts:c},{body:{conversationId:o}})},je=t.useCallback(e=>{S.current=0,H.current=e,J(!1),Q(e)},[Q]),te=t.useCallback(()=>{J(!0),N().then(()=>{O("aborted",{conversationId:u})})},[N,u,O]),Te=()=>{ze(),h([]),E(""),p(),v.current=T?.length?T:void 0,m({eventName:"chat_clear_button_clicked",properties:{conversationId:u}})},C=t.useCallback((e,l)=>{M(null),h(l),E(e),p(),v.current=void 0},[h,E,p]),be=t.useCallback(async(e,l)=>{te(),C(e,[]),Re(!0);try{const s=await ve(e,l);if(s===null)return!1;const r=s[s.length-1]?.role==="user"?[...s,{id:k.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,r),!0}finally{l?.aborted||Re(!1)}},[C,ve,te]);at.useInitialConversation({conversationId:R.conversationId,fetchedConversation:R.fetchedConversation,effectiveAuthToken:le,restoreSession:C,loadAndRestoreSession:be,onLoadFailed:()=>C("",[])});const{openForm:Qe}=it.useChatForm(),We=ct.useWidget();return t.useImperativeHandle(R.chatFunctionsRef,()=>({submitMessage:ee,updateInputMessage(e){_(e)},clearChat:Te,openForm:e=>{We?.setView("chat"),Qe(e,void 0)},focusInput:()=>{_e.current?.focus()}})),{messages:b,sendMessage:j,addToolApprovalResponse:je,isLoading:Ae,isStreaming:Ce,isBusy:Ie,error:Ke,setError:M,isSubmitDisabled:X,input:I,handleInputChange:ke,handleInputKeyDown:Ye,handleSubmit:ee,stop:te,clear:Te,inputRef:_e,isMobile:$e,files:A,setFiles:Y,isNewChat:Ge,conversationId:u,restoreSession:C,loadAndRestoreSession:be,isSessionLoading:Ne,authToken:y?ae:ce,refreshSession:y?ie:ue,getCaptchaHeader:F,invalidateCaptcha:p,inputNotification:He,showInputNotification:q,clearInputNotification:Ve}};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 at } from "@ai-sdk/react";
3
- import { normalizeFileType as it } from "./file-upload-input.js";
4
- import { DefaultChatTransport as ct } from "ai";
5
- import { useRef as i, useEffect as _, useState as k, useMemo as Oe, useCallback as $, useImperativeHandle as lt } from "react";
6
- import { useInkeepConfig as ut } from "../../providers/config-provider.js";
7
- import { useChatAuth as dt } from "../../providers/chat-auth-provider.js";
8
- import { useMediaQuery as pt } from "../../hooks/use-media-query.js";
9
- import { useConversationLoader as ft } from "../../hooks/use-conversation-loader.js";
10
- import { useInitialConversation as mt } 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 gt } from "../../providers/base-events-provider.js";
13
- import { useChatForm as ht } from "../../providers/chat-form-provider.js";
14
- import { useWidget as vt } from "../../providers/widget-provider.js";
15
- import { useControllableState as yt } from "@radix-ui/react-use-controllable-state";
16
- import { useStreamingEvents as Rt } from "../../hooks/use-streaming-events.js";
17
- import { useInputNotification as It } from "../../hooks/use-input-notification.js";
18
- import { resolveStreamingAuthError as Ct, DEFAULT_ERROR_MESSAGE as ne, isRecoverableError as Et, isNetworkError as Ne, RECOVERABLE_NOTIFICATION_DURATION_MS as Pe, PAYLOAD_TOO_LARGE_MESSAGE as oe, NETWORK_ERROR_MESSAGE as St, resolveHttpStatusCode as At, RATE_LIMIT_MESSAGE as wt, RECOVERABLE_FALLBACK_MESSAGE as Be, estimateRequestBodyBytes as Tt, MAX_REQUEST_BODY_BYTES as bt } from "./chat-error-helpers.js";
19
- const Ht = () => {
20
- const { baseSettings: ae, aiChatSettings: v } = ut(), [c = "", y] = yt({
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
+ import { useInputNotification as Ct } from "../../hooks/use-input-notification.js";
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 } = gt(), { setConversationId: De, emitToParent: x } = Rt(), 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,11 +31,11 @@ const Ht = () => {
31
31
  }
32
32
  });
33
33
  }, [c, g]);
34
- const [S, A] = k(""), Le = (e) => A(e.target.value), {
35
- shouldBypassCaptcha: $e,
34
+ const [C, A] = k(""), Ge = (e) => A(e.target.value), {
35
+ shouldBypassCaptcha: Ke,
36
36
  filters: ce,
37
37
  userProperties: U,
38
- analyticsProperties: z
38
+ analyticsProperties: G
39
39
  } = ae, {
40
40
  authToken: le,
41
41
  isAuthenticated: R,
@@ -44,57 +44,57 @@ const Ht = () => {
44
44
  sessionToken: pe,
45
45
  refreshSession: fe,
46
46
  getCaptchaHeader: O,
47
- invalidateCaptcha: p,
47
+ invalidateCaptcha: d,
48
48
  effectiveAuthToken: me,
49
- applicableRefreshSession: Ue
50
- } = dt(), {
51
- onInputMessageChange: ze,
49
+ applicableRefreshSession: ze
50
+ } = mt(), {
51
+ onInputMessageChange: He,
52
52
  filters: ge,
53
53
  baseUrl: he,
54
- agentUrl: Ge,
54
+ agentUrl: qe,
55
55
  context: ve,
56
56
  headers: ye,
57
57
  appId: N,
58
- apiKey: G,
59
- files: w
58
+ apiKey: K,
59
+ files: T
60
60
  } = v, Re = i(O);
61
61
  Re.current = O;
62
- const Ie = Ge || `${he}/run/api/chat`, { loadConversation: Ce } = ft({
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
- invalidateCaptcha: p,
68
- refreshSession: Ue
69
- }), [Ke, Ee] = k(!1), K = i(null);
70
- K.current = pe;
71
- const q = i(null);
72
- q.current = le;
73
- const H = i(void 0);
74
- H.current = U && Object.keys(U).length > 0 ? U : void 0;
75
- const j = i(void 0);
76
- j.current = z && Object.keys(z).length > 0 ? z : void 0;
77
- const I = i(0), P = i(null), V = i(null), h = i(void 0), qe = w?.map(
67
+ invalidateCaptcha: d,
68
+ refreshSession: ze
69
+ }), [We, Se] = k(!1), z = i(null);
70
+ z.current = pe;
71
+ const H = i(null);
72
+ H.current = le;
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
- }, [qe]);
84
- const Se = i(ye);
85
- Se.current = ye;
86
- const W = i(void 0);
87
- W.current = ce || ge ? JSON.stringify({ ...ce, ...ge }) : void 0;
88
- const He = (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 ? oe : St;
91
- switch (At(e)) {
90
+ return P.current?.files?.length ? Le : De;
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 ?? Be;
95
+ return t.detail ?? t.error?.message ?? $e;
96
96
  } catch {
97
- return e.message?.trim() || Be;
97
+ return e.message?.trim() || $e;
98
98
  }
99
99
  case 401:
100
100
  return ue ? "Authentication failed. Please try again." : ne;
@@ -103,23 +103,23 @@ const Ht = () => {
103
103
  case 413:
104
104
  return oe;
105
105
  case 429:
106
- return wt;
106
+ return Be;
107
107
  default:
108
108
  return ne;
109
109
  }
110
- }, [C, Y] = k([]), je = Oe(
111
- () => new ct({
112
- api: Ie,
110
+ }, [I, Y] = k([]), Ye = Oe(
111
+ () => new dt({
112
+ api: Ee,
113
113
  headers: () => {
114
- const e = G ?? q.current ?? K.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
- ...W.current ? { "inkeep-filters": W.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
- ...H.current ? { userProperties: H.current } : {},
137
- ...j.current ? { properties: j.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, G]
149
+ [Ee, ve, N, K]
150
150
  ), {
151
- messages: T,
151
+ messages: w,
152
152
  sendMessage: J,
153
153
  addToolApprovalResponse: Q,
154
154
  status: Ae,
155
155
  setMessages: m,
156
156
  stop: B,
157
157
  error: D
158
- } = at({
159
- transport: je,
158
+ } = lt({
159
+ transport: Ye,
160
160
  onData(e) {
161
161
  x(e.type, e.data);
162
162
  },
@@ -177,26 +177,26 @@ const Ht = () => {
177
177
  },
178
178
  onError(e) {
179
179
  console.error("onError", { code: e.code, message: e.message });
180
- const l = $e || G ? null : Ct(e);
181
- if (l !== null && I.current < 1) {
182
- I.current++;
183
- const s = V.current, r = 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 u = await de();
187
- if (!u) throw new Error("Auth token refresh failed");
188
- q.current = u;
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 u = await fe();
191
- u && (K.current = u);
190
+ const n = await fe();
191
+ n && (z.current = n);
192
192
  } else
193
- p();
194
- if (s) {
195
- Q(s);
193
+ d();
194
+ if (o) {
195
+ Q(o);
196
196
  return;
197
197
  }
198
- r && (m((u) => {
199
- let a = [...u];
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
201
  }), J(
202
202
  {
@@ -209,64 +209,64 @@ const Ht = () => {
209
209
  { body: r.body }
210
210
  ));
211
211
  })().catch(() => {
212
- I.current = 0, p(), m((u) => {
213
- const a = [...u], 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 d = ne;
215
+ const u = ne;
216
216
  return f.role === "user" ? a.push({
217
217
  id: F(16),
218
218
  role: "assistant",
219
- parts: [{ type: "text", text: d }]
220
- }) : f.parts = [{ type: "text", text: d }], a;
219
+ parts: [{ type: "text", text: u }]
220
+ }) : f.parts = [{ type: "text", text: u }], a;
221
221
  });
222
222
  });
223
223
  return;
224
224
  }
225
- I.current = 0, l !== null && p();
226
- const t = Et(e) || Ne(e), n = He(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: "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
- ), m((r) => {
239
- let o = [...r];
240
- return o.at(-1)?.role === "assistant" && (o = o.slice(0, -1)), o.at(-1)?.role === "user" && (o = o.slice(0, -1)), o;
238
+ ), m((p) => {
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), te.current = e;
242
+ const r = P.current?.content;
243
+ r && A(r), te.current = e;
244
244
  return;
245
245
  }
246
- m((s) => {
247
- const r = [...s], o = r[r.length - 1];
248
- return o && (o.role === "user" ? r.push({
246
+ m((o) => {
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
- }) : o.parts = [{ type: "text", text: n }]), r;
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(""), Y([]), p());
259
- }, [R, B, m, y, p]);
260
- const Te = Ae === "submitted", X = Ae === "streaming", Ve = Oe(() => {
261
- const e = (s) => {
262
- if (!s || typeof s != "object") return !1;
263
- const r = s;
257
+ const e = Te.current;
258
+ Te.current = R, e !== R && (B(), b(null), m([]), y(""), A(""), Y([]), d());
259
+ }, [R, B, m, y, d]);
260
+ const we = Ae === "submitted", X = Ae === "streaming", Je = Oe(() => {
261
+ const e = (o) => {
262
+ if (!o || typeof o != "object") return !1;
263
+ const r = o;
264
264
  return typeof r.type == "string" && r.type.startsWith("tool-");
265
- }, t = [...T ?? []].reverse().find((s) => s.role === "assistant");
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 || X);
269
- }, [T, X]), [We, Z] = k(!1), be = X || Ve && !We, Me = Te || be, Ye = T.length === 0, ee = !S.trim() && C.length === 0 || Me, Je = pt("(max-width: 768px)"), [Qe, b] = k(null), te = 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
272
  if (te.current === D) {
@@ -276,63 +276,63 @@ const Ht = () => {
276
276
  b(D);
277
277
  }
278
278
  }, [D]);
279
- const Xe = () => b(null), { inputNotification: Ze, showInputNotification: L, clearInputNotification: et } = It(), _e = i(null);
279
+ const tt = () => b(null), { inputNotification: st, showInputNotification: L, clearInputNotification: rt } = Ct(), _e = i(null);
280
280
  _(() => {
281
- ze?.(S);
282
- }, [S]);
283
- const tt = (e) => {
281
+ He?.(C);
282
+ }, [C]);
283
+ const nt = (e) => {
284
284
  e.key === "Enter" && !e.shiftKey && !ee && !e.nativeEvent.isComposing && (e.preventDefault(), se());
285
- }, se = async (e = S) => {
286
- if (ee && (!e || e.trim().length === 0) && C.length === 0 || !e.trim() && !C.length && !h.current?.length)
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, d) => f + d.size, 0),
290
+ rawFileBytes: I.reduce((f, u) => f + u.size, 0),
291
291
  encodedPartsBytes: (h.current ?? []).reduce(
292
- (f, d) => f + d.url.length,
292
+ (f, u) => f + u.url.length,
293
293
  0
294
294
  )
295
- }) > bt) {
295
+ }) > Mt) {
296
296
  L(
297
297
  { title: "Message too large", message: oe },
298
298
  Pe
299
299
  );
300
300
  return;
301
301
  }
302
- const t = C;
303
- Y([]), A(""), I.current = 0, V.current = null, Z(!1);
304
- let n = c;
305
- n || (n = `conv_${F(16)}`, y(n));
306
- const s = F(21);
307
- De(n), await g({
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
+ const o = F(21);
307
+ Ue(s), await g({
308
308
  eventName: "user_message_submitted",
309
309
  properties: {
310
- conversationId: n,
311
- messageId: s
310
+ conversationId: s,
311
+ messageId: o
312
312
  }
313
313
  });
314
314
  const r = h.current;
315
315
  h.current = void 0;
316
- let o = [];
316
+ let p = [];
317
317
  if (t.length > 0)
318
318
  try {
319
- o = await Promise.all(
319
+ p = await Promise.all(
320
320
  t.map((f) => {
321
- const d = it(f);
322
- return new Promise((ot, 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
- xe(new Error(`Failed to read file "${d.name}"`));
326
+ xe(new Error(`Failed to read file "${u.name}"`));
327
327
  return;
328
328
  }
329
- ot({
329
+ ct({
330
330
  type: "file",
331
331
  url: M.result,
332
- mediaType: d.type,
333
- filename: d.name
332
+ mediaType: u.type,
333
+ filename: u.name
334
334
  });
335
- }, M.onerror = () => xe(new Error(`Failed to read file "${d.name}"`)), M.readAsDataURL(d);
335
+ }, M.onerror = () => xe(new Error(`Failed to read file "${u.name}"`)), M.readAsDataURL(u);
336
336
  });
337
337
  })
338
338
  );
@@ -343,19 +343,19 @@ const Ht = () => {
343
343
  });
344
344
  return;
345
345
  }
346
- const u = o.length || r?.length ? [...o, ...r ?? []] : void 0, a = [
346
+ const n = p.length || r?.length ? [...p, ...r ?? []] : void 0, a = [
347
347
  ...e.trim() ? [{ type: "text", text: e }] : [],
348
- ...u ?? []
348
+ ...n ?? []
349
349
  ];
350
350
  P.current = {
351
351
  content: e,
352
- messageId: s,
353
- body: { conversationId: n },
354
- files: u
355
- }, J({ id: s, parts: a }, { body: { conversationId: n } });
356
- }, st = $(
352
+ messageId: o,
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, V.current = e, Z(!1), Q(e);
358
+ E.current = 0, j.current = e, Z(!1), Q(e);
359
359
  },
360
360
  [Q]
361
361
  ), re = $(() => {
@@ -363,24 +363,24 @@ const Ht = () => {
363
363
  x("aborted", { conversationId: c });
364
364
  });
365
365
  }, [B, c, x]), ke = () => {
366
- Xe(), m([]), y(""), p(), 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
- b(null), m(l), y(e), p(), h.current = void 0;
374
+ b(null), m(l), y(e), d(), h.current = void 0;
375
375
  },
376
- [m, y, p]
376
+ [m, y, d]
377
377
  ), Fe = $(
378
378
  async (e, l) => {
379
- re(), 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
- const s = t[t.length - 1]?.role === "user" ? [
383
+ const o = t[t.length - 1]?.role === "user" ? [
384
384
  ...t,
385
385
  {
386
386
  id: F(16),
@@ -393,68 +393,68 @@ const Ht = () => {
393
393
  ]
394
394
  }
395
395
  ] : t;
396
- return E(e, s), !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, re]
401
+ [S, Ie, re]
402
402
  );
403
- mt({
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: rt } = ht(), nt = vt();
412
- return lt(v.chatFunctionsRef, () => ({
411
+ const { openForm: at } = Rt(), it = Et();
412
+ return pt(v.chatFunctionsRef, () => ({
413
413
  submitMessage: se,
414
414
  updateInputMessage(e) {
415
415
  A(e);
416
416
  },
417
417
  clearChat: ke,
418
418
  openForm: (e) => {
419
- nt?.setView("chat"), rt(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,
425
+ messages: w,
426
426
  sendMessage: J,
427
- addToolApprovalResponse: st,
428
- isLoading: Te,
427
+ addToolApprovalResponse: ot,
428
+ isLoading: we,
429
429
  isStreaming: be,
430
430
  isBusy: Me,
431
- error: Qe,
431
+ error: et,
432
432
  setError: b,
433
433
  isSubmitDisabled: ee,
434
- input: S,
435
- handleInputChange: Le,
436
- handleInputKeyDown: tt,
434
+ input: C,
435
+ handleInputChange: Ge,
436
+ handleInputKeyDown: nt,
437
437
  handleSubmit: se,
438
438
  stop: re,
439
439
  clear: ke,
440
440
  inputRef: _e,
441
- isMobile: Je,
442
- files: C,
441
+ isMobile: Ze,
442
+ files: I,
443
443
  setFiles: Y,
444
- isNewChat: Ye,
444
+ isNewChat: Xe,
445
445
  conversationId: c,
446
- restoreSession: E,
446
+ restoreSession: S,
447
447
  loadAndRestoreSession: Fe,
448
- isSessionLoading: Ke,
448
+ isSessionLoading: We,
449
449
  authToken: R ? le : pe,
450
450
  refreshSession: R ? de : fe,
451
451
  getCaptchaHeader: O,
452
- invalidateCaptcha: p,
453
- inputNotification: Ze,
452
+ invalidateCaptcha: d,
453
+ inputNotification: st,
454
454
  showInputNotification: L,
455
- clearInputNotification: et
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-20260721212136",
3
+ "version": "0.0.0-dev-20260721224224",
4
4
  "description": "",
5
5
  "homepage": "",
6
6
  "repository": {