@bangdb/web-sdk 1.0.10 → 1.0.11

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.
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var Y=`
1
+ var te=`
2
2
  :root {
3
3
  --thread-content-max-width: 32rem;
4
4
  }
@@ -583,7 +583,7 @@ code.hljs {
583
583
  .hljs-strong {
584
584
  font-weight: bold
585
585
  }
586
- }`;var W=`
586
+ }`;var oe=`
587
587
  :root {
588
588
  --border-xheavy: var(--border);
589
589
  }
@@ -1046,10 +1046,10 @@ code.hljs {
1046
1046
  .prose > :last-child:not(.not-prose *) {
1047
1047
  margin-bottom: 0;
1048
1048
  }
1049
- `;import{configureStore as Ie}from"@reduxjs/toolkit";import{createSlice as Le}from"@reduxjs/toolkit";var je={activeIndex:"",activeSession:"",sessions:[],useGenAi:!1,mode:0,tools:[]},J=Le({name:"chat",initialState:je,reducers:{changeMode:(n,e)=>{n.mode=e.payload},setActiveIndex:(n,e)=>{n.activeIndex=e.payload},setActiveSession:(n,e)=>{n.activeSession=e.payload},setSessions:(n,e)=>{n.sessions=e.payload},setUseGenAi:(n,e)=>{n.useGenAi=e.payload},addTool:(n,e)=>{n.tools.some(t=>t.id===e.payload.id)||n.tools.push(e.payload)},removeTool:(n,e)=>{n.tools=n.tools.filter(t=>t.id!==e.payload)}}}),{setActiveIndex:V,setActiveSession:X,setSessions:St,setUseGenAi:Lt,changeMode:z,addTool:Q,removeTool:P}=J.actions,Z=J.reducer;import{createAsyncThunk as re,createSlice as Me}from"@reduxjs/toolkit";var S=class{constructor(e){this.rawResponse=e}detectModelVersion(){let e=this.extractOutput();return!e||e.length===0||!Array.isArray(e)?"unknown":e?.[0]?.content||e?.[1]?.content?"gpt5":e[0]?.message?"gpt4":e?.some(t=>t?.text)?"file-chat":"unknown"}extractOutput(){let e=this.rawResponse;return e?.choices||e?.a?.choices||e?.output||e?.a?.output||e?.content||e?.a?.content||[]}normalizeGPT4Choice(e){return{output:e?.message?.content||""}}normalizeFileChatResponse(e){return{output:e?.text?.value}}normalizeGPT5Output(e){return{output:e.content.map(t=>t.text).join(`
1049
+ `;import{configureStore as tt}from"@reduxjs/toolkit";import{createSlice as Ge}from"@reduxjs/toolkit";var Ve={activeIndex:"",activeSession:"",sessions:[],useGenAi:!1,mode:0,tools:[]},re=Ge({name:"chat",initialState:Ve,reducers:{hydrateChatState:(n,e)=>({...n,...e.payload,mode:n.mode}),changeMode:(n,e)=>{n.mode=e.payload},setActiveIndex:(n,e)=>{n.activeIndex=e.payload},setActiveSession:(n,e)=>{n.activeSession=e.payload},setSessions:(n,e)=>{n.sessions=e.payload},setUseGenAi:(n,e)=>{n.useGenAi=e.payload},addTool:(n,e)=>{n.tools.some(t=>t.id===e.payload.id)||n.tools.push(e.payload)},removeTool:(n,e)=>{n.tools=n.tools.filter(t=>t.id!==e.payload)},resetChatState:n=>{n.sessions=[],n.useGenAi=!1,n.tools=[]}}}),{hydrateChatState:Jt,setActiveIndex:ne,setActiveSession:ae,setSessions:ie,setUseGenAi:Xt,changeMode:L,addTool:se,removeTool:G,resetChatState:Kt}=re.actions,le=re.reducer;import{createAsyncThunk as R,createSlice as Je}from"@reduxjs/toolkit";var I=class{constructor(e){this.rawResponse=e}detectModelVersion(){let e=this.extractOutput();return!e||e.length===0||!Array.isArray(e)?"unknown":e?.[0]?.content||e?.[1]?.content?"gpt5":e[0]?.message?"gpt4":e?.some(t=>t?.text)?"file-chat":"unknown"}extractOutput(){let e=this.rawResponse;return e?.choices||e?.a?.choices||e?.output||e?.a?.output||e?.content||e?.a?.content||[]}normalizeGPT4Choice(e){return{output:e?.message?.content||""}}normalizeFileChatResponse(e){return{output:e?.text?.value}}normalizeGPT5Output(e){return{output:e.content.map(t=>t.text).join(`
1050
1050
 
1051
- `)}}parse(){let e=this.extractOutput(),t=this.detectModelVersion(),o=[];return t==="gpt4"?o=e?.filter(({message:r})=>r?.content).map(r=>this.normalizeGPT4Choice(r)):t==="gpt5"?o=e?.filter(r=>r?.content?.length>0).map(r=>this.normalizeGPT5Output(r)):t==="file-chat"&&(o=e?.filter(({text:r})=>r)?.map(r=>this.normalizeFileChatResponse(r))),{messages:o,model:t,raw:this.rawResponse}}};var ee=async({baseURL:n,payload:e,apikey:t})=>{try{return await(await fetch("https://"+n+"/ai/vector/chat",{method:"POST",body:JSON.stringify(e),headers:{"x-bang-api-key":t,"x-bang-api-src":"chat-applet"}})).json()}catch{return{error:"Failed to get the response"}}},_=async({baseURL:n,payload:e,apikey:t})=>{try{return await(await fetch("https://"+n+"/ai/vector/metadata",{method:"POST",body:JSON.stringify(e),headers:{"x-bang-api-key":t,"x-bang-api-src":"chat-applet"}})).json()}catch(o){console.error(o)}};var ze={},q={query:"",chatData:[],streamingMessage:null,isLoading:!1},ne=Me({name:"chatSession",initialState:ze,reducers:{initSession:(n,e)=>{let t=e.payload;n[t]||(n[t]=q)},setLoading:(n,e)=>{let{sessionId:t,loading:o}=e.payload;n[t]||(n[t]=q),n[t].isLoading=o},setQuery:(n,e)=>{let{sessionId:t,query:o}=e.payload;n[t]||(n[t]=q),n[t].query=o},appendChatData:(n,e)=>{let{sessionId:t,chatData:o}=e.payload;n[t]||(n[t]=q),n[t].chatData=[...n[t].chatData||[],...o]},setChatData:(n,e)=>{let{sessionId:t,chatData:o}=e.payload;n[t]||(n[t]=q),n[t].chatData=o},setStreamingMessage:(n,e)=>{let{sessionId:t,message:o}=e.payload;n[t]&&(n[t].streamingMessage=o)}}}),{initSession:Ae,setQuery:N,setChatData:Nt,appendChatData:te,setStreamingMessage:F,setLoading:oe}=ne.actions,ae=re("chatSession/streamResponse",async({sessionId:n,query:e,indexName:t,config:{backendURL:o,apikey:r,userid:a}},{getState:s,dispatch:i})=>{let c=s(),{chatData:p,isLoading:d}=c.chatSessions[n];if(!e?.trim()||d)return;i(oe({sessionId:n,loading:!0}));let l={query:e,a:{choices:[]}};i(F({sessionId:n,message:l})),i(N({sessionId:n,query:""}));let g=p?.filter(x=>x&&x?.op!=="ADD_FILES"&&!x?.source_file&&!x?.source)?.length,h=Array.isArray(p)?p?.map(x=>{let{messages:E}=new S(x).parse(),L=E?.map(j=>j?.output)?.filter(Boolean)?.join(`
1052
- `);return!x?.query||!L||L.startsWith("Error: ")?null:{q:x?.query,a:L}})?.filter(x=>x!==null):[],{tools:b}=c.chat,m=b?.[0],u=m?.id==="feeling-lucky"?"GenAI":void 0,y=m?.id==="kpi",w=Date.now(),k=await ee({baseURL:o,apikey:r,payload:{name:t,qnum:g?g+1:1,fall_back:u,type:y?"kpi":void 0,sessionid:n,userid:a,prev_qa:y?void 0:h,query:l?.query}}),v=new S(k),{raw:C,messages:f}=v.parse();if(i(oe({sessionId:n,loading:!1})),f?.length>0){for(let x=0;x<f.length;x++){let L=(f[x]?.output||"")?.split(" "),j="";for(let M=0;M<L.length;M++)await new Promise(I=>setTimeout(I,20)),j=j+(j?" ":"")+L[M],i(F({sessionId:n,message:{...l,a:{choices:[{message:{content:j}}]}}}))}i(te({sessionId:n,chatData:[{...C,query:l?.query,queryTime:Date.now()-w}]})),i(F({sessionId:n,message:null}))}else i(te({sessionId:n,chatData:[{query:l?.query,queryTime:Date.now()-w,a:{choices:[{message:{content:C?.a?.choices?.[0]?.message?.content||C?.error||"There is no context in the vector index and fall back option is null"}}]}}]}))}),ie=re("chatSession/initializeState",async({indexName:n},{dispatch:e})=>{let t="GUEST_SESSION";e(V(n)),e(X(t)),e(Ae(t))});var se=ne.reducer;var le=Ie({reducer:{chat:Z,chatSessions:se}});import pe from"highlight.js";import $e from"markdown-it";import Ne from"@vscode/markdown-it-katex";var qe=function(n,e,t){let o=t,r=0,a=n.length;for(;o<e.length;){let s=e[o];if(r<=0&&e.slice(o,o+a)===n)return o;s==="\\"?o++:s==="{"?r++:s==="}"&&r--,o++}return-1},He=function(n){return n.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")},Oe=/^\\begin{/,De=function(n,e){let t,o=[],r=new RegExp("("+e.map(a=>He(a.left)).join("|")+")");for(;t=n.search(r),t!==-1;){t>0&&(o.push({type:"text",data:n.slice(0,t)}),n=n.slice(t));let a=e.findIndex(c=>n.startsWith(c.left));if(t=qe(e[a].right,n,e[a].left.length),t===-1)break;let s=n.slice(0,t+e[a].right.length),i=Oe.test(s)?s:n.slice(e[a].left.length,t);o.push({type:"math",data:i,rawData:s,display:e[a].display}),n=n.slice(t+e[a].right.length)}return n!==""&&o.push({type:"text",data:n}),o},de=De;import"katex/dist/contrib/mhchem.min.js";function ce(n){return new Promise(e=>{setTimeout(e,n)})}import{debounce as Re}from"lodash";var he=new $e({html:!0,breaks:!0,linkify:!0,highlight:function(n,e){let t=e??"auto";if(e&&pe.getLanguage(e))try{return`<pre class="language-${e}"><div class="ai-chat-code-title">${e}<a class="ai-chat-code-copy cursor-pointer">Copy</a></div><code class="hljs">`+pe.highlight(n,{language:t,ignoreIllegals:!0}).value+"</code></pre>"}catch{}return'<pre><code class="hljs">'+n+"</code></pre>"}}).enable(["table","code","fence","blockquote","heading","lheading","paragraph"]).enable(["autolink","linkify","backticks","image","link","newline"]).enable(["emphasis","html_inline"]).use(Ne);typeof window<"u"&&window.document.addEventListener("click",n=>{if(n.target?.classList?.contains("ai-chat-code-copy")){let e=n.target.parentNode?.nextSibling?.innerText;navigator.clipboard.writeText(e).then(async()=>{n.target.innerHTML='<span style="margin-right:3px">Copied</span>\u2705',await ce(3e3),n.target.innerText="Copy"}).catch(t=>{alert(`Error copying code: ${t.message}`)})}});var Be={fn:n=>{n()}},ro=Re((n=()=>{})=>{Be.fn(n)},10);var Pe=n=>n.replace(/(```mermaid)(?![^]*?```)/g,"```"),_e=n=>de(n,[{left:"\\[",right:"\\]",display:!0},{left:"\\(",right:"\\)",display:!1}]).reduce((t,o)=>{if(o.type==="text")return t+o.data;let r=o.display?`$$${o.data}$$`:`$${o.data}$`;return t+r},""),Fe=n=>{let e="",t="",o=!1,r="think-wrapper",a=s=>{let i=s.replace(/<script([^>]*)>/gi,"&lt;script$1&gt;");return i=i.replace(/<\/script>/gi,"&lt;/script&gt;"),i=i.replace(/<script([^>]*)\s*\/>/gi,"&lt;script$1 /&gt;"),i};for(let s=0;s<n.length;s++){let i=n[s],c=n.slice(s,s+7),p=n.slice(s,s+8);if(!o&&c==="<think>"){o=!0,e+=`<div class="${r}">`,s+=6;continue}if(o&&p==="</think>"){o=!1,e+="</div>",s+=7;continue}o?t+=i:e+=i}if(t){let s=a(t),i=he.render(s);e=e.replace(`<div class="${r}">`,`<div class="${r}">${i}`)}return e},Ue=n=>n.replace(/\[source_id:\s*([^\]|]+)(?:\s*\|\s*category:\s*([^\]]+))?\]\.?/g,(e,t,o)=>o?`<source-tag data-source-id="${t.trim()}" data-category="${o.trim()}"></source-tag>`:`<source-tag data-source-id="${t.trim()}"></source-tag>`),H=n=>{let e=Fe(n),t=_e(e),o=Pe(t),r=Ue(o);return he.render(r)};import*as me from"echarts";import"echarts/theme/dark-bold.js";import{createGrid as Ye,ModuleRegistry as We,AllCommunityModule as Je,themeQuartz as Ve,colorSchemeVariable as Xe}from"ag-grid-community";function be(n,e="",t={}){if(typeof n!="object"||n===null||Array.isArray(n))return t;for(let[o,r]of Object.entries(n)){let a=e?`${e}.${o}`:o;typeof r=="object"&&r!==null&&!Array.isArray(r)?be(r,a,t):t[a]=r}return t}var Ke=["#5470c6","#c5e542","#9d9ec1","#ee6666","#73c0de","#3ba272","#fc8452","#9a60b4","#ea7ccc"],Ge={color:Ke,backgroundColor:"transparent",tooltip:{trigger:"axis",axisPointer:{type:"shadow"}},legend:{show:!0,type:"scroll",bottom:0,top:null},toolbox:{show:!0,feature:{saveAsImage:{}}}},A=class{constructor(e){this.data=e}parse(){let e=[];if(!this.data)return{charts:[],errors:["Invalid input: null or undefined"]};if(typeof this.data!="object")return{charts:[],errors:[`Invalid input type: expected object, got ${typeof this.data}`]};let t=this.extractArrays(this.data,[]),o=Object.entries(this.data).filter(([,a])=>typeof a=="number"&&!Number.isNaN(a)).map(([a,s])=>({title:a,type:"card",options:{title:a,value:s}}));if(t.length===0&&o.length===0)return{charts:[],errors:["No valid categorical data found"]};let r=[...o];for(let{title:a,items:s}of t){if(s.length===0){e.push(`"${a}": Array is empty \u2014 skipped`);continue}let i=s.map(p=>be(p)).filter(p=>typeof p=="object"&&p!==null&&!Array.isArray(p)),c=this.detectChartStructure(i);if(c){let p=this.convertToChartData(i,c);if(p.length===0){e.push(`"${a}": No valid rows after conversion \u2014 skipped`);continue}let d=this.isSimpleCategoricalPie(p)?"pie":"bar";r.push({title:a,type:d,options:{...Ge,...this.toChartSeries(p,d)}})}else r.push({title:a,type:"table",options:{columns:Array.from(new Set(i.flatMap(p=>Object.keys(p)))),rows:i}})}return e.length>0?{charts:r,errors:e}:{charts:r}}extractArrays(e,t){if(Array.isArray(e)){let o=e.flatMap((a,s)=>Array.isArray(a)?[]:[a]),r=e.flatMap((a,s)=>Array.isArray(a)?this.extractArrays(a,[...t,`[${s}]`]):[]);return[...o.length?[{title:t.length?t.join("."):"Root Data",items:o}]:[],...r]}return e&&typeof e=="object"?Object.entries(e).flatMap(([o,r])=>this.extractArrays(r,[...t,o])):[]}detectChartStructure(e){if(e.length===0)return null;let t=new Set;for(let s of e)for(let i of Object.keys(s))t.add(i);let o=Array.from(t),r=o.filter(s=>typeof e[0]?.[s]=="string"),a=o.filter(s=>typeof e[0]?.[s]=="number");return a.length===0||r.length>1?null:{labelKey:r[0]??"__auto__",valueKeys:a}}isSimpleCategoricalPie(e){return e.length?e.every(t=>t.values.length===1):!1}convertToChartData(e,t){return e.map((o,r)=>{let a=t.labelKey==="__auto__"?null:o[t.labelKey];return{labelValue:a!=null?String(a):`Item ${r+1}`,labelKey:t.labelKey,values:t.valueKeys.map(i=>({[i]:Number(o[i])||0}))}})}toChartSeries(e,t){if(t==="bar"){let r={};return e.forEach((a,s)=>{a.values.forEach(i=>{let[c,p]=Object.entries(i)[0];r[c]||(r[c]=new Array(e.length).fill(0)),r[c][s]=p})}),{xAxis:{type:"category",data:e.map(a=>a.labelValue).filter(Boolean)},yAxis:{type:"value"},series:Object.entries(r).map(([a,s])=>({name:a,type:"bar",stack:"total",data:s}))}}let o=Object.keys(e[0]?.values?.[0]??{})[0]??"value";return{tooltip:{trigger:"item"},series:[{name:"Data",type:"pie",radius:["40%","70%"],label:{show:!1},labelLine:{show:!1},avoidLabelOverlap:!1,data:e.map(r=>({name:r.labelValue,value:r.values[0]?.[o]??0}))}]}}};var ge=!1;function Qe(){ge||(We.registerModules([Je]),ge=!0)}var Ze=Ve.withPart(Xe).withParams({fontFamily:"var(--font-body)",headerFontFamily:"var(--font-body)",borderColor:"var(--border)",backgroundColor:"var(--background)",foregroundColor:"var(--foreground)",headerTextColor:"var(--foreground)",headerBackgroundColor:"var(--card)",rowVerticalPaddingScale:1.4,headerColumnResizeHandleColor:"var(--secondary)",wrapperBorderRadius:2});function et(n){if(typeof n!="string")return!1;try{return JSON.parse(n),!0}catch{return!1}}function tt(n,e){return n<=1||e==="table"?1:e==="card"?Math.min(n,4):2}function ot(n,e){return e===1||n==="table"?"1 / -1":"span 1"}function rt(n){let e=document.createElement("div");e.style.cssText=`
1051
+ `)}}parse(){let e=this.extractOutput(),t=this.detectModelVersion(),o=[];return t==="gpt4"?o=e?.filter(({message:r})=>r?.content).map(r=>this.normalizeGPT4Choice(r)):t==="gpt5"?o=e?.filter(r=>r?.content?.length>0).map(r=>this.normalizeGPT5Output(r)):t==="file-chat"&&(o=e?.filter(({text:r})=>r)?.map(r=>this.normalizeFileChatResponse(r))),{messages:o,model:t,raw:this.rawResponse}}};var Ze="brs_access_key",We="brs_secret_key",D=n=>({"Content-Type":"application/json; charset=UTF-8","x-bang-api-key":n,"x-bang-api-src":"chat-applet"}),B=async({baseURL:n,payload:e,apikey:t})=>{try{return await(await fetch("https://"+n+"/ai/session/create",{method:"POST",body:JSON.stringify(e),headers:D(t)})).json()}catch{return{error:"Failed to get the response"}}},de=async({baseURL:n,payload:e,apikey:t})=>{try{return await(await fetch("https://"+n+"/ai/session/list",{method:"POST",body:JSON.stringify(e),headers:D(t)})).json()}catch{return{error:"Failed to get the response"}}},ce=async({baseURL:n,payload:e,apikey:t})=>{try{return await(await fetch("https://"+n+"/ai/session/search",{method:"POST",body:JSON.stringify(e),headers:D(t)})).json()}catch{return{error:"Failed to get the response"}}},pe=async({baseURL:n,payload:e,apikey:t})=>{try{return await(await fetch("https://"+n+"/ai/vector/chat",{method:"POST",body:JSON.stringify(e),headers:D(t)})).json()}catch{return{error:"Failed to get the response"}}},V=async({baseURL:n,payload:e,apikey:t})=>{try{return await(await fetch("https://"+n+"/ai/vector/metadata",{method:"POST",body:JSON.stringify(e),headers:D(t)})).json()}catch(o){console.error(o)}},be=async({baseURL:n,payload:e,apikey:t})=>{try{return await(await fetch("https://"+n+"/ai/vector/upsert",{method:"POST",body:JSON.stringify(e),headers:D(t)})).json()}catch(o){return{error:o?.message||"Failed to upsert files"}}},he=async({baseURL:n,payload:e,apikey:t})=>{try{return await(await fetch("https://"+n+"/ai/session/add",{method:"POST",body:JSON.stringify(e),headers:D(t)})).json()}catch(o){return{error:o?.message||"Failed to save files to session"}}},ue=async({apikey:n,resourceURL:e,bucketName:t,fileName:o,file:r})=>{try{let a="https://"+e,i=await(await fetch(`${a}/brs/${t}/putfile`,{method:"POST",body:JSON.stringify({access_key:Ze,secret_key:We,fsize:r.size,bucket_name:t,key:o}),headers:D(n)})).json();if(i?.error)return{error:i?.error||"Failed to initialize file upload"};let{next_key:l,nslice:d,chunk_size:c}=i,u=l,g=0,b=await r.arrayBuffer();for(let h=0;h<d;h++){let m=b.slice(g*c,(g+1)*c),w=await(await fetch(`${a}/brs/${t}/putfile?key=${u}&nslice=${d}`,{method:"POST",body:m,headers:{"Content-Type":"application/octet-stream","x-bang-api-key":n,"x-bang-api-src":"chat-applet"}})).json();if(w?.error)return{error:w?.error||"Failed to upload file chunk"};u=w.next_key,g++}return{key:l}}catch(a){return{error:a?.message||"Failed to upload file"}}};var Xe={},Ke={query:"",files:[],queryFiles:[],chatData:[],streamingMessage:null,isLoading:!1},N=()=>({...Ke}),me=Je({name:"chatSession",initialState:Xe,reducers:{initSession:(n,e)=>{let t=e.payload;n[t]||(n[t]=N())},setLoading:(n,e)=>{let{sessionId:t,loading:o}=e.payload;n[t]||(n[t]=N()),n[t].isLoading=o},setQuery:(n,e)=>{let{sessionId:t,query:o}=e.payload;n[t]||(n[t]=N()),n[t].query=o},appendChatData:(n,e)=>{let{sessionId:t,chatData:o}=e.payload;n[t]||(n[t]=N()),n[t].chatData=[...n[t].chatData||[],...o]},setChatData:(n,e)=>{let{sessionId:t,chatData:o}=e.payload;n[t]||(n[t]=N()),n[t].chatData=o},setFiles:(n,e)=>{let{sessionId:t,files:o}=e.payload;n[t]||(n[t]=N()),n[t].files=o},setQueryFiles:(n,e)=>{let{sessionId:t,files:o}=e.payload;n[t]||(n[t]=N()),n[t].queryFiles=o},updateFileStatus:(n,e)=>{let{sessionId:t,fileId:o,patch:r}=e.payload;n[t]&&(n[t].files=(n[t].files||[]).map(a=>a.id===o?{...a,...r}:a),n[t].queryFiles=(n[t].queryFiles||[]).map(a=>a.id===o?{...a,...r}:a))},setStreamingMessage:(n,e)=>{let{sessionId:t,message:o}=e.payload;n[t]&&(n[t].streamingMessage=o)},hydrateSessionsState:(n,e)=>{let t={};for(let[o,r]of Object.entries(e.payload||{}))t[o]={...N(),...r,chatData:Array.isArray(r?.chatData)?r.chatData:[],files:Array.isArray(r?.files)?r.files:[],queryFiles:Array.isArray(r?.queryFiles)?r.queryFiles:[],streamingMessage:null,isLoading:!1};return t}}}),{initSession:fe,setQuery:_,appendChatData:W,setStreamingMessage:Z,setLoading:ge,hydrateSessionsState:co,setChatData:ye,setFiles:X,setQueryFiles:Y,updateFileStatus:O}=me.actions,J=R("chatSession/sendFiles",async({files:n,index_time_sec:e,log_sid:t,indexName:o,sessionId:r,config:{backendURL:a,apikey:s,userid:i,org:l}},{getState:d,dispatch:c})=>{let g=d().chatSessions[r],b=n||g?.files||[];if(!b.length)return;let h=b.map(w=>({id:w.id,name:w.name,type:w.type,status:w.status,error:w.error,errorSeverity:w.errorSeverity,metadata:w.metadata,bucket_name:w.bucket_name??`${o}_bucket`,sizeBytes:w.sizeBytes,_u_:w.metadata?._u_,_g_:w.metadata?._g_,index_time_sec:w.metadata?.index_time_sec??e,log_sid:t})),m={sessionid:r,userid:i,op:"ADD_FILES",log_sid:t,files:h,org:l},x=await he({baseURL:a,apikey:s,payload:m});if(x&&!x?.error){c(W({sessionId:r,chatData:[m]}));let w=new Set(b.map(p=>p.id));c(X({sessionId:r,files:(g?.files||[]).filter(p=>!w.has(p.id))}))}}),et=R("chatSession/embedFiles",async({files:n,sessionId:e,indexName:t,config:o},{dispatch:r})=>{for(let d of n)r(O({sessionId:e,fileId:d.id,patch:{status:"embedding",error:null}}));let a=n.map(d=>{let{_u_:c=[],_g_:u=[],description:g,...b}=d.metadata||{};return{doc:encodeURIComponent(d.name),bucket_name:d.bucket_name??`${t}_bucket`,...b??{},metadata:{_u_:c,_g_:u,description:g,source:encodeURIComponent(d.name),origin:"direct_upload"}}}),s=await be({baseURL:o.backendURL,apikey:o.apikey,payload:{name:t,docs:a,userid:o.userid,sessionid:e||"defaultOpen"}}),i=Array.isArray(s?.error)?s.error:s?.error?[String(s.error)]:[];if(i.length>0){let d=/file \[([^\]]+)] is already indexed/;for(let c of n){let u=i.find(b=>b.includes(c.name)),g=i.some(b=>d.test(b));r(O({sessionId:e,fileId:c.id,patch:{status:"error",errorSeverity:g?"success":"error",error:g?"The file is already indexed.":"failed to embed : "+(u||i[0])}}))}await r(J({files:n.map(c=>({...c,status:"error",error:c.error||"failed to embed : "+(i[0]||"Unknown error")})),index_time_sec:s?.index_time_sec,log_sid:s?.sid,indexName:t,sessionId:e,config:o}));return}let l=n.map(d=>({...d,status:"done",error:null,metadata:{...d.metadata||{},index_time_sec:s?.index_time_sec}}));for(let d of l)r(O({sessionId:e,fileId:d.id,patch:{status:"done",error:null,metadata:d.metadata}}));await r(J({files:l,index_time_sec:s?.index_time_sec,log_sid:s?.sid,indexName:t,sessionId:e,config:o}))}),ve=R("chatSession/uploadAndUpsertIntoIndex",async({acceptedFiles:n,indexName:e,sessionId:t,config:o},{dispatch:r})=>{let a=[],s=[],i=`${e}_bucket`;for(let l of n){if(r(O({sessionId:t,fileId:l.id,patch:{status:"uploading",error:null}})),!l.file){s.push({...l,status:"error",error:"File data is no longer available. Please attach it again."});continue}let d=await ue({apikey:o.apikey,resourceURL:o.resourceURL,bucketName:i,fileName:encodeURIComponent(l.name),file:l.file});console.log("upload",d),d?.error?(s.push({...l,status:"error",error:d.error}),r(O({sessionId:t,fileId:l.id,patch:{status:"error",error:d.error}}))):a.push({...l,bucket_name:i})}console.log("filesToEmbed",a),console.log("failedFiles",s),a.length>0&&await r(et({files:a,indexName:e,sessionId:t,config:o})),s.length>0&&await r(J({files:s,indexName:e,sessionId:t,config:o}))}),xe=R("chatSession/streamResponse",async({sessionId:n,query:e,indexName:t,config:{backendURL:o,apikey:r,userid:a,org:s}},{getState:i,dispatch:l})=>{let d=i(),{chatData:c,isLoading:u}=d.chatSessions[n];if(!e?.trim()||u)return;l(ge({sessionId:n,loading:!0}));let g={query:e,a:{choices:[]}};l(Z({sessionId:n,message:g})),l(_({sessionId:n,query:""}));let b=c?.filter(M=>M&&M?.op!=="ADD_FILES"&&!M?.source_file&&!M?.source)?.length,h=Array.isArray(c)?c?.map(M=>{let{messages:j}=new I(M).parse(),E=j?.map(S=>S?.output)?.filter(Boolean)?.join(`
1052
+ `);return!M?.query||!E||E.startsWith("Error: ")?null:{q:M?.query,a:E}})?.filter(M=>M!==null):[],{tools:m}=d.chat,x=m?.[0],w=x?.id==="feeling-lucky"?"GenAI":void 0,p=x?.id==="kpi",y=Date.now(),v=await pe({baseURL:o,apikey:r,payload:{name:t,qnum:b?b+1:1,fall_back:w,type:p?"kpi":void 0,sessionid:n,userid:a,prev_qa:p?void 0:h,query:g?.query,org:s}});v?.session_title&&await B({baseURL:o,apikey:r,payload:{userid:a,org:s,update:"yes",name:t,description:v?.session_title,sessionid:n,sid:s+":"+a+":"+n}});let k=new I(v),{raw:f,messages:T}=k.parse();if(l(ge({sessionId:n,loading:!1})),T?.length>0){for(let M=0;M<T.length;M++){let E=(T[M]?.output||"")?.split(" "),S="";for(let z=0;z<E.length;z++)await new Promise(P=>setTimeout(P,20)),S=S+(S?" ":"")+E[z],l(Z({sessionId:n,message:{...g,a:{choices:[{message:{content:S}}]}}}))}l(W({sessionId:n,chatData:[{...f,query:g?.query,queryTime:Date.now()-y}]})),l(Z({sessionId:n,message:null}))}else l(W({sessionId:n,chatData:[{query:g?.query,queryTime:Date.now()-y,a:{choices:[{message:{content:f?.a?.choices?.[0]?.message?.content||f?.error||"There is no context in the vector index and fall back option is null"}}]}}]}))});var we=me.reducer;var Me=tt({reducer:{chat:le,chatSessions:we},middleware:n=>n({serializableCheck:{ignoredActionPaths:["meta.arg.acceptedFiles"]}})});import je from"highlight.js";import it from"markdown-it";import st from"@vscode/markdown-it-katex";var ot=function(n,e,t){let o=t,r=0,a=n.length;for(;o<e.length;){let s=e[o];if(r<=0&&e.slice(o,o+a)===n)return o;s==="\\"?o++:s==="{"?r++:s==="}"&&r--,o++}return-1},rt=function(n){return n.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")},nt=/^\\begin{/,at=function(n,e){let t,o=[],r=new RegExp("("+e.map(a=>rt(a.left)).join("|")+")");for(;t=n.search(r),t!==-1;){t>0&&(o.push({type:"text",data:n.slice(0,t)}),n=n.slice(t));let a=e.findIndex(l=>n.startsWith(l.left));if(t=ot(e[a].right,n,e[a].left.length),t===-1)break;let s=n.slice(0,t+e[a].right.length),i=nt.test(s)?s:n.slice(e[a].left.length,t);o.push({type:"math",data:i,rawData:s,display:e[a].display}),n=n.slice(t+e[a].right.length)}return n!==""&&o.push({type:"text",data:n}),o},ke=at;import"katex/dist/contrib/mhchem.min.js";function Te(n){return new Promise(e=>{setTimeout(e,n)})}var Ce=n=>{try{let e=new Map,t=n??[];for(let o=0;o<t.length;o++){let r=t[o];if(r?.query)try{let a=JSON.parse(r?.query);e.set(r.id,a)}catch{}}return Array.from(e.values())}catch(e){return console.error(e),[]}};import{debounce as lt}from"lodash";var Ee=new it({html:!0,breaks:!0,linkify:!0,highlight:function(n,e){let t=e??"auto";if(e&&je.getLanguage(e))try{return`<pre class="language-${e}"><div class="ai-chat-code-title">${e}<a class="ai-chat-code-copy cursor-pointer">Copy</a></div><code class="hljs">`+je.highlight(n,{language:t,ignoreIllegals:!0}).value+"</code></pre>"}catch{}return'<pre><code class="hljs">'+n+"</code></pre>"}}).enable(["table","code","fence","blockquote","heading","lheading","paragraph"]).enable(["autolink","linkify","backticks","image","link","newline"]).enable(["emphasis","html_inline"]).use(st);typeof window<"u"&&window.document.addEventListener("click",n=>{if(n.target?.classList?.contains("ai-chat-code-copy")){let e=n.target.parentNode?.nextSibling?.innerText;navigator.clipboard.writeText(e).then(async()=>{n.target.innerHTML='<span style="margin-right:3px">Copied</span>\u2705',await Te(3e3),n.target.innerText="Copy"}).catch(t=>{alert(`Error copying code: ${t.message}`)})}});var dt={fn:n=>{n()}},So=lt((n=()=>{})=>{dt.fn(n)},10);var ct=n=>n.replace(/(```mermaid)(?![^]*?```)/g,"```"),pt=n=>ke(n,[{left:"\\[",right:"\\]",display:!0},{left:"\\(",right:"\\)",display:!1}]).reduce((t,o)=>{if(o.type==="text")return t+o.data;let r=o.display?`$$${o.data}$$`:`$${o.data}$`;return t+r},""),bt=n=>{let e="",t="",o=!1,r="think-wrapper",a=s=>{let i=s.replace(/<script([^>]*)>/gi,"&lt;script$1&gt;");return i=i.replace(/<\/script>/gi,"&lt;/script&gt;"),i=i.replace(/<script([^>]*)\s*\/>/gi,"&lt;script$1 /&gt;"),i};for(let s=0;s<n.length;s++){let i=n[s],l=n.slice(s,s+7),d=n.slice(s,s+8);if(!o&&l==="<think>"){o=!0,e+=`<div class="${r}">`,s+=6;continue}if(o&&d==="</think>"){o=!1,e+="</div>",s+=7;continue}o?t+=i:e+=i}if(t){let s=a(t),i=Ee.render(s);e=e.replace(`<div class="${r}">`,`<div class="${r}">${i}`)}return e},ht=n=>n.replace(/\[source_id:\s*([^\]|]+)(?:\s*\|\s*category:\s*([^\]]+))?\]\.?/g,(e,t,o)=>o?`<source-tag data-source-id="${t.trim()}" data-category="${o.trim()}"></source-tag>`:`<source-tag data-source-id="${t.trim()}"></source-tag>`),U=n=>{let e=bt(n),t=pt(e),o=ct(t),r=ht(o);return Ee.render(r)};import*as Le from"echarts";import"echarts/theme/dark-bold.js";import{createGrid as mt,ModuleRegistry as ft,AllCommunityModule as yt,themeQuartz as vt,colorSchemeVariable as xt}from"ag-grid-community";function Ie(n,e="",t={}){if(typeof n!="object"||n===null||Array.isArray(n))return t;for(let[o,r]of Object.entries(n)){let a=e?`${e}.${o}`:o;typeof r=="object"&&r!==null&&!Array.isArray(r)?Ie(r,a,t):t[a]=r}return t}var ut=["#5470c6","#c5e542","#9d9ec1","#ee6666","#73c0de","#3ba272","#fc8452","#9a60b4","#ea7ccc"],gt={color:ut,backgroundColor:"transparent",tooltip:{trigger:"axis",axisPointer:{type:"shadow"}},legend:{show:!0,type:"scroll",bottom:0,top:null,left:"center"},toolbox:{show:!0,right:0,top:-20,feature:{saveAsImage:{}}},grid:{top:32,right:16,bottom:48,left:40,containLabel:!0}},A=class{constructor(e){this.data=e}parse(){let e=[];if(!this.data)return{charts:[],errors:["Invalid input: null or undefined"]};if(typeof this.data!="object")return{charts:[],errors:[`Invalid input type: expected object, got ${typeof this.data}`]};let t=this.extractArrays(this.data,[]),o=Object.entries(this.data).filter(([,a])=>typeof a=="number"&&!Number.isNaN(a)).map(([a,s])=>({title:a,type:"card",options:{title:a,value:s}}));if(t.length===0&&o.length===0)return{charts:[],errors:["No valid categorical data found"]};let r=[...o];for(let{title:a,items:s}of t){if(s.length===0){e.push(`"${a}": Array is empty \u2014 skipped`);continue}let i=s.map(d=>Ie(d)).filter(d=>typeof d=="object"&&d!==null&&!Array.isArray(d)),l=this.detectChartStructure(i);if(l){let d=this.convertToChartData(i,l);if(d.length===0){e.push(`"${a}": No valid rows after conversion \u2014 skipped`);continue}let c=this.isSimpleCategoricalPie(d)?"pie":"bar";r.push({title:a,type:c,options:{...gt,...this.toChartSeries(d,c)}})}else r.push({title:a,type:"table",options:{columns:Array.from(new Set(i.flatMap(d=>Object.keys(d)))),rows:i}})}return e.length>0?{charts:r,errors:e}:{charts:r}}extractArrays(e,t){if(Array.isArray(e)){let o=e.flatMap(a=>Array.isArray(a)?[]:[a]),r=e.flatMap((a,s)=>Array.isArray(a)?this.extractArrays(a,[...t,`[${s}]`]):[]);return[...o.length?[{title:t.length?t.join("."):"Root Data",items:o}]:[],...r]}return e&&typeof e=="object"?Object.entries(e).flatMap(([o,r])=>this.extractArrays(r,[...t,o])):[]}detectChartStructure(e){if(e.length===0)return null;let t=new Set;for(let s of e)for(let i of Object.keys(s))t.add(i);let o=Array.from(t),r=o.filter(s=>typeof e[0]?.[s]=="string"),a=o.filter(s=>typeof e[0]?.[s]=="number");return a.length===0||r.length>1?null:{labelKey:r[0]??"__auto__",valueKeys:a}}isSimpleCategoricalPie(e){return e.length?e.every(t=>t.values.length===1):!1}convertToChartData(e,t){return e.map((o,r)=>{let a=t.labelKey==="__auto__"?null:o[t.labelKey];return{labelValue:a!=null?String(a):`Item ${r+1}`,labelKey:t.labelKey,values:t.valueKeys.map(i=>({[i]:Number(o[i])||0}))}})}toChartSeries(e,t){if(t==="bar"){let r={};return e.forEach((a,s)=>{a.values.forEach(i=>{let[l,d]=Object.entries(i)[0];r[l]||(r[l]=new Array(e.length).fill(0)),r[l][s]=d})}),{grid:{containLabel:!0,left:"3%",right:"3%",bottom:"15%",top:40},xAxis:{type:"category",data:e.map(a=>a.labelValue).filter(Boolean)},yAxis:{type:"value",splitLine:{lineStyle:{type:"solid"}}},series:Object.entries(r).map(([a,s])=>({name:a,type:"bar",stack:"total",data:s}))}}let o=Object.keys(e[0]?.values?.[0]??{})[0]??"value";return{tooltip:{trigger:"item"},series:[{name:"Data",type:"pie",radius:["40%","70%"],label:{show:!1},labelLine:{show:!1},avoidLabelOverlap:!1,data:e.map(r=>({name:r.labelValue,value:r.values[0]?.[o]??0}))}]}}};var Se=!1;function wt(){Se||(ft.registerModules([yt]),Se=!0)}var Mt=vt.withPart(xt).withParams({fontFamily:"var(--font-body)",headerFontFamily:"var(--font-body)",borderColor:"var(--border)",backgroundColor:"var(--background)",foregroundColor:"var(--foreground)",headerTextColor:"var(--foreground)",headerBackgroundColor:"var(--card)",rowVerticalPaddingScale:1.4,headerColumnResizeHandleColor:"var(--secondary)",wrapperBorderRadius:2});function kt(n){if(typeof n!="string")return!1;try{return JSON.parse(n),!0}catch{return!1}}function Tt(n,e){return n<=1||e==="table"?1:e==="card"?Math.min(n,4):2}function Ct(n,e){return e===1||n==="table"?"1 / -1":"span 1"}function jt(n){let e=document.createElement("div");e.style.cssText=`
1053
1053
  background: var(--card);
1054
1054
  border-radius: var(--radius-md);
1055
1055
  padding: 1rem 1.25rem;
@@ -1058,39 +1058,42 @@ code.hljs {
1058
1058
  gap: 0.5rem;
1059
1059
  height: 6rem;
1060
1060
  justify-content: center;
1061
- `;let t=document.createElement("span");t.style.cssText="font-size: 0.875rem; font-weight: 500; color: var(--foreground); text-transform: capitalize;",t.textContent=String(n.title??"").replace(/_/g," ").replace(/\./g," ");let o=document.createElement("span");o.style.cssText="font-size: 1.25rem; font-weight: 700; color: var(--foreground); line-height: 1.2;";let r=n.value;return typeof r=="number"&&Number.isFinite(r)&&!Number.isInteger(r)?o.textContent=String(Number.parseFloat(r.toFixed(4))):o.textContent=String(r??"\u2014"),e.appendChild(t),e.appendChild(o),e}function nt(n){Qe();let e=document.createElement("div");e.style.cssText="width: 100%; height: 400px;";let t={theme:Ze,rowData:n.rows,columnDefs:(n.columns??[]).map(r=>({headerName:r,field:r})),pagination:!0,paginationPageSize:50,animateRows:!0},o=()=>{e.__bdbGridInitialized||(e.__bdbGridInitialized=!0,Ye(e,t))};return requestAnimationFrame(()=>{if(e.isConnected)o();else{let r=new MutationObserver(()=>{e.isConnected&&(r.disconnect(),o())});r.observe(document.body,{childList:!0,subtree:!0})}}),e}function at(n,e){let t=document.createElement("div");t.style.cssText=`
1061
+ `;let t=document.createElement("span");t.style.cssText="font-size: 0.875rem; font-weight: 500; color: var(--foreground); text-transform: capitalize;",t.textContent=String(n.title??"").replace(/_/g," ").replace(/\./g," ");let o=document.createElement("span");o.style.cssText="font-size: 1.25rem; font-weight: 700; color: var(--foreground); line-height: 1.2;";let r=n.value;return typeof r=="number"&&Number.isFinite(r)&&!Number.isInteger(r)?o.textContent=String(Number.parseFloat(r.toFixed(4))):o.textContent=String(r??"\u2014"),e.appendChild(t),e.appendChild(o),e}function Et(n){wt();let e=document.createElement("div");e.style.cssText="width: 100%; height: 400px;";let t={theme:Mt,rowData:n.rows,columnDefs:(n.columns??[]).map(r=>({headerName:r,field:r})),pagination:!0,paginationPageSize:50,animateRows:!0},o=()=>{e.__bdbGridInitialized||(e.__bdbGridInitialized=!0,mt(e,t))};return requestAnimationFrame(()=>{if(e.isConnected)o();else{let r=new MutationObserver(()=>{e.isConnected&&(r.disconnect(),o())});r.observe(document.body,{childList:!0,subtree:!0})}}),e}function It(n,e){let t=document.createElement("div");t.style.cssText=`
1062
1062
  width: 100%;
1063
- height: 360px;
1064
- `;let o=null,r=()=>{if(o)return;o=me.init(t,"dark-bold",{renderer:"canvas"}),o.setOption(n,!0),new ResizeObserver(()=>o?.resize()).observe(t)};return requestAnimationFrame(()=>{if(document.contains(t)||t.isConnected)r();else{let a=new MutationObserver(()=>{t.isConnected&&(a.disconnect(),r())});a.observe(document.body,{childList:!0,subtree:!0})}}),t}function ue(n){let e=document.createElement("div");e.style.cssText="margin-top: 1rem; display: flex; flex-direction: column; gap: 1.25rem;";let t=n;if(et(n))try{t=JSON.parse(n)}catch{return e}let o=t?.tool_results??[];if(!o.length)return e;let r=o.length;for(let a=0;a<o.length;a++){let s=o[a],i=s?.data;if(!i)continue;let{charts:c}=new A(i).parse();if(!c.length)continue;let p=document.createElement("div");if(p.style.cssText="width: 100%;",s?.tool){let h=document.createElement("h4");h.style.cssText=`
1063
+ max-width: 520px;
1064
+ height: 240px;
1065
+ margin: 0 auto;
1066
+ display: block;
1067
+ `;let o=null,r=()=>{if(o)return;o=Le.init(t,"dark-bold",{renderer:"canvas"}),o.setOption(n,!0),o.resize(),new ResizeObserver(()=>o?.resize()).observe(t)};return requestAnimationFrame(()=>{if(document.contains(t)||t.isConnected)r();else{let a=new MutationObserver(()=>{t.isConnected&&(a.disconnect(),r())});a.observe(document.body,{childList:!0,subtree:!0})}}),t}function De(n){let e=document.createElement("div");e.style.cssText="margin-top: 1rem; display: flex; flex-direction: column; gap: 1.25rem; width: 100%;";let t=n;if(kt(n))try{t=JSON.parse(n)}catch{return e}let o=t?.tool_results??[];if(!o.length)return e;for(let r=0;r<o.length;r++){let a=o[r],s=a?.data;if(!s)continue;let{charts:i}=new A(s).parse();if(!i.length)continue;let l=i.length,d=document.createElement("div");if(d.style.cssText="width: 100%;",a?.tool){let b=document.createElement("h4");b.style.cssText=`
1065
1068
  font-size: 13px;
1066
1069
  font-weight: 600;
1067
1070
  color: var(--foreground);
1068
1071
  margin: 0 0 0.25rem 0;
1069
1072
  font-family: var(--font-body);
1070
1073
  text-transform: capitalize;
1071
- `,h.textContent=String(s.tool).replace(/_/g," "),p.appendChild(h)}if(s?.description){let h=document.createElement("p");h.style.cssText=`
1074
+ `,b.textContent=String(a.tool).replace(/_/g," "),d.appendChild(b)}if(a?.description){let b=document.createElement("p");b.style.cssText=`
1072
1075
  font-size: 12px;
1073
1076
  color: var(--muted-foreground);
1074
1077
  margin: 0 0 0.75rem 0;
1075
1078
  font-family: var(--font-body);
1076
1079
  line-height: 1.5;
1077
- `,h.textContent=s.description,p.appendChild(h)}let d=document.createElement("hr");d.style.cssText="border: none; border-top: 1px solid var(--border); margin-bottom: 0.75rem;",p.appendChild(d);let l=tt(r,c[0]?.type),g=document.createElement("div");g.style.cssText=`
1080
+ `,b.textContent=a.description,d.appendChild(b)}let c=document.createElement("hr");c.style.cssText="border: none; border-top: 1px solid var(--border); margin-bottom: 0.75rem;",d.appendChild(c);let u=Tt(l,i[0]?.type),g=document.createElement("div");g.style.cssText=`
1078
1081
  display: grid;
1079
- grid-template-columns: repeat(${l}, minmax(0, 1fr));
1082
+ grid-template-columns: repeat(${u}, minmax(0, 1fr));
1080
1083
  gap: 0.5rem;
1081
1084
  width: 100%;
1082
1085
  padding: 1rem 0;
1083
- `;for(let h=0;h<c.length;h++){let b=c[h],m=document.createElement("div");m.style.gridColumn=ot(b.type,r);let u;switch(b.type){case"card":u=rt(b.options);break;case"table":u=nt(b.options);break;case"bar":case"pie":u=at(b.options,b.type);break;default:u=document.createElement("div")}m.appendChild(u),g.appendChild(m)}p.appendChild(g),e.appendChild(p)}return e}function fe(n,e="",t={}){for(let o in n){let r=n[o],a=e?`${e}.${o}`:o;typeof r=="object"&&r!==null&&!Array.isArray(r)?fe(r,a,t):(typeof r=="number"||typeof r=="string")&&(t[a]=r)}return t}var D=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
1086
+ `;for(let b=0;b<i.length;b++){let h=i[b],m=document.createElement("div");m.style.gridColumn=Ct(h.type,l),h.type==="card"&&(m.style.justifySelf="start");let x;switch(h.type){case"card":x=jt(h.options);break;case"table":x=Et(h.options);break;case"bar":case"pie":x=It(h.options,h.type);break;default:x=document.createElement("div")}m.appendChild(x),g.appendChild(m)}d.appendChild(g),e.appendChild(d)}return e}function Ne(n,e="",t={}){for(let o in n){let r=n[o],a=e?`${e}.${o}`:o;typeof r=="object"&&r!==null&&!Array.isArray(r)?Ne(r,a,t):(typeof r=="number"||typeof r=="string")&&(t[a]=r)}return t}var H=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
1084
1087
  <rect width="14" height="14" x="8" y="8" rx="2" ry="2"/>
