@inkeep/agents-ui 0.15.12 → 0.15.14

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.
Files changed (116) hide show
  1. package/dist/index.cjs +1 -1
  2. package/dist/index.js +230 -220
  3. package/dist/primitives/atoms/combobox.cjs +1 -0
  4. package/dist/primitives/atoms/combobox.js +275 -0
  5. package/dist/primitives/atoms/icons/built-in-icons.cjs +1 -1
  6. package/dist/primitives/atoms/icons/built-in-icons.d.ts +2 -0
  7. package/dist/primitives/atoms/icons/built-in-icons.js +33 -31
  8. package/dist/primitives/atoms/icons/inkeep-default-icons.cjs +1 -1
  9. package/dist/primitives/atoms/icons/inkeep-default-icons.js +4 -1
  10. package/dist/primitives/components/chat-history/index.cjs +1 -0
  11. package/dist/primitives/components/chat-history/index.d.ts +27 -0
  12. package/dist/primitives/components/chat-history/index.js +105 -0
  13. package/dist/primitives/components/embedded-chat/use-captcha.cjs +1 -0
  14. package/dist/primitives/components/embedded-chat/use-captcha.d.ts +23 -6
  15. package/dist/primitives/components/embedded-chat/use-captcha.js +67 -0
  16. package/dist/primitives/components/embedded-chat/use-inkeep-chat.cjs +2 -2
  17. package/dist/primitives/components/embedded-chat/use-inkeep-chat.d.ts +12 -3
  18. package/dist/primitives/components/embedded-chat/use-inkeep-chat.js +252 -144
  19. package/dist/primitives/components/embedded-chat/use-stream-processor.cjs +1 -1
  20. package/dist/primitives/components/embedded-chat/use-stream-processor.d.ts +2 -0
  21. package/dist/primitives/components/embedded-chat/use-stream-processor.js +127 -90
  22. package/dist/primitives/components/embedded-chat.cjs +4 -4
  23. package/dist/primitives/components/embedded-chat.d.ts +26 -2
  24. package/dist/primitives/components/embedded-chat.js +1304 -1149
  25. package/dist/primitives/components/index.cjs +1 -1
  26. package/dist/primitives/components/index.d.ts +1 -0
  27. package/dist/primitives/components/index.js +20 -18
  28. package/dist/primitives/hooks/use-anonymous-session.cjs +1 -0
  29. package/dist/primitives/hooks/use-anonymous-session.d.ts +12 -0
  30. package/dist/primitives/hooks/use-anonymous-session.js +57 -0
  31. package/dist/primitives/hooks/use-conversation-loader.cjs +1 -0
  32. package/dist/primitives/hooks/use-conversation-loader.d.ts +13 -0
  33. package/dist/primitives/hooks/use-conversation-loader.js +36 -0
  34. package/dist/primitives/hooks/use-inkeep-api-client.cjs +1 -0
  35. package/dist/primitives/hooks/use-inkeep-api-client.d.ts +33 -0
  36. package/dist/primitives/hooks/use-inkeep-api-client.js +87 -0
  37. package/dist/primitives/hooks/use-local-storage.cjs +1 -0
  38. package/dist/primitives/hooks/use-local-storage.d.ts +8 -0
  39. package/dist/primitives/hooks/use-local-storage.js +26 -0
  40. package/dist/primitives/hooks/use-simple-scroll.cjs +1 -1
  41. package/dist/primitives/hooks/use-simple-scroll.d.ts +12 -1
  42. package/dist/primitives/hooks/use-simple-scroll.js +45 -12
  43. package/dist/primitives/index.cjs +1 -1
  44. package/dist/primitives/index.js +157 -151
  45. package/dist/primitives/providers/base-events-provider.cjs +1 -1
  46. package/dist/primitives/providers/base-events-provider.js +1 -1
  47. package/dist/primitives/providers/chat-history-provider.cjs +1 -0
  48. package/dist/primitives/providers/chat-history-provider.d.ts +32 -0
  49. package/dist/primitives/providers/chat-history-provider.js +105 -0
  50. package/dist/primitives/providers/index.cjs +1 -1
  51. package/dist/primitives/providers/index.d.ts +1 -0
  52. package/dist/primitives/providers/index.js +55 -52
  53. package/dist/primitives/utils/component-ids.cjs +1 -1
  54. package/dist/primitives/utils/component-ids.d.ts +56 -0
  55. package/dist/primitives/utils/component-ids.js +31 -1
  56. package/dist/primitives/utils/default-settings.cjs +1 -1
  57. package/dist/primitives/utils/default-settings.d.ts +2 -0
  58. package/dist/primitives/utils/default-settings.js +6 -4
  59. package/dist/primitives/utils/form.cjs +1 -1
  60. package/dist/primitives/utils/form.d.ts +1 -1
  61. package/dist/primitives/utils/form.js +3 -1
  62. package/dist/react/chat-button-modal.cjs +1 -0
  63. package/dist/react/chat-button-modal.d.ts +22 -0
  64. package/dist/react/chat-button-modal.js +41 -0
  65. package/dist/react/chat-button.cjs +1 -1
  66. package/dist/react/chat-button.js +42 -38
  67. package/dist/react/embedded-chat.cjs +1 -1
  68. package/dist/react/embedded-chat.js +285 -240
  69. package/dist/react/index.cjs +1 -1
  70. package/dist/react/index.d.ts +1 -0
  71. package/dist/react/index.js +230 -220
  72. package/dist/react/sidebar-chat.cjs +1 -1
  73. package/dist/react/sidebar-chat.js +26 -22
  74. package/dist/styled/components/chat-bubble.cjs +1 -1
  75. package/dist/styled/components/chat-bubble.js +1 -1
  76. package/dist/styled/components/chat-history.cjs +1 -0
  77. package/dist/styled/components/chat-history.d.ts +15 -0
  78. package/dist/styled/components/chat-history.js +197 -0
  79. package/dist/styled/components/data-summary-group.cjs +1 -1
  80. package/dist/styled/components/data-summary-group.js +24 -24
  81. package/dist/styled/components/embedded-chat/session-loading.cjs +1 -0
  82. package/dist/styled/components/embedded-chat/session-loading.d.ts +1 -0
  83. package/dist/styled/components/embedded-chat/session-loading.js +26 -0
  84. package/dist/styled/components/embedded-chat.cjs +1 -1
  85. package/dist/styled/components/embedded-chat.d.ts +22 -1
  86. package/dist/styled/components/embedded-chat.js +735 -565
  87. package/dist/styled/components/embedded-search.cjs +1 -1
  88. package/dist/styled/components/embedded-search.js +1 -1
  89. package/dist/styled/components/index.cjs +1 -1
  90. package/dist/styled/components/index.d.ts +1 -0
  91. package/dist/styled/components/index.js +22 -20
  92. package/dist/styled/components/message.cjs +1 -1
  93. package/dist/styled/components/message.js +191 -183
  94. package/dist/styled/components/sidebar-chat.cjs +1 -1
  95. package/dist/styled/components/sidebar-chat.js +1 -1
  96. package/dist/styled/components/ui/recipes/ai-chat-page-wrapper.cjs +1 -1
  97. package/dist/styled/components/ui/recipes/ai-chat-page-wrapper.js +3 -2
  98. package/dist/styled/components/ui/recipes/combobox.cjs +1 -0
  99. package/dist/styled/components/ui/recipes/combobox.d.ts +4 -0
  100. package/dist/styled/components/ui/recipes/combobox.js +57 -0
  101. package/dist/styled/components/ui/recipes/index.cjs +1 -1
  102. package/dist/styled/components/ui/recipes/index.d.ts +1 -0
  103. package/dist/styled/components/ui/recipes/index.js +29 -27
  104. package/dist/styled/components/ui/recipes/modal.d.ts +1 -1
  105. package/dist/styled/components/ui/recipes/scrollable.d.ts +1 -1
  106. package/dist/styled/components/ui/recipes/select.d.ts +1 -1
  107. package/dist/styled/index.cjs +1 -1
  108. package/dist/styled/index.js +193 -185
  109. package/dist/styled/inkeep.css.cjs +328 -6
  110. package/dist/styled/inkeep.css.js +328 -6
  111. package/dist/types/config/ai.d.ts +17 -1
  112. package/dist/types/config/base.d.ts +21 -0
  113. package/dist/types/config/settings/form.d.ts +9 -1
  114. package/dist/types/icons/built-in.d.ts +1 -1
  115. package/dist/types/icons/custom.d.ts +3 -0
  116. package/package.json +6 -5
