@inkeep/agents-ui 0.17.4 → 0.17.6

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 +1 @@
1
- "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("react/jsx-runtime"),r=require("react"),b=require("../../atoms/icons/custom-icon.cjs"),_=require("../../providers/image-preview-provider.cjs"),y=require("../../providers/message-provider.cjs"),m=require("./chat-provider.cjs"),p=require("../../atoms/file-upload.cjs"),g=require("../../utils/misc.cjs"),c=require("../../utils/compose-event-handlers.cjs"),o=require("../factory.cjs"),w=require("../../providers/config-provider.cjs"),E={"application/pdf":"filePdf","text/plain":"fileText","text/markdown":"fileMarkdown","text/html":"fileHtml","text/csv":"fileCsv","text/x-log":"fileLog","application/json":"fileJson","text/x-sql":"fileSql","application/x-sql":"fileSql","text/x-script.python":"filePy","text/x-python":"filePy","text/x-python-script":"filePy"};function C(t){return t.startsWith("image/")}const u={"image/png":[".png"],"image/jpeg":[".jpg",".jpeg"],"image/webp":[".webp"],"application/pdf":[".pdf"],"text/plain":[".txt",".text",".bat",".cfg",".conf",".def",".dic",".in",".list"],"text/x-log":[".log"],"text/markdown":[".md",".markdown"],"text/html":[".html",".htm"],"text/csv":[".csv"],"text/xml":[".xml"],"text/css":[".css"],"application/json":[".json"],"application/yaml":[".yaml",".yml"],"application/x-yaml":[".yaml",".yml"],"text/x-yaml":[".yaml",".yml"],"application/toml":[".toml"],"application/x-toml":[".toml"],"application/graphql":[".graphql",".gql"],"application/x-graphql":[".graphql",".gql"],"text/x-graphql":[".graphql",".gql"],"application/x-ndjson":[".ndjson"],"application/json5":[".json5"],"application/x-json5":[".json5"],"application/javascript":[".js",".mjs"],"text/javascript":[".js",".mjs"],"application/typescript":[".ts"],"text/x-typescript":[".ts"],"text/jsx":[".jsx"],"text/tsx":[".tsx"],"text/x-sh":[".sh"],"text/x-bash":[".bash"],"application/x-bash":[".bash"],"text/x-zsh":[".zsh"],"text/x-shellscript":[".sh",".ksh"],"application/x-powershell":[".ps1"],"text/vbscript":[".vbs"],"text/x-awk":[".awk"],"application/x-awk":[".awk"],"text/x-c":[".c",".h"],"text/x-c++":[".cpp",".cc",".cxx",".hh"],"text/x-csharp":[".cs"],"text/x-objectivec":[".m"],"text/x-objectivec++":[".mm"],"text/x-java":[".java"],"text/x-scala":[".scala"],"application/x-scala":[".scala"],"text/x-kotlin":[".kt"],"text/x-groovy":[".groovy"],"text/x-clojure":[".clj"],"text/x-go":[".go"],"text/x-golang":[".go"],"text/x-rust":[".rs"],"application/x-rust":[".rs"],"text/x-swift":[".swift"],"text/x-dart":[".dart"],"text/x-python":[".py"],"text/x-script.python":[".py"],"text/x-python-script":[".py"],"text/x-ruby":[".rb"],"text/x-perl":[".pl"],"text/x-lua":[".lua"],"text/x-r":[".r"],"text/x-R":[".r"],"text/x-julia":[".jl"],"text/x-elixir":[".ex"],"text/x-erlang":[".erl"],"text/x-haskell":[".hs"],"text/x-lisp":[".lisp"],"text/x-php":[".php"],"application/x-php":[".php"],"application/x-httpd-php":[".php"],"application/x-httpd-php-source":[".php"],"text/x-tex":[".tex"],"text/x-rst":[".rst"],"text/x-handlebars":[".hbs"],"text/x-mustache":[".mustache"],"text/x-ejs":[".ejs"],"text/x-jinja2":[".jinja",".jinja2"],"text/x-liquid":[".liquid"],"text/x-erb":[".erb"],"text/x-twig":[".twig"],"text/x-pug":[".pug"],"text/x-jade":[".jade"],"text/x-tmpl":[".tmpl"],"text/x-astro":[".astro"],"text/x-sass":[".sass"],"text/x-scss":[".scss"],"text/x-less":[".less"],"text/x-sql":[".sql"],"application/x-sql":[".sql"],"text/x-makefile":[".makefile",".mk"],"text/x-cmake":[".cmake"],"text/x-dockerfile":[".dockerfile"],"text/x-gradle":[".gradle"],"text/x-ini":[".ini"],"text/x-properties":[".properties"],"text/x-protobuf":[".proto"],"application/x-protobuf":[".proto"],"text/x-hcl":[".hcl"],"text/x-terraform":[".tf"],"application/x-terraform":[".tf"],"text/x-diff":[".diff"],"text/x-patch":[".patch"],"application/x-patch":[".patch"],"text/x-asm":[".asm",".s"],"message/rfc822":[".eml",".mht",".mhtml",".mime",".nws"],"text/srt":[".srt"],"application/x-subrip":[".srt"],"text/x-subrip":[".srt"],"text/vtt":[".vtt"],"text/x-vcard":[".vcf"],"text/calendar":[".ics",".ifb"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":[".docx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":[".xlsx"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":[".pptx"],"application/vnd.oasis.opendocument.text":[".odt"],"application/vnd.oasis.opendocument.spreadsheet":[".ods"],"application/vnd.oasis.opendocument.presentation":[".odp"],"application/vnd.apple.pages":[".pages"],"application/vnd.apple.numbers":[".numbers"],"application/vnd.apple.keynote":[".key"],"application/x-iwork-pages-sffpages":[".pages"],"application/x-iwork-numbers-sffnumbers":[".numbers"],"application/x-iwork-keynote-sffkey":[".key"]},j=new Set(Object.keys(u)),F=10,I=1024*1024*10,N=Object.entries(u).reduce((t,[e,i])=>{for(const n of i)t[n]=e;return t},{});function k(t){if(t.type)return t;const e=`.${t.name.split(".").pop()?.toLowerCase()}`,i=N[e];return i?new File([t],t.name,{type:i}):t}function T(t){if(!t.length)return null;const e=i=>t.some(n=>n.errors.includes(i));return e("TOO_MANY_FILES")?{title:"Attachment limit reached",message:`You can only attach up to ${F} files per message.`}:e("FILE_INVALID_TYPE")?{title:"Unsupported file type",message:"Supported formats include images, PDFs, text, code, and document files."}:e("FILE_TOO_LARGE")?{title:"File too large",message:`Files must be smaller than ${I/1024/1024}MB.`}:e("FILE_EXISTS")?{title:"File already exists",message:`The file "${t.find(n=>n.errors.includes("FILE_EXISTS"))?.file.name??"file"}" is already attached to this message.`}:{title:"File rejected",message:"This file could not be added."}}const M=o.ikp("div",{_id:"aiChatMessage__Files"}),q=({children:t,...e})=>{const{message:i}=y.useMessage();if(i.role!=="user")return null;const n=(i.parts??[]).filter(s=>{if(s.type!=="file")return!1;const l=s.mediaType;return j.has(l??"")});return n.length?a.jsx(M,{...e,children:t(n)}):null},L=o.ikp("button",{_id:"aiChatMessage__File"}),A=({url:t,name:e,mediaType:i,onClick:n,...s})=>{const{openImagePreview:l}=_.useImagePreview(),[d,h]=r.useState(!0),f=r.useMemo(()=>new File([],e??"file",{type:i}),[e,i]);return a.jsx(P.Provider,{value:{file:f,objectUrl:t,isLoading:d,setIsLoading:h,onRemove:()=>{}},children:a.jsx(L,{type:"button","aria-label":C(i??"")?`Preview ${e??"file"}`:`Open ${e??"file"} in new tab`,"data-loading":g.dataAttr(d),onClick:c.composeEventHandlers(n,()=>{if(C(i??""))l({url:t,name:e??"file"});else if(t)if(t.startsWith("data:")){const v=document.createElement("a");v.href=t,v.download=e??"file",v.click()}else window.open(t,"_blank","noopener,noreferrer")}),...s})})},U=o.ikp("div",{_id:"aiChatInput__Fieldset"}),S=t=>{const e=p.useFileUploadApi();return a.jsx(U,{...e.getDropzoneProps({disableClick:!0}),"data-drag-over":g.dataAttr(e.dragging),...t})},R=({...t})=>{const{files:e,setFiles:i,showInputNotification:n}=m.useChat();return a.jsx(p.FileUploadRoot,{accept:u,maxFiles:F,maxFileSize:I,preventDocumentDrop:!0,acceptedFiles:e,onFileAccept:s=>i(s.files),onFileReject:s=>{const l=T(s.files);l&&n(l)},children:a.jsx(S,{...t})})},O=o.ikp("div",{_id:"aiChatInput__DropZone"}),H=o.ikp("div",{_id:"aiChatInput__Notification"}),D=t=>{const{inputNotification:e}=m.useChat();return e?a.jsx(H,{role:"alert",...t}):null},B=o.ikp("p",{_id:"aiChatInput__NotificationTitle"}),X=({children:t,...e})=>{const{inputNotification:i}=m.useChat();return i?.title?a.jsxs(B,{...e,children:[t,i.title]}):null},Y=o.ikp("p",{_id:"aiChatInput__NotificationMessage"}),$=t=>{const{inputNotification:e}=m.useChat();return a.jsx(Y,{...t,children:e?.message})},z=o.ikp("button",{_id:"aiChatInput__NotificationClose"}),Z=({onClick:t,...e})=>{const{clearInputNotification:i}=m.useChat();return a.jsx(z,{type:"button","aria-label":"Dismiss",onClick:c.composeEventHandlers(t,i),...e})},K=o.ikp("div",{_id:"aiChatInput__NotificationContent"}),V=o.ikp("div",{_id:"aiChatInput__NotificationHeader"}),W=o.ikp(b.CustomIcon,{_id:"aiChatInput__FileUploadButtonIcon",iconKey:"fileUpload"}),G=o.ikp("button",{_id:"aiChatInput__FileUploadButton"}),J=t=>{const{aiChatSettings:e}=w.useInkeepConfig(),i=p.useFileUploadApi(),{onClick:n,...s}=t;return a.jsx(G,{type:"button","aria-label":"Upload file",disabled:e.isViewOnly,onClick:c.composeEventHandlers(n,()=>i.openFilePicker()),...s})},Q=o.ikp("input",{_id:"aiChatInput__FileInput"}),tt=t=>{const e=p.useFileUploadApi();return a.jsx(Q,{...t,...e.getHiddenInputProps()})},et=o.ikp("div",{_id:"aiChatInput__FileList"}),it=({children:t,...e})=>{const n=p.useFileUploadApi().acceptedFiles;return n.length?a.jsx(et,{...e,children:t(n)}):null},P=r.createContext(null);function x(){const t=r.useContext(P);if(!t)throw new Error("useFileContext must be used within EmbeddedChatPrimitiveFileItem");return t}const nt=o.ikp("div",{_id:"aiChatInput__FileItem"}),at=({file:t,...e})=>{const i=p.useFileUploadApi(),[n,s]=r.useState(void 0),[l,d]=r.useState(!0);r.useEffect(()=>i.createFileUrl(t,f=>{s(f),d(!0)}),[t]);const h=()=>i.deleteFile(t);return a.jsx(P.Provider,{value:{file:t,objectUrl:n,isLoading:l,setIsLoading:d,onRemove:h},children:a.jsx(nt,{"data-loading":g.dataAttr(l),...e})})},ot=o.ikp("button",{_id:"aiChatInput__FilePreviewTrigger"}),st=({onClick:t,...e})=>{const{objectUrl:i,file:n}=x(),{openImagePreview:s}=_.useImagePreview();return a.jsx(ot,{type:"button","aria-label":`Preview ${n.name}`,disabled:!i,onClick:c.composeEventHandlers(t,()=>{i&&s({url:i,name:n.name})}),...e})},lt=o.ikp("span",{_id:"aiChatInput__FileContent"}),rt=t=>a.jsx(lt,{...t}),pt=o.ikp("img",{_id:"aiChatInput__FileThumbnail"}),ct=({onLoad:t,...e})=>{const{objectUrl:i,file:n,setIsLoading:s}=x();return a.jsx(pt,{src:i,alt:n.name,onLoad:c.composeEventHandlers(t,()=>s(!1)),...e})},dt=({className:t})=>{const{file:e}=x(),i=E[k(e).type]??"file";return a.jsx(b.CustomIcon,{iconKey:i,className:t})},mt=o.ikp("span",{_id:"aiChatInput__FileName"}),xt=t=>{const{file:e}=x();return a.jsx(mt,{...t,children:e.name})},ut=o.ikp("button",{_id:"aiChatInput__FileRemove"}),ht=o.ikp(b.CustomIcon,{_id:"aiChatInput__FileRemoveIcon",iconKey:"close"}),ft=({onClick:t,...e})=>{const{onRemove:i}=x();return a.jsx(ut,{type:"button","aria-label":"Remove file",onClick:c.composeEventHandlers(t,i),...e})};exports.ACCEPTED_FILE_MIME_TYPES=j;exports.EmbeddedChatPrimitiveDropZone=O;exports.EmbeddedChatPrimitiveFileContent=rt;exports.EmbeddedChatPrimitiveFileInput=tt;exports.EmbeddedChatPrimitiveFileItem=at;exports.EmbeddedChatPrimitiveFileList=it;exports.EmbeddedChatPrimitiveFileName=xt;exports.EmbeddedChatPrimitiveFilePreviewTrigger=st;exports.EmbeddedChatPrimitiveFileRemove=ft;exports.EmbeddedChatPrimitiveFileRemoveIcon=ht;exports.EmbeddedChatPrimitiveFileThumbnail=ct;exports.EmbeddedChatPrimitiveFileTypeIcon=dt;exports.EmbeddedChatPrimitiveFileUploadButton=J;exports.EmbeddedChatPrimitiveFileUploadButtonIcon=W;exports.EmbeddedChatPrimitiveInputFieldset=R;exports.EmbeddedChatPrimitiveInputNotification=D;exports.EmbeddedChatPrimitiveInputNotificationClose=Z;exports.EmbeddedChatPrimitiveInputNotificationContent=K;exports.EmbeddedChatPrimitiveInputNotificationHeader=V;exports.EmbeddedChatPrimitiveInputNotificationMessage=$;exports.EmbeddedChatPrimitiveInputNotificationTitle=X;exports.EmbeddedChatPrimitiveMessageFile=A;exports.EmbeddedChatPrimitiveMessageFiles=q;exports.FILE_ACCEPT_MAP=u;exports.FILE_TYPE_ICON_MAP=E;exports.MAX_FILES=F;exports.MAX_FILE_SIZE=I;exports.isImageMimeType=C;exports.normalizeFileType=k;
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("react/jsx-runtime"),p=require("react"),b=require("../../atoms/icons/custom-icon.cjs"),j=require("../../providers/image-preview-provider.cjs"),N=require("../../providers/message-provider.cjs"),u=require("./chat-provider.cjs"),m=require("../../atoms/file-upload.cjs"),F=require("../../utils/misc.cjs"),x=require("../../utils/compose-event-handlers.cjs"),s=require("../factory.cjs"),y=require("../../providers/config-provider.cjs"),k={"application/pdf":"filePdf","text/plain":"fileText","text/markdown":"fileMarkdown","text/html":"fileHtml","text/csv":"fileCsv","text/x-log":"fileLog","application/json":"fileJson","text/x-sql":"fileSql","application/x-sql":"fileSql","text/x-script.python":"filePy","text/x-python":"filePy","text/x-python-script":"filePy"};function C(e){return e.startsWith("image/")}const v={"image/png":[".png"],"image/jpeg":[".jpg",".jpeg"],"image/webp":[".webp"],"application/pdf":[".pdf"],"text/plain":[".txt",".text",".bat",".cfg",".conf",".def",".dic",".in",".list"],"text/x-log":[".log"],"text/markdown":[".md",".markdown"],"text/html":[".html",".htm"],"text/csv":[".csv"],"text/xml":[".xml"],"text/css":[".css"],"application/json":[".json"],"application/yaml":[".yaml",".yml"],"application/x-yaml":[".yaml",".yml"],"text/x-yaml":[".yaml",".yml"],"application/toml":[".toml"],"application/x-toml":[".toml"],"application/graphql":[".graphql",".gql"],"application/x-graphql":[".graphql",".gql"],"text/x-graphql":[".graphql",".gql"],"application/x-ndjson":[".ndjson"],"application/json5":[".json5"],"application/x-json5":[".json5"],"application/javascript":[".js",".mjs"],"text/javascript":[".js",".mjs"],"application/typescript":[".ts"],"text/x-typescript":[".ts"],"text/jsx":[".jsx"],"text/tsx":[".tsx"],"text/x-sh":[".sh"],"text/x-bash":[".bash"],"application/x-bash":[".bash"],"text/x-zsh":[".zsh"],"text/x-shellscript":[".sh",".ksh"],"application/x-powershell":[".ps1"],"text/vbscript":[".vbs"],"text/x-awk":[".awk"],"application/x-awk":[".awk"],"text/x-c":[".c",".h"],"text/x-c++":[".cpp",".cc",".cxx",".hh"],"text/x-csharp":[".cs"],"text/x-objectivec":[".m"],"text/x-objectivec++":[".mm"],"text/x-java":[".java"],"text/x-scala":[".scala"],"application/x-scala":[".scala"],"text/x-kotlin":[".kt"],"text/x-groovy":[".groovy"],"text/x-clojure":[".clj"],"text/x-go":[".go"],"text/x-golang":[".go"],"text/x-rust":[".rs"],"application/x-rust":[".rs"],"text/x-swift":[".swift"],"text/x-dart":[".dart"],"text/x-python":[".py"],"text/x-script.python":[".py"],"text/x-python-script":[".py"],"text/x-ruby":[".rb"],"text/x-perl":[".pl"],"text/x-lua":[".lua"],"text/x-r":[".r"],"text/x-R":[".r"],"text/x-julia":[".jl"],"text/x-elixir":[".ex"],"text/x-erlang":[".erl"],"text/x-haskell":[".hs"],"text/x-lisp":[".lisp"],"text/x-php":[".php"],"application/x-php":[".php"],"application/x-httpd-php":[".php"],"application/x-httpd-php-source":[".php"],"text/x-tex":[".tex"],"text/x-rst":[".rst"],"text/x-handlebars":[".hbs"],"text/x-mustache":[".mustache"],"text/x-ejs":[".ejs"],"text/x-jinja2":[".jinja",".jinja2"],"text/x-liquid":[".liquid"],"text/x-erb":[".erb"],"text/x-twig":[".twig"],"text/x-pug":[".pug"],"text/x-jade":[".jade"],"text/x-tmpl":[".tmpl"],"text/x-astro":[".astro"],"text/x-sass":[".sass"],"text/x-scss":[".scss"],"text/x-less":[".less"],"text/x-sql":[".sql"],"application/x-sql":[".sql"],"text/x-makefile":[".makefile",".mk"],"text/x-cmake":[".cmake"],"text/x-dockerfile":[".dockerfile"],"text/x-gradle":[".gradle"],"text/x-ini":[".ini"],"text/x-properties":[".properties"],"text/x-protobuf":[".proto"],"application/x-protobuf":[".proto"],"text/x-hcl":[".hcl"],"text/x-terraform":[".tf"],"application/x-terraform":[".tf"],"text/x-diff":[".diff"],"text/x-patch":[".patch"],"application/x-patch":[".patch"],"text/x-asm":[".asm",".s"],"message/rfc822":[".eml",".mht",".mhtml",".mime",".nws"],"text/srt":[".srt"],"application/x-subrip":[".srt"],"text/x-subrip":[".srt"],"text/vtt":[".vtt"],"text/x-vcard":[".vcf"],"text/calendar":[".ics",".ifb"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":[".docx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":[".xlsx"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":[".pptx"],"application/vnd.oasis.opendocument.text":[".odt"],"application/vnd.oasis.opendocument.spreadsheet":[".ods"],"application/vnd.oasis.opendocument.presentation":[".odp"],"application/vnd.apple.pages":[".pages"],"application/vnd.apple.numbers":[".numbers"],"application/vnd.apple.keynote":[".key"],"application/x-iwork-pages-sffpages":[".pages"],"application/x-iwork-numbers-sffnumbers":[".numbers"],"application/x-iwork-keynote-sffkey":[".key"]},w=new Set(Object.keys(v)),I=10,P=1024*1024*10,T=Object.entries(v).reduce((e,[t,i])=>{for(const n of i)e[n]=t;return e},{});function M(e){if(e.type)return e;const t=`.${e.name.split(".").pop()?.toLowerCase()}`,i=T[t];return i?new File([e],e.name,{type:i}):e}function q(e){if(!e.length)return null;const t=i=>e.some(n=>n.errors.includes(i));return t("TOO_MANY_FILES")?{title:"Attachment limit reached",message:`You can only attach up to ${I} files per message.`}:t("FILE_INVALID_TYPE")?{title:"Unsupported file type",message:"Supported formats include images, PDFs, text, code, and document files."}:t("FILE_TOO_LARGE")?{title:"File too large",message:`Files must be smaller than ${P/1024/1024}MB.`}:t("FILE_EXISTS")?{title:"File already exists",message:`The file "${e.find(n=>n.errors.includes("FILE_EXISTS"))?.file.name??"file"}" is already attached to this message.`}:{title:"File rejected",message:"This file could not be added."}}const L=s.ikp("div",{_id:"aiChatMessage__Files"}),f=new WeakSet;let E=!1;function A(e,t){const i=t.map(a=>{if(!a.providerMetadata)return{...a};try{return{...a,providerMetadata:structuredClone(a.providerMetadata)}}catch{return E||(E=!0,console.warn("[transformMessageFiles] providerMetadata is not structured-cloneable; passing a shared reference. A transformer that mutates it writes through into live message state.")),{...a}}});let n;try{n=e(i)}catch(a){return f.has(e)||(f.add(e),console.warn("[transformMessageFiles] transformer threw",a)),t}return Array.isArray(n)?n.filter(a=>a!=null):(f.has(e)||(f.add(e),console.warn("[transformMessageFiles] transformer must return an array, got:",n)),t)}const S=({children:e,...t})=>{const{message:i}=N.useMessage(),{aiChatSettings:n}=y.useInkeepConfig();if(i.role!=="user")return null;const a=(i.parts??[]).filter(l=>l.type==="file"),r=n.transformMessageFiles,d=(r?A(r,a):a).filter(l=>w.has(l.mediaType??""));return d.length?o.jsx(L,{...t,children:e(d)}):null},U=s.ikp("button",{_id:"aiChatMessage__File"}),R=({url:e,name:t,mediaType:i,onClick:n,...a})=>{const{openImagePreview:r}=j.useImagePreview(),[c,d]=p.useState(!0),l=p.useMemo(()=>new File([],t??"file",{type:i}),[t,i]);return o.jsx(_.Provider,{value:{file:l,objectUrl:e,isLoading:c,setIsLoading:d,onRemove:()=>{}},children:o.jsx(U,{type:"button","aria-label":C(i??"")?`Preview ${t??"file"}`:`Open ${t??"file"} in new tab`,"data-loading":F.dataAttr(c),onClick:x.composeEventHandlers(n,()=>{if(C(i??""))r({url:e,name:t??"file"});else if(e)if(e.startsWith("data:")){const g=document.createElement("a");g.href=e,g.download=t??"file",g.click()}else window.open(e,"_blank","noopener,noreferrer")}),...a})})},O=s.ikp("div",{_id:"aiChatInput__Fieldset"}),H=e=>{const t=m.useFileUploadApi();return o.jsx(O,{...t.getDropzoneProps({disableClick:!0}),"data-drag-over":F.dataAttr(t.dragging),...e})},D=({...e})=>{const{files:t,setFiles:i,showInputNotification:n}=u.useChat();return o.jsx(m.FileUploadRoot,{accept:v,maxFiles:I,maxFileSize:P,preventDocumentDrop:!0,acceptedFiles:t,onFileAccept:a=>i(a.files),onFileReject:a=>{const r=q(a.files);r&&n(r)},children:o.jsx(H,{...e})})},B=s.ikp("div",{_id:"aiChatInput__DropZone"}),X=s.ikp("div",{_id:"aiChatInput__Notification"}),Y=e=>{const{inputNotification:t}=u.useChat();return t?o.jsx(X,{role:"alert",...e}):null},$=s.ikp("p",{_id:"aiChatInput__NotificationTitle"}),z=({children:e,...t})=>{const{inputNotification:i}=u.useChat();return i?.title?o.jsxs($,{...t,children:[e,i.title]}):null},Z=s.ikp("p",{_id:"aiChatInput__NotificationMessage"}),W=e=>{const{inputNotification:t}=u.useChat();return o.jsx(Z,{...e,children:t?.message})},K=s.ikp("button",{_id:"aiChatInput__NotificationClose"}),V=({onClick:e,...t})=>{const{clearInputNotification:i}=u.useChat();return o.jsx(K,{type:"button","aria-label":"Dismiss",onClick:x.composeEventHandlers(e,i),...t})},G=s.ikp("div",{_id:"aiChatInput__NotificationContent"}),J=s.ikp("div",{_id:"aiChatInput__NotificationHeader"}),Q=s.ikp(b.CustomIcon,{_id:"aiChatInput__FileUploadButtonIcon",iconKey:"fileUpload"}),ee=s.ikp("button",{_id:"aiChatInput__FileUploadButton"}),te=e=>{const{aiChatSettings:t}=y.useInkeepConfig(),i=m.useFileUploadApi(),{onClick:n,...a}=e;return o.jsx(ee,{type:"button","aria-label":"Upload file",disabled:t.isViewOnly,onClick:x.composeEventHandlers(n,()=>i.openFilePicker()),...a})},ie=s.ikp("input",{_id:"aiChatInput__FileInput"}),ne=e=>{const t=m.useFileUploadApi();return o.jsx(ie,{...e,...t.getHiddenInputProps()})},ae=s.ikp("div",{_id:"aiChatInput__FileList"}),oe=({children:e,...t})=>{const n=m.useFileUploadApi().acceptedFiles;return n.length?o.jsx(ae,{...t,children:e(n)}):null},_=p.createContext(null);function h(){const e=p.useContext(_);if(!e)throw new Error("useFileContext must be used within EmbeddedChatPrimitiveFileItem");return e}const se=s.ikp("div",{_id:"aiChatInput__FileItem"}),re=({file:e,...t})=>{const i=m.useFileUploadApi(),[n,a]=p.useState(void 0),[r,c]=p.useState(!0);p.useEffect(()=>i.createFileUrl(e,l=>{a(l),c(!0)}),[e]);const d=()=>i.deleteFile(e);return o.jsx(_.Provider,{value:{file:e,objectUrl:n,isLoading:r,setIsLoading:c,onRemove:d},children:o.jsx(se,{"data-loading":F.dataAttr(r),...t})})},le=s.ikp("button",{_id:"aiChatInput__FilePreviewTrigger"}),pe=({onClick:e,...t})=>{const{objectUrl:i,file:n}=h(),{openImagePreview:a}=j.useImagePreview();return o.jsx(le,{type:"button","aria-label":`Preview ${n.name}`,disabled:!i,onClick:x.composeEventHandlers(e,()=>{i&&a({url:i,name:n.name})}),...t})},ce=s.ikp("span",{_id:"aiChatInput__FileContent"}),de=e=>o.jsx(ce,{...e}),me=s.ikp("img",{_id:"aiChatInput__FileThumbnail"}),xe=({onLoad:e,...t})=>{const{objectUrl:i,file:n,setIsLoading:a}=h();return o.jsx(me,{src:i,alt:n.name,onLoad:x.composeEventHandlers(e,()=>a(!1)),...t})},ue=({className:e})=>{const{file:t}=h(),i=k[M(t).type]??"file";return o.jsx(b.CustomIcon,{iconKey:i,className:e})},he=s.ikp("span",{_id:"aiChatInput__FileName"}),fe=e=>{const{file:t}=h();return o.jsx(he,{...e,children:t.name})},ve=s.ikp("button",{_id:"aiChatInput__FileRemove"}),ge=s.ikp(b.CustomIcon,{_id:"aiChatInput__FileRemoveIcon",iconKey:"close"}),Ce=({onClick:e,...t})=>{const{onRemove:i}=h();return o.jsx(ve,{type:"button","aria-label":"Remove file",onClick:x.composeEventHandlers(e,i),...t})};exports.ACCEPTED_FILE_MIME_TYPES=w;exports.EmbeddedChatPrimitiveDropZone=B;exports.EmbeddedChatPrimitiveFileContent=de;exports.EmbeddedChatPrimitiveFileInput=ne;exports.EmbeddedChatPrimitiveFileItem=re;exports.EmbeddedChatPrimitiveFileList=oe;exports.EmbeddedChatPrimitiveFileName=fe;exports.EmbeddedChatPrimitiveFilePreviewTrigger=pe;exports.EmbeddedChatPrimitiveFileRemove=Ce;exports.EmbeddedChatPrimitiveFileRemoveIcon=ge;exports.EmbeddedChatPrimitiveFileThumbnail=xe;exports.EmbeddedChatPrimitiveFileTypeIcon=ue;exports.EmbeddedChatPrimitiveFileUploadButton=te;exports.EmbeddedChatPrimitiveFileUploadButtonIcon=Q;exports.EmbeddedChatPrimitiveInputFieldset=D;exports.EmbeddedChatPrimitiveInputNotification=Y;exports.EmbeddedChatPrimitiveInputNotificationClose=V;exports.EmbeddedChatPrimitiveInputNotificationContent=G;exports.EmbeddedChatPrimitiveInputNotificationHeader=J;exports.EmbeddedChatPrimitiveInputNotificationMessage=W;exports.EmbeddedChatPrimitiveInputNotificationTitle=z;exports.EmbeddedChatPrimitiveMessageFile=R;exports.EmbeddedChatPrimitiveMessageFiles=S;exports.FILE_ACCEPT_MAP=v;exports.FILE_TYPE_ICON_MAP=k;exports.MAX_FILES=I;exports.MAX_FILE_SIZE=P;exports.isImageMimeType=C;exports.normalizeFileType=M;
@@ -1,16 +1,16 @@
1
1
  "use client";
2
- import { jsx as a, jsxs as j } from "react/jsx-runtime";
3
- import C, { useState as h, useEffect as E, useMemo as w } from "react";
2
+ import { jsx as s, jsxs as k } from "react/jsx-runtime";
3
+ import P, { useState as g, useEffect as M, useMemo as N } from "react";
4
4
  import { CustomIcon as v } from "../../atoms/icons/custom-icon.js";
5
- import { useImagePreview as I } from "../../providers/image-preview-provider.js";
6
- import { useMessage as k } from "../../providers/message-provider.js";
7
- import { useChat as c } from "./chat-provider.js";
8
- import { useFileUploadApi as d, FileUploadRoot as N } from "../../atoms/file-upload.js";
9
- import { dataAttr as g } from "../../utils/misc.js";
10
- import { composeEventHandlers as r } from "../../utils/compose-event-handlers.js";
5
+ import { useImagePreview as y } from "../../providers/image-preview-provider.js";
6
+ import { useMessage as T } from "../../providers/message-provider.js";
7
+ import { useChat as m } from "./chat-provider.js";
8
+ import { useFileUploadApi as x, FileUploadRoot as L } from "../../atoms/file-upload.js";
9
+ import { dataAttr as b } from "../../utils/misc.js";
10
+ import { composeEventHandlers as d } from "../../utils/compose-event-handlers.js";
11
11
  import { ikp as o } from "../factory.js";
12
- import { useInkeepConfig as T } from "../../providers/config-provider.js";
13
- const L = {
12
+ import { useInkeepConfig as j } from "../../providers/config-provider.js";
13
+ const q = {
14
14
  "application/pdf": "filePdf",
15
15
  "text/plain": "fileText",
16
16
  "text/markdown": "fileMarkdown",
@@ -24,7 +24,7 @@ const L = {
24
24
  "text/x-python": "filePy",
25
25
  "text/x-python-script": "filePy"
26
26
  };
27
- function F(t) {
27
+ function C(t) {
28
28
  return t.startsWith("image/");
29
29
  }
30
30
  const _ = {
@@ -173,7 +173,7 @@ const _ = {
173
173
  "application/x-iwork-pages-sffpages": [".pages"],
174
174
  "application/x-iwork-numbers-sffnumbers": [".numbers"],
175
175
  "application/x-iwork-keynote-sffkey": [".key"]
176
- }, M = new Set(Object.keys(_)), P = 10, y = 1024 * 1024 * 10, q = Object.entries(_).reduce(
176
+ }, S = new Set(Object.keys(_)), E = 10, w = 1024 * 1024 * 10, A = Object.entries(_).reduce(
177
177
  (t, [e, i]) => {
178
178
  for (const n of i) t[n] = e;
179
179
  return t;
@@ -182,7 +182,7 @@ const _ = {
182
182
  );
183
183
  function R(t) {
184
184
  if (t.type) return t;
185
- const e = `.${t.name.split(".").pop()?.toLowerCase()}`, i = q[e];
185
+ const e = `.${t.name.split(".").pop()?.toLowerCase()}`, i = A[e];
186
186
  return i ? new File([t], t.name, { type: i }) : t;
187
187
  }
188
188
  function U(t) {
@@ -190,13 +190,13 @@ function U(t) {
190
190
  const e = (i) => t.some((n) => n.errors.includes(i));
191
191
  return e("TOO_MANY_FILES") ? {
192
192
  title: "Attachment limit reached",
193
- message: `You can only attach up to ${P} files per message.`
193
+ message: `You can only attach up to ${E} files per message.`
194
194
  } : e("FILE_INVALID_TYPE") ? {
195
195
  title: "Unsupported file type",
196
196
  message: "Supported formats include images, PDFs, text, code, and document files."
197
197
  } : e("FILE_TOO_LARGE") ? {
198
198
  title: "File too large",
199
- message: `Files must be smaller than ${y / 1024 / 1024}MB.`
199
+ message: `Files must be smaller than ${w / 1024 / 1024}MB.`
200
200
  } : e("FILE_EXISTS") ? {
201
201
  title: "File already exists",
202
202
  message: `The file "${t.find((n) => n.errors.includes("FILE_EXISTS"))?.file.name ?? "file"}" is already attached to this message.`
@@ -205,266 +205,285 @@ function U(t) {
205
205
  message: "This file could not be added."
206
206
  };
207
207
  }
208
- const S = o("div", {
208
+ const O = o("div", {
209
209
  _id: "aiChatMessage__Files"
210
- }), dt = ({ children: t, ...e }) => {
211
- const { message: i } = k();
212
- if (i.role !== "user") return null;
213
- const n = (i.parts ?? []).filter((s) => {
214
- if (s.type !== "file") return !1;
215
- const l = s.mediaType;
216
- return M.has(l ?? "");
210
+ }), f = /* @__PURE__ */ new WeakSet();
211
+ let I = !1;
212
+ function D(t, e) {
213
+ const i = e.map((a) => {
214
+ if (!a.providerMetadata) return { ...a };
215
+ try {
216
+ return { ...a, providerMetadata: structuredClone(a.providerMetadata) };
217
+ } catch {
218
+ return I || (I = !0, console.warn(
219
+ "[transformMessageFiles] providerMetadata is not structured-cloneable; passing a shared reference. A transformer that mutates it writes through into live message state."
220
+ )), { ...a };
221
+ }
217
222
  });
218
- return n.length ? /* @__PURE__ */ a(S, { ...e, children: t(n) }) : null;
219
- }, A = o("button", {
223
+ let n;
224
+ try {
225
+ n = t(i);
226
+ } catch (a) {
227
+ return f.has(t) || (f.add(t), console.warn("[transformMessageFiles] transformer threw", a)), e;
228
+ }
229
+ return Array.isArray(n) ? n.filter((a) => a != null) : (f.has(t) || (f.add(t), console.warn("[transformMessageFiles] transformer must return an array, got:", n)), e);
230
+ }
231
+ const ut = ({ children: t, ...e }) => {
232
+ const { message: i } = T(), { aiChatSettings: n } = j();
233
+ if (i.role !== "user") return null;
234
+ const a = (i.parts ?? []).filter((l) => l.type === "file"), r = n.transformMessageFiles, c = (r ? D(r, a) : a).filter(
235
+ (l) => S.has(l.mediaType ?? "")
236
+ );
237
+ return c.length ? /* @__PURE__ */ s(O, { ...e, children: t(c) }) : null;
238
+ }, $ = o("button", {
220
239
  _id: "aiChatMessage__File"
221
- }), xt = ({
240
+ }), ft = ({
222
241
  url: t,
223
242
  name: e,
224
243
  mediaType: i,
225
244
  onClick: n,
226
- ...s
245
+ ...a
227
246
  }) => {
228
- const { openImagePreview: l } = I(), [p, m] = h(!0), u = w(
247
+ const { openImagePreview: r } = y(), [p, c] = g(!0), l = N(
229
248
  () => new File([], e ?? "file", { type: i }),
230
249
  [e, i]
231
250
  );
232
- return /* @__PURE__ */ a(
233
- b.Provider,
251
+ return /* @__PURE__ */ s(
252
+ F.Provider,
234
253
  {
235
- value: { file: u, objectUrl: t, isLoading: p, setIsLoading: m, onRemove: () => {
254
+ value: { file: l, objectUrl: t, isLoading: p, setIsLoading: c, onRemove: () => {
236
255
  } },
237
- children: /* @__PURE__ */ a(
238
- A,
256
+ children: /* @__PURE__ */ s(
257
+ $,
239
258
  {
240
259
  type: "button",
241
- "aria-label": F(i ?? "") ? `Preview ${e ?? "file"}` : `Open ${e ?? "file"} in new tab`,
242
- "data-loading": g(p),
243
- onClick: r(n, () => {
244
- if (F(i ?? ""))
245
- l({ url: t, name: e ?? "file" });
260
+ "aria-label": C(i ?? "") ? `Preview ${e ?? "file"}` : `Open ${e ?? "file"} in new tab`,
261
+ "data-loading": b(p),
262
+ onClick: d(n, () => {
263
+ if (C(i ?? ""))
264
+ r({ url: t, name: e ?? "file" });
246
265
  else if (t)
247
266
  if (t.startsWith("data:")) {
248
- const f = document.createElement("a");
249
- f.href = t, f.download = e ?? "file", f.click();
267
+ const h = document.createElement("a");
268
+ h.href = t, h.download = e ?? "file", h.click();
250
269
  } else
251
270
  window.open(t, "_blank", "noopener,noreferrer");
252
271
  }),
253
- ...s
272
+ ...a
254
273
  }
255
274
  )
256
275
  }
257
276
  );
258
- }, O = o("div", {
277
+ }, B = o("div", {
259
278
  _id: "aiChatInput__Fieldset"
260
- }), D = (t) => {
261
- const e = d();
262
- return /* @__PURE__ */ a(
263
- O,
279
+ }), z = (t) => {
280
+ const e = x();
281
+ return /* @__PURE__ */ s(
282
+ B,
264
283
  {
265
284
  ...e.getDropzoneProps({ disableClick: !0 }),
266
- "data-drag-over": g(e.dragging),
285
+ "data-drag-over": b(e.dragging),
267
286
  ...t
268
287
  }
269
288
  );
270
- }, mt = ({
289
+ }, ht = ({
271
290
  ...t
272
291
  }) => {
273
- const { files: e, setFiles: i, showInputNotification: n } = c();
274
- return /* @__PURE__ */ a(
275
- N,
292
+ const { files: e, setFiles: i, showInputNotification: n } = m();
293
+ return /* @__PURE__ */ s(
294
+ L,
276
295
  {
277
296
  accept: _,
278
- maxFiles: P,
279
- maxFileSize: y,
297
+ maxFiles: E,
298
+ maxFileSize: w,
280
299
  preventDocumentDrop: !0,
281
300
  acceptedFiles: e,
282
- onFileAccept: (s) => i(s.files),
283
- onFileReject: (s) => {
284
- const l = U(s.files);
285
- l && n(l);
301
+ onFileAccept: (a) => i(a.files),
302
+ onFileReject: (a) => {
303
+ const r = U(a.files);
304
+ r && n(r);
286
305
  },
287
- children: /* @__PURE__ */ a(D, { ...t })
306
+ children: /* @__PURE__ */ s(z, { ...t })
288
307
  }
289
308
  );
290
- }, ut = o("div", {
309
+ }, gt = o("div", {
291
310
  _id: "aiChatInput__DropZone"
292
- }), $ = o("div", {
311
+ }), H = o("div", {
293
312
  _id: "aiChatInput__Notification"
294
- }), ft = (t) => {
295
- const { inputNotification: e } = c();
296
- return e ? /* @__PURE__ */ a($, { role: "alert", ...t }) : null;
297
- }, B = o("p", {
313
+ }), vt = (t) => {
314
+ const { inputNotification: e } = m();
315
+ return e ? /* @__PURE__ */ s(H, { role: "alert", ...t }) : null;
316
+ }, X = o("p", {
298
317
  _id: "aiChatInput__NotificationTitle"
299
- }), ht = ({
318
+ }), bt = ({
300
319
  children: t,
301
320
  ...e
302
321
  }) => {
303
- const { inputNotification: i } = c();
304
- return i?.title ? /* @__PURE__ */ j(B, { ...e, children: [
322
+ const { inputNotification: i } = m();
323
+ return i?.title ? /* @__PURE__ */ k(X, { ...e, children: [
305
324
  t,
306
325
  i.title
307
326
  ] }) : null;
308
- }, z = o("p", {
327
+ }, Y = o("p", {
309
328
  _id: "aiChatInput__NotificationMessage"
310
- }), vt = (t) => {
311
- const { inputNotification: e } = c();
312
- return /* @__PURE__ */ a(z, { ...t, children: e?.message });
313
- }, H = o("button", {
329
+ }), _t = (t) => {
330
+ const { inputNotification: e } = m();
331
+ return /* @__PURE__ */ s(Y, { ...t, children: e?.message });
332
+ }, W = o("button", {
314
333
  _id: "aiChatInput__NotificationClose"
315
- }), gt = ({
334
+ }), Ft = ({
316
335
  onClick: t,
317
336
  ...e
318
337
  }) => {
319
- const { clearInputNotification: i } = c();
320
- return /* @__PURE__ */ a(
321
- H,
338
+ const { clearInputNotification: i } = m();
339
+ return /* @__PURE__ */ s(
340
+ W,
322
341
  {
323
342
  type: "button",
324
343
  "aria-label": "Dismiss",
325
- onClick: r(t, i),
344
+ onClick: d(t, i),
326
345
  ...e
327
346
  }
328
347
  );
329
- }, _t = o("div", {
348
+ }, Ct = o("div", {
330
349
  _id: "aiChatInput__NotificationContent"
331
- }), bt = o("div", {
350
+ }), It = o("div", {
332
351
  _id: "aiChatInput__NotificationHeader"
333
- }), Ft = o(v, {
352
+ }), Pt = o(v, {
334
353
  _id: "aiChatInput__FileUploadButtonIcon",
335
354
  iconKey: "fileUpload"
336
- }), X = o("button", {
355
+ }), K = o("button", {
337
356
  _id: "aiChatInput__FileUploadButton"
338
- }), Ct = (t) => {
339
- const { aiChatSettings: e } = T(), i = d(), { onClick: n, ...s } = t;
340
- return /* @__PURE__ */ a(
341
- X,
357
+ }), yt = (t) => {
358
+ const { aiChatSettings: e } = j(), i = x(), { onClick: n, ...a } = t;
359
+ return /* @__PURE__ */ s(
360
+ K,
342
361
  {
343
362
  type: "button",
344
363
  "aria-label": "Upload file",
345
364
  disabled: e.isViewOnly,
346
- onClick: r(n, () => i.openFilePicker()),
347
- ...s
365
+ onClick: d(n, () => i.openFilePicker()),
366
+ ...a
348
367
  }
349
368
  );
350
- }, Y = o("input", {
369
+ }, Z = o("input", {
351
370
  _id: "aiChatInput__FileInput"
352
- }), It = (t) => {
353
- const e = d();
354
- return /* @__PURE__ */ a(Y, { ...t, ...e.getHiddenInputProps() });
355
- }, K = o("div", {
371
+ }), jt = (t) => {
372
+ const e = x();
373
+ return /* @__PURE__ */ s(Z, { ...t, ...e.getHiddenInputProps() });
374
+ }, V = o("div", {
356
375
  _id: "aiChatInput__FileList"
357
- }), Pt = ({ children: t, ...e }) => {
358
- const n = d().acceptedFiles;
359
- return n.length ? /* @__PURE__ */ a(K, { ...e, children: t(n) }) : null;
360
- }, b = C.createContext(null);
361
- function x() {
362
- const t = C.useContext(b);
376
+ }), Et = ({ children: t, ...e }) => {
377
+ const n = x().acceptedFiles;
378
+ return n.length ? /* @__PURE__ */ s(V, { ...e, children: t(n) }) : null;
379
+ }, F = P.createContext(null);
380
+ function u() {
381
+ const t = P.useContext(F);
363
382
  if (!t) throw new Error("useFileContext must be used within EmbeddedChatPrimitiveFileItem");
364
383
  return t;
365
384
  }
366
- const Z = o("div", {
385
+ const G = o("div", {
367
386
  _id: "aiChatInput__FileItem"
368
- }), yt = ({ file: t, ...e }) => {
369
- const i = d(), [n, s] = h(void 0), [l, p] = h(!0);
370
- E(() => i.createFileUrl(t, (u) => {
371
- s(u), p(!0);
387
+ }), wt = ({ file: t, ...e }) => {
388
+ const i = x(), [n, a] = g(void 0), [r, p] = g(!0);
389
+ M(() => i.createFileUrl(t, (l) => {
390
+ a(l), p(!0);
372
391
  }), [t]);
373
- const m = () => i.deleteFile(t);
374
- return /* @__PURE__ */ a(b.Provider, { value: { file: t, objectUrl: n, isLoading: l, setIsLoading: p, onRemove: m }, children: /* @__PURE__ */ a(Z, { "data-loading": g(l), ...e }) });
375
- }, V = o("button", {
392
+ const c = () => i.deleteFile(t);
393
+ return /* @__PURE__ */ s(F.Provider, { value: { file: t, objectUrl: n, isLoading: r, setIsLoading: p, onRemove: c }, children: /* @__PURE__ */ s(G, { "data-loading": b(r), ...e }) });
394
+ }, J = o("button", {
376
395
  _id: "aiChatInput__FilePreviewTrigger"
377
- }), jt = ({
396
+ }), kt = ({
378
397
  onClick: t,
379
398
  ...e
380
399
  }) => {
381
- const { objectUrl: i, file: n } = x(), { openImagePreview: s } = I();
382
- return /* @__PURE__ */ a(
383
- V,
400
+ const { objectUrl: i, file: n } = u(), { openImagePreview: a } = y();
401
+ return /* @__PURE__ */ s(
402
+ J,
384
403
  {
385
404
  type: "button",
386
405
  "aria-label": `Preview ${n.name}`,
387
406
  disabled: !i,
388
- onClick: r(t, () => {
389
- i && s({ url: i, name: n.name });
407
+ onClick: d(t, () => {
408
+ i && a({ url: i, name: n.name });
390
409
  }),
391
410
  ...e
392
411
  }
393
412
  );
394
- }, W = o("span", {
413
+ }, Q = o("span", {
395
414
  _id: "aiChatInput__FileContent"
396
- }), Et = (t) => /* @__PURE__ */ a(W, { ...t }), G = o("img", {
415
+ }), Mt = (t) => /* @__PURE__ */ s(Q, { ...t }), tt = o("img", {
397
416
  _id: "aiChatInput__FileThumbnail"
398
- }), wt = ({
417
+ }), Nt = ({
399
418
  onLoad: t,
400
419
  ...e
401
420
  }) => {
402
- const { objectUrl: i, file: n, setIsLoading: s } = x();
403
- return /* @__PURE__ */ a(
404
- G,
421
+ const { objectUrl: i, file: n, setIsLoading: a } = u();
422
+ return /* @__PURE__ */ s(
423
+ tt,
405
424
  {
406
425
  src: i,
407
426
  alt: n.name,
408
- onLoad: r(t, () => s(!1)),
427
+ onLoad: d(t, () => a(!1)),
409
428
  ...e
410
429
  }
411
430
  );
412
- }, kt = ({ className: t }) => {
413
- const { file: e } = x(), i = L[R(e).type] ?? "file";
414
- return /* @__PURE__ */ a(v, { iconKey: i, className: t });
415
- }, J = o("span", {
431
+ }, Tt = ({ className: t }) => {
432
+ const { file: e } = u(), i = q[R(e).type] ?? "file";
433
+ return /* @__PURE__ */ s(v, { iconKey: i, className: t });
434
+ }, et = o("span", {
416
435
  _id: "aiChatInput__FileName"
417
- }), Nt = (t) => {
418
- const { file: e } = x();
419
- return /* @__PURE__ */ a(J, { ...t, children: e.name });
420
- }, Q = o("button", {
436
+ }), Lt = (t) => {
437
+ const { file: e } = u();
438
+ return /* @__PURE__ */ s(et, { ...t, children: e.name });
439
+ }, it = o("button", {
421
440
  _id: "aiChatInput__FileRemove"
422
- }), Tt = o(v, {
441
+ }), qt = o(v, {
423
442
  _id: "aiChatInput__FileRemoveIcon",
424
443
  iconKey: "close"
425
- }), Lt = ({
444
+ }), St = ({
426
445
  onClick: t,
427
446
  ...e
428
447
  }) => {
429
- const { onRemove: i } = x();
430
- return /* @__PURE__ */ a(
431
- Q,
448
+ const { onRemove: i } = u();
449
+ return /* @__PURE__ */ s(
450
+ it,
432
451
  {
433
452
  type: "button",
434
453
  "aria-label": "Remove file",
435
- onClick: r(t, i),
454
+ onClick: d(t, i),
436
455
  ...e
437
456
  }
438
457
  );
439
458
  };
440
459
  export {
441
- M as ACCEPTED_FILE_MIME_TYPES,
442
- ut as EmbeddedChatPrimitiveDropZone,
443
- Et as EmbeddedChatPrimitiveFileContent,
444
- It as EmbeddedChatPrimitiveFileInput,
445
- yt as EmbeddedChatPrimitiveFileItem,
446
- Pt as EmbeddedChatPrimitiveFileList,
447
- Nt as EmbeddedChatPrimitiveFileName,
448
- jt as EmbeddedChatPrimitiveFilePreviewTrigger,
449
- Lt as EmbeddedChatPrimitiveFileRemove,
450
- Tt as EmbeddedChatPrimitiveFileRemoveIcon,
451
- wt as EmbeddedChatPrimitiveFileThumbnail,
452
- kt as EmbeddedChatPrimitiveFileTypeIcon,
453
- Ct as EmbeddedChatPrimitiveFileUploadButton,
454
- Ft as EmbeddedChatPrimitiveFileUploadButtonIcon,
455
- mt as EmbeddedChatPrimitiveInputFieldset,
456
- ft as EmbeddedChatPrimitiveInputNotification,
457
- gt as EmbeddedChatPrimitiveInputNotificationClose,
458
- _t as EmbeddedChatPrimitiveInputNotificationContent,
459
- bt as EmbeddedChatPrimitiveInputNotificationHeader,
460
- vt as EmbeddedChatPrimitiveInputNotificationMessage,
461
- ht as EmbeddedChatPrimitiveInputNotificationTitle,
462
- xt as EmbeddedChatPrimitiveMessageFile,
463
- dt as EmbeddedChatPrimitiveMessageFiles,
460
+ S as ACCEPTED_FILE_MIME_TYPES,
461
+ gt as EmbeddedChatPrimitiveDropZone,
462
+ Mt as EmbeddedChatPrimitiveFileContent,
463
+ jt as EmbeddedChatPrimitiveFileInput,
464
+ wt as EmbeddedChatPrimitiveFileItem,
465
+ Et as EmbeddedChatPrimitiveFileList,
466
+ Lt as EmbeddedChatPrimitiveFileName,
467
+ kt as EmbeddedChatPrimitiveFilePreviewTrigger,
468
+ St as EmbeddedChatPrimitiveFileRemove,
469
+ qt as EmbeddedChatPrimitiveFileRemoveIcon,
470
+ Nt as EmbeddedChatPrimitiveFileThumbnail,
471
+ Tt as EmbeddedChatPrimitiveFileTypeIcon,
472
+ yt as EmbeddedChatPrimitiveFileUploadButton,
473
+ Pt as EmbeddedChatPrimitiveFileUploadButtonIcon,
474
+ ht as EmbeddedChatPrimitiveInputFieldset,
475
+ vt as EmbeddedChatPrimitiveInputNotification,
476
+ Ft as EmbeddedChatPrimitiveInputNotificationClose,
477
+ Ct as EmbeddedChatPrimitiveInputNotificationContent,
478
+ It as EmbeddedChatPrimitiveInputNotificationHeader,
479
+ _t as EmbeddedChatPrimitiveInputNotificationMessage,
480
+ bt as EmbeddedChatPrimitiveInputNotificationTitle,
481
+ ft as EmbeddedChatPrimitiveMessageFile,
482
+ ut as EmbeddedChatPrimitiveMessageFiles,
464
483
  _ as FILE_ACCEPT_MAP,
465
- L as FILE_TYPE_ICON_MAP,
466
- P as MAX_FILES,
467
- y as MAX_FILE_SIZE,
468
- F as isImageMimeType,
484
+ q as FILE_TYPE_ICON_MAP,
485
+ E as MAX_FILES,
486
+ w as MAX_FILE_SIZE,
487
+ C as isImageMimeType,
469
488
  R as normalizeFileType
470
489
  };
@@ -1,2 +1,2 @@
1
- "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ze=require("@ai-sdk/react"),Xe=require("./file-upload-input.cjs"),Ye=require("ai"),t=require("react"),et=require("../../providers/config-provider.cjs"),tt=require("../../providers/chat-auth-provider.cjs"),st=require("../../hooks/use-media-query.cjs"),rt=require("../../hooks/use-conversation-loader.cjs"),nt=require("../../hooks/use-initial-conversation.cjs"),k=require("../../utils/generate-uid.cjs"),at=require("../../providers/base-events-provider.cjs"),ot=require("../../providers/chat-form-provider.cjs"),it=require("../../providers/widget-provider.cjs"),ct=require("@radix-ui/react-use-controllable-state"),ut=require("../../hooks/use-streaming-events.cjs"),lt=require("../../hooks/use-input-notification.cjs"),p=require("./chat-error-helpers.cjs"),dt=()=>{const{baseSettings:se,aiChatSettings:E}=et.useInkeepConfig(),[c="",m]=ct.useControllableState({prop:E.conversationIdOverride,defaultProp:E.conversationIdOverride??""}),{logEvent:h}=at.useBaseEvents(),{setConversationId:ke,emitToParent:F}=ut.useStreamingEvents(),re=t.useRef(c);t.useEffect(()=>{const e=re.current;re.current=c,e!==c&&h({eventName:"chat_conversation_changed",properties:{conversationId:c,previousConversationId:e}})},[c,h]);const[S,C]=t.useState(""),Fe=e=>C(e.target.value),{shouldBypassCaptcha:_e,filters:ne,userProperties:N,analyticsProperties:O}=se,{authToken:ae,isAuthenticated:v,isAuthConfigured:oe,refreshAuthToken:ie,sessionToken:ce,refreshSession:ue,getCaptchaHeader:_,invalidateCaptcha:d,effectiveAuthToken:le,applicableRefreshSession:Pe}=tt.useChatAuth(),{onInputMessageChange:xe,filters:de,baseUrl:pe,agentUrl:qe,context:fe,headers:ge,appId:P,apiKey:U,files:I}=E,he=t.useRef(_);he.current=_;const me=qe||`${pe}/run/api/chat`,{loadConversation:ve}=rt.useConversationLoader({baseUrl:pe,appId:P,authToken:le,getCaptchaHeader:_,invalidateCaptcha:d,refreshSession:Pe}),[Le,ye]=t.useState(!1),D=t.useRef(null);D.current=ce;const $=t.useRef(null);$.current=ae;const B=t.useRef(void 0);B.current=N&&Object.keys(N).length>0?N:void 0;const G=t.useRef(void 0);G.current=O&&Object.keys(O).length>0?O:void 0;const y=t.useRef(0),H=t.useRef(null),K=t.useRef(null),R=t.useRef(void 0),Ne=I?.map(e=>`${e.filename??""}:${e.mediaType}:${e.url.length}:${e.url.slice(0,64)}:${e.url.slice(-32)}`).join(`
2
- `)??"";t.useEffect(()=>{R.current=I?.length?I:void 0},[Ne]);const Re=t.useRef(ge);Re.current=ge;const z=t.useRef(void 0);z.current=ne||de?JSON.stringify({...ne,...de}):void 0;const Oe=e=>{switch(p.resolveHttpStatusCode(e)){case 400:try{const s=JSON.parse(e.message??"");return s.detail??s.error?.message??p.RECOVERABLE_FALLBACK_MESSAGE}catch{return e.message?.trim()||p.RECOVERABLE_FALLBACK_MESSAGE}case 401:return oe?"Authentication failed. Please try again.":p.DEFAULT_ERROR_MESSAGE;case 403:return`There seems to be a configuration error. Please contact ${se.organizationDisplayName??"Administrator"}`;case 429:return p.RATE_LIMIT_MESSAGE;default:return p.DEFAULT_ERROR_MESSAGE}},[A,j]=t.useState([]),Ue=t.useMemo(()=>new Ye.DefaultChatTransport({api:me,headers:()=>{const e=U??$.current??D.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}`}:{},...z.current?{"inkeep-filters":z.current}:{},...Re.current}},prepareSendMessagesRequest:async e=>{const a=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,...B.current?{userProperties:B.current}:{},...G.current?{properties:G.current}:{}},headers:{...e.headers,...a}}},body:{requestContext:fe}}),[me,fe,P,U]),{messages:b,sendMessage:V,addToolApprovalResponse:J,status:Ee,setMessages:f,stop:x,error:q}=Ze.useChat({transport:Ue,onData(e){F(e.type,e.data)},async onFinish({message:e}){F("completion",{conversationId:c}),await h({eventName:"assistant_message_received",properties:{conversationId:c,messageId:e.id}}),h({eventName:"assistant_answer_displayed",properties:{conversationId:c,messageId:e.id}})},onError(e){console.error("onError",{code:e.code,message:e.message});const a=_e||U?null:p.resolveStreamingAuthError(e);if(a!==null&&y.current<1){y.current++;const n=K.current,r=H.current;(async()=>{if(a==="session"&&oe){const l=await ie();if(!l)throw new Error("Auth token refresh failed");$.current=l}else if(a==="session"){const l=await ue();l&&(D.current=l)}else d();if(n){J(n);return}r&&(f(l=>{let o=[...l];return o.at(-1)?.role==="assistant"&&(o=o.slice(0,-1)),o.at(-1)?.role==="user"&&(o=o.slice(0,-1)),o}),V({id:r.messageId,parts:[...r.content.trim()?[{type:"text",text:r.content}]:[],...r.files??[]]},{body:r.body}))})().catch(()=>{y.current=0,d(),f(l=>{const o=[...l],g=o[o.length-1];if(!g)return o;const L=p.DEFAULT_ERROR_MESSAGE;return g.role==="user"?o.push({id:k.generateUid(16),role:"assistant",parts:[{type:"text",text:L}]}):g.parts=[{type:"text",text:L}],o})});return}y.current=0,a!==null&&d();const s=p.isRecoverableError(e),u=Oe(e);if(h({eventName:"chat_error",properties:{conversationId:c,messageId:b.at(-1)?.id,error:e.message}}),s){Y({title:"Request failed",message:u},p.RECOVERABLE_NOTIFICATION_DURATION_MS),f(r=>{let i=[...r];return i.at(-1)?.role==="assistant"&&(i=i.slice(0,-1)),i.at(-1)?.role==="user"&&(i=i.slice(0,-1)),i});const n=H.current?.content;n&&C(n),X.current=e;return}f(n=>{const r=[...n],i=r[r.length-1];return i&&(i.role==="user"?r.push({id:k.generateUid(16),role:"assistant",parts:[{type:"text",text:u}]}):i.parts=[{type:"text",text:u}]),r})}}),Se=t.useRef(v);t.useEffect(()=>{const e=Se.current;Se.current=v,e!==v&&(x(),w(null),f([]),m(""),C(""),j([]),d())},[v,x,f,m,d]);const Ce=Ee==="submitted",Q=Ee==="streaming",De=t.useMemo(()=>{const e=n=>{if(!n||typeof n!="object")return!1;const r=n;return typeof r.type=="string"&&r.type.startsWith("tool-")},s=[...b??[]].reverse().find(n=>n.role==="assistant");if(!s)return!1;const u=s.parts?.at(-1);return!(!e(u)||u.state!=="output-available"||!u.approval?.id||Q)},[b,Q]),[$e,W]=t.useState(!1),Ie=Q||De&&!$e,Ae=Ce||Ie,Be=b.length===0,Z=!S.trim()&&A.length===0||Ae,Ge=st.useMediaQuery("(max-width: 768px)"),[He,w]=t.useState(null),X=t.useRef(null);t.useEffect(()=>{if(q){if(X.current===q){X.current=null;return}w(q)}},[q]);const Ke=()=>w(null),{inputNotification:ze,showInputNotification:Y,clearInputNotification:je}=lt.useInputNotification(),be=t.useRef(null);t.useEffect(()=>{xe?.(S)},[S]);const Ve=e=>{e.key==="Enter"&&!e.shiftKey&&!Z&&!e.nativeEvent.isComposing&&(e.preventDefault(),ee())},ee=async(e=S)=>{if(Z&&(!e||e.trim().length===0)&&A.length===0||!e.trim()&&!A.length&&!R.current?.length)return;const a=A;j([]),C(""),y.current=0,K.current=null,W(!1);let s=c;s||(s=`conv_${k.generateUid(16)}`,m(s));const u=k.generateUid(21);ke(s),await h({eventName:"user_message_submitted",properties:{conversationId:s,messageId:u}});const n=R.current;R.current=void 0;let r=[];if(a.length>0)try{r=await Promise.all(a.map(o=>{const g=Xe.normalizeFileType(o);return new Promise((L,Te)=>{const T=new FileReader;T.onload=()=>{if(typeof T.result!="string"){Te(new Error(`Failed to read file "${g.name}"`));return}L({type:"file",url:T.result,mediaType:g.type,filename:g.name})},T.onerror=()=>Te(new Error(`Failed to read file "${g.name}"`)),T.readAsDataURL(g)})}))}catch{Y({title:"Failed to attach files",message:"Could not read one or more files. Please try again."});return}const i=r.length||n?.length?[...r,...n??[]]:void 0,l=[...e.trim()?[{type:"text",text:e}]:[],...i??[]];H.current={content:e,messageId:u,body:{conversationId:s},files:i},V({id:u,parts:l},{body:{conversationId:s}})},Je=t.useCallback(e=>{y.current=0,K.current=e,W(!1),J(e)},[J]),te=t.useCallback(()=>{W(!0),x().then(()=>{F("aborted",{conversationId:c})})},[x,c,F]),we=()=>{Ke(),f([]),m(""),d(),R.current=I?.length?I:void 0,h({eventName:"chat_clear_button_clicked",properties:{conversationId:c}})},M=t.useCallback((e,a)=>{w(null),f(a),m(e),d(),R.current=void 0},[f,m,d]),Me=t.useCallback(async(e,a)=>{te(),M(e,[]),ye(!0);try{const s=await ve(e,a);if(s===null)return!1;const n=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 M(e,n),!0}finally{a?.aborted||ye(!1)}},[M,ve,te]);nt.useInitialConversation({conversationId:E.conversationId,effectiveAuthToken:le,loadAndRestoreSession:Me,onLoadFailed:()=>M("",[])});const{openForm:Qe}=ot.useChatForm(),We=it.useWidget();return t.useImperativeHandle(E.chatFunctionsRef,()=>({submitMessage:ee,updateInputMessage(e){C(e)},clearChat:we,openForm:e=>{We?.setView("chat"),Qe(e,void 0)},focusInput:()=>{be.current?.focus()}})),{messages:b,sendMessage:V,addToolApprovalResponse:Je,isLoading:Ce,isStreaming:Ie,isBusy:Ae,error:He,setError:w,isSubmitDisabled:Z,input:S,handleInputChange:Fe,handleInputKeyDown:Ve,handleSubmit:ee,stop:te,clear:we,inputRef:be,isMobile:Ge,files:A,setFiles:j,isNewChat:Be,conversationId:c,restoreSession:M,loadAndRestoreSession:Me,isSessionLoading:Le,authToken:v?ae:ce,refreshSession:v?ie:ue,getCaptchaHeader:_,invalidateCaptcha:d,inputNotification:ze,showInputNotification:Y,clearInputNotification:je}};exports.useInkeepChat=dt;
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ze=require("@ai-sdk/react"),Xe=require("./file-upload-input.cjs"),Ye=require("ai"),t=require("react"),et=require("../../providers/config-provider.cjs"),tt=require("../../providers/chat-auth-provider.cjs"),st=require("../../hooks/use-media-query.cjs"),rt=require("../../hooks/use-conversation-loader.cjs"),nt=require("../../hooks/use-initial-conversation.cjs"),k=require("../../utils/generate-uid.cjs"),at=require("../../providers/base-events-provider.cjs"),ot=require("../../providers/chat-form-provider.cjs"),it=require("../../providers/widget-provider.cjs"),ct=require("@radix-ui/react-use-controllable-state"),ut=require("../../hooks/use-streaming-events.cjs"),lt=require("../../hooks/use-input-notification.cjs"),f=require("./chat-error-helpers.cjs"),dt=()=>{const{baseSettings:se,aiChatSettings:m}=et.useInkeepConfig(),[c="",v]=ct.useControllableState({prop:m.conversationIdOverride,defaultProp:m.conversationIdOverride??""}),{logEvent:h}=at.useBaseEvents(),{setConversationId:ke,emitToParent:F}=ut.useStreamingEvents(),re=t.useRef(c);t.useEffect(()=>{const e=re.current;re.current=c,e!==c&&h({eventName:"chat_conversation_changed",properties:{conversationId:c,previousConversationId:e}})},[c,h]);const[S,I]=t.useState(""),Fe=e=>I(e.target.value),{shouldBypassCaptcha:_e,filters:ne,userProperties:N,analyticsProperties:O}=se,{authToken:ae,isAuthenticated:y,isAuthConfigured:oe,refreshAuthToken:ie,sessionToken:ce,refreshSession:ue,getCaptchaHeader:_,invalidateCaptcha:d,effectiveAuthToken:le,applicableRefreshSession:Pe}=tt.useChatAuth(),{onInputMessageChange:xe,filters:de,baseUrl:fe,agentUrl:qe,context:pe,headers:ge,appId:P,apiKey:U,files:A}=m,he=t.useRef(_);he.current=_;const me=qe||`${fe}/run/api/chat`,{loadConversation:ve}=rt.useConversationLoader({baseUrl:fe,appId:P,authToken:le,getCaptchaHeader:_,invalidateCaptcha:d,refreshSession:Pe}),[Le,ye]=t.useState(!1),D=t.useRef(null);D.current=ce;const $=t.useRef(null);$.current=ae;const B=t.useRef(void 0);B.current=N&&Object.keys(N).length>0?N:void 0;const G=t.useRef(void 0);G.current=O&&Object.keys(O).length>0?O:void 0;const R=t.useRef(0),H=t.useRef(null),K=t.useRef(null),C=t.useRef(void 0),Ne=A?.map(e=>`${e.filename??""}:${e.mediaType}:${e.url.length}:${e.url.slice(0,64)}:${e.url.slice(-32)}`).join(`
2
+ `)??"";t.useEffect(()=>{C.current=A?.length?A:void 0},[Ne]);const Re=t.useRef(ge);Re.current=ge;const z=t.useRef(void 0);z.current=ne||de?JSON.stringify({...ne,...de}):void 0;const Oe=e=>{switch(f.resolveHttpStatusCode(e)){case 400:try{const s=JSON.parse(e.message??"");return s.detail??s.error?.message??f.RECOVERABLE_FALLBACK_MESSAGE}catch{return e.message?.trim()||f.RECOVERABLE_FALLBACK_MESSAGE}case 401:return oe?"Authentication failed. Please try again.":f.DEFAULT_ERROR_MESSAGE;case 403:return`There seems to be a configuration error. Please contact ${se.organizationDisplayName??"Administrator"}`;case 429:return f.RATE_LIMIT_MESSAGE;default:return f.DEFAULT_ERROR_MESSAGE}},[b,j]=t.useState([]),Ue=t.useMemo(()=>new Ye.DefaultChatTransport({api:me,headers:()=>{const e=U??$.current??D.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}`}:{},...z.current?{"inkeep-filters":z.current}:{},...Re.current}},prepareSendMessagesRequest:async e=>{const a=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,...B.current?{userProperties:B.current}:{},...G.current?{properties:G.current}:{}},headers:{...e.headers,...a}}},body:{requestContext:pe}}),[me,pe,P,U]),{messages:w,sendMessage:V,addToolApprovalResponse:J,status:Ce,setMessages:p,stop:x,error:q}=Ze.useChat({transport:Ue,onData(e){F(e.type,e.data)},async onFinish({message:e}){F("completion",{conversationId:c}),await h({eventName:"assistant_message_received",properties:{conversationId:c,messageId:e.id}}),h({eventName:"assistant_answer_displayed",properties:{conversationId:c,messageId:e.id}})},onError(e){console.error("onError",{code:e.code,message:e.message});const a=_e||U?null:f.resolveStreamingAuthError(e);if(a!==null&&R.current<1){R.current++;const n=K.current,r=H.current;(async()=>{if(a==="session"&&oe){const l=await ie();if(!l)throw new Error("Auth token refresh failed");$.current=l}else if(a==="session"){const l=await ue();l&&(D.current=l)}else d();if(n){J(n);return}r&&(p(l=>{let o=[...l];return o.at(-1)?.role==="assistant"&&(o=o.slice(0,-1)),o.at(-1)?.role==="user"&&(o=o.slice(0,-1)),o}),V({id:r.messageId,parts:[...r.content.trim()?[{type:"text",text:r.content}]:[],...r.files??[]]},{body:r.body}))})().catch(()=>{R.current=0,d(),p(l=>{const o=[...l],g=o[o.length-1];if(!g)return o;const L=f.DEFAULT_ERROR_MESSAGE;return g.role==="user"?o.push({id:k.generateUid(16),role:"assistant",parts:[{type:"text",text:L}]}):g.parts=[{type:"text",text:L}],o})});return}R.current=0,a!==null&&d();const s=f.isRecoverableError(e),u=Oe(e);if(h({eventName:"chat_error",properties:{conversationId:c,messageId:w.at(-1)?.id,error:e.message}}),s){Y({title:"Request failed",message:u},f.RECOVERABLE_NOTIFICATION_DURATION_MS),p(r=>{let i=[...r];return i.at(-1)?.role==="assistant"&&(i=i.slice(0,-1)),i.at(-1)?.role==="user"&&(i=i.slice(0,-1)),i});const n=H.current?.content;n&&I(n),X.current=e;return}p(n=>{const r=[...n],i=r[r.length-1];return i&&(i.role==="user"?r.push({id:k.generateUid(16),role:"assistant",parts:[{type:"text",text:u}]}):i.parts=[{type:"text",text:u}]),r})}}),Ee=t.useRef(y);t.useEffect(()=>{const e=Ee.current;Ee.current=y,e!==y&&(x(),M(null),p([]),v(""),I(""),j([]),d())},[y,x,p,v,d]);const Se=Ce==="submitted",Q=Ce==="streaming",De=t.useMemo(()=>{const e=n=>{if(!n||typeof n!="object")return!1;const r=n;return typeof r.type=="string"&&r.type.startsWith("tool-")},s=[...w??[]].reverse().find(n=>n.role==="assistant");if(!s)return!1;const u=s.parts?.at(-1);return!(!e(u)||u.state!=="output-available"||!u.approval?.id||Q)},[w,Q]),[$e,W]=t.useState(!1),Ie=Q||De&&!$e,Ae=Se||Ie,Be=w.length===0,Z=!S.trim()&&b.length===0||Ae,Ge=st.useMediaQuery("(max-width: 768px)"),[He,M]=t.useState(null),X=t.useRef(null);t.useEffect(()=>{if(q){if(X.current===q){X.current=null;return}M(q)}},[q]);const Ke=()=>M(null),{inputNotification:ze,showInputNotification:Y,clearInputNotification:je}=lt.useInputNotification(),be=t.useRef(null);t.useEffect(()=>{xe?.(S)},[S]);const Ve=e=>{e.key==="Enter"&&!e.shiftKey&&!Z&&!e.nativeEvent.isComposing&&(e.preventDefault(),ee())},ee=async(e=S)=>{if(Z&&(!e||e.trim().length===0)&&b.length===0||!e.trim()&&!b.length&&!C.current?.length)return;const a=b;j([]),I(""),R.current=0,K.current=null,W(!1);let s=c;s||(s=`conv_${k.generateUid(16)}`,v(s));const u=k.generateUid(21);ke(s),await h({eventName:"user_message_submitted",properties:{conversationId:s,messageId:u}});const n=C.current;C.current=void 0;let r=[];if(a.length>0)try{r=await Promise.all(a.map(o=>{const g=Xe.normalizeFileType(o);return new Promise((L,Te)=>{const T=new FileReader;T.onload=()=>{if(typeof T.result!="string"){Te(new Error(`Failed to read file "${g.name}"`));return}L({type:"file",url:T.result,mediaType:g.type,filename:g.name})},T.onerror=()=>Te(new Error(`Failed to read file "${g.name}"`)),T.readAsDataURL(g)})}))}catch{Y({title:"Failed to attach files",message:"Could not read one or more files. Please try again."});return}const i=r.length||n?.length?[...r,...n??[]]:void 0,l=[...e.trim()?[{type:"text",text:e}]:[],...i??[]];H.current={content:e,messageId:u,body:{conversationId:s},files:i},V({id:u,parts:l},{body:{conversationId:s}})},Je=t.useCallback(e=>{R.current=0,K.current=e,W(!1),J(e)},[J]),te=t.useCallback(()=>{W(!0),x().then(()=>{F("aborted",{conversationId:c})})},[x,c,F]),we=()=>{Ke(),p([]),v(""),d(),C.current=A?.length?A:void 0,h({eventName:"chat_clear_button_clicked",properties:{conversationId:c}})},E=t.useCallback((e,a)=>{M(null),p(a),v(e),d(),C.current=void 0},[p,v,d]),Me=t.useCallback(async(e,a)=>{te(),E(e,[]),ye(!0);try{const s=await ve(e,a);if(s===null)return!1;const n=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 E(e,n),!0}finally{a?.aborted||ye(!1)}},[E,ve,te]);nt.useInitialConversation({conversationId:m.conversationId,fetchedConversation:m.fetchedConversation,effectiveAuthToken:le,restoreSession:E,loadAndRestoreSession:Me,onLoadFailed:()=>E("",[])});const{openForm:Qe}=ot.useChatForm(),We=it.useWidget();return t.useImperativeHandle(m.chatFunctionsRef,()=>({submitMessage:ee,updateInputMessage(e){I(e)},clearChat:we,openForm:e=>{We?.setView("chat"),Qe(e,void 0)},focusInput:()=>{be.current?.focus()}})),{messages:w,sendMessage:V,addToolApprovalResponse:Je,isLoading:Se,isStreaming:Ie,isBusy:Ae,error:He,setError:M,isSubmitDisabled:Z,input:S,handleInputChange:Fe,handleInputKeyDown:Ve,handleSubmit:ee,stop:te,clear:we,inputRef:be,isMobile:Ge,files:b,setFiles:j,isNewChat:Be,conversationId:c,restoreSession:E,loadAndRestoreSession:Me,isSessionLoading:Le,authToken:y?ae:ce,refreshSession:y?ie:ue,getCaptchaHeader:_,invalidateCaptcha:d,inputNotification:ze,showInputNotification:Y,clearInputNotification:je}};exports.useInkeepChat=dt;
@@ -17,9 +17,9 @@ import { useStreamingEvents as gt } from "../../hooks/use-streaming-events.js";
17
17
  import { useInputNotification as ht } from "../../hooks/use-input-notification.js";
18
18
  import { resolveStreamingAuthError as vt, DEFAULT_ERROR_MESSAGE as ne, isRecoverableError as yt, RECOVERABLE_NOTIFICATION_DURATION_MS as It, resolveHttpStatusCode as Ct, RATE_LIMIT_MESSAGE as Rt, RECOVERABLE_FALLBACK_MESSAGE as Ne } from "./chat-error-helpers.js";
19
19
  const Bt = () => {
20
- const { baseSettings: oe, aiChatSettings: I } = at(), [c = "", g] = mt({
21
- prop: I.conversationIdOverride,
22
- defaultProp: I.conversationIdOverride ?? ""
20
+ const { baseSettings: oe, aiChatSettings: g } = at(), [c = "", h] = mt({
21
+ prop: g.conversationIdOverride,
22
+ defaultProp: g.conversationIdOverride ?? ""
23
23
  }), { logEvent: m } = pt(), { setConversationId: Pe, emitToParent: x } = gt(), ae = i(c);
24
24
  M(() => {
25
25
  const e = ae.current;
@@ -31,14 +31,14 @@ const Bt = () => {
31
31
  }
32
32
  });
33
33
  }, [c, m]);
34
- const [C, R] = k(""), Oe = (e) => R(e.target.value), {
34
+ const [R, S] = k(""), Oe = (e) => S(e.target.value), {
35
35
  shouldBypassCaptcha: De,
36
36
  filters: ie,
37
37
  userProperties: $,
38
38
  analyticsProperties: B
39
39
  } = oe, {
40
40
  authToken: ce,
41
- isAuthenticated: h,
41
+ isAuthenticated: v,
42
42
  isAuthConfigured: le,
43
43
  refreshAuthToken: ue,
44
44
  sessionToken: pe,
@@ -56,8 +56,8 @@ const Bt = () => {
56
56
  headers: ve,
57
57
  appId: N,
58
58
  apiKey: U,
59
- files: S
60
- } = I, ye = i(_);
59
+ files: w
60
+ } = g, ye = i(_);
61
61
  ye.current = _;
62
62
  const Ie = Be || `${ge}/run/api/chat`, { loadConversation: Ce } = lt({
63
63
  baseUrl: ge,
@@ -74,12 +74,12 @@ const Bt = () => {
74
74
  K.current = $ && Object.keys($).length > 0 ? $ : void 0;
75
75
  const q = i(void 0);
76
76
  q.current = B && Object.keys(B).length > 0 ? B : void 0;
77
- const v = i(0), j = i(null), G = i(null), y = i(void 0), ze = S?.map(
77
+ const y = i(0), j = i(null), G = i(null), I = i(void 0), ze = w?.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
  M(() => {
82
- y.current = S?.length ? S : void 0;
82
+ I.current = w?.length ? w : void 0;
83
83
  }, [ze]);
84
84
  const Se = i(ve);
85
85
  Se.current = ve;
@@ -103,7 +103,7 @@ const Bt = () => {
103
103
  default:
104
104
  return ne;
105
105
  }
106
- }, [w, J] = k([]), Ke = _e(
106
+ }, [A, J] = k([]), Ke = _e(
107
107
  () => new nt({
108
108
  api: Ie,
109
109
  headers: () => {
@@ -144,7 +144,7 @@ const Bt = () => {
144
144
  }),
145
145
  [Ie, he, N, U]
146
146
  ), {
147
- messages: A,
147
+ messages: b,
148
148
  sendMessage: W,
149
149
  addToolApprovalResponse: Q,
150
150
  status: we,
@@ -174,8 +174,8 @@ const Bt = () => {
174
174
  onError(e) {
175
175
  console.error("onError", { code: e.code, message: e.message });
176
176
  const n = De || U ? null : vt(e);
177
- if (n !== null && v.current < 1) {
178
- v.current++;
177
+ if (n !== null && y.current < 1) {
178
+ y.current++;
179
179
  const r = G.current, s = j.current;
180
180
  (async () => {
181
181
  if (n === "session" && le) {
@@ -205,7 +205,7 @@ const Bt = () => {
205
205
  { body: s.body }
206
206
  ));
207
207
  })().catch(() => {
208
- v.current = 0, p(), d((u) => {
208
+ y.current = 0, p(), d((u) => {
209
209
  const o = [...u], f = o[o.length - 1];
210
210
  if (!f) return o;
211
211
  const D = ne;
@@ -218,13 +218,13 @@ const Bt = () => {
218
218
  });
219
219
  return;
220
220
  }
221
- v.current = 0, n !== null && p();
221
+ y.current = 0, n !== null && p();
222
222
  const t = yt(e), l = He(e);
223
223
  if (m({
224
224
  eventName: "chat_error",
225
225
  properties: {
226
226
  conversationId: c,
227
- messageId: A.at(-1)?.id,
227
+ messageId: b.at(-1)?.id,
228
228
  error: e.message
229
229
  }
230
230
  }), t) {
@@ -236,7 +236,7 @@ const Bt = () => {
236
236
  return a.at(-1)?.role === "assistant" && (a = a.slice(0, -1)), a.at(-1)?.role === "user" && (a = a.slice(0, -1)), a;
237
237
  });
238
238
  const r = j.current?.content;
239
- r && R(r), ee.current = e;
239
+ r && S(r), ee.current = e;
240
240
  return;
241
241
  }
242
242
  d((r) => {
@@ -248,43 +248,43 @@ const Bt = () => {
248
248
  }) : a.parts = [{ type: "text", text: l }]), s;
249
249
  });
250
250
  }
251
- }), Ae = i(h);
251
+ }), Ae = i(v);
252
252
  M(() => {
253
253
  const e = Ae.current;
254
- Ae.current = h, e !== h && (P(), b(null), d([]), g(""), R(""), J([]), p());
255
- }, [h, P, d, g, p]);
254
+ Ae.current = v, e !== v && (P(), E(null), d([]), h(""), S(""), J([]), p());
255
+ }, [v, P, d, h, p]);
256
256
  const be = we === "submitted", Z = we === "streaming", qe = _e(() => {
257
257
  const e = (r) => {
258
258
  if (!r || typeof r != "object") return !1;
259
259
  const s = r;
260
260
  return typeof s.type == "string" && s.type.startsWith("tool-");
261
- }, t = [...A ?? []].reverse().find((r) => r.role === "assistant");
261
+ }, t = [...b ?? []].reverse().find((r) => r.role === "assistant");
262
262
  if (!t) return !1;
263
263
  const l = t.parts?.at(-1);
264
264
  return !(!e(l) || l.state !== "output-available" || !l.approval?.id || Z);
265
- }, [A, Z]), [je, X] = k(!1), Ee = Z || qe && !je, Te = be || Ee, Ge = A.length === 0, Y = !C.trim() && w.length === 0 || Te, Ve = ct("(max-width: 768px)"), [Je, b] = k(null), ee = i(null);
265
+ }, [b, Z]), [je, X] = k(!1), Ee = Z || qe && !je, Te = be || Ee, Ge = b.length === 0, Y = !R.trim() && A.length === 0 || Te, Ve = ct("(max-width: 768px)"), [Je, E] = k(null), ee = i(null);
266
266
  M(() => {
267
267
  if (O) {
268
268
  if (ee.current === O) {
269
269
  ee.current = null;
270
270
  return;
271
271
  }
272
- b(O);
272
+ E(O);
273
273
  }
274
274
  }, [O]);
275
- const We = () => b(null), { inputNotification: Qe, showInputNotification: te, clearInputNotification: Ze } = ht(), Me = i(null);
275
+ const We = () => E(null), { inputNotification: Qe, showInputNotification: te, clearInputNotification: Ze } = ht(), Me = i(null);
276
276
  M(() => {
277
- $e?.(C);
278
- }, [C]);
277
+ $e?.(R);
278
+ }, [R]);
279
279
  const Xe = (e) => {
280
280
  e.key === "Enter" && !e.shiftKey && !Y && !e.nativeEvent.isComposing && (e.preventDefault(), se());
281
- }, se = async (e = C) => {
282
- if (Y && (!e || e.trim().length === 0) && w.length === 0 || !e.trim() && !w.length && !y.current?.length)
281
+ }, se = async (e = R) => {
282
+ if (Y && (!e || e.trim().length === 0) && A.length === 0 || !e.trim() && !A.length && !I.current?.length)
283
283
  return;
284
- const n = w;
285
- J([]), R(""), v.current = 0, G.current = null, X(!1);
284
+ const n = A;
285
+ J([]), S(""), y.current = 0, G.current = null, X(!1);
286
286
  let t = c;
287
- t || (t = `conv_${F(16)}`, g(t));
287
+ t || (t = `conv_${F(16)}`, h(t));
288
288
  const l = F(21);
289
289
  Pe(t), await m({
290
290
  eventName: "user_message_submitted",
@@ -293,8 +293,8 @@ const Bt = () => {
293
293
  messageId: l
294
294
  }
295
295
  });
296
- const r = y.current;
297
- y.current = void 0;
296
+ const r = I.current;
297
+ I.current = void 0;
298
298
  let s = [];
299
299
  if (n.length > 0)
300
300
  try {
@@ -337,7 +337,7 @@ const Bt = () => {
337
337
  }, W({ id: l, parts: u }, { body: { conversationId: t } });
338
338
  }, Ye = L(
339
339
  (e) => {
340
- v.current = 0, G.current = e, X(!1), Q(e);
340
+ y.current = 0, G.current = e, X(!1), Q(e);
341
341
  },
342
342
  [Q]
343
343
  ), re = L(() => {
@@ -345,20 +345,20 @@ const Bt = () => {
345
345
  x("aborted", { conversationId: c });
346
346
  });
347
347
  }, [P, c, x]), ke = () => {
348
- We(), d([]), g(""), p(), y.current = S?.length ? S : void 0, m({
348
+ We(), d([]), h(""), p(), I.current = w?.length ? w : void 0, m({
349
349
  eventName: "chat_clear_button_clicked",
350
350
  properties: {
351
351
  conversationId: c
352
352
  }
353
353
  });
354
- }, E = L(
354
+ }, C = L(
355
355
  (e, n) => {
356
- b(null), d(n), g(e), p(), y.current = void 0;
356
+ E(null), d(n), h(e), p(), I.current = void 0;
357
357
  },
358
- [d, g, p]
358
+ [d, h, p]
359
359
  ), Fe = L(
360
360
  async (e, n) => {
361
- re(), E(e, []), Re(!0);
361
+ re(), C(e, []), Re(!0);
362
362
  try {
363
363
  const t = await Ce(e, n);
364
364
  if (t === null) return !1;
@@ -375,24 +375,26 @@ const Bt = () => {
375
375
  ]
376
376
  }
377
377
  ] : t;
378
- return E(e, r), !0;
378
+ return C(e, r), !0;
379
379
  } finally {
380
380
  n?.aborted || Re(!1);
381
381
  }
382
382
  },
383
- [E, Ce, re]
383
+ [C, Ce, re]
384
384
  );
385
385
  ut({
386
- conversationId: I.conversationId,
386
+ conversationId: g.conversationId,
387
+ fetchedConversation: g.fetchedConversation,
387
388
  effectiveAuthToken: fe,
389
+ restoreSession: C,
388
390
  loadAndRestoreSession: Fe,
389
- onLoadFailed: () => E("", [])
391
+ onLoadFailed: () => C("", [])
390
392
  });
391
393
  const { openForm: et } = dt(), tt = ft();
392
- return ot(I.chatFunctionsRef, () => ({
394
+ return ot(g.chatFunctionsRef, () => ({
393
395
  submitMessage: se,
394
396
  updateInputMessage(e) {
395
- R(e);
397
+ S(e);
396
398
  },
397
399
  clearChat: ke,
398
400
  openForm: (e) => {
@@ -402,16 +404,16 @@ const Bt = () => {
402
404
  Me.current?.focus();
403
405
  }
404
406
  })), {
405
- messages: A,
407
+ messages: b,
406
408
  sendMessage: W,
407
409
  addToolApprovalResponse: Ye,
408
410
  isLoading: be,
409
411
  isStreaming: Ee,
410
412
  isBusy: Te,
411
413
  error: Je,
412
- setError: b,
414
+ setError: E,
413
415
  isSubmitDisabled: Y,
414
- input: C,
416
+ input: R,
415
417
  handleInputChange: Oe,
416
418
  handleInputKeyDown: Xe,
417
419
  handleSubmit: se,
@@ -419,15 +421,15 @@ const Bt = () => {
419
421
  clear: ke,
420
422
  inputRef: Me,
421
423
  isMobile: Ve,
422
- files: w,
424
+ files: A,
423
425
  setFiles: J,
424
426
  isNewChat: Ge,
425
427
  conversationId: c,
426
- restoreSession: E,
428
+ restoreSession: C,
427
429
  loadAndRestoreSession: Fe,
428
430
  isSessionLoading: Ue,
429
- authToken: h ? ce : pe,
430
- refreshSession: h ? ue : de,
431
+ authToken: v ? ce : pe,
432
+ refreshSession: v ? ue : de,
431
433
  getCaptchaHeader: _,
432
434
  invalidateCaptcha: p,
433
435
  inputNotification: Qe,
@@ -1 +1 @@
1
- "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("react"),f=({conversationId:e,effectiveAuthToken:s,loadAndRestoreSession:u,onLoadFailed:l})=>{const r=o.useRef(null),c=o.useRef(u);c.current=u;const a=o.useRef(l);a.current=l,o.useEffect(()=>{if(!e||!s||r.current===e)return;r.current=e;const t=new AbortController,i=n=>{r.current=null,console.error("[useInitialConversation] failed to load conversation:",e,n),a.current?.()};return(async()=>{try{!await c.current(e,t.signal)&&!t.signal.aborted&&i()}catch(n){t.signal.aborted||i(n)}})(),()=>{r.current=null,t.abort()}},[e,s])};exports.useInitialConversation=f;
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react"),d=({conversationId:r,fetchedConversation:n,effectiveAuthToken:s,restoreSession:o,loadAndRestoreSession:c,onLoadFailed:i})=>{const e=t.useRef(null),a=t.useRef(o);a.current=o;const f=t.useRef(c);f.current=c;const R=t.useRef(i);R.current=i,t.useEffect(()=>{if(n&&!r&&console.warn("[useInitialConversation] fetchedConversation was provided without conversationId and will be ignored"),!r||e.current===r)return;if(n){e.current=r,a.current(r,n);return}if(!s)return;e.current=r;const u=new AbortController,b=l=>{e.current=null,console.error("[useInitialConversation] failed to load conversation:",r,l),R.current?.()};return(async()=>{try{!await f.current(r,u.signal)&&!u.signal.aborted&&b()}catch(l){u.signal.aborted||b(l)}})(),()=>{e.current=null,u.abort()}},[r,n,s])};exports.useInitialConversation=d;
@@ -1,8 +1,13 @@
1
+ import { Message } from '../../types/message';
1
2
  interface UseInitialConversationOptions {
2
3
  /** The conversationId provided via props to load and restore. */
3
4
  conversationId: string | undefined;
5
+ /** Pre-fetched messages — when provided, skips the network fetch entirely. */
6
+ fetchedConversation: Message[] | undefined;
4
7
  /** Resolved auth token — fetch is skipped until one is available. */
5
8
  effectiveAuthToken: string | null;
9
+ /** Restores a session with the given id and messages (no fetch). */
10
+ restoreSession: (sessionId: string, messages: Message[]) => void;
6
11
  /** Returns true if the conversation was loaded successfully, false otherwise. */
7
12
  loadAndRestoreSession: (sessionId: string, signal?: AbortSignal) => Promise<boolean>;
8
13
  /** Called when the load fails (404 or other error) — use to reset conversation state. */
@@ -10,7 +15,8 @@ interface UseInitialConversationOptions {
10
15
  }
11
16
  /**
12
17
  * Loads and restores a conversation by ID once an auth token is available.
18
+ * When `fetchedConversation` is provided, seeds the session directly without fetching.
13
19
  * Calls `onLoadFailed` if the conversation is not found or the fetch fails.
14
20
  */
15
- export declare const useInitialConversation: ({ conversationId, effectiveAuthToken, loadAndRestoreSession, onLoadFailed, }: UseInitialConversationOptions) => void;
21
+ export declare const useInitialConversation: ({ conversationId, fetchedConversation, effectiveAuthToken, restoreSession, loadAndRestoreSession, onLoadFailed, }: UseInitialConversationOptions) => void;
16
22
  export {};
@@ -1,34 +1,45 @@
1
1
  "use client";
2
- import { useRef as o, useEffect as f } from "react";
3
- const C = ({
2
+ import { useRef as l, useEffect as d } from "react";
3
+ const p = ({
4
4
  conversationId: r,
5
- effectiveAuthToken: l,
6
- loadAndRestoreSession: s,
7
- onLoadFailed: c
5
+ fetchedConversation: e,
6
+ effectiveAuthToken: o,
7
+ restoreSession: s,
8
+ loadAndRestoreSession: c,
9
+ onLoadFailed: i
8
10
  }) => {
9
- const t = o(null), u = o(s);
10
- u.current = s;
11
- const a = o(c);
12
- a.current = c, f(() => {
13
- if (!r || !l || t.current === r) return;
11
+ const t = l(null), a = l(s);
12
+ a.current = s;
13
+ const f = l(c);
14
+ f.current = c;
15
+ const b = l(i);
16
+ b.current = i, d(() => {
17
+ if (e && !r && console.warn(
18
+ "[useInitialConversation] fetchedConversation was provided without conversationId and will be ignored"
19
+ ), !r || t.current === r) return;
20
+ if (e) {
21
+ t.current = r, a.current(r, e);
22
+ return;
23
+ }
24
+ if (!o) return;
14
25
  t.current = r;
15
- const e = new AbortController(), i = (n) => {
16
- t.current = null, console.error("[useInitialConversation] failed to load conversation:", r, n), a.current?.();
26
+ const n = new AbortController(), w = (u) => {
27
+ t.current = null, console.error("[useInitialConversation] failed to load conversation:", r, u), b.current?.();
17
28
  };
18
29
  return (async () => {
19
30
  try {
20
- !await u.current(
31
+ !await f.current(
21
32
  r,
22
- e.signal
23
- ) && !e.signal.aborted && i();
24
- } catch (n) {
25
- e.signal.aborted || i(n);
33
+ n.signal
34
+ ) && !n.signal.aborted && w();
35
+ } catch (u) {
36
+ n.signal.aborted || w(u);
26
37
  }
27
38
  })(), () => {
28
- t.current = null, e.abort();
39
+ t.current = null, n.abort();
29
40
  };
30
- }, [r, l]);
41
+ }, [r, e, o]);
31
42
  };
32
43
  export {
33
- C as useInitialConversation
44
+ p as useInitialConversation
34
45
  };
@@ -1 +1 @@
1
- "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l=require("react/jsx-runtime"),t=require("react"),p=require("./config-provider.cjs"),n=t.createContext(void 0),g=({children:e})=>{const{baseSettings:s,componentType:o}=p.useInkeepConfig(),{tags:r,analyticsProperties:i}=s,c="0.17.4",a=t.useMemo(()=>({widgetLibraryVersion:c,componentType:o,tags:r}),[o,r,c]),v={logEvent:t.useCallback(async u=>{const E={...a,...u.properties,...i},d={eventName:u.eventName,properties:E};return s.onEvent?.(d)},[s,a,i])};return l.jsx(n.Provider,{value:v,children:e})},m=()=>{const e=t.useContext(n);if(!e)throw new Error("useBaseEvents must be used within a BaseEventsProvider");return e};exports.BaseEventsContext=n;exports.BaseEventsProvider=g;exports.useBaseEvents=m;
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l=require("react/jsx-runtime"),t=require("react"),p=require("./config-provider.cjs"),n=t.createContext(void 0),g=({children:e})=>{const{baseSettings:s,componentType:o}=p.useInkeepConfig(),{tags:r,analyticsProperties:i}=s,c="0.17.6",a=t.useMemo(()=>({widgetLibraryVersion:c,componentType:o,tags:r}),[o,r,c]),v={logEvent:t.useCallback(async u=>{const E={...a,...u.properties,...i},d={eventName:u.eventName,properties:E};return s.onEvent?.(d)},[s,a,i])};return l.jsx(n.Provider,{value:v,children:e})},m=()=>{const e=t.useContext(n);if(!e)throw new Error("useBaseEvents must be used within a BaseEventsProvider");return e};exports.BaseEventsContext=n;exports.BaseEventsProvider=g;exports.useBaseEvents=m;
@@ -3,7 +3,7 @@ import { jsx as u } from "react/jsx-runtime";
3
3
  import { createContext as E, useMemo as d, useCallback as l, useContext as g } from "react";
4
4
  import { useInkeepConfig as x } from "./config-provider.js";
5
5
  const c = E(void 0), b = ({ children: e }) => {
6
- const { baseSettings: t, componentType: o } = x(), { tags: s, analyticsProperties: n } = t, r = "0.17.4", i = d(
6
+ const { baseSettings: t, componentType: o } = x(), { tags: s, analyticsProperties: n } = t, r = "0.17.6", i = d(
7
7
  () => ({
8
8
  widgetLibraryVersion: r,
9
9
  componentType: o,
@@ -1 +1 @@
1
- "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const j=require("react/jsx-runtime"),u=require("react"),B=require("./config-provider.cjs"),O=require("./chat-auth-provider.cjs"),U=require("../hooks/use-events-api.cjs"),x=require("./base-events-provider.cjs"),M=({children:g})=>{const{baseSettings:n,aiChatSettings:h,componentType:i}=B.useInkeepConfig(),{tags:t,analyticsProperties:r,privacyPreferences:y,userProperties:o}=n,c="0.17.4",a=u.useMemo(()=>({widgetLibraryVersion:c,componentType:i}),[i,c]),{effectiveAuthToken:b,applicableRefreshSession:f,getCaptchaHeader:E,invalidateCaptcha:P}=O.useChatAuth(),{baseUrl:m,appId:A,analyticsApiBaseUrl:C,headers:I}=h,p=y?.optOutAllAnalytics??!1,{logEvent:l}=U.useEventsApi({baseUrl:C??m,appId:A,authToken:b,getCaptchaHeader:E,invalidateCaptcha:P,refreshSession:f,headers:I}),k={logEvent:u.useCallback(async s=>{const q={eventName:s.eventName,properties:{...a,...t?{tags:t}:{},...s.properties,...r}};if(!p){const e=s.properties??{},v=typeof e.conversationId=="string"?e.conversationId:void 0,d=typeof e.messageId=="string"?e.messageId:void 0,S=!!o&&Object.keys(o).length>0,w={...t?{tags:t}:{},...r??{}},T={...a,...s.properties};l({body:{type:s.eventName,...v?{conversationId:v}:{},...d?{messageId:d}:{},...S?{userProperties:o}:{},properties:w,metadata:T}})}try{return await n.onEvent?.(q)}catch(e){console.warn("[events] onEvent callback threw",e)}},[n,a,t,r,l,p,o])};return j.jsx(x.BaseEventsContext.Provider,{value:k,children:g})};exports.ChatBaseEventsProvider=M;
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const j=require("react/jsx-runtime"),u=require("react"),B=require("./config-provider.cjs"),O=require("./chat-auth-provider.cjs"),U=require("../hooks/use-events-api.cjs"),x=require("./base-events-provider.cjs"),M=({children:g})=>{const{baseSettings:n,aiChatSettings:h,componentType:i}=B.useInkeepConfig(),{tags:t,analyticsProperties:r,privacyPreferences:y,userProperties:o}=n,c="0.17.6",a=u.useMemo(()=>({widgetLibraryVersion:c,componentType:i}),[i,c]),{effectiveAuthToken:b,applicableRefreshSession:f,getCaptchaHeader:E,invalidateCaptcha:P}=O.useChatAuth(),{baseUrl:m,appId:A,analyticsApiBaseUrl:C,headers:I}=h,p=y?.optOutAllAnalytics??!1,{logEvent:l}=U.useEventsApi({baseUrl:C??m,appId:A,authToken:b,getCaptchaHeader:E,invalidateCaptcha:P,refreshSession:f,headers:I}),k={logEvent:u.useCallback(async s=>{const q={eventName:s.eventName,properties:{...a,...t?{tags:t}:{},...s.properties,...r}};if(!p){const e=s.properties??{},v=typeof e.conversationId=="string"?e.conversationId:void 0,d=typeof e.messageId=="string"?e.messageId:void 0,S=!!o&&Object.keys(o).length>0,w={...t?{tags:t}:{},...r??{}},T={...a,...s.properties};l({body:{type:s.eventName,...v?{conversationId:v}:{},...d?{messageId:d}:{},...S?{userProperties:o}:{},properties:w,metadata:T}})}try{return await n.onEvent?.(q)}catch(e){console.warn("[events] onEvent callback threw",e)}},[n,a,t,r,l,p,o])};return j.jsx(x.BaseEventsContext.Provider,{value:k,children:g})};exports.ChatBaseEventsProvider=M;
@@ -6,7 +6,7 @@ import { useChatAuth as O } from "./chat-auth-provider.js";
6
6
  import { useEventsApi as j } from "../hooks/use-events-api.js";
7
7
  import { BaseEventsContext as M } from "./base-events-provider.js";
8
8
  const F = ({ children: m }) => {
9
- const { baseSettings: r, aiChatSettings: g, componentType: i } = N(), { tags: t, analyticsProperties: n, privacyPreferences: f, userProperties: o } = r, c = "0.17.4", a = x(
9
+ const { baseSettings: r, aiChatSettings: g, componentType: i } = N(), { tags: t, analyticsProperties: n, privacyPreferences: f, userProperties: o } = r, c = "0.17.6", a = x(
10
10
  () => ({
11
11
  widgetLibraryVersion: c,
12
12
  componentType: i
@@ -654,6 +654,9 @@ video {
654
654
  .top-\\[5\\%\\] {
655
655
  top: 5%;
656
656
  }
657
+ .isolate {
658
+ isolation: isolate;
659
+ }
657
660
  .z-10 {
658
661
  z-index: 10;
659
662
  }
@@ -655,6 +655,9 @@ video {
655
655
  .top-\\[5\\%\\] {
656
656
  top: 5%;
657
657
  }
658
+ .isolate {
659
+ isolation: isolate;
660
+ }
658
661
  .z-10 {
659
662
  z-index: 10;
660
663
  }
@@ -3,6 +3,8 @@ import { GetHelpOption, CustomMessageAction } from './settings/actions';
3
3
  import { SearchAndChatFilters } from './filters';
4
4
  import { ComponentsConfig } from './components';
5
5
  import { FileUIPart } from 'ai';
6
+ import { Message } from '../message';
7
+ export type { FileUIPart } from 'ai';
6
8
  export interface InkeepAIChatSettings {
7
9
  /**
8
10
  * Headers for requests
@@ -43,6 +45,27 @@ export interface InkeepAIChatSettings {
43
45
  * @beta This type is subject to change.
44
46
  */
45
47
  files?: FileUIPart[];
48
+ /**
49
+ * Transform the file attachments displayed on a user message before they render as
50
+ * chips. Called per message at render time with the message's file parts, for live
51
+ * and history-loaded messages alike. The input includes all of the message's file
52
+ * parts regardless of MIME type; the widget's accepted-file-types filter is
53
+ * re-applied to the returned list, so unsupported types still never render. Return
54
+ * the parts to display: omit entries to hide them, or return shallow-modified copies
55
+ * (for example, with a friendlier filename) to rename them. Display-only, so it does
56
+ * not affect what is sent to the agent, stored, or visible to the LLM. Not a
57
+ * security boundary: hidden parts are still sent, stored in conversation history,
58
+ * and present in client memory, and if the transformer throws or returns a
59
+ * non-array, the widget fails open and renders the original untransformed parts.
60
+ * Null entries in a returned array are dropped, treated as intent to omit rather
61
+ * than as a failure. Every returned (whitelisted) part is displayed verbatim, so
62
+ * returning entries that were not in the input adds chips for files the user never
63
+ * attached. Must be pure and cheap, since it runs on every message render.
64
+ * Return new or copied objects and do not mutate the input parts.
65
+ *
66
+ * @beta This type is subject to change.
67
+ */
68
+ transformMessageFiles?: (files: FileUIPart[]) => Array<FileUIPart | null | undefined>;
46
69
  /**
47
70
  * The placeholder text to display in the chat input field when empty.
48
71
  * Use this to provide guidance on what kind of questions users can ask.
@@ -144,6 +167,13 @@ export interface InkeepAIChatSettings {
144
167
  * restore a previous conversation state.
145
168
  */
146
169
  conversationIdOverride?: string;
170
+ /**
171
+ * Pre-fetched conversation messages to render without fetching.
172
+ * Requires `conversationId` to be set.
173
+ *
174
+ * @beta This prop is subject to change.
175
+ */
176
+ fetchedConversation?: Message[];
147
177
  /**
148
178
  * When enabled, prevents users from sending new messages.
149
179
  * Useful for displaying archived or shared chat sessions.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inkeep/agents-ui",
3
- "version": "0.17.4",
3
+ "version": "0.17.6",
4
4
  "description": "",
5
5
  "homepage": "",
6
6
  "repository": {