1085
1088
  <path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>
1086
- </svg>`,it=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
1089
+ </svg>`,St=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
1087
1090
  <circle cx="12" cy="12" r="10"/>
1088
1091
  <path d="M12 16v-4M12 8h.01"/>
1089
- </svg>`,st=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
1092
+ </svg>`,Lt=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
1090
1093
  <circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/>
1091
- </svg>`,lt=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
1094
+ </svg>`,Dt=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
1092
1095
  <path d="M20 6 9 17l-5-5"/>
1093
- </svg>`,dt=`
1096
+ </svg>`,Nt=`
1094
1097
  display: inline-flex;
1095
1098
  align-items: center;
1096
1099
  justify-content: center;
@@ -1103,7 +1106,7 @@ code.hljs {
1103
1106
  cursor: pointer;
1104
1107
  transition: background 0.15s, color 0.15s, border-color 0.15s;
1105
1108
  flex-shrink: 0;
1106
- `;function O(n,e){let t=document.createElement("button");return t.setAttribute("aria-label",e),t.style.cssText=dt,t.innerHTML=n,t.addEventListener("mouseenter",()=>{t.style.background="color-mix(in oklab, var(--foreground) 7%, transparent)",t.style.color="var(--foreground)",t.style.borderColor="var(--ring)"}),t.addEventListener("mouseleave",()=>{t.style.background="var(--card)",t.style.color="var(--muted-foreground)",t.style.borderColor="var(--border)"}),t}function ct(n,e){let t=document.querySelector(".bdb-usage-dropdown");if(t){t.remove();return}let o=document.createElement("div");o.className="bdb-usage-dropdown",o.style.cssText=`
1109
+ `;function F(n,e){let t=document.createElement("button");return t.setAttribute("aria-label",e),t.style.cssText=Nt,t.innerHTML=n,t.addEventListener("mouseenter",()=>{t.style.background="color-mix(in oklab, var(--foreground) 7%, transparent)",t.style.color="var(--foreground)",t.style.borderColor="var(--ring)"}),t.addEventListener("mouseleave",()=>{t.style.background="var(--card)",t.style.color="var(--muted-foreground)",t.style.borderColor="var(--border)"}),t}function zt(n,e){let t=document.querySelector(".bdb-usage-dropdown");if(t){t.remove();return}let o=document.createElement("div");o.className="bdb-usage-dropdown",o.style.cssText=`
1107
1110
  position: absolute;
1108
1111
  bottom: calc(100% + 6px);
1109
1112
  right: 0;
@@ -1123,7 +1126,7 @@ code.hljs {
1123
1126
  letter-spacing: 0.05em;
1124
1127
  text-transform: uppercase;
1125
1128
  border-bottom: 1px solid var(--border);
1126
- `,r.textContent="Usage Stats",o.appendChild(r);let a=document.createElement("div");a.style.cssText="padding: 0.25rem 0;";for(let[c,p]of Object.entries(e)){let d=document.createElement("div");d.style.cssText=`
1129
+ `,r.textContent="Usage Stats",o.appendChild(r);let a=document.createElement("div");a.style.cssText="padding: 0.25rem 0;";for(let[l,d]of Object.entries(e)){let c=document.createElement("div");c.style.cssText=`
1127
1130
  display: flex;
1128
1131
  align-items: center;
1129
1132
  justify-content: space-between;
@@ -1131,17 +1134,17 @@ code.hljs {
1131
1134
  padding: 0.3rem 0.75rem;
1132
1135
  font-size: 12px;
1133
1136
  color: var(--foreground);
1134
- `,d.addEventListener("mouseenter",()=>{d.style.background="color-mix(in oklab, var(--foreground) 5%, transparent)"}),d.addEventListener("mouseleave",()=>{d.style.background="transparent"});let l=document.createElement("span");l.style.cssText="color: var(--muted-foreground); text-transform: capitalize;",l.textContent=c.split(".").pop()?.replace(/_/g," ")??c;let g=document.createElement("span");g.style.cssText="font-weight: 500; font-variant-numeric: tabular-nums;",g.textContent=String(p),d.appendChild(l),d.appendChild(g),a.appendChild(d)}o.appendChild(a);let s=n.parentElement;s.style.position="relative",s.appendChild(o);let i=c=>{!o.contains(c.target)&&c.target!==n&&(o.remove(),document.removeEventListener("click",i,!0))};setTimeout(()=>document.addEventListener("click",i,!0),0)}function pt(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}var ht=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
1137
+ `,c.addEventListener("mouseenter",()=>{c.style.background="color-mix(in oklab, var(--foreground) 5%, transparent)"}),c.addEventListener("mouseleave",()=>{c.style.background="transparent"});let u=document.createElement("span");u.style.cssText="color: var(--muted-foreground); text-transform: capitalize;",u.textContent=l.split(".").pop()?.replace(/_/g," ")??l;let g=document.createElement("span");g.style.cssText="font-weight: 500; font-variant-numeric: tabular-nums;",g.textContent=String(d),c.appendChild(u),c.appendChild(g),a.appendChild(c)}o.appendChild(a);let s=n.parentElement;s.style.position="relative",s.appendChild(o);let i=l=>{!o.contains(l.target)&&l.target!==n&&(o.remove(),document.removeEventListener("click",i,!0))};setTimeout(()=>document.addEventListener("click",i,!0),0)}function At(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}var Ot=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
1135
1138
  <circle cx="12" cy="12" r="10"/>
1136
1139
  <path d="M12 6v6l4 2"/>
1137
- </svg>`;function ye(n){let{textToCopy:e,queryTimeMs:t,usageData:o,onInfo:r}=n,a=document.createElement("div");a.style.cssText=`
1140
+ </svg>`;function ze(n){let{textToCopy:e,queryTimeMs:t,usageData:o,onInfo:r}=n,a=document.createElement("div");a.style.cssText=`
1138
1141
  display: flex;
1139
1142
  align-items: center;
1140
1143
  justify-content: space-between;
1141
1144
  gap: 0.5rem;
1142
1145
  padding: 0.375rem 0;
1143
1146
  min-height: 38px;
1144
- `;let s=document.createElement("div");s.style.cssText="display: flex; align-items: center; gap: 6px;";let i=O(D,"Copy to clipboard");if(i.addEventListener("click",async()=>{try{await navigator.clipboard.writeText(e),i.innerHTML=lt,i.style.color="var(--primary)",i.style.borderColor="var(--primary)",setTimeout(()=>{i.innerHTML=D,i.style.color="",i.style.borderColor=""},2e3)}catch{}}),s.appendChild(i),r){let c=O(it,"View response context");c.addEventListener("click",()=>r()),s.appendChild(c)}if(typeof t=="number"&&Number.isFinite(t)){let c=document.createElement("span");c.style.cssText="display: inline-flex; align-items: center; gap: 4px; padding-inline: 4px; font-size: 11px; color: var(--muted-foreground); user-select: none;";let p=document.createElement("span");p.innerHTML=ht,p.style.display="inline-flex";let d=document.createElement("span");d.textContent=`Thought for ${pt(t)}`,c.appendChild(p),c.appendChild(d),s.appendChild(c)}if(a.appendChild(s),o&&typeof o=="object"){let c=fe(o);if(Object.keys(c).length>0){let p=document.createElement("div");p.style.cssText="display: flex; align-items: center; position: relative;";let d=O(st,"Show usage stats");d.addEventListener("click",l=>{l.stopPropagation(),ct(d,c)}),p.appendChild(d),a.appendChild(p)}}return a}var ve=!1;function bt(n){if(ve)return;ve=!0;let e=document.createElement("style");e.textContent=`
1147
+ `;let s=document.createElement("div");s.style.cssText="display: flex; align-items: center; gap: 6px;";let i=F(H,"Copy to clipboard");if(i.addEventListener("click",async()=>{try{await navigator.clipboard.writeText(e),i.innerHTML=Dt,i.style.color="var(--primary)",i.style.borderColor="var(--primary)",setTimeout(()=>{i.innerHTML=H,i.style.color="",i.style.borderColor=""},2e3)}catch{}}),s.appendChild(i),r){let l=F(St,"View response context");l.addEventListener("click",()=>r()),s.appendChild(l)}if(typeof t=="number"&&Number.isFinite(t)){let l=document.createElement("span");l.style.cssText="display: inline-flex; align-items: center; gap: 4px; padding-inline: 4px; font-size: 11px; color: var(--muted-foreground); user-select: none;";let d=document.createElement("span");d.innerHTML=Ot,d.style.display="inline-flex";let c=document.createElement("span");c.textContent=`Thought for ${At(t)}`,l.appendChild(d),l.appendChild(c),s.appendChild(l)}if(a.appendChild(s),o&&typeof o=="object"){let l=Ne(o);if(Object.keys(l).length>0){let d=document.createElement("div");d.style.cssText="display: flex; align-items: center; position: relative;";let c=F(Lt,"Show usage stats");c.addEventListener("click",u=>{u.stopPropagation(),zt(c,l)}),d.appendChild(c),a.appendChild(d)}}return a}var Ae=!1;function Ut(n){if(Ae)return;Ae=!0;let e=document.createElement("style");e.textContent=`
1145
1148
  @keyframes bdb-drawer-in {
1146
1149
  from { transform: translateX(100%); opacity: 0; }
1147
1150
  to { transform: translateX(0); opacity: 1; }
@@ -1287,13 +1290,13 @@ code.hljs {
1287
1290
  .bdb-json-pre .json-num { color: #f08d49; }
1288
1291
  .bdb-json-pre .json-bool { color: #c59bc1; }
1289
1292
  .bdb-json-pre .json-null { color: #de7176; }
1290
- `,n.appendChild?n.appendChild(e):document.head.appendChild(e)}function gt(n){return JSON.stringify(n,null,2).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)/g,t=>{let o="json-num";return/^"/.test(t)?o=/:$/.test(t)?"json-key":"json-str":/true|false/.test(t)?o="json-bool":/null/.test(t)&&(o="json-null"),`<span class="${o}">${t}</span>`})}function mt(n,e,t){n.forEach(o=>o.classList.toggle("active",o.dataset.tab===t)),e.forEach(o=>o.classList.toggle("active",o.dataset.content===t))}function xe(n){let{item:e,indexName:t,shadowRoot:o,onClose:r}=n;bt(o);let a=document.createElement("div");a.style.cssText="position: fixed; inset: 0; z-index: 1000000;";let s=document.createElement("div");s.className="bdb-drawer-overlay",s.addEventListener("click",v),a.appendChild(s);let i=document.createElement("div");i.className="bdb-drawer-panel",a.appendChild(i);let c=document.createElement("div");c.className="bdb-drawer-header";let p=document.createElement("h3");p.className="bdb-drawer-title",p.textContent="Response Details";let d=document.createElement("button");d.className="bdb-drawer-close",d.setAttribute("aria-label","Close drawer"),d.innerHTML=`<svg width="14" height="14" viewBox="0 0 14 14" fill="none">
1293
+ `,n.appendChild?n.appendChild(e):document.head.appendChild(e)}function Ft(n){return JSON.stringify(n,null,2).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)/g,t=>{let o="json-num";return/^"/.test(t)?o=/:$/.test(t)?"json-key":"json-str":/true|false/.test(t)?o="json-bool":/null/.test(t)&&(o="json-null"),`<span class="${o}">${t}</span>`})}function Ht(n,e,t){n.forEach(o=>o.classList.toggle("active",o.dataset.tab===t)),e.forEach(o=>o.classList.toggle("active",o.dataset.content===t))}function Oe(n){let{item:e,indexName:t,shadowRoot:o,onClose:r}=n;Ut(o);let a=document.createElement("div");a.style.cssText="position: fixed; inset: 0; z-index: 1000000;";let s=document.createElement("div");s.className="bdb-drawer-overlay",s.addEventListener("click",v),a.appendChild(s);let i=document.createElement("div");i.className="bdb-drawer-panel",a.appendChild(i);let l=document.createElement("div");l.className="bdb-drawer-header";let d=document.createElement("h3");d.className="bdb-drawer-title",d.textContent="Response Details";let c=document.createElement("button");c.className="bdb-drawer-close",c.setAttribute("aria-label","Close drawer"),c.innerHTML=`<svg width="14" height="14" viewBox="0 0 14 14" fill="none">
1291
1294
  <path d="M1 1l12 12M13 1L1 13" stroke="currentColor" stroke-width="1.75" stroke-linecap="round"/>
1292
- </svg>`,d.addEventListener("click",v),c.appendChild(p),c.appendChild(d),i.appendChild(c);let l=document.createElement("div");l.className="bdb-drawer-tabs",[{id:"response",label:"Response"},{id:"json",label:"Response JSON"}].forEach(({id:f,label:x})=>{let E=document.createElement("button");E.className="bdb-drawer-tab"+(f==="response"?" active":""),E.dataset.tab=f,E.textContent=x,E.addEventListener("click",()=>{let L=i.querySelectorAll(".bdb-drawer-tab"),j=i.querySelectorAll(".bdb-drawer-tab-content");mt(L,j,f)}),l.appendChild(E)}),i.appendChild(l);let h=document.createElement("div");h.className="bdb-drawer-body",i.appendChild(h);let b=document.createElement("div");if(b.className="bdb-drawer-tab-content active",b.dataset.content="response",e?.query){let f=document.createElement("div");f.style.cssText=`
1295
+ </svg>`,c.addEventListener("click",v),l.appendChild(d),l.appendChild(c),i.appendChild(l);let u=document.createElement("div");u.className="bdb-drawer-tabs",[{id:"response",label:"Response"},{id:"json",label:"Response JSON"}].forEach(({id:f,label:T})=>{let M=document.createElement("button");M.className="bdb-drawer-tab"+(f==="response"?" active":""),M.dataset.tab=f,M.textContent=T,M.addEventListener("click",()=>{let j=i.querySelectorAll(".bdb-drawer-tab"),E=i.querySelectorAll(".bdb-drawer-tab-content");Ht(j,E,f)}),u.appendChild(M)}),i.appendChild(u);let b=document.createElement("div");b.className="bdb-drawer-body",i.appendChild(b);let h=document.createElement("div");if(h.className="bdb-drawer-tab-content active",h.dataset.content="response",e?.query){let f=document.createElement("div");f.style.cssText=`
1293
1296
  display: flex;
1294
1297
  justify-content: flex-end;
1295
1298
  margin-bottom: 1rem;
1296
- `;let x=document.createElement("div");x.style.cssText=`
1299
+ `;let T=document.createElement("div");T.style.cssText=`
1297
1300
  max-width: 80%;
1298
1301
  background: var(--secondary);
1299
1302
  color: var(--secondary-foreground);
@@ -1302,11 +1305,11 @@ code.hljs {
1302
1305
  font-size: 13px;
1303
1306
  line-height: 1.55;
1304
1307
  word-break: break-word;
1305
- `,x.textContent=e.query,f.appendChild(x),b.appendChild(f)}let m=new S(e),{messages:u}=m.parse(),y=u.map(f=>f.output??"").join(`
1308
+ `,T.textContent=e.query,f.appendChild(T),h.appendChild(f)}let m=new I(e),{messages:x}=m.parse(),w=x.map(f=>f.output??"").join(`
1306
1309
 
1307
- `);if(y){let f=document.createElement("div");f.className="bdb-ai-bubble ai-md prose",f.style.cssText="font-size: 13px; line-height: 1.65; color: var(--foreground);",f.innerHTML=H(y),b.appendChild(f)}h.appendChild(b);let w=document.createElement("div");w.className="bdb-drawer-tab-content",w.dataset.content="json";let k=document.createElement("pre");k.className="bdb-json-pre",k.innerHTML=gt(e),w.appendChild(k),h.appendChild(w);function v(){i.style.animation="bdb-drawer-out 0.18s ease-in both",s.style.opacity="0",s.style.transition="opacity 0.18s",setTimeout(()=>{a.remove(),r()},180)}let C=f=>{f.key==="Escape"&&(v(),document.removeEventListener("keydown",C))};return document.addEventListener("keydown",C),a}import{jsPDF as ut}from"jspdf";import ft from"jspdf-autotable";import*as we from"echarts";function U(n,e){let t=URL.createObjectURL(n),o=document.createElement("a");o.href=t,o.download=e,document.body.appendChild(o),o.click(),setTimeout(()=>{document.body.removeChild(o),URL.revokeObjectURL(t)},100)}function ke(n){let{messages:e}=new S(n).parse();return e.map(t=>t.output).filter(Boolean).join(`
1310
+ `);if(w){let f=document.createElement("div");f.className="bdb-ai-bubble ai-md prose",f.style.cssText="font-size: 13px; line-height: 1.65; color: var(--foreground);",f.innerHTML=U(w),h.appendChild(f)}b.appendChild(h);let p=document.createElement("div");p.className="bdb-drawer-tab-content",p.dataset.content="json";let y=document.createElement("pre");y.className="bdb-json-pre",y.innerHTML=Ft(e),p.appendChild(y),b.appendChild(p);function v(){i.style.animation="bdb-drawer-out 0.18s ease-in both",s.style.opacity="0",s.style.transition="opacity 0.18s",setTimeout(()=>{a.remove(),r()},180)}let k=f=>{f.key==="Escape"&&(v(),document.removeEventListener("keydown",k))};return document.addEventListener("keydown",k),a}import{jsPDF as qt}from"jspdf";import Pt from"jspdf-autotable";import*as Ue from"echarts";function K(n,e){let t=URL.createObjectURL(n),o=document.createElement("a");o.href=t,o.download=e,document.body.appendChild(o),o.click(),setTimeout(()=>{document.body.removeChild(o),URL.revokeObjectURL(t)},100)}function Fe(n){let{messages:e}=new I(n).parse();return e.map(t=>t.output).filter(Boolean).join(`
1308
1311
 
1309
- `)}function Ce(n,e){let t=`# ${e}
1312
+ `)}function He(n,e){let t=`# ${e}
1310
1313
 
1311
1314
  `;t+=`*Exported on ${new Date().toLocaleString()}*
1312
1315
 
@@ -1315,12 +1318,12 @@ code.hljs {
1315
1318
  `;for(let r of n){r.query&&(t+=`**User:**
1316
1319
  ${r.query}
1317
1320
 
1318
- `);let a=ke(r);a&&(t+=`**AI:**
1321
+ `);let a=Fe(r);a&&(t+=`**AI:**
1319
1322
  ${a}
1320
1323
 
1321
- `)}let o=new Blob([t],{type:"text/markdown"});U(o,`chat-${new Date().toISOString().split("T")[0]}.md`)}function Te(n){let e=new Blob([JSON.stringify(n,null,2)],{type:"application/json"});U(e,`chat-${new Date().toISOString().split("T")[0]}.json`)}function yt(n){let e=n?._data??n?.a?._data;if(!e)return[];let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return[]}let o=t?.tool_results??[];if(!o.length)return[];let r=[];for(let a of o){if(!a?.data)continue;let{charts:s}=new A(a.data).parse();for(let i of s)r.push({...i,title:a.tool?String(a.tool).replace(/_/g," "):i.title})}return r}function vt(n,e=800,t=480){let o=document.createElement("div");o.style.cssText=`position: fixed; left: -10000px; top: 0; width: ${e}px; height: ${t}px;`,document.body.appendChild(o);try{let r=we.init(o,null,{renderer:"canvas",width:e,height:t}),a={...n,backgroundColor:"#ffffff",animation:!1,toolbox:{show:!1}};r.setOption(a,!0);let s=r.getDataURL({type:"png",pixelRatio:2,backgroundColor:"#ffffff"});return r.dispose(),s}catch(r){return console.error("[BangDB] chart render failed:",r),null}finally{document.body.removeChild(o)}}function Ee(n,e){try{let t=new ut,o=t.internal.pageSize.height,r=t.internal.pageSize.width,a=14,s=r-a*2,i=20,c=(d=10)=>{i>o-a-d&&(t.addPage(),i=a+10)};t.setFontSize(18),t.setFont("helvetica","bold"),t.setTextColor(0,0,0),t.text(e,a,i),i+=8,t.setFontSize(10),t.setFont("helvetica","normal"),t.setTextColor(100,100,100),t.text(`Exported on ${new Date().toLocaleString()}`,a,i),i+=8,t.setDrawColor(180,180,180),t.setLineWidth(.4),t.line(a,i,a+s,i),i+=8;for(let d of n){if(d.query){c(20),t.setFontSize(11),t.setFont("helvetica","bold"),t.setTextColor(60,130,100),t.text("You:",a,i),i+=6,t.setFont("helvetica","normal"),t.setTextColor(30,30,30);let h=t.splitTextToSize(d.query,s-4);for(let b of h)c(),t.text(b,a+4,i),i+=5.5;i+=4}let l=ke(d);if(l){c(20),t.setFontSize(11),t.setFont("helvetica","bold"),t.setTextColor(80,80,200),t.text("AI:",a,i),i+=6,t.setFont("helvetica","normal"),t.setTextColor(30,30,30);let h=l.replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/#{1,6}\s/g,"").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/\n{3,}/g,`
1324
+ `)}let o=new Blob([t],{type:"text/markdown"});K(o,`chat-${new Date().toISOString().split("T")[0]}.md`)}function qe(n){let e=new Blob([JSON.stringify(n,null,2)],{type:"application/json"});K(e,`chat-${new Date().toISOString().split("T")[0]}.json`)}function Bt(n){let e=n?._data??n?.a?._data;if(!e)return[];let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return[]}let o=t?.tool_results??[];if(!o.length)return[];let r=[];for(let a of o){if(!a?.data)continue;let{charts:s}=new A(a.data).parse();for(let i of s)r.push({...i,title:a.tool?String(a.tool).replace(/_/g," "):i.title})}return r}function Rt(n,e=800,t=480){let o=document.createElement("div");o.style.cssText=`position: fixed; left: -10000px; top: 0; width: ${e}px; height: ${t}px;`,document.body.appendChild(o);try{let r=Ue.init(o,null,{renderer:"canvas",width:e,height:t}),a={...n,backgroundColor:"#ffffff",animation:!1,toolbox:{show:!1}};r.setOption(a,!0);let s=r.getDataURL({type:"png",pixelRatio:2,backgroundColor:"#ffffff"});return r.dispose(),s}catch(r){return console.error("[BangDB] chart render failed:",r),null}finally{document.body.removeChild(o)}}function Pe(n,e){try{let t=new qt,o=t.internal.pageSize.height,r=t.internal.pageSize.width,a=14,s=r-a*2,i=20,l=(c=10)=>{i>o-a-c&&(t.addPage(),i=a+10)};t.setFontSize(18),t.setFont("helvetica","bold"),t.setTextColor(0,0,0),t.text(e,a,i),i+=8,t.setFontSize(10),t.setFont("helvetica","normal"),t.setTextColor(100,100,100),t.text(`Exported on ${new Date().toLocaleString()}`,a,i),i+=8,t.setDrawColor(180,180,180),t.setLineWidth(.4),t.line(a,i,a+s,i),i+=8;for(let c of n){if(c.query){l(20),t.setFontSize(11),t.setFont("helvetica","bold"),t.setTextColor(60,130,100),t.text("You:",a,i),i+=6,t.setFont("helvetica","normal"),t.setTextColor(30,30,30);let b=t.splitTextToSize(c.query,s-4);for(let h of b)l(),t.text(h,a+4,i),i+=5.5;i+=4}let u=Fe(c);if(u){l(20),t.setFontSize(11),t.setFont("helvetica","bold"),t.setTextColor(80,80,200),t.text("AI:",a,i),i+=6,t.setFont("helvetica","normal"),t.setTextColor(30,30,30);let b=u.replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/#{1,6}\s/g,"").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/\n{3,}/g,`
1322
1325
 
1323
- `),b=t.splitTextToSize(h,s-4);for(let m of b)c(),t.text(m,a+4,i),i+=5.5;i+=4}let g=yt(d);if(g.length>0){i+=2;for(let h of g)if(c(30),h.title&&(t.setFontSize(10),t.setFont("helvetica","bold"),t.setTextColor(60,60,60),t.text(String(h.title).replace(/_/g," ").replace(/\./g," "),a+4,i),i+=5),h.type==="card"){let b=h.options;t.setFontSize(10),t.setFont("helvetica","normal"),t.setTextColor(80,80,80);let m=String(b.title??"").replace(/_/g," "),u,y=b.value;typeof y=="number"&&Number.isFinite(y)&&!Number.isInteger(y)?u=String(Number.parseFloat(y.toFixed(4))):u=String(y??"\u2014"),t.text(`${m}: `,a+4,i),t.setFont("helvetica","bold"),t.setTextColor(30,30,30);let w=t.getTextWidth(`${m}: `);t.text(u,a+4+w,i),i+=7}else if(h.type==="table"){let b=h.options,m=b.columns??[],u=(b.rows??[]).map(w=>m.map(k=>{let v=w[k];return v==null?"":typeof v=="object"?JSON.stringify(v):String(v)}));ft(t,{startY:i,head:[m],body:u,margin:{left:a+4,right:a},styles:{fontSize:8,cellPadding:2},headStyles:{fillColor:[240,240,240],textColor:[40,40,40],fontStyle:"bold"},theme:"grid"}),i=(t.lastAutoTable?.finalY??i)+6}else if(h.type==="bar"||h.type==="pie"){let b=s-4,m=b*.6;c(m+10);let u=vt(h.options,800,480);if(u)try{t.addImage(u,"PNG",a+4,i,b,m),i+=m+6}catch(y){console.error("[BangDB] addImage failed:",y)}}}c(5),t.setDrawColor(220,220,220),t.setLineWidth(.2),t.line(a,i,a+s,i),i+=6}let p=t.output("blob");U(p,`chat-${new Date().toISOString().split("T")[0]}.pdf`)}catch(t){console.error("[BangDB] PDF export failed:",t)}}var $=class ${constructor(e){this.font={body:'"Inter", sans-serif',mono:'"JetBrains Mono", monospace'};this.tools=[];this.TOKENS={background:"oklch(0.2223 0.0060 271.1393)",foreground:"oklch(0.9551 0 0)",card:"oklch(0.2568 0.0076 274.6528)",cardForeground:"oklch(0.9551 0 0)",primary:"oklch(0.611 0.1217 157.75)",primaryForeground:"oklch(0.9491 0 0)",secondary:"oklch(0.2940 0.0130 272.9312)",secondaryForeground:"oklch(0.9551 0 0)",muted:"oklch(0.2940 0.0130 272.9312)",mutedForeground:"oklch(0.7058 0 0)",accent:"oklch(0.2795 0.0368 260.0310)",accentForeground:"oklch(0.7857 0.1153 246.6596)",border:"oklch(0.3289 0.0092 268.3843)",input:"oklch(0.3289 0.0092 268.3843)",ring:"oklch(0.611 0.1217 157.75)",radius:"0.5rem",shadowPanel:"0 32px 80px rgba(0,0,0,0.6), 0 0 0 1px rgba(255,255,255,0.06)",shadowBubble:"0 8px 32px color-mix(in oklab, oklch(0.611 0.1217 157.75) 40%, transparent)",shadowInput:"0 0 0 2px color-mix(in oklab, oklch(0.611 0.1217 157.75) 50%, transparent)"};this.store=le;this.apiConfig=null;this.bubbleEl=null;this.chatUIEl=null;this.chatAreaEl=null;this.renderedMessageIds=new Set;this.chatTitle="Chat with AI";this.logoUrl="";e.colorTokens&&(this.TOKENS={...this.TOKENS,...e.colorTokens}),e.title&&(this.chatTitle=e.title),e.logo&&(this.logoUrl=e.logo);let t=e.tools||$.DEFAULT_TOOLS,o=new Set($.DEFAULT_TOOLS.map(r=>r.id));this.tools=t.filter(r=>o.has(r.id)).map(r=>({id:r.id,name:r.name})),this.apiConfig=e.config,this.container=document.createElement("div"),this.container.id="ai-chat-widget-root",document.body.appendChild(this.container),this.root=this.container.attachShadow({mode:"open"}),this.injectGlobalFonts(),this.injectThemeVars(),this.root,this.init().then(()=>{this.mount(),this.store.subscribe(()=>{let r=this.store.getState(),a=r?.chat?.mode,{chatData:s,streamingMessage:i,isLoading:c}=r?.chatSessions?.[r?.chat?.activeSession]??{};this.handleModeChange(a),this.handleChatDataChange({streamingMessage:i,chatData:s,isLoading:c})})})}injectThemeVars(){let e=this.TOKENS,t=document.createElement("style");t.textContent=`
1326
+ `),h=t.splitTextToSize(b,s-4);for(let m of h)l(),t.text(m,a+4,i),i+=5.5;i+=4}let g=Bt(c);if(g.length>0){i+=2;for(let b of g)if(l(30),b.title&&(t.setFontSize(10),t.setFont("helvetica","bold"),t.setTextColor(60,60,60),t.text(String(b.title).replace(/_/g," ").replace(/\./g," "),a+4,i),i+=5),b.type==="card"){let h=b.options;t.setFontSize(10),t.setFont("helvetica","normal"),t.setTextColor(80,80,80);let m=String(h.title??"").replace(/_/g," "),x,w=h.value;typeof w=="number"&&Number.isFinite(w)&&!Number.isInteger(w)?x=String(Number.parseFloat(w.toFixed(4))):x=String(w??"\u2014"),t.text(`${m}: `,a+4,i),t.setFont("helvetica","bold"),t.setTextColor(30,30,30);let p=t.getTextWidth(`${m}: `);t.text(x,a+4+p,i),i+=7}else if(b.type==="table"){let h=b.options,m=h.columns??[],x=(h.rows??[]).map(p=>m.map(y=>{let v=p[y];return v==null?"":typeof v=="object"?JSON.stringify(v):String(v)}));Pt(t,{startY:i,head:[m],body:x,margin:{left:a+4,right:a},styles:{fontSize:8,cellPadding:2},headStyles:{fillColor:[240,240,240],textColor:[40,40,40],fontStyle:"bold"},theme:"grid"}),i=(t.lastAutoTable?.finalY??i)+6}else if(b.type==="bar"||b.type==="pie"){let h=s-4,m=h*.6;l(m+10);let x=Rt(b.options,800,480);if(x)try{t.addImage(x,"PNG",a+4,i,h,m),i+=m+6}catch(w){console.error("[BangDB] addImage failed:",w)}}}l(5),t.setDrawColor(220,220,220),t.setLineWidth(.2),t.line(a,i,a+s,i),i+=6}let d=t.output("blob");K(d,`chat-${new Date().toISOString().split("T")[0]}.pdf`)}catch(t){console.error("[BangDB] PDF export failed:",t)}}import Yt from"dayjs";var Be="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cGF0aCBkPSJNMy41NTU2NiAyNi44ODg5QzMuNTU1NjYgMjguNjA3MSA0Ljk0ODU2IDMwIDYuNjY2NzggMzBIMjUuMzMzNEMyNy4wNTE3IDMwIDI4LjQ0NDYgMjguNjA3MSAyOC40NDQ2IDI2Ljg4ODlWOS43Nzc3OEwyMC42NjY4IDJINi42NjY3OEM0Ljk0ODU2IDIgMy41NTU2NiAzLjM5Mjg5IDMuNTU1NjYgNS4xMTExMVYyNi44ODg5WiIgZmlsbD0iIzQwOEI1MiI+PC9wYXRoPjxwYXRoIG9wYWNpdHk9IjAuOCIgZD0iTTIwLjY2NyA2LjY2NjQ3QzIwLjY2NyA4LjM4NDY5IDIyLjA1OTkgOS43Nzc1OSAyMy43NzgxIDkuNzc3NTlIMjguNDQ0OEwyMC42NjcgMS45OTk4MVY2LjY2NjQ3WiIgZmlsbD0iIzg0QzI5MyI+PC9wYXRoPjxwYXRoIG9wYWNpdHk9IjAuOSIgZD0iTTExLjU3NzggMTMuNjY2N0gxMy43MDc1TDE2LjAwMDIgMTYuOTYxNEwxOC40MjUyIDEzLjY2NjdIMjAuNDYzMUwxNy4wMTkxIDE4LjE2NTRMMjAuNjY2OCAyMy4wMDAxSDE4LjQ5NjZMMTYuMDAwMiAxOS40MzQ3TDEzLjM3MTUgMjMuMDAwMUgxMS4zMzM1TDE0Ljk4MTIgMTguMTY1NEwxMS41Nzc4IDEzLjY2NjdaIiBmaWxsPSJ3aGl0ZSIgc3Ryb2tlPSJ3aGl0ZSIgc3Ryb2tlLXdpZHRoPSIwLjM1Ij48L3BhdGg+PC9zdmc+";var Re="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cGF0aCBkPSJNMy41NTU2NiAyNi44ODg5QzMuNTU1NjYgMjguNjA3MSA0Ljk0ODU2IDMwIDYuNjY2NzggMzBIMjUuMzMzNEMyNy4wNTE3IDMwIDI4LjQ0NDYgMjguNjA3MSAyOC40NDQ2IDI2Ljg4ODlWOS43Nzc3OEwyMC42NjY4IDJINi42NjY3OEM0Ljk0ODU2IDIgMy41NTU2NiAzLjM5Mjg5IDMuNTU1NjYgNS4xMTExMVYyNi44ODg5WiIgZmlsbD0iIzNFNzREQyI+PC9wYXRoPjxwYXRoIG9wYWNpdHk9IjAuOCIgZD0iTTIwLjY2NjUgNi42NjY3MkMyMC42NjY1IDguMzg0OTQgMjIuMDU5NCA5Ljc3NzgzIDIzLjc3NzYgOS43Nzc4M0gyOC40NDQzTDIwLjY2NjUgMi4wMDAwNVY2LjY2NjcyWiIgZmlsbD0iIzZFOUNGNCI+PC9wYXRoPjxwYXRoIG9wYWNpdHk9IjAuOSIgZD0iTTkuODYzNzcgMTMuNDZIMTIuMDA0NEwxMy4zNDU5IDIwLjM2NzJIMTMuNDMxNkwxNC44NTg3IDE0LjM1OUgxNy4yMjc3TDE4LjU2OTIgMjAuMzY3MkgxOC42NTQ4TDIwLjAyNDggMTMuNDZIMjIuMTM3TDE5Ljk5NjMgMjIuNzkzM0gxNy40NDE4TDE2LjAwMDQgMTYuODcwOEgxNS45MTQ3TDE0LjQ0NDggMjIuNzkzM0gxMS44OTAzTDkuODYzNzcgMTMuNDZaIiBmaWxsPSJ3aGl0ZSIgc3Ryb2tlPSIjMDA4MUQxIiBzdHJva2Utd2lkdGg9IjAuMTE2NjY3Ij48L3BhdGg+PC9zdmc+";var _e="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIzNjAwIiBoZWlnaHQ9IjM2MDAiIHZpZXdCb3g9IjAgMCAzNjAwIDM2MDAiIGZpbGw9Im5vbmUiPg0KICAgIDxwYXRoIGQ9Ik0wIDgwMEMwIDM1OC4xNzIgMzU4LjE3MiAwIDgwMCAwSDI4MDBDMzI0MS44MyAwIDM2MDAgMzU4LjE3MiAzNjAwIDgwMFYyODAwQzM2MDAgMzI0MS44MyAzMjQxLjgzIDM2MDAgMjgwMCAzNjAwSDgwMEMzNTguMTcyIDM2MDAgMCAzMjQxLjgzIDAgMjgwMFY4MDBaIiBmaWxsPSIjRTAxRTVBIi8+DQogICAgPHBhdGggZD0iTTE3MjIgMTEyNS45OEMxNjEwIDExMjUuOTggMTU1NCAxMTk5Ljk4IDE1NTQgMTMyMS45OEMxNTU0IDEzOTMuOTggMTU4MCAxNDc5Ljk4IDE2MzIgMTU3OS45OEMxNTg2IDE3NDMuOTggMTUxNCAxOTI5Ljk4IDE0NDAgMjA3OS45OEMxMjEyIDIxODUuOTggMTEwMCAyMjg3Ljk4IDExMDAgMjM5OS45OEMxMTAwIDI0ODUuOTggMTE3OCAyNTc3Ljk4IDEyNzggMjU3Ny45OEMxNDE0IDI1NzcuOTggMTUxOCAyMzg1Ljk4IDE1OTIgMjIzNS45OEMxNzIyIDIxODUuOTggMTg2OCAyMTM1Ljk4IDIwMDQgMjEwOS45OEMyMDk0IDIxODUuOTggMjE3NCAyMjIzLjk4IDIyNTAgMjIyMy45OEMyMzc2IDIyMjMuOTggMjQ1NiAyMTI3Ljk4IDI0NTYgMjA0My45OEMyNDU2IDE5NTcuOTggMjM4NiAxODc1Ljk4IDIyMzQgMTg3NS45OEMyMTg0IDE4NzUuOTggMjEzNiAxODg1Ljk4IDIwNzYgMTg5MS45OEMxOTk0IDE4MDMuOTggMTkwOCAxNjgzLjk4IDE4NDQgMTU2MS45OEMxODY2IDE0NjEuOTggMTg3MiAxMzkzLjk4IDE4NzIgMTMzMy45OEMxODcyIDExNzUuOTggMTgxMCAxMTI1Ljk4IDE3MjIgMTEyNS45OFpNMTc1MCAxNzU1Ljk4QzE4MDAgMTgyNy45OCAxODQ4IDE4OTUuOTggMTkwMiAxOTU3Ljk4QzE4MTggMTk3Ny45OCAxNzM0IDIwMDcuOTggMTY1MiAyMDM1Ljk4QzE2ODYgMTk0My45OCAxNzI0IDE4NDkuOTggMTc1MCAxNzU1Ljk4WiIgZmlsbD0id2hpdGUiLz4NCjwvc3ZnPg==";var Ye="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAYAAADimHc4AAAACXBIWXMAAAsTAAALEwEAmpwYAAAD+UlEQVR4nO2ZXUhTYRzGB2baTKikCAtDouk055w6Tx+mRIkVVjIRBLPsQvwq8/Om267sJgKNrropxEAvtLsM+jDoonqvytF2UWEJUYFBZR/6j3c62dbOPMfNs+28zwPPzd5zdnb+v3fv/znvMRggCIIgCIIgCIIgCIIgSEbM6aplTtcMc7oJdvvYNfNy6k2NFgBQfKcshI8aAIj2Tbpj2gDgFAzAiykXjUw8ocHhcRocHqPRiUnPZ0rHmc6sOQBe0Gu3R/3MP1M6znRmzQHwmR1Y4IHhccXjTGeOAoCx/wp84+644nGmM2sOINgSM/JgUvE405k1B8AbKi8yn+lyTTjUONOZNQcAuwGAxZABwAkAQtugNQCTTRLaDAAkABDZDAAkABDZDAAkABDZDAAkABDZDAAkABDZDAAkAIi2C05bqY8Slt32LgUAtPSx/kw/AI6hdADQ0ueebvEDcLDdDABa2bzPTl0/E5eL3z2XSDn77QCglUsvmP1m/9nJLZpeX3gANUPpfgAq+zMBIBzb6y3U+Gyz4uNb36f4AbCdsgY9jn9nUW0+AMjZVm2l+vtbqW9hsZCRjp98vPfvOqod2U55RwoBwGtLpc1TFF4c32JGOn76Htf5LYlOXN9F2ZJdXAC55UVUfWunJ7X4FkcNADXxM9g1+PJV3mcSCwCPiHz2dc4mBS2KUgBq42eoa51/vonsdRZ9A8gqLqGKK7vp4qcNIYvR7E6hQx3ZEY+fB1pyqNm1Ufa6vfMJVHdvG1kqCvUJoPWtf1oJdPsHIx2+vIeyitYufmbZSzzHhfr3dX1fT1UDGfoDIHfDnbOLDdGssiEqjZ+h+k/Pb//Gr7YHxT0Ax50dlFtWpKrw3LzYgc1U7XdwFzryPUuXsADapo2K1vu12v3kzx4Nj9PEANA+bZT9u595lEYFVQWKvytw1vKGrKbwfAniPaT3j0BLEI+NJ29mUM+v4Lm/ey7RM75SLwhn99ObxDq+JssWnj9Nq/lXxg0A3+0Dvi8jW4BpI5Vdyo747iePoS1u+Rja/WNxAqh9Oo47AF7zJ9COL/IzMdK7n7IReGEx/+cdXd3+UNwC8K7FDr4WzysHsNr4Gaz4Ta9TSWrcG9Y9xDUAk88WdNOr1BUBhPPy3fe8js/Jnl6g9KFP9wBMSw2y8mqm50lUDkA48ZMfz1MPPyentDhiv1s3AExLth4voIaHaRGPn/xcnvsj/Xt1B8AUoy/fhQdQGuWX78IDqInyy3fhAbSGsfsJADo2AwAJAEQ2AwAJAEQ2AwAJAEQ2AwAJAEQ2AwAJAEQ2AwAJAEQ2AwBJbACwGwBYDBkAnAAgtA0QBEEQBEEQBEEQBEEQZAiuf1njulfecT1jAAAAAElFTkSuQmCC";var $e="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTAiIGhlaWdodD0iNTAiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cGF0aCBkPSJNMy41NTU2NiAyNi44ODg5QzMuNTU1NjYgMjguNjA3MSA0Ljk0ODU2IDMwIDYuNjY2NzggMzBIMjUuMzMzNEMyNy4wNTE3IDMwIDI4LjQ0NDYgMjguNjA3MSAyOC40NDQ2IDI2Ljg4ODlWOS43Nzc3OEwyMC42NjY4IDJINi42NjY3OEM0Ljk0ODU2IDIgMy41NTU2NiAzLjM5Mjg5IDMuNTU1NjYgNS4xMTExMVYyNi44ODg5WiIgZmlsbD0iIzQxOENENiI+PC9wYXRoPjxwYXRoIG9wYWNpdHk9IjAuOCIgZD0iTTIwLjY2ODUgNi42NjY0N0MyMC42Njg1IDguMzg0NjkgMjIuMDYxMyA5Ljc3NzU5IDIzLjc3OTYgOS43Nzc1OUgyOC40NDYyTDIwLjY2ODUgMS45OTk4MVY2LjY2NjQ3WiIgZmlsbD0iIzdDQkRGRiI+PC9wYXRoPjxnIG9wYWNpdHk9IjAuOSI+PHBhdGggZD0iTTEyLjIxNDYgMjMuMDA3NUMxMC44MzUxIDIxLjYwNTUgOS40MTUzMyAyMC4yMDUxIDguMDAzNDIgMTguODM5OUM5LjMyNjU5IDE3LjUzNzEgMTAuNzAzOCAxNi4xODI2IDEyLjA4NjggMTQuODEwNkMxMi40NTA4IDE1LjE3MzEgMTIuODE2NiAxNS41MzcyIDEzLjE4MzEgMTUuOTAyNUMxMi4xNzM3IDE2LjkwODMgMTEuMTY5NSAxNy45MDYxIDEwLjE5IDE4Ljg4MjhDMTEuMjE3OCAxOS44OTI3IDEyLjIzNzggMjAuOTEwNSAxMy4yNDk4IDIxLjkzNjFDMTIuOTAzNyAyMi4yOTIyIDEyLjU1ODYgMjIuNjQ5NCAxMi4yMTQ2IDIzLjAwNzVaIiBmaWxsPSJ3aGl0ZSI+PC9wYXRoPjxwYXRoIGQ9Ik0yMC4xMTAxIDIyLjk5MjNDMTkuNzY3OCAyMi42MzYxIDE5LjQyNDYgMjIuMjgwOSAxOS4wODAzIDIxLjkyNjdDMjAuMDk1NSAyMC45MDA4IDIxLjExODkgMTkuODgzIDIyLjE1MDMgMTguODczNUMyMS4xNzMgMTcuOTAxNSAyMC4xNyAxNi45MDY3IDE5LjE2MDQgMTUuOTAyNUMxOS41MjY5IDE1LjUzNzggMTkuODkyNSAxNS4xNzQ1IDIwLjI1NjIgMTQuODEzMUMyMS42NDA0IDE2LjE4MzEgMjMuMDE2NyAxNy41MzI1IDI0LjMzNjggMTguODI3MkMyMi45MjE5IDIwLjE4ODYgMjEuNDk2OSAyMS41ODgzIDIwLjExMDEgMjIuOTkyM1oiIGZpbGw9IndoaXRlIj48L3BhdGg+PHBhdGggZD0iTTE1Ljg4MjcgMjQuMTc1NEgxNC40MjcyTDE2LjUzNzIgMTMuNzg4M0gxOC4wNTQ0TDE1Ljg4MjcgMjQuMTc1NFoiIGZpbGw9IndoaXRlIj48L3BhdGg+PHBhdGggZD0iTTEyLjIxNDYgMjMuMDA3NUMxMC44MzUxIDIxLjYwNTUgOS40MTUzMyAyMC4yMDUxIDguMDAzNDIgMTguODM5OUM5LjMyNjU5IDE3LjUzNzEgMTAuNzAzOCAxNi4xODI2IDEyLjA4NjggMTQuODEwNkMxMi40NTA4IDE1LjE3MzEgMTIuODE2NiAxNS41MzcyIDEzLjE4MzEgMTUuOTAyNUMxMi4xNzM3IDE2LjkwODMgMTEuMTY5NSAxNy45MDYxIDEwLjE5IDE4Ljg4MjhDMTEuMjE3OCAxOS44OTI3IDEyLjIzNzggMjAuOTEwNSAxMy4yNDk4IDIxLjkzNjFDMTIuOTAzNyAyMi4yOTIyIDEyLjU1ODYgMjIuNjQ5NCAxMi4yMTQ2IDIzLjAwNzVaIiBzdHJva2U9IndoaXRlIiBzdHJva2Utd2lkdGg9IjAuMjMzMzMzIj48L3BhdGg+PHBhdGggZD0iTTIwLjExMDEgMjIuOTkyM0MxOS43Njc4IDIyLjYzNjEgMTkuNDI0NiAyMi4yODA5IDE5LjA4MDMgMjEuOTI2N0MyMC4wOTU1IDIwLjkwMDggMjEuMTE4OSAxOS44ODMgMjIuMTUwMyAxOC44NzM1QzIxLjE3MyAxNy45MDE1IDIwLjE3IDE2LjkwNjcgMTkuMTYwNCAxNS45MDI1QzE5LjUyNjkgMTUuNTM3OCAxOS44OTI1IDE1LjE3NDUgMjAuMjU2MiAxNC44MTMxQzIxLjY0MDQgMTYuMTgzMSAyMy4wMTY3IDE3LjUzMjUgMjQuMzM2OCAxOC44MjcyQzIyLjkyMTkgMjAuMTg4NiAyMS40OTY5IDIxLjU4ODMgMjAuMTEwMSAyMi45OTIzWiIgc3Ryb2tlPSJ3aGl0ZSIgc3Ryb2tlLXdpZHRoPSIwLjIzMzMzMyI+PC9wYXRoPjxwYXRoIGQ9Ik0xNS44ODI3IDI0LjE3NTRIMTQuNDI3MkwxNi41MzcyIDEzLjc4ODNIMTguMDU0NEwxNS44ODI3IDI0LjE3NTRaIiBzdHJva2U9IndoaXRlIiBzdHJva2Utd2lkdGg9IjAuMjMzMzMzIj48L3BhdGg+PC9nPjwvc3ZnPg==";var q=class q{constructor(e){this.font={body:'"Inter", sans-serif',mono:'"JetBrains Mono", monospace'};this.tools=[];this.TOKENS={background:"oklch(0.2223 0.0060 271.1393)",foreground:"oklch(0.9551 0 0)",card:"oklch(0.2568 0.0076 274.6528)",cardForeground:"oklch(0.9551 0 0)",primary:"oklch(0.611 0.1217 157.75)",primaryForeground:"oklch(0.9491 0 0)",secondary:"oklch(0.2940 0.0130 272.9312)",secondaryForeground:"oklch(0.9551 0 0)",muted:"oklch(0.2940 0.0130 272.9312)",mutedForeground:"oklch(0.7058 0 0)",accent:"oklch(0.2795 0.0368 260.0310)",accentForeground:"oklch(0.7857 0.1153 246.6596)",border:"oklch(0.3289 0.0092 268.3843)",input:"oklch(0.3289 0.0092 268.3843)",ring:"oklch(0.611 0.1217 157.75)",radius:"0.5rem",shadowPanel:"0 32px 80px rgba(0,0,0,0.6), 0 0 0 1px rgba(255,255,255,0.06)",shadowBubble:"0 8px 32px color-mix(in oklab, oklch(0.611 0.1217 157.75) 40%, transparent)",shadowInput:"0 0 0 2px color-mix(in oklab, oklch(0.611 0.1217 157.75) 50%, transparent)"};this.store=Me;this.apiConfig=null;this.bubbleEl=null;this.chatUIEl=null;this.chatAreaEl=null;this.renderedMessageIds=new Set;this.logoUrl="";this.closeAnimationTimeout=null;this.activePanelView="sessions";this.lastMode=0;this.sessionListRenderRequest=0;this.pendingFileBlobs=new Map;this.enableIndexing=!1;this.allowedUploadFileTypes={"application/pdf":[".pdf"],"text/plain":[".txt",".text"],"text/markdown":[".md"],"text/html":[".html"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":[".docx"],"application/msword":[".doc"],"text/csv":[".csv"],"application/json":[".json"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":[".xlsx"],"application/vnd.ms-excel":[".xls"]};e.colorTokens&&(this.TOKENS={...this.TOKENS,...e.colorTokens}),e.enableIndexing===!0&&(this.enableIndexing=!0),e.logo&&(this.logoUrl=e.logo);let t=e.tools||q.DEFAULT_TOOLS,o=new Set(q.DEFAULT_TOOLS.map(r=>r.id));this.tools=t.filter(r=>o.has(r.id)).map(r=>({id:r.id,name:r.name})),this.apiConfig=e.config,this.container=document.createElement("div"),this.container.id="ai-chat-widget-root",document.body.appendChild(this.container),this.root=this.container.attachShadow({mode:"open"}),this.injectGlobalFonts(),this.injectThemeVars(),this.root,this.init().then(()=>{this.mount(),this.store.subscribe(()=>{let r=this.store.getState(),a=r?.chat?.mode,{chatData:s,streamingMessage:i,isLoading:l}=r?.chatSessions?.[r?.chat?.activeSession]??{};a!==this.lastMode&&(this.lastMode=a,this.handleModeChange(a)),this.handleChatDataChange({streamingMessage:i,chatData:s,isLoading:l})})})}injectThemeVars(){let e=this.TOKENS,t=document.createElement("style");t.textContent=`
1324
1327
  :host {
1325
1328
  --background: ${e.background};
1326
1329
  --foreground: ${e.foreground};
@@ -1345,11 +1348,56 @@ ${a}
1345
1348
  --shadow-panel: ${e.shadowPanel};
1346
1349
  --shadow-bubble: ${e.shadowBubble};
1347
1350
  --shadow-input: ${e.shadowInput};
1351
+ --scrollbar-track: color-mix(in oklab, var(--card) 60%, transparent);
1352
+ --scrollbar-thumb: color-mix(in oklab, var(--card) 65%, var(--foreground) 15%);
1353
+ --scrollbar-thumb-hover: color-mix(in oklab, var(--card) 75%, var(--foreground) 15%);
1348
1354
  /* Convenience aliases */
1349
1355
  --font-body: ${this.font.body};
1350
1356
  --font-mono: ${this.font.mono};
1351
1357
  }
1352
- `,this.root.appendChild(t)}injectGlobalFonts(){let e="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=JetBrains+Mono:ital,wght@0,100..800;1,100..800",t=document.createElement("link");t.rel="preconnect",t.href="https://fonts.googleapis.com";let o=document.createElement("link");o.rel="preconnect",o.href="https://fonts.gstatic.com",o.crossOrigin="";let r=document.createElement("link");r.type="text/css",r.rel="stylesheet",r.href=e,this.root.appendChild(t),this.root.appendChild(o),this.root.appendChild(r),document.head.appendChild(t),document.head.appendChild(o),document.head.appendChild(r)}mount(){let e=this.createChatBubble();this.root.appendChild(e),this.bubbleEl=e}async init(){await this.store.dispatch(ie({indexName:this.apiConfig?.indexName}))}handleChatDataChange({chatData:e,streamingMessage:t,isLoading:o}){if(!this.chatAreaEl)return;e||(e=[]);let r=this.chatAreaEl.querySelector(".chat-data-container"),a=this.chatAreaEl.querySelector("#bangdb-chat-area"),s=this.chatAreaEl.querySelector("#bdb-empty-state"),i=()=>{requestAnimationFrame(()=>{a.scrollTo({top:a.scrollHeight,behavior:"smooth"})})},c=e.length>0||!!t?.query;s.style.display=c?"none":"flex";for(let b=0;b<e.length;b++){let m=e[b],u=`msg-${b}`;if(m?.query&&!this.renderedMessageIds.has(u)){this.renderedMessageIds.add(u),r.insertBefore(this.userRequestMessage(m.query),r.querySelector("#chat-window-anchor"));let y=new S(m),{messages:w}=y.parse();w?.length>0&&r.insertBefore(this.aiResponseMessage(m),r.querySelector("#chat-window-anchor")),i()}}let p="bdb-streaming-msg",d=this.root.querySelector(`#${p}`);if(t?.query){d||(d=document.createElement("div"),d.id=p,r.insertBefore(d,r.querySelector("#chat-window-anchor")),d.appendChild(this.userRequestMessage(t.query)),d.style.minHeight=`${a.clientHeight*.8}px`);let b=d.querySelector(".bdb-streaming-ai-area"),m=t.output?.output??"";if(o&&!m&&!b)b=document.createElement("div"),b.className="bdb-streaming-ai-area",b.appendChild(this.loadingIndicator()),d.appendChild(b);else if(m){b||(b=document.createElement("div"),b.className="bdb-streaming-ai-area",d.appendChild(b));let u=b.querySelector(".ai-md");u?u.innerHTML=H(m):(b.innerHTML="",b.appendChild(this.aiResponseMessage(t)))}s.style.display="none",i()}else d&&(d.style.minHeight="0",d.remove());let l=this.chatAreaEl.querySelector(".bdb-textarea"),g=this.chatAreaEl.querySelector(".bdb-send-btn"),h=this.chatAreaEl.querySelector(".bdb-tools-trigger");l&&(l.style.opacity="1"),g&&(g.disabled=!!o||!l?.value.trim()),h&&(h.disabled=!!o,h.style.opacity=o?"0.5":"1",h.style.pointerEvents=o?"none":"auto")}handleModeChange(e){let t=this.bubbleEl?.querySelector(".chat-bubble");if(t)switch(e){case 0:if(t.classList.remove("is-open"),t.setAttribute("aria-label","Open chat"),this.chatUIEl){let r=this.chatUIEl.querySelector(".bdb-chat-panel");r&&(r.style.animation="bdb-panel-out 0.18s ease-in both",r&&(r.style.animation="bdb-panel-out 0.18s ease-in both"),setTimeout(()=>{this.chatUIEl&&(this.chatUIEl.style.display="none")},180))}break;case 1:if(t.setAttribute("aria-label","Close chat"),!this.chatUIEl)this.chatUIEl=this.createChatUI(),this.bubbleEl?.appendChild(this.chatUIEl);else{this.chatUIEl.style.display="";let r=this.chatUIEl.querySelector(".bdb-chat-panel");r&&(r.style.animation="bdb-panel-in 0.25s cubic-bezier(0.34, 1.56, 0.64, 1) both")}t.classList.add("is-open"),this.chatUIEl?.querySelector(".bdb-chat-panel")?.classList.remove("is-fullscreen"),requestAnimationFrame(()=>this.updatePanelPosition());break;case 2:if(t.setAttribute("aria-label","Close chat"),!this.chatUIEl)this.chatUIEl=this.createChatUI(),this.bubbleEl?.appendChild(this.chatUIEl);else{this.chatUIEl.style.display="";let r=this.chatUIEl.querySelector(".bdb-chat-panel");r&&(r.style.animation="bdb-panel-in 0.25s cubic-bezier(0.34, 1.56, 0.64, 1) both")}t.classList.add("is-open");let o=this.chatUIEl?.querySelector(".bdb-chat-panel");o&&(o.classList.add("is-fullscreen"),o.style.top="",o.style.bottom="",o.style.left="",o.style.right="");break}}updatePanelPosition(){if(!this.chatUIEl||!this.bubbleEl)return;let e=this.chatUIEl.querySelector(".bdb-chat-panel");if(!e||e.classList.contains("is-fullscreen"))return;let t=parseInt(this.bubbleEl.style.left)||0,o=parseInt(this.bubbleEl.style.top)||0,r=52,a=52,s=750,i=window.innerWidth,c=window.innerHeight,p=12,d=o+a/2;if(d<c/3)e.style.top=a+p+"px",e.style.bottom="auto";else if(d>2*c/3)e.style.bottom=a+p+"px",e.style.top="auto";else{let l=d-s/2,g=Math.max(8,Math.min(l,c-s-8));e.style.top=g-o+"px",e.style.bottom="auto"}t+r/2<i/2?(e.style.left="0",e.style.right="auto"):(e.style.right="0",e.style.left="auto")}createChatBubble(){let e=document.createElement("div");e.classList.add("bdb-bubble-container"),e.innerHTML=`
1358
+
1359
+ .bdb-scroll,
1360
+ .bdb-textarea {
1361
+ scrollbar-width: thin;
1362
+ scrollbar-color: var(--scrollbar-thumb) var(--scrollbar-track);
1363
+ }
1364
+
1365
+ .bdb-scroll:hover,
1366
+ .bdb-textarea:hover,
1367
+ .bdb-textarea:focus {
1368
+ scrollbar-color: var(--scrollbar-thumb-hover) var(--scrollbar-track);
1369
+ }
1370
+
1371
+ .bdb-scroll::-webkit-scrollbar,
1372
+ .bdb-textarea::-webkit-scrollbar {
1373
+ width: 10px;
1374
+ height: 10px;
1375
+ }
1376
+
1377
+ .bdb-scroll::-webkit-scrollbar-track,
1378
+ .bdb-textarea::-webkit-scrollbar-track {
1379
+ background: var(--scrollbar-track);
1380
+ border-radius: var(--radius-full);
1381
+ }
1382
+
1383
+ .bdb-scroll::-webkit-scrollbar-thumb,
1384
+ .bdb-textarea::-webkit-scrollbar-thumb {
1385
+ background: var(--scrollbar-thumb);
1386
+ border: 2px solid var(--scrollbar-track);
1387
+ border-radius: var(--radius-full);
1388
+ background-clip: padding-box;
1389
+ }
1390
+
1391
+ .bdb-scroll::-webkit-scrollbar-thumb:hover,
1392
+ .bdb-textarea::-webkit-scrollbar-thumb:hover {
1393
+ background: var(--scrollbar-thumb-hover);
1394
+ }
1395
+
1396
+ .bdb-scroll::-webkit-scrollbar-corner,
1397
+ .bdb-textarea::-webkit-scrollbar-corner {
1398
+ background: transparent;
1399
+ }
1400
+ `,this.root.appendChild(t)}injectGlobalFonts(){let e="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=JetBrains+Mono:ital,wght@0,100..800;1,100..800",t=document.createElement("link");t.rel="preconnect",t.href="https://fonts.googleapis.com";let o=document.createElement("link");o.rel="preconnect",o.href="https://fonts.gstatic.com",o.crossOrigin="";let r=document.createElement("link");r.type="text/css",r.rel="stylesheet",r.href=e,this.root.appendChild(t),this.root.appendChild(o),this.root.appendChild(r),document.head.appendChild(t),document.head.appendChild(o),document.head.appendChild(r)}mount(){let e=this.createChatBubble();this.root.appendChild(e),this.bubbleEl=e}async init(){this.store.dispatch(ne(this.apiConfig?.indexName))}async fetchSessionsFromApi(){if(!this.apiConfig)return;let{chat:e}=this.store.getState(),{activeIndex:t}=e;try{let r=(await de({payload:{filter:`{name = "${t}"}`,org:this.apiConfig.org,userid:this.apiConfig.userid},baseURL:this.apiConfig.backendURL,apikey:this.apiConfig.apikey}))?.sessions||[];this.store.dispatch(ie(r))}catch{}}async fetchSessionChatsFromApi(e){if(!this.apiConfig)return[];try{let t=await ce({payload:{filter:`{org = "${this.apiConfig.org}" AND source ~ NA}`,sessionid:e,userid:this.apiConfig.userid},baseURL:this.apiConfig.backendURL,apikey:this.apiConfig.apikey});return Ce(t?.queries)?.reverse()}catch{return[]}}getClampedBubblePosition(e,t){let a=Math.max(24,window.innerWidth-52-24),s=Math.max(24,window.innerHeight-52-24);return{left:Math.min(Math.max(e,24),a),top:Math.min(Math.max(t,24),s)}}getDefaultBubblePosition(){return this.getClampedBubblePosition(window.innerWidth-24-52,window.innerHeight-24-52)}resetRenderedMessages(){if(this.renderedMessageIds.clear(),!this.chatAreaEl)return;let e=this.chatAreaEl.querySelector(".chat-data-container"),t=this.chatAreaEl.querySelector("#bdb-streaming-msg"),o=this.chatAreaEl.querySelector("#bdb-empty-state");t&&t.remove(),e&&(e.innerHTML='<div id="chat-window-anchor" style="overflow-anchor: auto; height: 1px;"></div>'),o&&(o.style.display="flex")}handleChatDataChange({chatData:e,streamingMessage:t,isLoading:o}){if(!this.chatAreaEl)return;e||(e=[]);let r=this.chatAreaEl.querySelector(".chat-data-container"),a=this.chatAreaEl.querySelector("#bangdb-chat-area"),s=this.chatAreaEl.querySelector("#bdb-empty-state"),i=()=>{requestAnimationFrame(()=>{a.scrollTo({top:a.scrollHeight,behavior:"smooth"})})},l=e.length>0||!!t?.query;s.style.display=l?"none":"flex",this.renderedMessageIds.size>e.length&&this.resetRenderedMessages();for(let h=0;h<e.length;h++){let m=e[h],x=`msg-${h}`;if((m?.query||m?.files?.length>0)&&!this.renderedMessageIds.has(x)){this.renderedMessageIds.add(x),r.insertBefore(this.userRequestMessage(m.query,m.files,m.log_sid),r.querySelector("#chat-window-anchor"));let p=new I(m),{messages:y}=p.parse();m?.query&&y?.length>0&&r.insertBefore(this.aiResponseMessage(m),r.querySelector("#chat-window-anchor")),i()}}let d="bdb-streaming-msg",c=this.root.querySelector(`#${d}`);if(t?.query){c||(c=document.createElement("div"),c.id=d,r.insertBefore(c,r.querySelector("#chat-window-anchor")),c.appendChild(this.userRequestMessage(t.query)),c.style.minHeight=`${a.clientHeight*.8}px`);let h=c.querySelector(".bdb-streaming-ai-area"),m=t.output?.output??"";if(o&&!m&&!h)h=document.createElement("div"),h.className="bdb-streaming-ai-area",h.appendChild(this.loadingIndicator()),c.appendChild(h);else if(m){h||(h=document.createElement("div"),h.className="bdb-streaming-ai-area",c.appendChild(h));let x=h.querySelector(".ai-md");x?x.innerHTML=U(m):(h.innerHTML="",h.appendChild(this.aiResponseMessage(t)))}s.style.display="none",i()}else c&&(c.style.minHeight="0",c.remove());let u=this.chatAreaEl.querySelector(".bdb-textarea"),g=this.chatAreaEl.querySelector(".bdb-send-btn"),b=this.chatAreaEl.querySelector(".bdb-tools-trigger");if(u&&(u.style.opacity="1"),g){let h=this.store.getState(),m=h.chatSessions[h.chat.activeSession],x=(m?.queryFiles||[]).length>0,w=(m?.files||[]).some(p=>this.isFileBusy(p));g.disabled=!!o||w||!u?.value.trim()&&!x}b&&(b.disabled=!!o,b.style.opacity=o?"0.5":"1",b.style.pointerEvents=o?"none":"auto")}handleModeChange(e){let t=this.bubbleEl?.querySelector(".chat-bubble");if(t)switch(e){case 0:if(t.classList.remove("is-open"),t.setAttribute("aria-label","Open chat"),this.chatUIEl){let r=this.chatUIEl.querySelector(".bdb-chat-panel");r&&(r.style.animation="bdb-panel-out 0.18s ease-in both",this.closeAnimationTimeout&&window.clearTimeout(this.closeAnimationTimeout),this.closeAnimationTimeout=window.setTimeout(()=>{this.chatUIEl&&(this.chatUIEl.style.display="none"),this.closeAnimationTimeout=null},180))}break;case 1:if(t.setAttribute("aria-label","Close chat"),this.closeAnimationTimeout&&(window.clearTimeout(this.closeAnimationTimeout),this.closeAnimationTimeout=null),!this.chatUIEl)this.chatUIEl=this.createChatUI(),this.bubbleEl?.appendChild(this.chatUIEl);else{this.chatUIEl.style.display="";let r=this.chatUIEl.querySelector(".bdb-chat-panel");r&&(r.style.animation="bdb-panel-in 0.25s cubic-bezier(0.34, 1.56, 0.64, 1) both")}t.classList.add("is-open"),this.chatUIEl?.querySelector(".bdb-chat-panel")?.classList.remove("is-fullscreen"),this.renderPanelView(),requestAnimationFrame(()=>this.updatePanelPosition());break;case 2:if(t.setAttribute("aria-label","Close chat"),this.closeAnimationTimeout&&(window.clearTimeout(this.closeAnimationTimeout),this.closeAnimationTimeout=null),!this.chatUIEl)this.chatUIEl=this.createChatUI(),this.bubbleEl?.appendChild(this.chatUIEl);else{this.chatUIEl.style.display="";let r=this.chatUIEl.querySelector(".bdb-chat-panel");r&&(r.style.animation="bdb-panel-in 0.25s cubic-bezier(0.34, 1.56, 0.64, 1) both")}t.classList.add("is-open");let o=this.chatUIEl?.querySelector(".bdb-chat-panel");o&&(o.classList.add("is-fullscreen"),o.style.top="",o.style.bottom="",o.style.left="",o.style.right=""),this.renderPanelView();break}}renderPanelView(){if(this.activePanelView==="sessions"){this.renderSessionList();return}this.renderChatView()}renderActiveSession(){let e=this.store.getState(),t=e.chatSessions[e.chat.activeSession];this.handleChatDataChange({chatData:t?.chatData,streamingMessage:t?.streamingMessage,isLoading:t?.isLoading})}renderChatView(){if(!this.chatUIEl)return;let e=this.chatUIEl.querySelector(".bdb-chat-body");e&&(this.activePanelView="chat",this.syncPanelHeader(),e.innerHTML="",this.chatAreaEl=null,this.resetRenderedMessages(),e.appendChild(this.chatArea()),this.renderActiveSession())}async renderSessionList(){if(!this.chatUIEl)return;let e=this.chatUIEl.querySelector(".bdb-chat-body");if(!e)return;let t=++this.sessionListRenderRequest;this.activePanelView="sessions",this.chatAreaEl=null,this.resetRenderedMessages(),this.syncPanelHeader(),e.innerHTML="",e.appendChild(this.sessionListLoadingView()),await this.fetchSessionsFromApi(),t===this.sessionListRenderRequest&&this.activePanelView==="sessions"&&(e.innerHTML="",e.appendChild(this.sessionListView()))}syncPanelHeader(){if(!this.chatUIEl)return;let e=this.chatUIEl.querySelector(".bdb-chat-title"),t=this.chatUIEl.querySelector(".js-sessions-btn"),o=this.chatUIEl.querySelector(".bdb-download-items");e&&(e.textContent=this.activePanelView==="sessions"?"Chats":this.getActiveSessionTitle()),t&&(t.style.display=this.activePanelView==="chat"?"flex":"none"),o&&(o.style.display=this.activePanelView==="chat"?"block":"none")}async openSession(e){this.store.dispatch(ae(e)),this.store.dispatch(fe(e));let t=await this.fetchSessionChatsFromApi(e);this.store.dispatch(ye({sessionId:e,chatData:t})),this.renderChatView()}async createNewSession(){let e=crypto.randomUUID().replace(/-/g,"").slice(0,10);(await B({baseURL:this.apiConfig?.backendURL,apikey:this.apiConfig?.apikey,payload:{userid:this.apiConfig?.userid,sessionid:e,name:this.apiConfig?.indexName,description:"New chat",org:this.apiConfig?.org}}))?.sid&&this.openSession(e)}getSessionTitle(e,t){let o=t?.description||"";return o.trim()?o.trim().slice(0,56):e==="GUEST_SESSION"?"Default chat":"New chat"}getActiveSessionTitle(){let e=this.store.getState(),t=e.chat.activeSession,o=e.chat.sessions||[];for(let r of o)try{let a=typeof r?.session=="string"?JSON.parse(r.session):r?.session||r;if(a?.sessionid===t){let s=a?.description||"";if(s.trim())return s.trim().slice(0,56)}}catch{}return"Chats"}updatePanelPosition(){if(!this.chatUIEl||!this.bubbleEl)return;let e=this.chatUIEl.querySelector(".bdb-chat-panel");if(!e||e.classList.contains("is-fullscreen"))return;let t=parseInt(this.bubbleEl.style.left)||0,o=parseInt(this.bubbleEl.style.top)||0,r=52,a=52,s=750,i=window.innerWidth,l=window.innerHeight,d=12,c=o+a/2;if(c<l/3)e.style.top=a+d+"px",e.style.bottom="auto";else if(c>2*l/3)e.style.bottom=a+d+"px",e.style.top="auto";else{let u=c-s/2,g=Math.max(8,Math.min(u,l-s-8));e.style.top=g-o+"px",e.style.bottom="auto"}t+r/2<i/2?(e.style.left="0",e.style.right="auto"):(e.style.right="0",e.style.left="auto")}createChatBubble(){let e=document.createElement("div");e.classList.add("bdb-bubble-container"),e.innerHTML=`
1353
1401
  <style>
1354
1402
  .bdb-bubble-container {
1355
1403
  position: fixed;
@@ -1401,10 +1449,6 @@ ${a}
1401
1449
  transition: transform 0.2s ease, opacity 0.15s ease;
1402
1450
  color: var(--primary-foreground);
1403
1451
  }
1404
- .chat-bubble.is-open .icon-chat {
1405
- opacity: 0;
1406
- transform: rotate(90deg) scale(0.6);
1407
- }
1408
1452
  </style>
1409
1453
 
1410
1454
 
@@ -1416,7 +1460,7 @@ ${a}
1416
1460
  </span>
1417
1461
 
1418
1462
  </button>
1419
- `,e.addEventListener("click",()=>{if(e._didDrag)return;let{chat:t}=this.store.getState();t?.mode===0&&this.store.dispatch(z(1))});{let t=!1,o=0,r=0,a=0,s=0,i=window.innerWidth-24-52,c=window.innerHeight-24-52;try{let p=localStorage.getItem("bdb-bubble-position");if(p){let{left:d,top:l}=JSON.parse(p);i=d,c=l}}catch{}e.style.bottom="auto",e.style.right="auto",e.style.left=i+"px",e.style.top=c+"px",e.addEventListener("pointerdown",p=>{t=!0,e._didDrag=!1,o=p.clientX,r=p.clientY,a=i,s=c,e.style.transition="none",e.setPointerCapture(p.pointerId)}),e.addEventListener("pointermove",p=>{if(!t)return;let d=p.clientX-o,l=p.clientY-r;Math.hypot(d,l)>4&&(e._didDrag=!0),i=a+d,c=s+l,e.style.left=i+"px",e.style.top=c+"px"}),e.addEventListener("pointerup",p=>{if(!t||(t=!1,e.releasePointerCapture(p.pointerId),!e._didDrag))return;let d=52,l=52,g=24,h=window.innerWidth,b=window.innerHeight,m=i+d/2,u=c+l/2,y=[{left:g,top:g},{left:(h-d)/2,top:g},{left:h-g-d,top:g},{left:g,top:(b-l)/2},{left:h-g-d,top:(b-l)/2},{left:g,top:b-g-l},{left:(h-d)/2,top:b-g-l},{left:h-g-d,top:b-g-l}],w=y[0],k=1/0;for(let v of y){let C=Math.hypot(v.left+d/2-m,v.top+l/2-u);C<k&&(k=C,w=v)}i=w.left,c=w.top,e.style.transition="left 0.4s cubic-bezier(0.2,0.8,0.2,1), top 0.4s cubic-bezier(0.2,0.8,0.2,1)",e.style.left=i+"px",e.style.top=c+"px";try{localStorage.setItem("bdb-bubble-position",JSON.stringify({left:i,top:c}))}catch{}this.updatePanelPosition()})}return e}createChatUI(){let e=document.createElement("div");e.addEventListener("click",l=>l.stopPropagation()),e.addEventListener("pointerdown",l=>l.stopPropagation()),e.innerHTML=`
1463
+ `,e.addEventListener("click",()=>{if(e._didDrag)return;let{chat:t}=this.store.getState();t?.mode===0?(this.activePanelView="sessions",this.store.dispatch(L(1))):this.store.dispatch(L(0))});{let t=!1,o=0,r=0,a=0,s=0,i=this.getDefaultBubblePosition(),l=i.left,d=i.top;e.style.bottom="auto",e.style.right="auto",e.style.left=l+"px",e.style.top=d+"px",window.addEventListener("resize",()=>{let c=this.getClampedBubblePosition(l,d);l=c.left,d=c.top,e.style.left=l+"px",e.style.top=d+"px",this.updatePanelPosition()}),e.addEventListener("pointerdown",c=>{t=!0,e._didDrag=!1,o=c.clientX,r=c.clientY,a=l,s=d,e.style.transition="none",e.setPointerCapture(c.pointerId)}),e.addEventListener("pointermove",c=>{if(!t)return;let u=c.clientX-o,g=c.clientY-r;Math.hypot(u,g)>4&&(e._didDrag=!0),l=a+u,d=s+g,e.style.left=l+"px",e.style.top=d+"px"}),e.addEventListener("pointerup",c=>{if(!t||(t=!1,e.releasePointerCapture(c.pointerId),!e._didDrag))return;let u=52,g=52,b=24,h=window.innerWidth,m=window.innerHeight,x=l+u/2,w=d+g/2,p=[{left:b,top:b},{left:(h-u)/2,top:b},{left:h-b-u,top:b},{left:b,top:(m-g)/2},{left:h-b-u,top:(m-g)/2},{left:b,top:m-b-g},{left:(h-u)/2,top:m-b-g},{left:h-b-u,top:m-b-g}],y=p[0],v=1/0;for(let k of p){let f=Math.hypot(k.left+u/2-x,k.top+g/2-w);f<v&&(v=f,y=k)}l=y.left,d=y.top,e.style.transition="left 0.4s cubic-bezier(0.2,0.8,0.2,1), top 0.4s cubic-bezier(0.2,0.8,0.2,1)",e.style.left=l+"px",e.style.top=d+"px",this.updatePanelPosition()})}return e}createChatUI(){let e=document.createElement("div");e.addEventListener("click",u=>u.stopPropagation()),e.addEventListener("pointerdown",u=>u.stopPropagation()),e.innerHTML=`
1420
1464
  <style>
1421
1465
  .bdb-chat-widget {
1422
1466
  display: flex;
@@ -1477,13 +1521,15 @@ ${a}
1477
1521
  display: flex;
1478
1522
  align-items: center;
1479
1523
  gap: 0.25rem;
1480
- overflow: hidden;
1524
+ overflow: visible;
1481
1525
  min-width: 0;
1482
1526
  flex: 1;
1483
1527
  max-width: calc(100% - 150px);
1484
1528
  }
1485
1529
 
1486
1530
  .bdb-chat-title {
1531
+ flex: 1;
1532
+ min-width: 0;
1487
1533
  font-size: 15px;
1488
1534
  font-weight: 600;
1489
1535
  font-family: var(--font-body);
@@ -1633,6 +1679,7 @@ ${a}
1633
1679
  gap: 4px;
1634
1680
  flex-shrink: 0;
1635
1681
  flex-wrap: nowrap;
1682
+ overflow: visible;
1636
1683
  }
1637
1684
 
1638
1685
  .bdb-icon-btn {
@@ -1654,6 +1701,40 @@ ${a}
1654
1701
  color: var(--foreground);
1655
1702
  }
1656
1703
 
1704
+ .bdb-icon-tooltip {
1705
+ position: relative;
1706
+ display: inline-flex;
1707
+ align-items: center;
1708
+ }
1709
+
1710
+ .bdb-icon-tooltip-text {
1711
+ position: absolute;
1712
+ top: calc(100% + 8px);
1713
+ right: 0;
1714
+ padding: 6px 8px;
1715
+ border-radius: 8px;
1716
+ background: color-mix(in oklab, var(--card) 92%, black);
1717
+ color: var(--foreground);
1718
+ border: 1px solid color-mix(in oklab, var(--border) 85%, transparent);
1719
+ box-shadow: 0 10px 26px rgba(0,0,0,0.28);
1720
+ font-size: 12px;
1721
+ line-height: 1.2;
1722
+ white-space: nowrap;
1723
+ opacity: 0;
1724
+ visibility: hidden;
1725
+ pointer-events: none;
1726
+ transition: opacity 0.14s ease, transform 0.14s ease, visibility 0.14s;
1727
+ transform: translateY(-2px);
1728
+ z-index: 1002;
1729
+ }
1730
+
1731
+ .bdb-icon-tooltip:hover .bdb-icon-tooltip-text,
1732
+ .bdb-icon-tooltip:focus-within .bdb-icon-tooltip-text {
1733
+ opacity: 1;
1734
+ visibility: visible;
1735
+ transform: translateY(0);
1736
+ }
1737
+
1657
1738
  .bdb-download-dropdown {
1658
1739
  position: absolute;
1659
1740
  top: 100%;
@@ -1665,7 +1746,7 @@ ${a}
1665
1746
  box-shadow: 0 4px 12px rgba(0,0,0,0.2);
1666
1747
  display: none;
1667
1748
  flex-direction: column;
1668
- min-width: 140px;
1749
+ min-width: 190px;
1669
1750
  z-index: 1000;
1670
1751
  padding: 4px;
1671
1752
  }
@@ -1693,6 +1774,12 @@ ${a}
1693
1774
  background: var(--secondary);
1694
1775
  }
1695
1776
 
1777
+ .bdb-dropdown-separator {
1778
+ height: 1px;
1779
+ margin: 4px;
1780
+ background: var(--border);
1781
+ }
1782
+
1696
1783
  .bdb-chat-panel {
1697
1784
  display: flex;
1698
1785
  flex-direction: column;
@@ -1716,6 +1803,11 @@ ${a}
1716
1803
  to { opacity: 1; transform: scale(1) translateY(0); }
1717
1804
  }
1718
1805
 
1806
+ @keyframes bdb-panel-out {
1807
+ from { opacity: 1; transform: scale(1) translateY(0); }
1808
+ to { opacity: 0; transform: scale(0.92) translateY(10px); }
1809
+ }
1810
+
1719
1811
  .bdb-chat-panel.is-fullscreen {
1720
1812
  position: fixed !important;
1721
1813
  inset: 0 !important;
@@ -1758,7 +1850,7 @@ ${a}
1758
1850
  <!-- </div>-->
1759
1851
 
1760
1852
  <div class="bdb-chat-title-container">
1761
- <h3 class="bdb-chat-title">${this.chatTitle}</h3>
1853
+ <h3 class="bdb-chat-title">Chats</h3>
1762
1854
  <span class="bdb-info-tooltip">
1763
1855
  <button
1764
1856
  type="button"
@@ -1788,32 +1880,46 @@ ${a}
1788
1880
  </div>
1789
1881
 
1790
1882
  <div class="bdb-header-actions" style="position: relative;">
1791
- <button class="bdb-icon-btn js-fullscreen-btn" aria-label="Toggle fullscreen" title="Fullscreen">
1792
- <svg width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg">
1793
- <path d="M1.5 1h4v1.5h-2.5v2.5h-1.5v-4zm8 0h4v4h-1.5v-2.5h-2.5v-1.5zm-8 8h1.5v2.5h2.5v1.5h-4v-4zm10.5 2.5v-2.5h1.5v4h-4v-1.5h2.5z" fill="currentColor"/>
1883
+ <button class="bdb-icon-btn js-more-btn" aria-label="More options" title="More options" aria-haspopup="menu" aria-expanded="false">
1884
+ <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round">
1885
+ <circle cx="5" cy="12" r="1.6"></circle>
1886
+ <circle cx="12" cy="12" r="1.6"></circle>
1887
+ <circle cx="19" cy="12" r="1.6"></circle>
1794
1888
  </svg>
1795
1889
  </button>
1796
1890
 
1797
- <button class="bdb-icon-btn js-download-btn" aria-label="Download chat" title="Download">
1798
- <svg width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg">
1799
- <path d="M7.5 10.5l-4-4h2.5v-5h3v5h2.5l-4 4zm-5 2h10v1.5h-10v-1.5z" fill="currentColor"/>
1800
- </svg>
1801
- </button>
1802
-
1803
- <div class="bdb-download-dropdown" id="bdb-download-dropdown">
1804
- <button class="bdb-dropdown-item" id="js-download-md">
1805
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="16" y1="13" x2="8" y2="13"></line><line x1="16" y1="17" x2="8" y2="17"></line><polyline points="10 9 9 9 8 9"></polyline></svg>
1806
- Markdown (.md)
1807
- </button>
1808
- <button class="bdb-dropdown-item" id="js-download-pdf">
1809
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><path d="M9 15v-6h2a2 2 0 0 1 2 2v2a2 2 0 0 1-2 2h-2"></path></svg>
1810
- PDF (.pdf)
1891
+ <div class="bdb-download-dropdown" id="bdb-header-menu" role="menu">
1892
+ <button class="bdb-dropdown-item js-sessions-btn" role="menuitem" style="display: none;">
1893
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
1894
+ <path d="M21 15a2 2 0 0 1-2 2H8l-5 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
1895
+ <path d="M8 9h8"></path>
1896
+ <path d="M8 13h5"></path>
1897
+ </svg>
1898
+ All chats
1811
1899
  </button>
1812
- <button class="bdb-dropdown-item" id="js-download-json">
1813
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><path d="M8 13h2m0 0v4m0-4v-2a2 2 0 0 1 4 0v2m0 0h2"></path></svg>
1814
- JSON (.json)
1900
+ <button class="bdb-dropdown-item js-fullscreen-btn" role="menuitem">
1901
+ <svg width="14" height="14" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg">
1902
+ <path d="M1.5 1h4v1.5h-2.5v2.5h-1.5v-4zm8 0h4v4h-1.5v-2.5h-2.5v-1.5zm-8 8h1.5v2.5h2.5v1.5h-4v-4zm10.5 2.5v-2.5h1.5v4h-4v-1.5h2.5z" fill="currentColor"/>
1903
+ </svg>
1904
+ Toggle fullscreen
1815
1905
  </button>
1816
- </div>
1906
+
1907
+ <div class="bdb-download-items">
1908
+ <div class="bdb-dropdown-separator"></div>
1909
+ <button class="bdb-dropdown-item" id="js-download-md">
1910
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="16" y1="13" x2="8" y2="13"></line><line x1="16" y1="17" x2="8" y2="17"></line><polyline points="10 9 9 9 8 9"></polyline></svg>
1911
+ Markdown (.md)
1912
+ </button>
1913
+ <button class="bdb-dropdown-item" id="js-download-pdf">
1914
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><path d="M9 15v-6h2a2 2 0 0 1 2 2v2a2 2 0 0 1-2 2h-2"></path></svg>
1915
+ PDF (.pdf)
1916
+ </button>
1917
+ <button class="bdb-dropdown-item" id="js-download-json">
1918
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><path d="M8 13h2m0 0v4m0-4v-2a2 2 0 0 1 4 0v2m0 0h2"></path></svg>
1919
+ JSON (.json)
1920
+ </button>
1921
+ </div>
1922
+ </div>
1817
1923
 
1818
1924
  <button class="bdb-icon-btn js-close-btn" aria-label="Close chat" title="Close">
1819
1925
  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
@@ -1826,16 +1932,147 @@ ${a}
1826
1932
  <div class="bdb-chat-body" style="display: flex; flex-direction: column; flex: 1; overflow: hidden;"></div>
1827
1933
  </div>
1828
1934
  </div>
1829
- `;let t=e.querySelector(".bdb-chat-panel"),o=e.querySelector(".bdb-chat-body"),r=e.querySelector(".bdb-chat-title-container"),a=e.querySelector(".bdb-chat-header");if(a&&this.bubbleEl){let l=!1,g=0,h=0,b=0,m=0,u=parseInt(this.bubbleEl.style.left)||0,y=parseInt(this.bubbleEl.style.top)||0;a.addEventListener("pointerdown",k=>{k.target?.closest("button, a, input, textarea, select, [role='button']")||(l=!0,this.bubbleEl._didDrag=!1,g=k.clientX,h=k.clientY,u=parseInt(this.bubbleEl.style.left)||0,y=parseInt(this.bubbleEl.style.top)||0,b=u,m=y,this.bubbleEl.style.transition="none",a.setPointerCapture(k.pointerId))}),a.addEventListener("pointermove",k=>{if(!l)return;let v=k.clientX-g,C=k.clientY-h;Math.hypot(v,C)>4&&(this.bubbleEl._didDrag=!0),u=b+v,y=m+C,this.bubbleEl.style.left=u+"px",this.bubbleEl.style.top=y+"px",this.updatePanelPosition()});let w=k=>{if(!l)return;l=!1;try{a.releasePointerCapture(k.pointerId)}catch{}if(!this.bubbleEl._didDrag)return;let v=52,C=52,f=24,x=window.innerWidth,E=window.innerHeight,L=u+v/2,j=y+C/2,M=[{left:f,top:f},{left:(x-v)/2,top:f},{left:x-f-v,top:f},{left:f,top:(E-C)/2},{left:x-f-v,top:(E-C)/2},{left:f,top:E-f-C},{left:(x-v)/2,top:E-f-C},{left:x-f-v,top:E-f-C}],I=M[0],K=1/0;for(let B of M){let G=Math.hypot(B.left+v/2-L,B.top+C/2-j);G<K&&(K=G,I=B)}u=I.left,y=I.top,this.bubbleEl.style.transition="left 0.4s cubic-bezier(0.2,0.8,0.2,1), top 0.4s cubic-bezier(0.2,0.8,0.2,1)",this.bubbleEl.style.left=u+"px",this.bubbleEl.style.top=y+"px";try{localStorage.setItem("bdb-bubble-position",JSON.stringify({left:u,top:y}))}catch{}this.updatePanelPosition()};a.addEventListener("pointerup",w),a.addEventListener("pointercancel",w)}if(t.querySelector(".js-fullscreen-btn")?.addEventListener("click",()=>{this.store.getState().chat.mode===2?this.store.dispatch(z(1)):this.store.dispatch(z(2))}),t.querySelector(".js-close-btn")?.addEventListener("click",()=>{let l=this.store.getState().chat.mode;l===2?this.store.dispatch(z(1)):l===1&&this.store.dispatch(z(0))}),this.logoUrl){let l=document.createElement("div"),g=document.createElement("img");g.src=this.logoUrl,g.style.cssText="width: 24px; height: 24px; margin-right: 0.5rem;",l.appendChild(g),r.prepend(l)}let s=t.querySelector(".js-download-btn"),i=t.querySelector("#bdb-download-dropdown"),c=t.querySelector("#js-download-md"),p=t.querySelector("#js-download-pdf"),d=t.querySelector("#js-download-json");if(s&&i){s.addEventListener("click",h=>{h.stopPropagation(),i.classList.toggle("show")});let l=h=>{let b=h.composedPath();!b.includes(i)&&!b.includes(s)&&i.classList.remove("show")};this.root.addEventListener("click",l,!0),document.addEventListener("click",l,!0);let g=()=>{let h=this.store.getState(),b=h.chat.activeSession;return h.chatSessions[b]?.chatData||[]};c?.addEventListener("click",()=>{Ce(g(),this.chatTitle),i.classList.remove("show")}),p?.addEventListener("click",()=>{Ee(g(),this.chatTitle),i.classList.remove("show")}),d?.addEventListener("click",()=>{Te(g()),i.classList.remove("show")})}return o.appendChild(this.chatArea()),e}chatArea(){let e=document.createElement("div");e.style.cssText="display: flex; flex-direction: column; flex: 1; overflow: hidden; position: relative;",e.innerHTML=`
1935
+ `;let t=e.querySelector(".bdb-chat-panel"),o=e.querySelector(".bdb-chat-title-container"),r=e.querySelector(".bdb-chat-header");if(r&&this.bubbleEl){let u=!1,g=0,b=0,h=0,m=0,x=parseInt(this.bubbleEl.style.left)||0,w=parseInt(this.bubbleEl.style.top)||0;r.addEventListener("pointerdown",y=>{y.target?.closest("button, a, input, textarea, select, [role='button']")||(u=!0,this.bubbleEl._didDrag=!1,g=y.clientX,b=y.clientY,x=parseInt(this.bubbleEl.style.left)||0,w=parseInt(this.bubbleEl.style.top)||0,h=x,m=w,this.bubbleEl.style.transition="none",r.setPointerCapture(y.pointerId))}),r.addEventListener("pointermove",y=>{if(!u)return;let v=y.clientX-g,k=y.clientY-b;Math.hypot(v,k)>4&&(this.bubbleEl._didDrag=!0),x=h+v,w=m+k,this.bubbleEl.style.left=x+"px",this.bubbleEl.style.top=w+"px",this.updatePanelPosition()});let p=y=>{if(!u)return;u=!1;try{r.releasePointerCapture(y.pointerId)}catch{}if(!this.bubbleEl._didDrag)return;let v=52,k=52,f=24,T=window.innerWidth,M=window.innerHeight,j=x+v/2,E=w+k/2,S=[{left:f,top:f},{left:(T-v)/2,top:f},{left:T-f-v,top:f},{left:f,top:(M-k)/2},{left:T-f-v,top:(M-k)/2},{left:f,top:M-f-k},{left:(T-v)/2,top:M-f-k},{left:T-f-v,top:M-f-k}],z=S[0],P=1/0;for(let Q of S){let ee=Math.hypot(Q.left+v/2-j,Q.top+k/2-E);ee<P&&(P=ee,z=Q)}x=z.left,w=z.top,this.bubbleEl.style.transition="left 0.4s cubic-bezier(0.2,0.8,0.2,1), top 0.4s cubic-bezier(0.2,0.8,0.2,1)",this.bubbleEl.style.left=x+"px",this.bubbleEl.style.top=w+"px",this.updatePanelPosition()};r.addEventListener("pointerup",p),r.addEventListener("pointercancel",p)}let a=t.querySelector("#bdb-header-menu"),s=t.querySelector(".js-more-btn");if(t.querySelector(".js-fullscreen-btn")?.addEventListener("click",()=>{this.store.getState().chat.mode===2?this.store.dispatch(L(1)):this.store.dispatch(L(2)),a?.classList.remove("show"),s?.setAttribute("aria-expanded","false")}),t.querySelector(".js-sessions-btn")?.addEventListener("click",()=>{a?.classList.remove("show"),s?.setAttribute("aria-expanded","false"),this.renderSessionList()}),t.querySelector(".js-close-btn")?.addEventListener("click",()=>{let u=this.store.getState().chat.mode;u===2?this.store.dispatch(L(1)):u===1&&this.store.dispatch(L(0))}),document.addEventListener("pointerdown",u=>{let g=this.store.getState().chat.mode;if(g===0||!this.chatUIEl)return;let b=u.composedPath(),h=t.querySelector(".bdb-chat-widget"),m=this.bubbleEl,x=this.root.querySelector(".bdb-upload-overlay");if(!(m&&b.includes(m))&&!(x&&b.includes(x))){if(!b.includes(t)){this.store.dispatch(L(0));return}g===2&&h&&!b.includes(h)&&this.store.dispatch(L(0))}},!0),this.logoUrl){let u=document.createElement("div"),g=document.createElement("img");g.src=this.logoUrl,g.style.cssText="width: 24px; height: 24px; margin-right: 0.5rem;",u.appendChild(g),o.prepend(u)}let i=a,l=t.querySelector("#js-download-md"),d=t.querySelector("#js-download-pdf"),c=t.querySelector("#js-download-json");if(s&&i){s.addEventListener("click",b=>{b.stopPropagation(),i.classList.toggle("show"),s.setAttribute("aria-expanded",i.classList.contains("show")?"true":"false")});let u=b=>{let h=b.composedPath();!h.includes(i)&&!h.includes(s)&&(i.classList.remove("show"),s.setAttribute("aria-expanded","false"))};this.root.addEventListener("click",u,!0),document.addEventListener("click",u,!0);let g=()=>{let b=this.store.getState(),h=b.chat.activeSession;return b.chatSessions[h]?.chatData||[]};l?.addEventListener("click",()=>{He(g(),this.getActiveSessionTitle()),i.classList.remove("show"),s.setAttribute("aria-expanded","false")}),d?.addEventListener("click",()=>{Pe(g(),this.getActiveSessionTitle()),i.classList.remove("show"),s.setAttribute("aria-expanded","false")}),c?.addEventListener("click",()=>{qe(g()),i.classList.remove("show"),s.setAttribute("aria-expanded","false")})}return this.syncPanelHeader(),this.renderSessionList(),e}sessionListLoadingView(){let e=document.createElement("div");return e.style.cssText="display: flex; align-items: center; justify-content: center; flex: 1; color: var(--muted-foreground); font-size: 13px; font-family: var(--font-body);",e.textContent="Loading chats...",e}sessionListView(){let e=document.createElement("div");e.style.cssText="display: flex; flex-direction: column; flex: 1; overflow: hidden;",e.innerHTML=`
1830
1936
  <style>
1831
- .bdb-scroll {
1832
- scrollbar-width: thin;
1833
- scrollbar-color: color-mix(in oklab, var(--foreground) 10%, transparent) transparent;
1834
- scroll-behavior: smooth;
1937
+ .bdb-session-list {
1938
+ display: flex;
1939
+ flex-direction: column;
1940
+ gap: 0.75rem;
1941
+ height: 100%;
1942
+ overflow-y: auto;
1943
+ padding: 1rem;
1944
+ box-sizing: border-box;
1945
+ }
1946
+
1947
+ .bdb-new-chat-btn,
1948
+ .bdb-session-item {
1949
+ width: 100%;
1950
+ border: 1px solid var(--border);
1951
+ border-radius: var(--radius-lg);
1952
+ background: color-mix(in oklab, var(--card) 92%, transparent);
1953
+ color: var(--foreground);
1954
+ font-family: var(--font-body);
1955
+ cursor: pointer;
1956
+ text-align: left;
1957
+ box-sizing: border-box;
1958
+ transition: border-color 0.15s, background 0.15s, transform 0.15s;
1959
+ }
1960
+
1961
+ .bdb-new-chat-btn:hover,
1962
+ .bdb-session-item:hover {
1963
+ border-color: color-mix(in oklab, var(--primary) 70%, var(--border));
1964
+ background: color-mix(in oklab, var(--primary) 10%, var(--card));
1965
+ transform: translateY(-1px);
1966
+ }
1967
+
1968
+ .bdb-new-chat-btn {
1969
+ display: flex;
1970
+ align-items: center;
1971
+ gap: 0.75rem;
1972
+ padding: 0.875rem 1rem;
1973
+ font-size: 14px;
1974
+ font-weight: 600;
1975
+ }
1976
+
1977
+ .bdb-new-chat-icon {
1978
+ display: inline-flex;
1979
+ align-items: center;
1980
+ justify-content: center;
1981
+ width: 32px;
1982
+ height: 32px;
1983
+ border-radius: var(--radius-md);
1984
+ background: var(--primary);
1985
+ color: var(--primary-foreground);
1986
+ flex-shrink: 0;
1987
+ }
1988
+
1989
+ .bdb-session-item {
1990
+ display: flex;
1991
+ gap: 0.75rem;
1992
+ padding: 0.875rem;
1993
+ }
1994
+
1995
+ .bdb-session-avatar {
1996
+ display: inline-flex;
1997
+ align-items: center;
1998
+ justify-content: center;
1999
+ width: 34px;
2000
+ height: 34px;
2001
+ border-radius: var(--radius-md);
2002
+ background: color-mix(in oklab, var(--foreground) 8%, transparent);
2003
+ color: var(--muted-foreground);
2004
+ flex-shrink: 0;
2005
+ }
2006
+
2007
+ .bdb-session-content {
2008
+ min-width: 0;
2009
+ flex: 1;
2010
+ }
2011
+
2012
+ .bdb-session-title {
2013
+ margin: 0;
2014
+ color: var(--foreground);
2015
+ font-size: 14px;
2016
+ font-weight: 600;
2017
+ line-height: 1.35;
2018
+ overflow: hidden;
2019
+ text-overflow: ellipsis;
2020
+ white-space: nowrap;
2021
+ }
2022
+
2023
+ .bdb-session-meta {
2024
+ margin: 0.25rem 0 0;
2025
+ color: var(--muted-foreground);
2026
+ font-size: 12px;
2027
+ line-height: 1.35;
2028
+ }
2029
+
2030
+ .bdb-session-empty {
2031
+ display: flex;
2032
+ flex-direction: column;
2033
+ align-items: center;
2034
+ justify-content: center;
2035
+ min-height: 160px;
2036
+ padding: 1rem;
2037
+ color: var(--muted-foreground);
2038
+ text-align: center;
2039
+ font-size: 13px;
2040
+ line-height: 1.5;
1835
2041
  }
2042
+
2043
+ .bdb-session-items {
2044
+ display: flex;
2045
+ flex-direction: column;
2046
+ gap: 0.75rem;
2047
+ }
2048
+ </style>
1836
2049
 
1837
- .bdb-scroll:hover {
1838
- scrollbar-color: color-mix(in oklab, var(--foreground) 18%, transparent) transparent;
2050
+ <div class="bdb-session-list bdb-scroll">
2051
+ <button class="bdb-new-chat-btn" type="button">
2052
+ <span class="bdb-new-chat-icon">
2053
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
2054
+ <path d="M12 5v14"></path>
2055
+ <path d="M5 12h14"></path>
2056
+ </svg>
2057
+ </span>
2058
+ <span>New chat</span>
2059
+ </button>
2060
+ <div class="bdb-session-items"></div>
2061
+ </div>
2062
+ `;let t=e.querySelector(".bdb-session-items"),r=(this.store.getState().chat?.sessions||[])?.map(a=>{try{return JSON.parse(a?.session)}catch{return null}})?.filter(Boolean)?.sort((a,s)=>Number(s?.create_time)-Number(a?.create_time));if(r.length===0){let a=document.createElement("div");a.className="bdb-session-empty",a.textContent="No saved chats yet. Start a new chat to begin.",t.appendChild(a)}for(let a of r){let s=a?.sessionid,i=document.createElement("button");i.type="button",i.className="bdb-session-item",i.innerHTML=`
2063
+ <span class="bdb-session-avatar">
2064
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
2065
+ <path d="M21 15a2 2 0 0 1-2 2H8l-5 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
2066
+ </svg>
2067
+ </span>
2068
+ <span class="bdb-session-content">
2069
+ <p class="bdb-session-title"></p>
2070
+ <p class="bdb-session-meta"></p>
2071
+ </span>
2072
+ `,i.querySelector(".bdb-session-title").textContent=this.getSessionTitle(s,a),i.querySelector(".bdb-session-meta").textContent=`Created at ${Yt(a?.create_time/1e3).format("DD MMM YYYY, hh:mm A")}`,i.addEventListener("click",()=>this.openSession(s)),t.appendChild(i)}return e.querySelector(".bdb-new-chat-btn")?.addEventListener("click",async()=>await this.createNewSession()),e}chatArea(){let e=document.createElement("div");e.style.cssText="display: flex; flex-direction: column; flex: 1; overflow: hidden; position: relative;",e.innerHTML=`
2073
+ <style>
2074
+ .bdb-scroll {
2075
+ scroll-behavior: smooth;
1839
2076
  }
1840
2077
 
1841
2078
  .bdb-empty-state {
@@ -1952,7 +2189,16 @@ ${a}
1952
2189
  <div class="bdb-scroll" id="bangdb-chat-area"
1953
2190
  style="height: 100%; overflow-x: hidden; overflow-y: auto; padding: 1rem 1.25rem; display: flex; flex-direction: column; width: 100%; box-sizing: border-box;">
1954
2191
 
1955
- <div style="width: 100%; display: flex; flex-direction: column; gap: 0.25rem; flex: 1; box-sizing: border-box;">
2192
+ <div style="
2193
+ width: 100%;
2194
+ max-width: 900px;
2195
+ margin: 0 auto;
2196
+ display: flex;
2197
+ flex-direction: column;
2198
+ gap: 0.25rem;
2199
+ flex: 1;
2200
+ box-sizing: border-box;
2201
+ ">
1956
2202
  <div class="bdb-empty-state" id="bdb-empty-state">
1957
2203
  <div class="bdb-empty-icon">
1958
2204
  <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
@@ -1963,7 +2209,13 @@ ${a}
1963
2209
  <p class="bdb-empty-sub">Ask me anything. I'm here to assist.</p>
1964
2210
  </div>
1965
2211
 
1966
- <div class="chat-data-container" style="display: flex; flex-direction: column; gap: 0.25rem; flex: 1;">
2212
+ <div class="chat-data-container" style="
2213
+ display: flex;
2214
+ flex-direction: column;
2215
+ gap: 0.375rem;
2216
+ flex: 1;
2217
+ width: 100%;
2218
+ ">
1967
2219
  <div id="chat-window-anchor" style="overflow-anchor: auto; height: 1px;"></div>
1968
2220
  </div>
1969
2221
  </div>
@@ -2014,7 +2266,21 @@ ${a}
2014
2266
  </div>
2015
2267
  <span>Thinking\u2026</span>
2016
2268
  </div>
2017
- `,e}userRequestMessage(e){let t=document.createElement("div");t.style.cssText="display: flex; justify-content: flex-end; margin-block: 0.375rem;",t.innerHTML=`
2269
+ `,e}formatFileSize(e){if(!e)return"0 B";let t=["B","KB","MB","GB"],o=e,r=0;for(;o>=1024&&r<t.length-1;)o=o/1024,r++;return`${o>=10||r===0?o.toFixed(0):o.toFixed(1)} ${t[r]}`}getFileIconMarkup(e){let t;switch(e){case"text/plain":t="/icons/document.svg";break;case"text/csv":case"application/csv":case"application/vnd.ms-excel":case"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":case"application/vnd.ms-excel.sheet.macroEnabled.12":case"application/vnd.openxmlformats-officedocument.spreadsheetml.template":case"application/vnd.ms-excel.template.macroEnabled.12":case"application/vnd.ms-excel.sheet.binary.macroEnabled.12":case"application/vnd.oasis.opendocument.spreadsheet":case"application/vnd.google-apps.spreadsheet":t=Be;break;case"application/vnd.openxmlformats-officedocument.wordprocessingml.document":case"application/msword":t=Re;break;case"application/pdf":t=_e;break;case"application/json":t=Ye;break;default:t=$e;break}return`
2270
+ <img width="30" height="30" src="${t}" />
2271
+ `}getFileStatusText(e){switch(e.status){case"uploading":return"Uploading...";case"embedding":return"Embedding...";case"downloading":return"Downloading...";case"done":return"Ready";case"error":return e.error||"Failed";default:return"Pending"}}isFileBusy(e){return["uploading","embedding","downloading"].includes(e.status)}getUploadAcceptValue(){return Object.entries(this.allowedUploadFileTypes).flatMap(([e,t])=>[e,...t]).join(",")}isAllowedUploadFile(e){let t="."+(e.name.split(".").pop()||"").toLowerCase();return!!this.allowedUploadFileTypes[e.type]?.includes(t)}createFileCard(e,t){let o=document.createElement("div");return o.className="bdb-file-card",o.innerHTML=`
2272
+ <div class="bdb-file-icon">${this.getFileIconMarkup(e.type)}</div>
2273
+ <div class="bdb-file-meta">
2274
+ <div class="bdb-file-name"></div>
2275
+ <div class="bdb-file-detail">
2276
+ ${this.isFileBusy(e)?'<span class="bdb-file-spinner" aria-hidden="true"></span>':""}
2277
+ <span class="bdb-file-detail-text"></span>
2278
+ </div>
2279
+ </div>
2280
+ ${t?.removable?`<button class="bdb-file-remove" type="button" aria-label="Remove file">
2281
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
2282
+ </button>`:""}
2283
+ `,o.querySelector(".bdb-file-name").textContent=decodeURIComponent(e.name),e.error&&o.classList.add("has-error"),o.querySelector(".bdb-file-detail-text").textContent=[this.formatFileSize(e.sizeBytes),this.getFileStatusText(e)].filter(Boolean).join(" - "),o.querySelector(".bdb-file-remove")?.addEventListener("click",r=>{r.stopPropagation(),t?.onRemove?.(e)}),t?.compact&&o.classList.add("is-compact"),o}userRequestMessage(e,t,o){let r=document.createElement("div");r.style.cssText="display: flex; justify-content: flex-end; margin-block: 0.375rem;",r.innerHTML=`
2018
2284
  <style>
2019
2285
  .bdb-user-stack {
2020
2286
  display: inline-flex;
@@ -2025,9 +2291,10 @@ ${a}
2025
2291
  }
2026
2292
 
2027
2293
  .bdb-user-bubble {
2028
- width: fit-content;
2029
- max-width: 100%;
2030
- background: var(--secondary);
2294
+ display: none;
2295
+ width: fit-content;
2296
+ max-width: 100%;
2297
+ background: var(--secondary);
2031
2298
  color: var(--secondary-foreground);
2032
2299
  border-radius: 18px 18px 4px 18px;
2033
2300
  padding: 0.6rem 1rem;
@@ -2050,15 +2317,102 @@ ${a}
2050
2317
  /* mimic action bar button baseline spacing */
2051
2318
  transform: translateY(-2px);
2052
2319
  }
2320
+
2321
+ .bdb-user-files {
2322
+ display: flex;
2323
+ flex-wrap: wrap;
2324
+ justify-content: flex-end;
2325
+ gap: 0.5rem;
2326
+ max-width: 100%;
2327
+ }
2328
+
2329
+ .bdb-file-card {
2330
+ display: flex;
2331
+ align-items: center;
2332
+ gap: 0.5rem;
2333
+ min-width: 180px;
2334
+ max-width: 260px;
2335
+ padding: 0.5rem 0.625rem;
2336
+ border: 1px solid var(--border);
2337
+ border-radius: var(--radius-md);
2338
+ background: color-mix(in oklab, var(--card) 82%, var(--foreground) 4%);
2339
+ color: var(--foreground);
2340
+ box-sizing: border-box;
2341
+ }
2342
+
2343
+ .bdb-file-card.has-error {
2344
+ border-color: #ef4444;
2345
+ color: #fca5a5;
2346
+ }
2347
+
2348
+ .bdb-file-icon {
2349
+ display: flex;
2350
+ align-items: center;
2351
+ justify-content: center;
2352
+ width: 34px;
2353
+ height: 34px;
2354
+ flex-shrink: 0;
2355
+ }
2356
+
2357
+ .bdb-file-icon svg {
2358
+ display: block;
2359
+ width: 34px;
2360
+ height: 34px;
2361
+ }
2362
+
2363
+ .bdb-file-meta {
2364
+ min-width: 0;
2365
+ flex: 1;
2366
+ }
2367
+
2368
+ .bdb-file-name {
2369
+ overflow: hidden;
2370
+ text-overflow: ellipsis;
2371
+ white-space: nowrap;
2372
+ font-size: 13px;
2373
+ font-weight: 600;
2374
+ }
2375
+
2376
+ .bdb-file-detail {
2377
+ display: flex;
2378
+ align-items: center;
2379
+ gap: 0.25rem;
2380
+ min-width: 0;
2381
+ color: var(--muted-foreground);
2382
+ font-size: 11px;
2383
+ margin-top: 0.125rem;
2384
+ }
2385
+
2386
+ .bdb-file-detail-text {
2387
+ overflow: hidden;
2388
+ text-overflow: ellipsis;
2389
+ white-space: nowrap;
2390
+ min-width: 0;
2391
+ }
2392
+
2393
+ .bdb-file-spinner {
2394
+ width: 11px;
2395
+ height: 11px;
2396
+ border-radius: var(--radius-full);
2397
+ border: 2px solid color-mix(in oklab, var(--muted-foreground) 35%, transparent);
2398
+ border-top-color: var(--primary);
2399
+ flex-shrink: 0;
2400
+ animation: bdb-file-spin 0.8s linear infinite;
2401
+ }
2402
+
2403
+ @keyframes bdb-file-spin {
2404
+ to { transform: rotate(360deg); }
2405
+ }
2053
2406
  </style>
2054
2407
 
2055
2408
  <div class="bdb-user-stack">
2409
+ <div class="bdb-user-files"></div>
2056
2410
  <div class="bdb-user-bubble"></div>
2057
2411
  <div class="bdb-user-actionbar"></div>
2058
2412
  </div>
2059
- `,t.querySelector(".bdb-user-bubble").textContent=e;let o=t.querySelector(".bdb-user-actionbar"),r=O(D,"Copy to clipboard");return r.addEventListener("click",async()=>{try{await navigator.clipboard.writeText(e),r.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>',r.style.color="var(--primary)",r.style.borderColor="var(--primary)",setTimeout(()=>{r.innerHTML=D,r.style.color="",r.style.borderColor=""},2e3)}catch{}}),o.appendChild(r),t}aiResponseMessage(e){let t=document.createElement("div");t.style.cssText="display: flex; gap: 0.625rem; align-items: flex-start; margin-block: 0.375rem;";let o=document.createElement("style");o.textContent=`
2060
- ${W}
2061
- ${Y}
2413
+ `;let a=r.querySelector(".bdb-user-files");if(t?.length){for(let d of t)a.appendChild(this.createFileCard(d));if(o||t[0]?.metadata?.index_time_sec){let d=document.createElement("div");d.style.cssText="width:100%;text-align:right;font-size:11px;color:var(--muted-foreground);",d.textContent=t[0]?.metadata?.index_time_sec?`DB took ${t[0].metadata.index_time_sec} seconds to finish indexing.`:"",a.appendChild(d)}}else a.style.display="none";let s=r.querySelector(".bdb-user-bubble"),i=r.querySelector(".bdb-user-actionbar");if(!e)return i.style.display="none",r;s.style.display="block",s.textContent=e;let l=F(H,"Copy to clipboard");return l.addEventListener("click",async()=>{try{await navigator.clipboard.writeText(e),l.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>',l.style.color="var(--primary)",l.style.borderColor="var(--primary)",setTimeout(()=>{l.innerHTML=H,l.style.color="",l.style.borderColor=""},2e3)}catch{}}),i.appendChild(l),r}aiResponseMessage(e){let t=document.createElement("div");t.style.cssText="display: flex; gap: 0.625rem; align-items: flex-start; margin-block: 0.375rem;";let o=document.createElement("style");o.textContent=`
2414
+ ${oe}
2415
+ ${te}
2062
2416
 
2063
2417
  .ai-md pre {
2064
2418
  padding: 1rem;
@@ -2068,7 +2422,8 @@ ${a}
2068
2422
 
2069
2423
  /* Bubble wrapper \u2014 flex column so charts + action bar stack below text */
2070
2424
  .bdb-ai-bubble {
2071
- flex: 1;
2425
+ width: fit-content;
2426
+ max-width: 100%;
2072
2427
  min-width: 0;
2073
2428
  padding: 0.5rem 0;
2074
2429
  font-size: 14px;
@@ -2083,20 +2438,359 @@ ${a}
2083
2438
  from { opacity: 0; transform: translateY(4px); }
2084
2439
  to { opacity: 1; transform: translateY(0); }
2085
2440
  }
2086
- `,t.appendChild(o);let r=document.createElement("div");r.className="bdb-ai-bubble",t.appendChild(r);let a=document.createElement("div");a.className="ai-md prose",r.appendChild(a);let s=new S(e),{messages:i}=s.parse(),c=i.map(m=>m?.output??"").join("");a.innerHTML=H(c),this.renderSourceTags(a,e);let p=e?._data??e?.a?._data;if(p){let m=ue(String(p));m.children.length>0&&r.appendChild(m)}let d=i.map(m=>m?.output??"").join(`
2441
+ `,t.appendChild(o);let r=document.createElement("div");r.className="bdb-ai-bubble",t.appendChild(r);let a=document.createElement("div");a.className="ai-md prose",r.appendChild(a);let s=new I(e),{messages:i}=s.parse(),l=i.map(m=>m?.output??"").join("");a.innerHTML=U(l),this.renderSourceTags(a,e);let d=e?._data??e?.a?._data;if(d){let m=De(String(d));m.children.length>0&&(r.style.width="100%",r.appendChild(m))}let c=i.map(m=>m?.output??"").join(`
2087
2442
 
2088
- `),l=e?.a?.usage??null,g=this.apiConfig?.indexName??"",h=this.root,b=ye({textToCopy:d,queryTimeMs:e?.queryTime,usageData:l,onInfo:()=>{let m=h.querySelector(".bdb-context-drawer-host");if(m){m.remove();return}let u=document.createElement("div");u.className="bdb-context-drawer-host";let y=xe({item:e,indexName:g,shadowRoot:h,onClose:()=>u.remove()});u.appendChild(y),h.appendChild(u)}});return r.appendChild(b),t}async renderSourceTags(e,t){let o=e.querySelectorAll("source-tag");if(!o.length)return;let r=t?.a?.metadata||t?.metadata||[];for(let a of o){let s=a.getAttribute("data-source-id"),i=a.getAttribute("data-category");if(!s||s.toLowerCase()==="na"){a.remove();continue}let c=document.createElement("span");c.style.cssText="display: block; padding: 0.75rem 0;";let p=s.split("##"),d=p[1]??s,l=p[2],g=document.createElement("span");if(g.style.cssText="display: block; font-size: 12px; color: var(--accent-foreground); padding-bottom: 0.5rem;",g.innerHTML=`
2443
+ `),u=e?.a?.usage??null,g=this.apiConfig?.indexName??"",b=this.root,h=ze({textToCopy:c,queryTimeMs:e?.queryTime,usageData:u,onInfo:()=>{let m=b.querySelector(".bdb-context-drawer-host");if(m){m.remove();return}let x=document.createElement("div");x.className="bdb-context-drawer-host";let w=Oe({item:e,indexName:g,shadowRoot:b,onClose:()=>x.remove()});x.appendChild(w),b.appendChild(x)}});return r.appendChild(h),t}async renderSourceTags(e,t){let o=e.querySelectorAll("source-tag");if(!o.length)return;let r=t?.a?.metadata||t?.metadata||[];for(let a of o){let s=a.getAttribute("data-source-id"),i=a.getAttribute("data-category");if(!s||s.toLowerCase()==="na"){a.remove();continue}let l=document.createElement("span");l.style.cssText="display: block; padding: 0.75rem 0;";let d=s.split("##"),c=d[1]??s,u=d[2],g=document.createElement("span");if(g.style.cssText="display: block; font-size: 12px; color: var(--accent-foreground); padding-bottom: 0.5rem;",g.innerHTML=`
2089
2444
  <span style="text-decoration: underline; color: var(--accent-foreground);">
2090
- Source: ${decodeURIComponent(d)}
2091
- ${l?`<span style="padding: 0 0.5rem;">|</span>Page: ${l}`:""}
2445
+ Source: ${decodeURIComponent(c)}
2446
+ ${u?`<span style="padding: 0 0.5rem;">|</span>Page: ${u}`:""}
2092
2447
  </span>
2093
2448
  ${i?`<span style="padding: 0 0.5rem;">|</span>Category: ${i}`:""}
2094
- `,c.appendChild(g),r.length>0){let h=r.find(b=>b?.source_id===s);h?.table_ids?.length&&await this.renderTables(c,h.table_ids),h?.image_ids?.length&&await this.renderImages(c,h.image_ids)}a.replaceWith(c)}}async renderTables(e,t){for(let o of t){let r=document.createElement("div");r.innerHTML=`<div style="display:grid;grid-template-columns:repeat(9,1fr);gap:2px;">
2449
+ `,l.appendChild(g),r.length>0){let b=r.find(h=>h?.source_id===s);b?.table_ids?.length&&await this.renderTables(l,b.table_ids),b?.image_ids?.length&&await this.renderImages(l,b.image_ids)}a.replaceWith(l)}}async renderTables(e,t){for(let o of t){let r=document.createElement("div");r.innerHTML=`<div style="display:grid;grid-template-columns:repeat(9,1fr);gap:2px;">
2095
2450
  ${Array.from({length:36}).map(()=>'<div style="height:2rem;background:rgba(255,255,255,0.05);border-radius:2px;"></div>').join("")}
2096
- </div>`,e.appendChild(r);try{let a=await _({baseURL:this.apiConfig.backendURL,apikey:this.apiConfig.apikey,payload:{name:this.apiConfig.indexName,type:"table",id:o}});a?.metadata?.text_as_html&&(r.innerHTML=`<div style="overflow-x:auto;margin-bottom:1rem;">${a.metadata.text_as_html}</div>`)}catch{r.innerHTML='<div style="color:#f87171;font-size:12px;margin-bottom:0.5rem;">Failed to load table</div>'}}}async renderImages(e,t){let o=document.createElement("div");o.style.cssText="display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 0.75rem; margin-top: 0.5rem;",e.appendChild(o);let{backendURL:r,resourceURL:a,apikey:s,indexName:i}=this.apiConfig,c=`${i}_img_bucket`;for(let p of t){let d=document.createElement("div");d.style.cssText="border-radius: 8px; overflow: hidden; border: 1px solid rgba(255,255,255,0.08); background: rgba(255,255,255,0.03);",d.innerHTML='<div style="height: 8rem; background: rgba(255,255,255,0.05); display:flex; align-items:center; justify-content:center; color: #71717a; font-size:12px;">Loading\u2026</div>',o.appendChild(d);try{let l=await _({baseURL:r,apikey:s,payload:{name:i,type:"image",id:p}});if(!l?.file_name){d.remove();continue}let g=`https://${a}/brs/get/${s}/${c}/${p}_${l.file_name}`;d.innerHTML=`
2451
+ </div>`,e.appendChild(r);try{let a=await V({baseURL:this.apiConfig.backendURL,apikey:this.apiConfig.apikey,payload:{name:this.apiConfig.indexName,type:"table",id:o}});a?.metadata?.text_as_html&&(r.innerHTML=`<div style="overflow-x:auto;margin-bottom:1rem;">${a.metadata.text_as_html}</div>`)}catch{r.innerHTML='<div style="color:#f87171;font-size:12px;margin-bottom:0.5rem;">Failed to load table</div>'}}}async renderImages(e,t){let o=document.createElement("div");o.style.cssText="display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 0.75rem; margin-top: 0.5rem;",e.appendChild(o);let{backendURL:r,resourceURL:a,apikey:s,indexName:i}=this.apiConfig,l=`${i}_img_bucket`;for(let d of t){let c=document.createElement("div");c.style.cssText="border-radius: 8px; overflow: hidden; border: 1px solid rgba(255,255,255,0.08); background: rgba(255,255,255,0.03);",c.innerHTML='<div style="height: 8rem; background: rgba(255,255,255,0.05); display:flex; align-items:center; justify-content:center; color: #71717a; font-size:12px;">Loading\u2026</div>',o.appendChild(c);try{let u=await V({baseURL:r,apikey:s,payload:{name:i,type:"image",id:d}});if(!u?.file_name){c.remove();continue}let g=`https://${a}/brs/get/${s}/${l}/${d}_${u.file_name}`;c.innerHTML=`
2097
2452
  <div style="height:8rem; background-image:url('${g}'); background-size:cover; background-position:center; cursor:pointer;"></div>
2098
- <div style="padding:0.375rem 0.5rem; font-size:11px; color:#a1a1aa; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">${l.file_name}</div>
2099
- `,d.querySelector("div")?.addEventListener("click",()=>{let h=document.createElement("div");h.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.9);z-index:9999999;display:flex;align-items:center;justify-content:center;cursor:zoom-out;",h.innerHTML=`<img src="${g}" alt="image" style="max-width:90vw;max-height:90vh;border-radius:8px;object-fit:contain;" />`,h.addEventListener("click",()=>h.remove()),document.body.appendChild(h)})}catch{d.remove()}}}chatQueryForm(){let e=document.createElement("div");e.innerHTML=`
2453
+ <div style="padding:0.375rem 0.5rem; font-size:11px; color:#a1a1aa; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">${u.file_name}</div>
2454
+ `,c.querySelector("div")?.addEventListener("click",()=>{let b=document.createElement("div");b.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.9);z-index:9999999;display:flex;align-items:center;justify-content:center;cursor:zoom-out;",b.innerHTML=`<img src="${g}" alt="image" style="max-width:90vw;max-height:90vh;border-radius:8px;object-fit:contain;" />`,b.addEventListener("click",()=>b.remove()),document.body.appendChild(b)})}catch{c.remove()}}}openFileUploadModal(e,t){let o=new Map,r=e.map(p=>({...p,metadata:{...p.metadata||{}}})),a="",s=document.createElement("div");s.innerHTML=`
2455
+ <style>
2456
+ .bdb-upload-overlay {
2457
+ position: fixed;
2458
+ inset: 0;
2459
+ z-index: 999999;
2460
+ display: flex;
2461
+ align-items: center;
2462
+ justify-content: center;
2463
+ padding: 1rem;
2464
+ background: rgba(0,0,0,0.58);
2465
+ backdrop-filter: blur(6px);
2466
+ box-sizing: border-box;
2467
+ }
2468
+
2469
+ .bdb-upload-modal {
2470
+ width: min(860px, 96vw);
2471
+ max-height: min(720px, 92vh);
2472
+ display: grid;
2473
+ grid-template-rows: auto 1fr auto;
2474
+ overflow: hidden;
2475
+ border: 1px solid var(--border);
2476
+ border-radius: var(--radius-lg);
2477
+ background: var(--card);
2478
+ color: var(--foreground);
2479
+ box-shadow: var(--shadow-panel);
2480
+ font-family: var(--font-body);
2481
+ }
2482
+
2483
+ .bdb-upload-header,
2484
+ .bdb-upload-footer {
2485
+ display: flex;
2486
+ align-items: center;
2487
+ justify-content: space-between;
2488
+ gap: 1rem;
2489
+ padding: 0.875rem 1rem;
2490
+ border-bottom: 1px solid var(--border);
2491
+ }
2492
+
2493
+ .bdb-upload-footer {
2494
+ border-top: 1px solid var(--border);
2495
+ border-bottom: 0;
2496
+ justify-content: flex-end;
2497
+ }
2498
+
2499
+ .bdb-upload-title {
2500
+ margin: 0;
2501
+ font-size: 15px;
2502
+ font-weight: 700;
2503
+ }
2504
+
2505
+ .bdb-upload-subtitle {
2506
+ margin: 0.125rem 0 0;
2507
+ color: var(--muted-foreground);
2508
+ font-size: 12px;
2509
+ }
2510
+
2511
+ .bdb-upload-body {
2512
+ min-height: 0;
2513
+ display: grid;
2514
+ grid-template-columns: minmax(280px, 0.8fr) minmax(320px, 1.2fr);
2515
+ gap: 0;
2516
+ overflow: hidden;
2517
+ }
2518
+
2519
+ .bdb-upload-dropzone {
2520
+ display: flex;
2521
+ flex-direction: column;
2522
+ align-items: center;
2523
+ justify-content: center;
2524
+ gap: 0.75rem;
2525
+ min-height: 360px;
2526
+ padding: 1.5rem;
2527
+ border-right: 1px solid var(--border);
2528
+ background: color-mix(in oklab, var(--muted) 55%, transparent);
2529
+ text-align: center;
2530
+ cursor: pointer;
2531
+ transition: background 0.15s, outline-color 0.15s;
2532
+ }
2533
+
2534
+ .bdb-upload-dropzone.is-dragging {
2535
+ outline: 2px dashed var(--primary);
2536
+ outline-offset: -12px;
2537
+ background: color-mix(in oklab, var(--primary) 10%, var(--muted));
2538
+ }
2539
+
2540
+ .bdb-upload-dropzone svg {
2541
+ color: var(--primary);
2542
+ }
2543
+
2544
+ .bdb-upload-dropzone strong {
2545
+ font-size: 15px;
2546
+ }
2547
+
2548
+ .bdb-upload-dropzone span {
2549
+ max-width: 260px;
2550
+ color: var(--muted-foreground);
2551
+ font-size: 12px;
2552
+ line-height: 1.5;
2553
+ }
2554
+
2555
+ .bdb-upload-list {
2556
+ min-height: 0;
2557
+ overflow-y: auto;
2558
+ padding: 0.5rem 0;
2559
+ }
2560
+
2561
+ .bdb-upload-empty {
2562
+ height: 100%;
2563
+ display: flex;
2564
+ align-items: center;
2565
+ justify-content: center;
2566
+ padding: 2rem;
2567
+ color: var(--muted-foreground);
2568
+ font-size: 13px;
2569
+ text-align: center;
2570
+ }
2571
+
2572
+ .bdb-upload-error {
2573
+ margin: 0.625rem 1rem 0;
2574
+ padding: 0.5rem 0.625rem;
2575
+ border: 1px solid color-mix(in oklab, #ef4444 65%, transparent);
2576
+ border-radius: var(--radius-sm);
2577
+ color: #fca5a5;
2578
+ background: color-mix(in oklab, #ef4444 12%, transparent);
2579
+ font-size: 12px;
2580
+ line-height: 1.4;
2581
+ }
2582
+
2583
+ .bdb-upload-row {
2584
+ border-bottom: 1px solid var(--border);
2585
+ padding: 0.75rem 1rem;
2586
+ }
2587
+
2588
+ .bdb-upload-row-head {
2589
+ display: flex;
2590
+ align-items: center;
2591
+ gap: 0.625rem;
2592
+ }
2593
+
2594
+ .bdb-upload-row-meta {
2595
+ min-width: 0;
2596
+ flex: 1;
2597
+ }
2598
+
2599
+ .bdb-upload-row-name {
2600
+ overflow: hidden;
2601
+ text-overflow: ellipsis;
2602
+ white-space: nowrap;
2603
+ font-size: 13px;
2604
+ font-weight: 700;
2605
+ }
2606
+
2607
+ .bdb-upload-row-size {
2608
+ color: var(--muted-foreground);
2609
+ font-size: 11px;
2610
+ margin-top: 0.125rem;
2611
+ }
2612
+
2613
+ .bdb-upload-fields {
2614
+ display: grid;
2615
+ gap: 0.5rem;
2616
+ margin-top: 0.75rem;
2617
+ }
2618
+
2619
+ .bdb-upload-fields label {
2620
+ display: grid;
2621
+ gap: 0.25rem;
2622
+ color: var(--muted-foreground);
2623
+ font-size: 11px;
2624
+ }
2625
+
2626
+ .bdb-upload-input,
2627
+ .bdb-upload-textarea {
2628
+ width: 100%;
2629
+ box-sizing: border-box;
2630
+ border: 1px solid var(--border);
2631
+ border-radius: var(--radius-sm);
2632
+ background: color-mix(in oklab, var(--background) 45%, transparent);
2633
+ color: var(--foreground);
2634
+ font: inherit;
2635
+ font-size: 12px;
2636
+ outline: none;
2637
+ padding: 0.45rem 0.55rem;
2638
+ }
2639
+
2640
+ .bdb-upload-textarea {
2641
+ resize: vertical;
2642
+ min-height: 58px;
2643
+ }
2644
+
2645
+ .bdb-upload-access {
2646
+ display: none;
2647
+ grid-template-columns: 1fr 1fr;
2648
+ gap: 0.5rem;
2649
+ }
2650
+
2651
+ .bdb-upload-check {
2652
+ display: flex !important;
2653
+ grid-template-columns: none !important;
2654
+ align-items: center;
2655
+ gap: 0.5rem !important;
2656
+ }
2657
+
2658
+ .bdb-upload-btn {
2659
+ display: inline-flex;
2660
+ align-items: center;
2661
+ justify-content: center;
2662
+ gap: 0.375rem;
2663
+ height: 34px;
2664
+ padding: 0 0.875rem;
2665
+ border-radius: var(--radius-md);
2666
+ border: 1px solid var(--border);
2667
+ background: transparent;
2668
+ color: var(--foreground);
2669
+ cursor: pointer;
2670
+ font-family: var(--font-body);
2671
+ font-size: 13px;
2672
+ font-weight: 600;
2673
+ }
2674
+
2675
+ .bdb-upload-btn.primary {
2676
+ border-color: var(--primary);
2677
+ background: var(--primary);
2678
+ color: var(--primary-foreground);
2679
+ }
2680
+
2681
+ .bdb-upload-btn:disabled {
2682
+ opacity: 0.45;
2683
+ cursor: not-allowed;
2684
+ }
2685
+
2686
+ .bdb-upload-icon {
2687
+ display: flex;
2688
+ align-items: center;
2689
+ justify-content: center;
2690
+ width: 34px;
2691
+ height: 34px;
2692
+ border-radius: var(--radius-sm);
2693
+ background: color-mix(in oklab, var(--primary) 14%, transparent);
2694
+ color: var(--primary);
2695
+ font-size: 9px;
2696
+ font-weight: 700;
2697
+ flex-shrink: 0;
2698
+ }
2699
+
2700
+ .bdb-upload-remove {
2701
+ display: flex;
2702
+ align-items: center;
2703
+ justify-content: center;
2704
+ width: 28px;
2705
+ height: 28px;
2706
+ border: none;
2707
+ border-radius: var(--radius-full);
2708
+ background: transparent;
2709
+ color: var(--muted-foreground);
2710
+ cursor: pointer;
2711
+ }
2712
+
2713
+ .bdb-upload-remove:hover {
2714
+ color: var(--foreground);
2715
+ background: color-mix(in oklab, var(--foreground) 8%, transparent);
2716
+ }
2717
+
2718
+ @media (max-width: 720px) {
2719
+ .bdb-upload-body {
2720
+ grid-template-columns: 1fr;
2721
+ }
2722
+
2723
+ .bdb-upload-dropzone {
2724
+ min-height: 180px;
2725
+ border-right: 0;
2726
+ border-bottom: 1px solid var(--border);
2727
+ }
2728
+
2729
+ .bdb-upload-access {
2730
+ grid-template-columns: 1fr;
2731
+ }
2732
+ }
2733
+ </style>
2734
+
2735
+ <div class="bdb-upload-overlay" role="dialog" aria-modal="true" aria-labelledby="bdb-upload-title">
2736
+ <div class="bdb-upload-modal">
2737
+ <div class="bdb-upload-header">
2738
+ <div>
2739
+ <h2 class="bdb-upload-title" id="bdb-upload-title">Upload files</h2>
2740
+ <p class="bdb-upload-subtitle">Attach files now. They upload only when you send the message.</p>
2741
+ </div>
2742
+ <button class="bdb-upload-btn" type="button" id="bdb-upload-close" aria-label="Close upload dialog">
2743
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
2744
+ </button>
2745
+ </div>
2746
+
2747
+ <div class="bdb-upload-body">
2748
+ <div class="bdb-upload-dropzone" id="bdb-upload-dropzone">
2749
+ <input id="bdb-upload-input" type="file" multiple hidden accept="${this.getUploadAcceptValue()}" />
2750
+ <svg width="96" height="96" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M12 13V3"/><path d="m8 7 4-4 4 4"/><path d="M20 17.5A2.5 2.5 0 0 1 17.5 20h-11A2.5 2.5 0 0 1 4 17.5V15"/></svg>
2751
+ <strong>Drag and drop files</strong>
2752
+ <span>Drop files here or browse from your computer. You can review metadata before confirming.</span>
2753
+ <button class="bdb-upload-btn primary" type="button" id="bdb-upload-browse">Browse files</button>
2754
+ </div>
2755
+
2756
+ <div class="bdb-upload-list" id="bdb-upload-list"></div>
2757
+ </div>
2758
+
2759
+ <div class="bdb-upload-footer">
2760
+ <button class="bdb-upload-btn" type="button" id="bdb-upload-cancel">Cancel</button>
2761
+ <button class="bdb-upload-btn primary" type="button" id="bdb-upload-confirm">Done</button>
2762
+ </div>
2763
+ </div>
2764
+ </div>
2765
+ `;let i=()=>s.remove();s.addEventListener("click",p=>p.stopPropagation()),s.addEventListener("pointerdown",p=>p.stopPropagation());let l=s.querySelector("#bdb-upload-list"),d=s.querySelector("#bdb-upload-dropzone"),c=s.querySelector("#bdb-upload-input"),u=s.querySelector("#bdb-upload-confirm"),g=p=>p.split(",").map(y=>y.trim()).filter(Boolean),b=p=>{a=p},h=()=>{a=""},m=(p,y)=>{r=r.map(v=>v.id===p?{...v,metadata:{...v.metadata||{},...y}}:v)},x=()=>{if(u.disabled=r.length===0,l.innerHTML="",a){let p=document.createElement("div");p.className="bdb-upload-error",p.textContent=a,l.appendChild(p)}if(r.length===0){let p=document.createElement("div");p.className="bdb-upload-empty",p.textContent="No files selected yet.",l.appendChild(p);return}for(let p of r){let y=document.createElement("div");y.className="bdb-upload-row",y.innerHTML=`
2766
+ <div class="bdb-upload-row-head">
2767
+ <div class="bdb-upload-icon">${this.getFileIconMarkup(p.type)}</div>
2768
+ <div class="bdb-upload-row-meta">
2769
+ <div class="bdb-upload-row-name"></div>
2770
+ <div class="bdb-upload-row-size"></div>
2771
+ </div>
2772
+ <button class="bdb-upload-remove" type="button" aria-label="Remove file">
2773
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
2774
+ </button>
2775
+ </div>
2776
+ <div class="bdb-upload-fields">
2777
+ <label>
2778
+ Description
2779
+ <textarea class="bdb-upload-textarea js-description" placeholder="Optional context for this file"></textarea>
2780
+ </label>
2781
+ ${p.type==="application/pdf"?'<label class="bdb-upload-check"><input class="js-ocr" type="checkbox" /> OCR</label>':""}
2782
+ <div class="bdb-upload-access">
2783
+ <label>
2784
+ Groups
2785
+ <input class="bdb-upload-input js-groups" placeholder="group-a, group-b" />
2786
+ </label>
2787
+ <label>
2788
+ Users
2789
+ <input class="bdb-upload-input js-users" placeholder="user-a, user-b" />
2790
+ </label>
2791
+ </div>
2792
+ </div>
2793
+ `,y.querySelector(".bdb-upload-row-name").textContent=p.name,y.querySelector(".bdb-upload-row-size").textContent=this.formatFileSize(p.sizeBytes);let v=y.querySelector(".js-description");v.value=p.metadata?.description||"",v.addEventListener("input",()=>{m(p.id,{description:v.value})});let k=y.querySelector(".js-ocr");k&&(k.checked=p.metadata?.hi_res==="hi_res",k.addEventListener("change",()=>{m(p.id,{hi_res:k.checked?"hi_res":"auto"})}));let f=y.querySelector(".js-groups");f.value=(p.metadata?._g_||[]).join(", "),f.addEventListener("input",()=>{m(p.id,{_g_:g(f.value)})});let T=y.querySelector(".js-users");T.value=(p.metadata?._u_||[]).join(", "),T.addEventListener("input",()=>{m(p.id,{_u_:g(T.value)})}),y.querySelector(".bdb-upload-remove").addEventListener("click",()=>{r=r.filter(M=>M.id!==p.id),o.delete(p.id),x()}),l.appendChild(y)}},w=p=>{let y=Array.from(p),v=y.filter(f=>!this.isAllowedUploadFile(f)),k=y.filter(f=>this.isAllowedUploadFile(f));v.length>0?b(`${v.length} file${v.length===1?"":"s"} skipped. Supported files: PDF, TXT, Markdown, HTML, DOC, DOCX, CSV, JSON, XLS, XLSX.`):h();for(let f of k){if(r.some(E=>E.name===f.name))continue;let T=crypto.randomUUID(),M={};f.type==="text/csv"&&(M.input_format="CSV"),f.type==="application/json"&&(M.input_format="JSON");let j={id:T,name:f.name,type:f.type||"application/octet-stream",sizeBytes:f.size,status:"pending",metadata:M};o.set(T,f),r.push(j)}x()};s.querySelector("#bdb-upload-close").addEventListener("click",i),s.querySelector("#bdb-upload-cancel").addEventListener("click",i),s.querySelector("#bdb-upload-browse").addEventListener("click",()=>c.click()),c.addEventListener("change",()=>{c.files&&w(c.files),c.value=""}),d.addEventListener("dragover",p=>{p.preventDefault(),d.classList.add("is-dragging")}),d.addEventListener("dragleave",()=>{d.classList.remove("is-dragging")}),d.addEventListener("drop",p=>{p.preventDefault(),d.classList.remove("is-dragging"),p.dataTransfer?.files&&w(p.dataTransfer.files)}),s.querySelector("#bdb-upload-confirm").addEventListener("click",()=>{t(r,o),i()}),this.root.appendChild(s),x()}chatQueryForm(){let e=document.createElement("div");e.innerHTML=`
2100
2794
  <style>
2101
2795
  .bdb-form-wrap {
2102
2796
  border-radius: var(--radius-lg);
@@ -2126,14 +2820,128 @@ ${a}
2126
2820
  max-height: 180px;
2127
2821
  overflow-y: auto;
2128
2822
  box-sizing: border-box;
2129
- scrollbar-width: thin;
2130
- scrollbar-color: color-mix(in oklab,var(--foreground) 10%,transparent) transparent;
2131
2823
  }
2132
2824
 
2133
2825
  .bdb-textarea::placeholder {
2134
2826
  color: var(--muted-foreground);
2135
2827
  }
2136
2828
 
2829
+ .bdb-pending-files {
2830
+ display: flex;
2831
+ flex-wrap: wrap;
2832
+ gap: 0.5rem;
2833
+ padding: 0.75rem 0.875rem 0;
2834
+ max-height: 116px;
2835
+ overflow-y: auto;
2836
+ box-sizing: border-box;
2837
+ }
2838
+
2839
+ .bdb-pending-files[hidden] {
2840
+ display: none;
2841
+ }
2842
+
2843
+ .bdb-file-card {
2844
+ display: flex;
2845
+ align-items: center;
2846
+ gap: 0.5rem;
2847
+ min-width: 180px;
2848
+ max-width: 240px;
2849
+ padding: 0.5rem 0.625rem;
2850
+ border: 1px solid var(--border);
2851
+ border-radius: var(--radius-md);
2852
+ background: color-mix(in oklab, var(--card) 82%, var(--foreground) 4%);
2853
+ color: var(--foreground);
2854
+ box-sizing: border-box;
2855
+ position: relative;
2856
+ }
2857
+
2858
+ .bdb-file-card.has-error {
2859
+ border-color: #ef4444;
2860
+ color: #fca5a5;
2861
+ }
2862
+
2863
+ .bdb-file-card.is-compact {
2864
+ max-width: 220px;
2865
+ }
2866
+
2867
+ .bdb-file-icon {
2868
+ display: flex;
2869
+ align-items: center;
2870
+ justify-content: center;
2871
+ width: 34px;
2872
+ height: 34px;
2873
+ flex-shrink: 0;
2874
+ }
2875
+
2876
+ .bdb-file-icon svg {
2877
+ display: block;
2878
+ width: 34px;
2879
+ height: 34px;
2880
+ }
2881
+
2882
+ .bdb-file-meta {
2883
+ min-width: 0;
2884
+ flex: 1;
2885
+ }
2886
+
2887
+ .bdb-file-name {
2888
+ overflow: hidden;
2889
+ text-overflow: ellipsis;
2890
+ white-space: nowrap;
2891
+ font-size: 13px;
2892
+ font-weight: 600;
2893
+ }
2894
+
2895
+ .bdb-file-detail {
2896
+ display: flex;
2897
+ align-items: center;
2898
+ gap: 0.25rem;
2899
+ min-width: 0;
2900
+ color: var(--muted-foreground);
2901
+ font-size: 11px;
2902
+ margin-top: 0.125rem;
2903
+ }
2904
+
2905
+ .bdb-file-detail-text {
2906
+ overflow: hidden;
2907
+ text-overflow: ellipsis;
2908
+ white-space: nowrap;
2909
+ min-width: 0;
2910
+ }
2911
+
2912
+ .bdb-file-spinner {
2913
+ width: 11px;
2914
+ height: 11px;
2915
+ border-radius: var(--radius-full);
2916
+ border: 2px solid color-mix(in oklab, var(--muted-foreground) 35%, transparent);
2917
+ border-top-color: var(--primary);
2918
+ flex-shrink: 0;
2919
+ animation: bdb-file-spin 0.8s linear infinite;
2920
+ }
2921
+
2922
+ @keyframes bdb-file-spin {
2923
+ to { transform: rotate(360deg); }
2924
+ }
2925
+
2926
+ .bdb-file-remove {
2927
+ display: flex;
2928
+ align-items: center;
2929
+ justify-content: center;
2930
+ width: 22px;
2931
+ height: 22px;
2932
+ border-radius: var(--radius-full);
2933
+ border: 1px solid var(--border);
2934
+ background: var(--card);
2935
+ color: var(--muted-foreground);
2936
+ cursor: pointer;
2937
+ flex-shrink: 0;
2938
+ }
2939
+
2940
+ .bdb-file-remove:hover {
2941
+ color: var(--foreground);
2942
+ background: color-mix(in oklab, var(--foreground) 8%, transparent);
2943
+ }
2944
+
2137
2945
  .bdb-form-footer {
2138
2946
  display: flex;
2139
2947
  align-items: center;
@@ -2265,6 +3073,7 @@ ${a}
2265
3073
  </style>
2266
3074
 
2267
3075
  <div class="bdb-form-wrap">
3076
+ <div class="bdb-pending-files" id="bdb-pending-files" hidden></div>
2268
3077
  <textarea
2269
3078
  class="bdb-textarea"
2270
3079
  rows="1"
@@ -2279,7 +3088,18 @@ ${a}
2279
3088
  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
2280
3089
  </button>
2281
3090
  </div>
2282
- <div style="position: relative;">
3091
+
3092
+ <div style="display: flex; align-items: center; gap: 0.25rem;">
3093
+ <div style="position: relative;">
3094
+ <button class="bdb-tools-btn" id="bdb-attachments-trigger" aria-haspopup="true" aria-expanded="false">
3095
+ <svg xmlns="http://www.w3.org/2000/svg" width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-plus-icon lucide-plus"><path d="M5 12h14"/><path d="M12 5v14"/></svg>
3096
+ </button>
3097
+
3098
+ <div class="bdb-tools-dropdown" id="bdb-attachments-dropdown">
3099
+ <button class="bdb-tool-item" id="bdb-upload-files-action">Upload files from computer</button>
3100
+ </div>
3101
+ </div>
3102
+ <div style="position: relative;">
2283
3103
  <button class="bdb-tools-btn" id="bdb-tools-trigger" aria-haspopup="true" aria-expanded="false">
2284
3104
  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path></svg>
2285
3105
  Tools
@@ -2288,10 +3108,12 @@ ${a}
2288
3108
  <!-- Dynamically populated -->
2289
3109
  </div>
2290
3110
  </div>
3111
+ </div>
2291
3112
  </div>
3113
+
2292
3114
  <button class="bdb-send-btn" disabled aria-label="Send message">
2293
3115
  <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-send" aria-hidden="true"><path d="M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"></path><path d="m21.854 2.147-10.94 10.939"></path></svg>
2294
3116
  </button>
2295
3117
  </div>
2296
3118
  </div>
2297
- `;let t=e.querySelector(".bdb-textarea"),o=e.querySelector(".bdb-send-btn"),r=e.querySelector("#bdb-tools-trigger"),a=e.querySelector("#bdb-tools-dropdown"),s=e.querySelector("#bdb-active-tool-badge"),i=e.querySelector("#bdb-active-tool-name"),c=e.querySelector(".bdb-tool-clear"),p=this.tools;p.length===0?r.style.display="none":(p.forEach(l=>{let g=document.createElement("button");g.className="bdb-tool-item",g.textContent=l.name,g.addEventListener("click",()=>{let h=this.store.getState().chat.tools;for(let b of h)b.id!==l.id&&this.store.dispatch(P(b.id));this.store.dispatch(Q({id:l.id,name:l.name})),i.textContent=l.name,s.style.display="inline-flex",a.classList.remove("show")}),a.appendChild(g)}),r.addEventListener("click",l=>{l.stopPropagation(),a.classList.toggle("show")}),document.addEventListener("click",l=>{!a.contains(l.target)&&l.target!==r&&a.classList.remove("show")})),c.addEventListener("click",()=>{let l=this.store.getState().chat.tools;for(let g of l)this.store.dispatch(P(g.id));s.style.display="none"});let d=()=>{t.style.height="auto",t.style.height=Math.min(t.scrollHeight,180)+"px"};return this.store.subscribe(()=>{let{chatSessions:l,chat:g}=this.store.getState(),h=l[g.activeSession]?.query||"";t.value!==h&&(t.value=h,d(),o.disabled=!h.trim())}),t.addEventListener("input",()=>{d();let l=t.value;o.disabled=!l.trim();let{activeSession:g}=this.store.getState().chat;this.store.dispatch(N({sessionId:g,query:l}))}),t.addEventListener("keydown",async l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),o.disabled||await this.sendQuery())}),o.addEventListener("click",()=>this.sendQuery()),e}async sendQuery(){let{chatSessions:e,chat:t}=this.store.getState(),{activeSession:o,activeIndex:r}=t,{query:a,isLoading:s}=e[o];if(s||!a?.trim())return;let i={query:a,output:[]};this.store.dispatch(N({sessionId:o,query:""})),await this.store.dispatch(ae({query:i?.query,sessionId:o,indexName:r,config:this.apiConfig}))}downloadChat(){}};$.DEFAULT_TOOLS=[{id:"kpi",name:"KPI (MCP)"}];var R=$;var Se=null;function xt(n){return Se=new R(n),Se}typeof window<"u"&&(window.BangdbChatWidget={init:xt});export{R as ChatWidget,xt as init};
3119
+ `;let t=e.querySelector(".bdb-textarea"),o=e.querySelector(".bdb-send-btn"),r=e.querySelector("#bdb-pending-files"),a=e.querySelector("#bdb-attachments-trigger"),s=e.querySelector("#bdb-attachments-dropdown"),i=e.querySelector("#bdb-upload-files-action"),l=e.querySelector("#bdb-tools-trigger"),d=e.querySelector("#bdb-tools-dropdown"),c=e.querySelector("#bdb-active-tool-badge"),u=e.querySelector("#bdb-active-tool-name"),g=e.querySelector(".bdb-tool-clear");a.addEventListener("click",p=>{p.stopPropagation(),s.classList.toggle("show")}),this.enableIndexing||(a.style.display="none");let b=()=>{let{chatSessions:p,chat:y}=this.store.getState(),v=p[y.activeSession],k=!!v?.query?.trim(),f=(v?.queryFiles||[]).length>0,T=(v?.files||[]).some(j=>this.isFileBusy(j)),M=!!v?.isLoading;o.disabled=M||T||!k&&!f},h=(p,y)=>{r.innerHTML="";let v=new Set(y.map(f=>f.id)),k=[...p.filter(f=>!v.has(f.id)),...y];r.hidden=k.length===0;for(let f of k){let T=p.some(M=>M.id===f.id);r.appendChild(this.createFileCard(f,{removable:T,compact:!0,onRemove:M=>{let{activeSession:j}=this.store.getState().chat,E=this.store.getState().chatSessions[j]?.queryFiles||[];this.pendingFileBlobs.delete(M.id),this.store.dispatch(Y({sessionId:j,files:E.filter(S=>S.id!==M.id)})),b()}}))}};i.addEventListener("click",()=>{s.classList.remove("show");let{activeSession:p}=this.store.getState().chat,y=this.store.getState().chatSessions[p]?.queryFiles||[];this.openFileUploadModal(y,(v,k)=>{for(let[M,j]of k.entries())this.pendingFileBlobs.set(M,j);let f=new Set(y.map(M=>M.id)),T=new Set(v.map(M=>M.id));for(let M of f)T.has(M)||this.pendingFileBlobs.delete(M);this.store.dispatch(Y({sessionId:p,files:v})),h(v,[]),b()})});let m=this.tools;m.length===0?l.style.display="none":(m.forEach(p=>{let y=document.createElement("button");y.className="bdb-tool-item",y.textContent=p.name,y.addEventListener("click",()=>{let v=this.store.getState().chat.tools;for(let k of v)k.id!==p.id&&this.store.dispatch(G(k.id));this.store.dispatch(se({id:p.id,name:p.name})),u.textContent=p.name,c.style.display="inline-flex",d.classList.remove("show")}),d.appendChild(y)}),l.addEventListener("click",p=>{p.stopPropagation(),d.classList.toggle("show")}),document.addEventListener("click",p=>{!d.contains(p.target)&&p.target!==l&&d.classList.remove("show")})),g.addEventListener("click",()=>{let p=this.store.getState().chat.tools;for(let y of p)this.store.dispatch(G(y.id));c.style.display="none"});let x=()=>{t.style.height="auto",t.style.height=Math.min(t.scrollHeight,180)+"px"};return this.store.subscribe(()=>{let{chatSessions:p,chat:y}=this.store.getState(),v=p[y.activeSession],k=v?.query||"",f=v?.queryFiles||[],T=v?.files||[];t.value!==k&&(t.value=k,x()),h(f,T),b()}),(()=>{let{chatSessions:p,chat:y}=this.store.getState(),v=p[y.activeSession],k=v?.query||"";t.value!==k&&(t.value=k,x()),h(v?.queryFiles||[],v?.files||[]),b()})(),t.addEventListener("input",()=>{x();let p=t.value,{activeSession:y}=this.store.getState().chat;this.store.dispatch(_({sessionId:y,query:p})),b()}),t.addEventListener("keydown",async p=>{p.key==="Enter"&&!p.shiftKey&&(p.preventDefault(),o.disabled||await this.sendQuery())}),o.addEventListener("click",()=>this.sendQuery()),e}async sendQuery(){let{chatSessions:e,chat:t}=this.store.getState(),{activeSession:o,activeIndex:r}=t,{query:a,isLoading:s,queryFiles:i=[]}=e[o];if(s||!a?.trim()&&i.length===0)return;let l={query:a,output:[]};if(this.store.dispatch(_({sessionId:o,query:""})),i.length>0){let d=i.map(c=>({...c,file:this.pendingFileBlobs.get(c.id)}));this.store.dispatch(X({sessionId:o,files:i})),this.store.dispatch(Y({sessionId:o,files:[]})),await this.store.dispatch(ve({acceptedFiles:d,sessionId:o,indexName:r,config:this.apiConfig}));for(let c of i)this.pendingFileBlobs.delete(c.id)}l?.query?.trim()&&await this.store.dispatch(xe({query:l?.query,sessionId:o,indexName:r,config:this.apiConfig}))}};q.DEFAULT_TOOLS=[{id:"kpi",name:"KPI (MCP)"}];var $=q;var Qe=null;function $t(n){return Qe=new $(n),Qe}typeof window<"u"&&(window.BangdbChatWidget={init:$t});export{$ as ChatWidget,$t as init};