@@ -0,0 +1,67 @@
1
+ "use client";
2
+ import { solveChallenge as m } from "altcha-lib";
3
+ import { useRef as p, useCallback as h, useEffect as x } from "react";
4
+ const w = 30 * 1e3;
5
+ function E(i) {
6
+ const e = /[?&]expires=(\d+)/.exec(i);
7
+ return e ? Number.parseInt(e[1], 10) * 1e3 : null;
8
+ }
9
+ const y = async (i) => {
10
+ try {
11
+ const e = await fetch(i, { method: "GET" });
12
+ if (!e.ok)
13
+ throw new Error(`Failed to fetch challenge: ${e.statusText}`);
14
+ const c = await e.json(), { challenge: s, algorithm: t, salt: r, maxnumber: n } = c, { promise: g } = await m(
15
+ s,
16
+ r,
17
+ t,
18
+ n
19
+ ), u = await g || void 0;
20
+ if (!u)
21
+ throw new Error("Challenge not solved");
22
+ return {
23
+ payload: { number: u.number, ...c },
24
+ expiresAt: E(r)
25
+ };
26
+ } catch (e) {
27
+ console.warn("[captcha] Error fetching/solving challenge:", e);
28
+ return;
29
+ }
30
+ }, k = ({
31
+ baseUrl: i,
32
+ shouldBypassCaptcha: e = !1,
33
+ shouldMakeInitialRequest: c = !0
34
+ }) => {
35
+ const s = `${i}/run/auth/pow/challenge`, t = p(null), r = p(null), n = h(() => {
36
+ const o = y(s);
37
+ t.current = o, o.then((l) => {
38
+ l && (r.current = l.expiresAt);
39
+ });
40
+ }, [s]), g = h(async () => {
41
+ if (e) return {};
42
+ t.current || n();
43
+ const o = t.current;
44
+ t.current = null, n();
45
+ const l = t.current, f = await o;
46
+ if (!f) {
47
+ const a = await l;
48
+ return a ? { "x-inkeep-challenge-solution": btoa(JSON.stringify(a.payload)) } : {};
49
+ }
50
+ if (f.expiresAt !== null && Date.now() >= f.expiresAt) {
51
+ const a = await l;
52
+ return a ? { "x-inkeep-challenge-solution": btoa(JSON.stringify(a.payload)) } : {};
53
+ }
54
+ return { "x-inkeep-challenge-solution": btoa(JSON.stringify(f.payload)) };
55
+ }, [e, n]), u = h(() => {
56
+ e || n();
57
+ }, [e, n]);
58
+ return x(() => {
59
+ if (!c || e) return;
60
+ const o = r.current !== null && Date.now() >= r.current - w;
61
+ (!t.current || o) && n();
62
+ }, [c, e, n]), { getCaptchaHeader: g, invalidate: u };
63
+ };
64
+ export {
65
+ y as fetchAndSolveChallenge,
66
+ k as useCaptcha
67
+ };
@@ -1,3 +1,3 @@
1
- "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const re=require("@ai-sdk/react"),ae=require("ai"),n=require("react"),oe=require("../../providers/config-provider.cjs"),ie=require("../../hooks/use-media-query.cjs"),U=require("../../utils/generate-uid.cjs"),ce=require("../../providers/base-events-provider.cjs"),ue=require("../../providers/chat-form-provider.cjs"),le=require("../../providers/widget-provider.cjs"),pe=require("@radix-ui/react-use-controllable-state"),de=require("../../hooks/use-streaming-events.cjs"),O=`Hmm..
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ne=require("@ai-sdk/react"),Oe=require("ai"),t=require("react"),Pe=require("../modal/modal-provider.cjs"),_e=require("../../providers/chat-bubble-provider.cjs"),Fe=require("../../providers/sidebar-chat-provider.cjs"),Be=require("../../providers/config-provider.cjs"),De=require("./use-captcha.cjs"),Ue=require("../../hooks/use-media-query.cjs"),Le=require("../../hooks/use-anonymous-session.cjs"),He=require("../../hooks/use-conversation-loader.cjs"),H=require("../../utils/generate-uid.cjs"),$e=require("../../providers/base-events-provider.cjs"),ze=require("../../providers/chat-form-provider.cjs"),We=require("../../providers/widget-provider.cjs"),Ke=require("@radix-ui/react-use-controllable-state"),je=require("../../hooks/use-streaming-events.cjs"),Ge=require("../../hooks/use-inkeep-api-client.cjs");function Je(f){const l=f.message??"";let r=Number(f.code)||Number(f.statusCode);if(Number.isNaN(r))try{r=Number(JSON.parse(l).status)}catch{}const d=Ge.parseAuthError(r,{detail:l});return d!==null?d:r===401?"session":null}const $=`Hmm..
2
2
 
3
- It seems I might be having some issues right now. Please clear the chat and try again.`,ge=()=>{const{baseSettings:C,aiChatSettings:l}=oe.useInkeepConfig(),[r="",I]=pe.useControllableState({prop:l.conversationId,defaultProp:l.conversationId??""}),{logEvent:o}=ce.useBaseEvents(),{setConversationId:B,emitToParent:p}=de.useStreamingEvents(),[i,d]=n.useState(""),H=e=>d(e.target.value),{filters:M}=C,{onInputMessageChange:W,filters:w,agentUrl:_,context:g,headers:m,apiKey:f}=l,z=e=>{switch(e.code){case 400:return e.message;case 403:return`There seems to be a configuration error. Please contact ${C.organizationDisplayName??"Administrator"}`;default:return O}},[K,h]=n.useState([]),[L,q]=n.useState(null),$=()=>({"x-inkeep-client-timezone":Intl.DateTimeFormat().resolvedOptions().timeZone,"x-inkeep-client-timestamp":new Date().toISOString()}),j=n.useMemo(()=>new ae.DefaultChatTransport({api:_,headers:{...f?{Authorization:`Bearer ${f}`}:{},...m},body:{requestContext:g}}),[_,f,m,g]),{messages:c,sendMessage:F,addToolApprovalResponse:G,status:x,setMessages:A,stop:Q,error:v}=re.useChat({transport:j,onData(e){p(e.type,e.data)},async onFinish(){p("completion",{conversationId:r}),await o({eventName:"assistant_message_received",properties:{conversationId:r}}),o({eventName:"assistant_answer_displayed",properties:{conversationId:r}})},onError(e){console.log("onError",e.message),o({eventName:"chat_error",properties:{conversationId:r,error:e.message}}),A(u=>{const s=[...u],t=s[s.length-1];if(t){const a=z(e);t.role==="user"?s.push({id:U.generateUid(16),role:"assistant",parts:[{type:"text",text:a}]}):t.parts=[{type:"text",text:a}]}return s})}}),P=x==="submitted",S=x==="streaming",J=n.useMemo(()=>{const e=a=>{if(!a||typeof a!="object")return!1;const N=a;return typeof N.type=="string"&&N.type.startsWith("tool-")},s=[...c??[]].reverse().find(a=>a.role==="assistant");if(!s)return!1;const t=s.parts?.at(-1);return!(!e(t)||t.state!=="output-available"||!t.approval?.id||S)},[c,S]),R=S||J,k=P||R,V=c.length===0,y=!i.trim()||k,Z=ie.useMediaQuery("(max-width: 768px)"),[X,E]=n.useState(null);n.useEffect(()=>{v&&E(v)},[v]);const Y=()=>E(null),D=n.useRef(null);n.useEffect(()=>{W?.(i)},[i]);const ee=e=>{e.key==="Enter"&&!e.shiftKey&&!y&&!e.nativeEvent.isComposing&&(e.preventDefault(),b())},b=async(e=i)=>{if(y&&(!e||e.trim().length===0))return;h([]),d(""),await o({eventName:"user_message_submitted",properties:{conversationId:r}});const u=M||w?JSON.stringify({...M,...w}):void 0,s={...m};u&&(s["inkeep-filters"]=u);let t=r;t||(t=`conv_${U.generateUid(16)}`,I(t)),B(t),F({text:e},{headers:{...$(),...s},body:{conversationId:t,requestContext:g}})},te=()=>{Q().then(()=>{p("aborted",{conversationId:r})})},T=()=>{Y(),A([]),I(""),h([]),q(null),o({eventName:"chat_clear_button_clicked",properties:{conversationId:r}})},{openForm:se}=ue.useChatForm(),ne=le.useWidget();return n.useImperativeHandle(l.chatFunctionsRef,()=>({submitMessage:b,updateInputMessage(e){d(e)},clearChat:T,openForm:e=>{ne?.setView("chat"),se(e,void 0)},focusInput:()=>{D.current?.focus()}})),{messages:c,sendMessage:F,addToolApprovalResponse:G,isLoading:P,isStreaming:R,isBusy:k,error:X,setError:E,isSubmitDisabled:y,input:i,handleInputChange:H,handleInputKeyDown:ee,handleSubmit:b,stop:te,clear:T,isEmpty:c.length===0,inputRef:D,isMobile:Z,messageAttachments:K,setMessageAttachments:h,selectedWorkflow:L,setSelectedWorkflow:q,isNewChat:V,conversationId:r}};exports.DEFAULT_ERROR_MESSAGE=O;exports.useInkeepChat=ge;
3
+ It seems I might be having some issues right now. Please clear the chat and try again.`,Qe=()=>{const{baseSettings:f,aiChatSettings:l}=Be.useInkeepConfig(),[r="",d]=Ke.useControllableState({prop:l.conversationId,defaultProp:l.conversationId??""}),ce=Pe.useModal(),ue=_e.useOptionalChatBubble(),le=Fe.useOptionalSidebarChat(),{logEvent:h}=$e.useBaseEvents(),{setConversationId:de,emitToParent:C}=je.useStreamingEvents(),[v,k]=t.useState(""),pe=e=>k(e.target.value),{shouldBypassCaptcha:z,filters:W,privacyPreferences:fe}=f,{onInputMessageChange:ge,filters:K,baseUrl:S,agentUrl:me,context:j,headers:G,appId:y,apiKey:p}=l,he=ce?.isOpen??ue?.isOpen??le?.isOpen??!0,{getCaptchaHeader:b,invalidate:u}=De.useCaptcha({baseUrl:S,shouldBypassCaptcha:z||!!p,shouldMakeInitialRequest:he}),J=t.useRef(b);J.current=b;const Q=me||`${S}/run/api/chat`,{sessionToken:q,refreshSession:w}=Le.useAnonymousSession({baseUrl:S,appId:y,getCaptchaHeader:b,invalidateCaptcha:u,optOutAllAnalytics:fe?.optOutAllAnalytics}),{loadConversation:V}=He.useConversationLoader({baseUrl:S,appId:y,authToken:p??q,getCaptchaHeader:b,invalidateCaptcha:u,refreshSession:p?void 0:w}),[ve,Z]=t.useState(!1),R=t.useRef(null);R.current=q;const g=t.useRef(0),X=t.useRef(null),x=t.useRef(null),Y=t.useRef(G);Y.current=G;const T=t.useRef(void 0);T.current=W||K?JSON.stringify({...W,...K}):void 0;const ye=e=>{switch(e.code){case 400:return e.message;case 403:return`There seems to be a configuration error. Please contact ${f.organizationDisplayName??"Administrator"}`;default:return $}},[be,I]=t.useState([]),[Ce,N]=t.useState(null),Se=t.useMemo(()=>new Oe.DefaultChatTransport({api:Q,headers:()=>({"x-inkeep-client-timezone":Intl.DateTimeFormat().resolvedOptions().timeZone,"x-inkeep-client-timestamp":new Date().toISOString(),...y?{"x-inkeep-app-id":y}:{},...R.current?{Authorization:`Bearer ${R.current}`}:{},...p?{Authorization:`Bearer ${p}`}:{},...T.current?{"inkeep-filters":T.current}:{},...Y.current}),prepareSendMessagesRequest:async e=>{const s=await J.current();return{body:{...e.body,id:e.id,messages:e.messages,trigger:e.trigger,messageId:e.messageId},headers:{...e.headers,...s}}},body:{requestContext:j}}),[Q,j,y,p]),{messages:A,sendMessage:O,addToolApprovalResponse:P,status:ee,setMessages:m,stop:te,error:_}=Ne.useChat({transport:Se,onData(e){C(e.type,e.data)},async onFinish(){C("completion",{conversationId:r}),await h({eventName:"assistant_message_received",properties:{conversationId:r}}),h({eventName:"assistant_answer_displayed",properties:{conversationId:r}})},onError(e){console.error("onError",{code:e.code,message:e.message});const s=z||p?null:Je(e);if(s!==null&&g.current<1){g.current++;const i=x.current,a=X.current;(async()=>{if(s==="session"){const o=await w();o&&(R.current=o)}else u();if(i){P(i);return}a&&(m(o=>{let n=[...o];return n.at(-1)?.role==="assistant"&&(n=n.slice(0,-1)),n.at(-1)?.role==="user"&&(n=n.slice(0,-1)),n}),O({text:a.content},{body:a.body}))})().catch(()=>{g.current=0,u(),m(o=>{const n=[...o],L=n[n.length-1];if(!L)return n;const ie=$;return L.role==="user"?n.push({id:H.generateUid(16),role:"assistant",parts:[{type:"text",text:ie}]}):L.parts=[{type:"text",text:ie}],n})});return}g.current=0,s!==null&&u(),h({eventName:"chat_error",properties:{conversationId:r,error:e.message}}),m(i=>{const a=[...i],c=a[a.length-1];if(c){const o=ye(e);c.role==="user"?a.push({id:H.generateUid(16),role:"assistant",parts:[{type:"text",text:o}]}):c.parts=[{type:"text",text:o}]}return a})}}),se=ee==="submitted",F=ee==="streaming",Re=t.useMemo(()=>{const e=c=>{if(!c||typeof c!="object")return!1;const o=c;return typeof o.type=="string"&&o.type.startsWith("tool-")},i=[...A??[]].reverse().find(c=>c.role==="assistant");if(!i)return!1;const a=i.parts?.at(-1);return!(!e(a)||a.state!=="output-available"||!a.approval?.id||F)},[A,F]),re=F||Re,ne=se||re,Ie=A.length===0,B=!v.trim()||ne,Ae=Ue.useMediaQuery("(max-width: 768px)"),[Ee,E]=t.useState(null);t.useEffect(()=>{_&&E(_)},[_]);const Me=()=>E(null),ae=t.useRef(null);t.useEffect(()=>{ge?.(v)},[v]);const ke=e=>{e.key==="Enter"&&!e.shiftKey&&!B&&!e.nativeEvent.isComposing&&(e.preventDefault(),D())},D=async(e=v)=>{if(B&&(!e||e.trim().length===0))return;I([]),k(""),g.current=0,x.current=null,await h({eventName:"user_message_submitted",properties:{conversationId:r}});let s=r;s||(s=`conv_${H.generateUid(16)}`,d(s)),de(s),X.current={content:e,body:{conversationId:s}},O({text:e},{body:{conversationId:s}})},qe=t.useCallback(e=>{g.current=0,x.current=e,P(e)},[P]),U=t.useCallback(()=>{te().then(()=>{C("aborted",{conversationId:r})})},[te,r,C]),oe=()=>{Me(),m([]),d(""),I([]),N(null),u(),h({eventName:"chat_clear_button_clicked",properties:{conversationId:r}})},M=t.useCallback((e,s)=>{E(null),m(s),d(e),I([]),N(null),u()},[m,d,u]),we=t.useCallback(async(e,s)=>{U(),M(e,[]),Z(!0);try{const i=await V(e,s);i!==null&&M(e,i)}finally{s?.aborted||Z(!1)}},[M,V,U]),{openForm:xe}=ze.useChatForm(),Te=We.useWidget();return t.useImperativeHandle(l.chatFunctionsRef,()=>({submitMessage:D,updateInputMessage(e){k(e)},clearChat:oe,openForm:e=>{Te?.setView("chat"),xe(e,void 0)},focusInput:()=>{ae.current?.focus()}})),{messages:A,sendMessage:O,addToolApprovalResponse:qe,isLoading:se,isStreaming:re,isBusy:ne,error:Ee,setError:E,isSubmitDisabled:B,input:v,handleInputChange:pe,handleInputKeyDown:ke,handleSubmit:D,stop:U,clear:oe,inputRef:ae,isMobile:Ae,messageAttachments:be,setMessageAttachments:I,selectedWorkflow:Ce,setSelectedWorkflow:N,isNewChat:Ie,conversationId:r,restoreSession:M,loadAndRestoreSession:we,isSessionLoading:ve,sessionToken:q,refreshSession:w,getCaptchaHeader:b,invalidateCaptcha:u}};exports.DEFAULT_ERROR_MESSAGE=$;exports.useInkeepChat=Qe;
@@ -1,6 +1,6 @@
1
1
  import { KeyboardEvent, Dispatch, SetStateAction, RefObject } from 'react';
2
2
  import { Message, MessageAttachment, Workflow } from '../../../types/index.ts';
3
- import { FileUIPart, ChatRequestOptions, ChatAddToolApproveResponseFunction } from 'ai';
3
+ import { FileUIPart, ChatRequestOptions } from 'ai';
4
4
  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.";
5
5
  export declare const useInkeepChat: () => {
6
6
  messages: Message[];
@@ -23,7 +23,10 @@ export declare const useInkeepChat: () => {
23
23
  parts?: never;
24
24
  messageId?: string;
25
25
  } | undefined, options?: ChatRequestOptions) => Promise<void>;
26
- addToolApprovalResponse: ChatAddToolApproveResponseFunction;
26
+ addToolApprovalResponse: (approval: {
27
+ id: string;
28
+ approved: boolean;
29
+ }) => void;
27
30
  isLoading: boolean;
28
31
  isStreaming: boolean;
29
32
  isBusy: boolean;
@@ -36,7 +39,6 @@ export declare const useInkeepChat: () => {
36
39
  handleSubmit: (content?: string) => Promise<void>;
37
40
  stop: () => void;
38
41
  clear: () => void;
39
- isEmpty: boolean;
40
42
  inputRef: RefObject<HTMLTextAreaElement | null>;
41
43
  isMobile: boolean;
42
44
  messageAttachments: MessageAttachment[];
@@ -45,4 +47,11 @@ export declare const useInkeepChat: () => {
45
47
  setSelectedWorkflow: Dispatch<SetStateAction<Workflow | null>>;
46
48
  isNewChat: boolean;
47
49
  conversationId: string;
50
+ restoreSession: (sessionId: string, loadedMessages: Message[]) => void;
51
+ loadAndRestoreSession: (sessionId: string, signal?: AbortSignal) => Promise<void>;
52
+ isSessionLoading: boolean;
53
+ sessionToken: string | null;
54
+ refreshSession: () => Promise<string | null>;
55
+ getCaptchaHeader: () => Promise<Record<string, string>>;
56
+ invalidateCaptcha: () => void;
48
57
  };
@@ -1,204 +1,312 @@
1
1
  "use client";
2
- import { useChat as re } from "@ai-sdk/react";
3
- import { DefaultChatTransport as ae } from "ai";
4
- import { useState as m, useMemo as H, useEffect as O, useRef as ie, useImperativeHandle as le } from "react";
5
- import { useInkeepConfig as ce } from "../../providers/config-provider.js";
6
- import { useMediaQuery as me } from "../../hooks/use-media-query.js";
2
+ import { useChat as De } from "@ai-sdk/react";
3
+ import { DefaultChatTransport as Pe } from "ai";
4
+ import { useState as C, useRef as l, useMemo as le, useEffect as ue, useCallback as x, useImperativeHandle as He } from "react";
5
+ import { useModal as Le } from "../modal/modal-provider.js";
6
+ import { useOptionalChatBubble as Ue } from "../../providers/chat-bubble-provider.js";
7
+ import { useOptionalSidebarChat as $e } from "../../providers/sidebar-chat-provider.js";
8
+ import { useInkeepConfig as ze } from "../../providers/config-provider.js";
9
+ import { useCaptcha as We } from "./use-captcha.js";
10
+ import { useMediaQuery as qe } from "../../hooks/use-media-query.js";
11
+ import { useAnonymousSession as Ke } from "../../hooks/use-anonymous-session.js";
12
+ import { useConversationLoader as Je } from "../../hooks/use-conversation-loader.js";
7
13
  import { generateUid as W } from "../../utils/generate-uid.js";
8
- import { useBaseEvents as pe } from "../../providers/base-events-provider.js";
9
- import { useChatForm as ue } from "../../providers/chat-form-provider.js";
10
- import { useWidget as fe } from "../../providers/widget-provider.js";
11
- import { useControllableState as ge } from "@radix-ui/react-use-controllable-state";
12
- import { useStreamingEvents as de } from "../../hooks/use-streaming-events.js";
13
- const he = `Hmm..
14
+ import { useBaseEvents as je } from "../../providers/base-events-provider.js";
15
+ import { useChatForm as Ge } from "../../providers/chat-form-provider.js";
16
+ import { useWidget as Qe } from "../../providers/widget-provider.js";
17
+ import { useControllableState as Ve } from "@radix-ui/react-use-controllable-state";
18
+ import { useStreamingEvents as Ze } from "../../hooks/use-streaming-events.js";
19
+ import { parseAuthError as Xe } from "../../hooks/use-inkeep-api-client.js";
20
+ function Ye(d) {
21
+ const u = d.message ?? "";
22
+ let s = Number(d.code) || Number(d.statusCode);
23
+ if (Number.isNaN(s))
24
+ try {
25
+ s = Number(JSON.parse(u).status);
26
+ } catch {
27
+ }
28
+ const p = Xe(s, { detail: u });
29
+ return p !== null ? p : s === 401 ? "session" : null;
30
+ }
31
+ const pe = `Hmm..
14
32
 
15
- It seems I might be having some issues right now. Please clear the chat and try again.`, Fe = () => {
16
- const { baseSettings: S, aiChatSettings: c } = ce(), [n = "", E] = ge({
17
- prop: c.conversationId,
18
- defaultProp: c.conversationId ?? ""
19
- }), { logEvent: r } = pe(), { setConversationId: q, emitToParent: p } = de(), [a, u] = m(""), z = (e) => u(e.target.value), {
20
- /* shouldBypassCaptcha, */
21
- filters: w
22
- } = S, {
23
- onInputMessageChange: K,
24
- filters: M,
25
- agentUrl: x,
26
- context: f,
27
- headers: g,
28
- apiKey: d
29
- } = c, U = (e) => {
33
+ It seems I might be having some issues right now. Please clear the chat and try again.`, vt = () => {
34
+ const { baseSettings: d, aiChatSettings: u } = ze(), [s = "", p] = Ve({
35
+ prop: u.conversationId,
36
+ defaultProp: u.conversationId ?? ""
37
+ }), me = Le(), de = Ue(), fe = $e(), { logEvent: h } = je(), { setConversationId: ge, emitToParent: S } = Ze(), [y, k] = C(""), he = (e) => k(e.target.value), { shouldBypassCaptcha: q, filters: K, privacyPreferences: ye } = d, {
38
+ onInputMessageChange: ve,
39
+ filters: J,
40
+ baseUrl: I,
41
+ agentUrl: be,
42
+ context: j,
43
+ headers: G,
44
+ appId: v,
45
+ apiKey: m
46
+ } = u, Ce = me?.isOpen ?? de?.isOpen ?? fe?.isOpen ?? !0, { getCaptchaHeader: b, invalidate: c } = We({
47
+ baseUrl: I,
48
+ shouldBypassCaptcha: q || !!m,
49
+ shouldMakeInitialRequest: Ce
50
+ }), Q = l(b);
51
+ Q.current = b;
52
+ const V = be || `${I}/run/api/chat`, { sessionToken: N, refreshSession: T } = Ke({
53
+ baseUrl: I,
54
+ appId: v,
55
+ getCaptchaHeader: b,
56
+ invalidateCaptcha: c,
57
+ optOutAllAnalytics: ye?.optOutAllAnalytics
58
+ }), { loadConversation: Z } = Je({
59
+ baseUrl: I,
60
+ appId: v,
61
+ authToken: m ?? N,
62
+ getCaptchaHeader: b,
63
+ invalidateCaptcha: c,
64
+ // Only pass refreshSession for anonymous-session flows; API key auth has no token to refresh.
65
+ refreshSession: m ? void 0 : T
66
+ }), [Se, X] = C(!1), A = l(null);
67
+ A.current = N;
68
+ const f = l(0), Y = l(null), O = l(null), ee = l(G);
69
+ ee.current = G;
70
+ const _ = l(void 0);
71
+ _.current = K || J ? JSON.stringify({ ...K, ...J }) : void 0;
72
+ const Ie = (e) => {
30
73
  switch (e.code) {
31
74
  case 400:
32
75
  return e.message;
33
76
  case 403:
34
- return `There seems to be a configuration error. Please contact ${S.organizationDisplayName ?? "Administrator"}`;
77
+ return `There seems to be a configuration error. Please contact ${d.organizationDisplayName ?? "Administrator"}`;
35
78
  default:
36
- return he;
79
+ return pe;
37
80
  }
38
- }, [$, h] = m([]), [L, _] = m(null), j = () => ({
39
- "x-inkeep-client-timezone": Intl.DateTimeFormat().resolvedOptions().timeZone,
40
- "x-inkeep-client-timestamp": (/* @__PURE__ */ new Date()).toISOString()
41
- }), G = H(
42
- () => new ae({
43
- api: x,
44
- headers: {
45
- ...d ? { Authorization: `Bearer ${d}` } : {},
46
- ...g
81
+ }, [Ae, R] = C([]), [Re, F] = C(null), we = le(
82
+ () => new Pe({
83
+ api: V,
84
+ headers: () => ({
85
+ "x-inkeep-client-timezone": Intl.DateTimeFormat().resolvedOptions().timeZone,
86
+ "x-inkeep-client-timestamp": (/* @__PURE__ */ new Date()).toISOString(),
87
+ ...v ? { "x-inkeep-app-id": v } : {},
88
+ ...A.current ? { Authorization: `Bearer ${A.current}` } : {},
89
+ ...m ? { Authorization: `Bearer ${m}` } : {},
90
+ ..._.current ? { "inkeep-filters": _.current } : {},
91
+ ...ee.current
92
+ }),
93
+ prepareSendMessagesRequest: async (e) => {
94
+ const t = await Q.current();
95
+ return {
96
+ body: {
97
+ ...e.body,
98
+ id: e.id,
99
+ messages: e.messages,
100
+ trigger: e.trigger,
101
+ messageId: e.messageId
102
+ },
103
+ headers: {
104
+ ...e.headers,
105
+ ...t
106
+ }
107
+ };
47
108
  },
48
109
  body: {
49
- requestContext: f
110
+ requestContext: j
50
111
  }
51
112
  }),
52
- [x, d, g, f]
113
+ [V, j, v, m]
53
114
  ), {
54
- messages: i,
55
- sendMessage: F,
56
- addToolApprovalResponse: J,
57
- status: k,
58
- setMessages: A,
59
- stop: Q,
60
- error: v
61
- } = re({
62
- transport: G,
115
+ messages: w,
116
+ sendMessage: B,
117
+ addToolApprovalResponse: D,
118
+ status: te,
119
+ setMessages: g,
120
+ stop: se,
121
+ error: P
122
+ } = De({
123
+ transport: we,
63
124
  onData(e) {
64
- p(e.type, e.data);
125
+ S(e.type, e.data);
65
126
  },
66
127
  async onFinish() {
67
- p("completion", { conversationId: n }), await r({
128
+ S("completion", { conversationId: s }), await h({
68
129
  eventName: "assistant_message_received",
69
130
  properties: {
70
- conversationId: n
131
+ conversationId: s
71
132
  }
72
- }), r({
133
+ }), h({
73
134
  eventName: "assistant_answer_displayed",
74
135
  properties: {
75
- conversationId: n
136
+ conversationId: s
76
137
  }
77
138
  });
78
139
  },
79
140
  onError(e) {
80
- console.log("onError", e.message), r({
141
+ console.error("onError", { code: e.code, message: e.message });
142
+ const t = q || m ? null : Ye(e);
143
+ if (t !== null && f.current < 1) {
144
+ f.current++;
145
+ const a = O.current, n = Y.current;
146
+ (async () => {
147
+ if (t === "session") {
148
+ const o = await T();
149
+ o && (A.current = o);
150
+ } else
151
+ c();
152
+ if (a) {
153
+ D(a);
154
+ return;
155
+ }
156
+ n && (g((o) => {
157
+ let r = [...o];
158
+ return r.at(-1)?.role === "assistant" && (r = r.slice(0, -1)), r.at(-1)?.role === "user" && (r = r.slice(0, -1)), r;
159
+ }), B({ text: n.content }, { body: n.body }));
160
+ })().catch(() => {
161
+ f.current = 0, c(), g((o) => {
162
+ const r = [...o], z = r[r.length - 1];
163
+ if (!z) return r;
164
+ const ce = pe;
165
+ return z.role === "user" ? r.push({
166
+ id: W(16),
167
+ role: "assistant",
168
+ parts: [{ type: "text", text: ce }]
169
+ }) : z.parts = [{ type: "text", text: ce }], r;
170
+ });
171
+ });
172
+ return;
173
+ }
174
+ f.current = 0, t !== null && c(), h({
81
175
  eventName: "chat_error",
82
176
  properties: {
83
- conversationId: n,
177
+ conversationId: s,
84
178
  error: e.message
85
179
  }
86
- }), A((l) => {
87
- const s = [...l], t = s[s.length - 1];
88
- if (t) {
89
- const o = U(e);
90
- t.role === "user" ? s.push({
180
+ }), g((a) => {
181
+ const n = [...a], i = n[n.length - 1];
182
+ if (i) {
183
+ const o = Ie(e);
184
+ i.role === "user" ? n.push({
91
185
  id: W(16),
92
186
  role: "assistant",
93
187
  parts: [{ type: "text", text: o }]
94
- }) : t.parts = [{ type: "text", text: o }];
188
+ }) : i.parts = [{ type: "text", text: o }];
95
189
  }
96
- return s;
190
+ return n;
97
191
  });
98
192
  }
99
- }), D = k === "submitted", y = k === "streaming", V = H(() => {
100
- const e = (o) => {
101
- if (!o || typeof o != "object") return !1;
102
- const B = o;
103
- return typeof B.type == "string" && B.type.startsWith("tool-");
104
- }, s = [...i ?? []].reverse().find((o) => o.role === "assistant");
105
- if (!s) return !1;
106
- const t = s.parts?.at(-1);
107
- return !(!e(t) || t.state !== "output-available" || !t.approval?.id || y);
108
- }, [i, y]), N = y || V, T = D || N, Z = i.length === 0, I = !a.trim() || T, X = me("(max-width: 768px)"), [Y, C] = m(null);
109
- O(() => {
110
- v && C(v);
111
- }, [v]);
112
- const ee = () => C(null), R = ie(null);
113
- O(() => {
114
- K?.(a);
115
- }, [a]);
116
- const te = (e) => {
117
- e.key === "Enter" && !e.shiftKey && !I && !e.nativeEvent.isComposing && (e.preventDefault(), b());
118
- }, b = async (e = a) => {
119
- if (I && (!e || e.trim().length === 0)) return;
120
- h([]), u(""), await r({
193
+ }), re = te === "submitted", H = te === "streaming", Me = le(() => {
194
+ const e = (i) => {
195
+ if (!i || typeof i != "object") return !1;
196
+ const o = i;
197
+ return typeof o.type == "string" && o.type.startsWith("tool-");
198
+ }, a = [...w ?? []].reverse().find((i) => i.role === "assistant");
199
+ if (!a) return !1;
200
+ const n = a.parts?.at(-1);
201
+ return !(!e(n) || n.state !== "output-available" || !n.approval?.id || H);
202
+ }, [w, H]), ne = H || Me, oe = re || ne, Ee = w.length === 0, L = !y.trim() || oe, xe = qe("(max-width: 768px)"), [ke, M] = C(null);
203
+ ue(() => {
204
+ P && M(P);
205
+ }, [P]);
206
+ const Ne = () => M(null), ae = l(null);
207
+ ue(() => {
208
+ ve?.(y);
209
+ }, [y]);
210
+ const Te = (e) => {
211
+ e.key === "Enter" && !e.shiftKey && !L && !e.nativeEvent.isComposing && (e.preventDefault(), U());
212
+ }, U = async (e = y) => {
213
+ if (L && (!e || e.trim().length === 0)) return;
214
+ R([]), k(""), f.current = 0, O.current = null, await h({
121
215
  eventName: "user_message_submitted",
122
216
  properties: {
123
- conversationId: n
217
+ conversationId: s
124
218
  }
125
219
  });
126
- const l = w || M ? JSON.stringify({
127
- ...w,
128
- ...M
129
- }) : void 0, s = {
130
- ...g
131
- };
132
- l && (s["inkeep-filters"] = l);
133
- let t = n;
134
- t || (t = `conv_${W(16)}`, E(t)), q(t), F(
220
+ let t = s;
221
+ t || (t = `conv_${W(16)}`, p(t)), ge(t), Y.current = {
222
+ content: e,
223
+ body: { conversationId: t }
224
+ }, B(
225
+ { text: e },
135
226
  {
136
- text: e
137
- },
138
- {
139
- headers: {
140
- ...j(),
141
- ...s
142
- },
143
- body: {
144
- conversationId: t,
145
- requestContext: f
146
- }
227
+ body: { conversationId: t }
147
228
  }
148
229
  );
149
- }, se = () => {
150
- Q().then(() => {
151
- p("aborted", { conversationId: n });
230
+ }, Oe = x(
231
+ (e) => {
232
+ f.current = 0, O.current = e, D(e);
233
+ },
234
+ [D]
235
+ ), $ = x(() => {
236
+ se().then(() => {
237
+ S("aborted", { conversationId: s });
152
238
  });
153
- }, P = () => {
154
- ee(), A([]), E(""), h([]), _(null), r({
239
+ }, [se, s, S]), ie = () => {
240
+ Ne(), g([]), p(""), R([]), F(null), c(), h({
155
241
  eventName: "chat_clear_button_clicked",
156
242
  properties: {
157
- conversationId: n
243
+ conversationId: s
158
244
  }
159
245
  });
160
- }, { openForm: ne } = ue(), oe = fe();
161
- return le(c.chatFunctionsRef, () => ({
162
- submitMessage: b,
246
+ }, E = x(
247
+ (e, t) => {
248
+ M(null), g(t), p(e), R([]), F(null), c();
249
+ },
250
+ [g, p, c]
251
+ ), _e = x(
252
+ async (e, t) => {
253
+ $(), E(e, []), X(!0);
254
+ try {
255
+ const a = await Z(e, t);
256
+ a !== null && E(e, a);
257
+ } finally {
258
+ t?.aborted || X(!1);
259
+ }
260
+ },
261
+ [E, Z, $]
262
+ ), { openForm: Fe } = Ge(), Be = Qe();
263
+ return He(u.chatFunctionsRef, () => ({
264
+ submitMessage: U,
163
265
  updateInputMessage(e) {
164
- u(e);
266
+ k(e);
165
267
  },
166
- clearChat: P,
268
+ clearChat: ie,
167
269
  openForm: (e) => {
168
- oe?.setView("chat"), ne(e, void 0);
270
+ Be?.setView("chat"), Fe(e, void 0);
169
271
  },
170
272
  focusInput: () => {
171
- R.current?.focus();
273
+ ae.current?.focus();
172
274
  }
173
275
  })), {
174
- messages: i,
175
- sendMessage: F,
176
- addToolApprovalResponse: J,
177
- isLoading: D,
178
- isStreaming: N,
179
- isBusy: T,
180
- error: Y,
181
- setError: C,
182
- isSubmitDisabled: I,
183
- input: a,
184
- handleInputChange: z,
185
- handleInputKeyDown: te,
186
- handleSubmit: b,
187
- stop: se,
188
- clear: P,
189
- isEmpty: i.length === 0,
190
- inputRef: R,
191
- isMobile: X,
276
+ messages: w,
277
+ sendMessage: B,
278
+ addToolApprovalResponse: Oe,
279
+ isLoading: re,
280
+ isStreaming: ne,
281
+ isBusy: oe,
282
+ error: ke,
283
+ setError: M,
284
+ isSubmitDisabled: L,
285
+ input: y,
286
+ handleInputChange: he,
287
+ handleInputKeyDown: Te,
288
+ handleSubmit: U,
289
+ stop: $,
290
+ clear: ie,
291
+ inputRef: ae,
292
+ isMobile: xe,
192
293
  // Additional state for attachments and workflow
193
- messageAttachments: $,
194
- setMessageAttachments: h,
195
- selectedWorkflow: L,
196
- setSelectedWorkflow: _,
197
- isNewChat: Z,
198
- conversationId: n
294
+ messageAttachments: Ae,
295
+ setMessageAttachments: R,
296
+ selectedWorkflow: Re,
297
+ setSelectedWorkflow: F,
298
+ isNewChat: Ee,
299
+ conversationId: s,
300
+ restoreSession: E,
301
+ loadAndRestoreSession: _e,
302
+ isSessionLoading: Se,
303
+ sessionToken: N,
304
+ refreshSession: T,
305
+ getCaptchaHeader: b,
306
+ invalidateCaptcha: c
199
307
  };
200
308
  };
201
309
  export {
202
- he as DEFAULT_ERROR_MESSAGE,
203
- Fe as useInkeepChat
310
+ pe as DEFAULT_ERROR_MESSAGE,
311
+ vt as useInkeepChat
204
312
  };
@@ -1 +1 @@
1
- "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react"),L=require("./use-inkeep-chat.cjs");function M(l,u,C){const[p,k]=r.useState([]),[y,x]=r.useState(new Map),[w,A]=r.useState(Date.now()),[P,d]=r.useState(!1),S=r.useRef(0),D=r.useRef(0),R=r.useRef([]),m=r.useRef(y);m.current=y;const T=r.useCallback(()=>{const t=[];let e="",o=[],i=!1;l.length>S.current&&(A(Date.now()),S.current=l.length),D.current=0;const c=new Map,a=(n=!1)=>{if(o.length>0){const s=`group-${D.current++}`,h=m.current.get(s);h?c.set(s,{...h,isCompleted:n}):c.set(s,{isCompleted:n}),t.push({type:"summary-group",summaries:[...o],groupKey:s}),o=[]}};for(const n of l)if(n.type==="text")a(!0),e+=n.text||"";else if(n.type==="data-summary")e.trim()&&(t.push({type:"text",text:e}),e=""),o.push(n.data);else if(n.type==="data-operation"){e.trim()&&(t.push({type:"text",text:e}),e="");const s=n.data;if(s?.type){if((s.type==="tool_call"||s.type==="tool_result")&&s.details?.data?.inDelegatedAgent===!1)continue;switch(s.type){case"agent_initializing":break;case"completion":{const{type:f}=s;o.push({type:f,label:"Completed"}),a(!0);break}case"error":{const f=s.message||"Unknown error";if(console.warn("Data operation error:",f),!t.length)a(!0),C(new Error(f)),i||(t.push({type:"text",text:L.DEFAULT_ERROR_MESSAGE}),i=!0);else{const{type:g,label:E}=s;o.push({type:g,label:E})}break}default:{const{type:f,label:g}=s;o.push({type:f,label:g});break}}}}else if(n.type==="data-artifact")if(n.data?.type?.toLowerCase()==="citation"){const s=n.data,h=s.artifactSummary||{title:s.name};e+=` ^${h?.title||s.name}^`}else e.trim()&&(t.push({type:"text",text:e}),e=""),t.push(n);else n.type==="data-component"?(e.trim()&&(t.push({type:"text",text:e}),e=""),a(!0),t.push(n)):(e.trim()&&(t.push({type:"text",text:e}),e=""),a(!0),t.push(n));return a(!u),e.trim()&&t.push({type:"text",text:e}),{processed:t,newTimings:c}},[l,u,C]);r.useEffect(()=>{if(R.current===l)return;R.current=l;const{processed:t,newTimings:e}=T();k(t),(e.size!==m.current.size||Array.from(e.entries()).some(([i,c])=>{const a=m.current.get(i);return!a||a.isCompleted!==c.isCompleted}))&&x(e)},[T,l]),r.useEffect(()=>{u||x(t=>{const e=new Map(t);let o=!1;for(const[i,c]of e.entries())c.isCompleted||(e.set(i,{...c,isCompleted:!0}),o=!0);return o?e:t})},[u]);const b=r.useCallback(()=>{const t=Date.now()-w,e=Array.from(m.current.values()).some(i=>!i.isCompleted),o=t>1e3&&!e;d(o)},[w]);r.useEffect(()=>{if(!u){d(!1);return}if(!(p.length>0)){d(!1);return}const e=setInterval(b,200);return()=>clearInterval(e)},[u,b,p.length]);const v=r.useMemo(()=>!!(!(p.length>0)&&u),[p.length,u]);return{processedParts:p,summaryTimings:y,shouldShowInitialLoading:v,shouldShowStreamDelayLoading:P}}exports.useStreamProcessor=M;
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l=require("react"),O=require("./use-inkeep-chat.cjs");function R(a,n){if(n)return a.findIndex(h=>h.type==="tool_call"&&h.toolCallId===n);const d=a.length-1;return d>=0&&a[d].type==="tool_call"?d:-1}function G(a){const n=a.ctx,h=a.details?.data,y=n?.toolCallId??n?.callId??a.toolCallId??h?.toolCallId;return typeof y=="string"?y:void 0}function q(a,n,d){const[h,y]=l.useState(!1),D=l.useRef(0),v=l.useRef(0),A=l.useRef(Date.now()),g=l.useRef(new Map),k=l.useRef(null),{processedParts:b,summaryTimings:P}=l.useMemo(()=>{const r=[];let t="",o=[],w=!1;a.length>D.current&&(A.current=Date.now(),D.current=a.length),v.current=0;const f=new Map,x=(s=!1)=>{if(o.length>0){const e=`group-${v.current++}`,u=g.current.get(e);u?f.set(e,{...u,isCompleted:s}):f.set(e,{isCompleted:s}),r.push({type:"summary-group",summaries:[...o],groupKey:e}),o=[]}};for(const s of a)if(s.type==="text")x(!0),t+=s.text||"";else if(s.type==="data-summary")t.trim()&&(r.push({type:"text",text:t}),t=""),o.push(s.data);else if(s.type==="data-operation"){t.trim()&&(r.push({type:"text",text:t}),t="");const e=s.data;if(e?.type){if((e.type==="tool_call"||e.type==="tool_result")&&e.details?.data?.inDelegatedAgent===!1)continue;switch(e.type){case"agent_initializing":break;case"completion":{const{type:i}=e;o.push({type:i,label:"Completed"}),x(!0);break}case"error":{const i=e.message||"Unknown error";if(console.warn("Data operation error:",i),!r.length)x(!0),k.current=i,w||(r.push({type:"text",text:O.DEFAULT_ERROR_MESSAGE}),w=!0);else{const{type:p,label:c}=e;o.push({type:p,label:c})}break}case"tool_call":{const{type:i,label:p}=e,c=G(e);o.push({type:i,label:p,...c&&{toolCallId:c}});break}case"tool_result":{const{type:i,label:p}=e,c=G(e),S={type:i,label:p},M=R(o,c);if(M>=0){o[M]=S;break}const T=r.filter(I=>I?.type==="summary-group");if(c){let I=!1;for(let m=T.length-1;m>=0;m--){const C=T[m].summaries;if(C?.length){const L=R(C,c);if(L>=0){C[L]=S,I=!0;break}}}if(I)break}else{const m=T[T.length-1]?.summaries;if(m?.length){const C=R(m,void 0);if(C>=0){m[C]=S;break}}}o.push(S);break}default:{const{type:i,label:p}=e;o.push({type:i,label:p});break}}}}else if(s.type==="data-artifact")if(s.data?.type?.toLowerCase()==="citation"){const e=s.data,u=e.artifactSummary||{title:e.name};t+=` ^${u?.title||e.name}^`}else t.trim()&&(r.push({type:"text",text:t}),t=""),r.push(s);else s.type==="data-component"?(t.trim()&&(r.push({type:"text",text:t}),t=""),x(!0),r.push(s)):(t.trim()&&(r.push({type:"text",text:t}),t=""),x(!0),r.push(s));if(x(!n),t.trim()&&r.push({type:"text",text:t}),!n)for(const[s,e]of f.entries())e.isCompleted||f.set(s,{...e,isCompleted:!0});const _=f.size!==g.current.size||Array.from(f.entries()).some(([s,e])=>{const u=g.current.get(s);return!u||u.isCompleted!==e.isCompleted})?f:g.current;return g.current=_,{processedParts:r,summaryTimings:_}},[a,n]);l.useEffect(()=>{k.current&&(d(new Error(k.current)),k.current=null)});const E=l.useCallback(()=>{const r=Date.now()-A.current,t=Array.from(g.current.values()).some(w=>!w.isCompleted),o=r>1e3&&!t;y(o)},[]);l.useEffect(()=>{if(!n){y(!1);return}if(!(b.length>0)){y(!1);return}const t=setInterval(E,200);return()=>clearInterval(t)},[n,E,b.length]);const z=l.useMemo(()=>!!(!(b.length>0)&&n),[b.length,n]);return{processedParts:b,summaryTimings:P,shouldShowInitialLoading:z,shouldShowStreamDelayLoading:h}}exports.useStreamProcessor=q;
@@ -6,6 +6,8 @@ interface DataSummary {
6
6
  type: string;
7
7
  label?: string;
8
8
  details?: Record<string, unknown>;
9
+ /** Used to match tool_result to tool_call when they're in different groups (e.g. approval in between) or parallel */
10
+ toolCallId?: string;
9
11
  }
10
12
  interface TextPart {
11
13
  type: 'text';