@object-ui/plugin-chatbot 7.3.0 → 11.2.0
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/CHANGELOG.md +30 -0
- package/dist/ChatbotEnhanced.d.ts +119 -0
- package/dist/ChatbotEnhanced.d.ts.map +1 -1
- package/dist/index.js +1138 -799
- package/dist/index.umd.cjs +1 -1
- package/dist/mapMessages.d.ts.map +1 -1
- package/dist/tool-display.d.ts +21 -0
- package/dist/tool-display.d.ts.map +1 -1
- package/dist/useObjectChat.d.ts +21 -0
- package/dist/useObjectChat.d.ts.map +1 -1
- package/package.json +5 -5
package/dist/index.umd.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require("react"),require("@object-ui/components"),require("lucide-react"),require("react/jsx-runtime"),require("@ai-sdk/react"),require("ai"),require("react-dom"),require("@object-ui/react"),require("use-stick-to-bottom"),require("class-variance-authority"),require("@radix-ui/react-slot"),require("streamdown"),require("nanoid"),require("shiki"),require("@radix-ui/react-use-controllable-state"),require("motion/react"),require("@object-ui/core")):typeof define==`function`&&define.amd?define([`exports`,`react`,`@object-ui/components`,`lucide-react`,`react/jsx-runtime`,`@ai-sdk/react`,`ai`,`react-dom`,`@object-ui/react`,`use-stick-to-bottom`,`class-variance-authority`,`@radix-ui/react-slot`,`streamdown`,`nanoid`,`shiki`,`@radix-ui/react-use-controllable-state`,`motion/react`,`@object-ui/core`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.ObjectUIPluginChatbot={},e.React,e.ObjectUIComponents,e.LucideReact,e.react_jsx_runtime,e._ai_sdk_react,e.ai,e.ReactDOM,e.ObjectUIReact,e.use_stick_to_bottom,e.class_variance_authority,e._radix_ui_react_slot,e.streamdown,e.nanoid,e.shiki,e._radix_ui_react_use_controllable_state,e.motion_react,e.ObjectUICore))})(this,function(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var v=Object.create,y=Object.defineProperty,b=Object.getOwnPropertyDescriptor,x=Object.getOwnPropertyNames,S=Object.getPrototypeOf,C=Object.prototype.hasOwnProperty,w=(e,t)=>{let n={};for(var r in e)y(n,r,{get:e[r],enumerable:!0});return t||y(n,Symbol.toStringTag,{value:`Module`}),n},T=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=x(t),a=0,o=i.length,s;a<o;a++)s=i[a],!C.call(e,s)&&s!==n&&y(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=b(t,s))||r.enumerable});return e},E=(e,t,n)=>(n=e==null?{}:v(S(e)),T(t||!e||!e.__esModule?y(n,`default`,{value:e,enumerable:!0}):n,e));t=E(t,1),s=E(s,1);function D(e=`msg`){return typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`${e}-${Date.now()}-${Math.random().toString(36).slice(2)}`}function O(e,t){return typeof e.content==`string`?e.content:t.filter(e=>e.type===`text`).map(e=>e.text??``).join(``)}function k(e){let t=e.filter(e=>e.type===`reasoning`||e.type===`reasoning-delta`).map(e=>e.text??``).join(`
|
|
2
|
-
`).trim();return t.length>0?t:void 0}function A(e){let t=e=>{if(e&&typeof e==`object`)return e;if(typeof e!=`string`)return;let t=e.trim();if(t.startsWith(`{`))try{let e=JSON.parse(t);return e&&typeof e==`object`?e:void 0}catch{return}},n=[e];e&&typeof e==`object`&&`value`in e&&n.push(e.value);let r;for(let e of n){let n=t(e);if(n){if(typeof n.status==`string`)return n;r??=n}}return r}function j(e){let t=A(e);if(!t)return;let n=t.pendingActionId;if(t.status===`pending_approval`&&typeof n==`string`&&n.length>0)return{pendingActionId:n,raw:t}}function M(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.trim().length>0):[]}function N(e){let t=A(e);if(!t||t.status!==`blueprint_proposed`)return;let n=t.blueprint,r=n&&typeof n==`object`?n:{},i=(Array.isArray(r.objects)?r.objects:[]).flatMap(e=>{let t=e;return typeof t?.name!=`string`||!t.name?[]:[{name:t.name,...typeof t.label==`string`&&t.label?{label:t.label}:{},fieldCount:Array.isArray(t.fields)?t.fields.length:0}]});if(i.length===0)return;let a=(e,t)=>typeof e==`number`&&Number.isFinite(e)?e:t,o=t.counts??{},s={objects:a(o.objects,i.length),views:a(o.views,Array.isArray(r.views)?r.views.length:0),dashboards:a(o.dashboards,Array.isArray(r.dashboards)?r.dashboards.length:0),seedData:a(o.seedData,Array.isArray(r.seedData)?r.seedData.length:0)},c=M(t.questions),l=t.questionChoices,u=Array.isArray(l)?l.flatMap(e=>{let t=e;if(typeof t?.text!=`string`||!t.text)return[];let n=Array.isArray(t.options)?t.options.filter(e=>typeof e==`string`&&e.trim().length>0):[];return n.length>=2?[{text:t.text,options:n}]:[]}):[],d=typeof t.summary==`string`&&t.summary?t.summary:typeof r.summary==`string`&&r.summary?r.summary:void 0,f=t.targetApp;return{...d?{summary:d}:{},objects:i,counts:s,questions:c.length?c:M(r.questions),...u.length?{questionChoices:u}:{},assumptions:M(r.assumptions),...typeof f==`string`&&f?{targetApp:f}:{}}}function P(e){let t=A(e);if(!t||t.status!==`changes_proposed`)return;let n=e=>typeof e==`string`&&e?e:void 0,r=t.changes,i=(Array.isArray(r)?r:[]).flatMap(e=>{let t=e;return typeof t?.verb!=`string`||!t.verb?[]:[{verb:t.verb,...n(t.object)?{object:n(t.object)}:{},...n(t.field)?{field:n(t.field)}:{},...n(t.type)?{type:n(t.type)}:{},...n(t.name)?{name:n(t.name)}:{},...n(t.details)?{details:n(t.details)}:{}}]});if(i.length!==0)return{...n(t.summary)?{summary:n(t.summary)}:{},changes:i}}function F(e){let t=A(e);if(!t||t.status!==`drafted`)return;let n=[];if(Array.isArray(t.drafted)){for(let e of t.drafted)if(e&&typeof e==`object`){let{type:t,name:r}=e;typeof t==`string`&&typeof r==`string`&&n.push({type:t,name:r})}}else typeof t.type==`string`&&typeof t.name==`string`&&n.push({type:t.type,name:t.name});if(n.length===0)return;let r=Array.isArray(t.failed)?t.failed.length:0,i=t.verification,a=i&&typeof i==`object`&&typeof i.errors==`number`&&typeof i.warnings==`number`?{errors:i.errors,warnings:i.warnings}:void 0,o=t.issues,s=Array.isArray(o)?o.flatMap(e=>{let t=e;return typeof t?.message!=`string`||!t.message?[]:[{severity:t.severity===`error`?`error`:`warning`,code:typeof t.code==`string`?t.code:`issue`,message:t.message,...typeof t.fix==`string`&&t.fix?{fix:t.fix}:{}}]}):[],c=t.nextSteps,l=Array.isArray(c)?c.filter(e=>typeof e==`string`&&e.trim().length>0):[];return{items:n,summary:typeof t.summary==`string`?t.summary:void 0,...typeof t.packageId==`string`&&t.packageId?{packageId:t.packageId}:{},...t.autoPublishable===!0?{autoPublishable:!0}:{},...r>0?{failedCount:r}:{},...l.length?{nextSteps:l}:{},...t.materialized===!0?{materialized:!0}:{},...a?{verification:a}:{},...s.length?{issues:s}:{}}}function I(e){return e.replace(/[._-]+/g,` `).replace(/\s+/g,` `).trim().replace(/\b\w/g,e=>e.toUpperCase())}function L(e){if(!e||!Array.isArray(e.items)||e.items.length===0)return;let t=e.items.find(e=>e.type===`app`);if(t)return{phase:`done`,appLabel:I(t.name),items:e.items,done:e.items.length,total:e.items.length}}function ee(e,t={}){return e.filter(e=>e.type===`dynamic-tool`?!0:typeof e.type==`string`&&e.type.startsWith(`tool-`)).map(e=>{let n=e.type===`dynamic-tool`?e.toolName??`tool`:typeof e.type==`string`?e.type.replace(/^tool-/,``):`tool`,r=e.output??e.result,i=j(r),a=F(r),o=N(r),s=P(r),c=e.state,l=(c===`input-available`||c===`input-streaming`)&&(r!==void 0||!t.liveTail)?`output-available`:c,u=i&&l!==`output-error`?`approval-requested`:l;return{toolCallId:e.toolCallId??e.id??`${e.type??`tool`}-${Math.random().toString(36).slice(2,8)}`,toolName:n,args:e.input??e.args,result:r,errorText:e.errorText,state:u,pendingActionId:i?.pendingActionId,draftReview:a,proposedPlan:o,proposedChanges:s}})}function te(e){let t=e.filter(e=>e.type===`source-url`||e.type===`source`).map(e=>({id:e.id,title:e.title,url:e.url??e.href})).filter(e=>!!e.url);return t.length>0?t:void 0}function ne(e){let t=e.filter(e=>e.type===`data-build-progress`).pop()?.data;if(!t||typeof t!=`object`)return;let n=t,r=Array.isArray(n.items)?n.items.filter(e=>typeof e?.type==`string`&&typeof e?.name==`string`).map(e=>({type:e.type,name:e.name})):[];return{phase:n.phase===`data`||n.phase===`done`?n.phase:`structure`,...typeof n.appLabel==`string`?{appLabel:n.appLabel}:{},items:r,done:typeof n.done==`number`?n.done:r.length,total:typeof n.total==`number`?n.total:r.length,...typeof n.seq==`number`?{seq:n.seq}:{}}}function re(e){let t=[];for(let n of e){if(n.type!==`data-chart`)continue;let e=n.data;if(!e||typeof e!=`object`)continue;let r=e,i=Array.isArray(r.data)?r.data:[],a=Array.isArray(r.series)?r.series.filter(e=>e&&typeof e.dataKey==`string`).map(e=>({dataKey:e.dataKey,...typeof e.label==`string`?{label:e.label}:{}})):[];a.length!==0&&t.push({...typeof r.chartType==`string`?{chartType:r.chartType}:{},...typeof r.title==`string`?{title:r.title}:{},data:i,...typeof r.xAxisKey==`string`?{xAxisKey:r.xAxisKey}:{},series:a})}return t.length>0?t:void 0}function R(e,t={}){let n=Array.isArray(e.parts)?e.parts:[],r=ee(n,{liveTail:t.streaming}),i=Array.isArray(e.toolInvocations)?e.toolInvocations:[],a=r.length>0?r:i,o=ne(n)??a.map(e=>L(e.draftReview)).find(e=>!!e);return{id:e.id??`msg-${Math.random().toString(36).slice(2,8)}`,role:e.role??`assistant`,content:O(e,n),reasoning:k(n),toolInvocations:a,sources:te(n),buildProgress:o,charts:re(n),streaming:t.streaming}}function ie(e,t={}){if(!Array.isArray(e)||e.length===0)return[];let n=e.length-1;return e.map((e,r)=>R(e,{streaming:!!t.isStreaming&&r===n&&e.role===`assistant`}))}function z(e){let t=[...e.messages].reverse().find(e=>e.role===`user`);return{body:{...e.body??{},id:e.id,messages:e.messages,trigger:e.trigger,messageId:e.messageId,...t?{turnId:t.id}:{}}}}function ae(e){return(e??[]).map((e,t)=>({id:e.id||`msg-${t}`,role:e.role||`user`,content:e.content||``,timestamp:typeof e.timestamp==`string`?e.timestamp:e.timestamp instanceof Date?e.timestamp.toISOString():void 0,metadata:e.metadata,streaming:e.streaming,toolInvocations:e.toolInvocations}))}function B(e={}){let{api:n,initialMessages:r,conversationId:i,systemPrompt:s,model:c,streamingEnabled:l=!0,headers:u,body:d,maxToolRoundtrips:f=5,onError:p,showTimestamp:m,autoResponse:h,autoResponseText:g,autoResponseDelay:_=1e3,onSend:v}=e,y=(0,t.useRef)(n?`api`:`local`).current===`api`,b=(0,t.useMemo)(()=>(r??[]).map((e,t)=>{if(Array.isArray(e.parts)&&e.parts.length>0)return{id:e.id||`msg-${t}`,role:e.role||`user`,parts:e.parts};let n=ae([e])[0],r=[];n.content&&r.push({type:`text`,text:n.content}),e.reasoning&&r.push({type:`reasoning`,text:e.reasoning});for(let e of n.toolInvocations??[])r.push({type:`tool-${e.toolName}`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.args,output:e.result,errorText:e.errorText,state:e.state});return{id:n.id||`msg-${t}`,role:n.role,parts:r.length>0?r:[{type:`text`,text:``}]}}),[]),x=(0,t.useRef)(c);x.current=c;let S=(0,a.useChat)({transport:(0,t.useMemo)(()=>{if(y)return new o.DefaultChatTransport({api:n,headers:{...u},body:{...d,...i?{conversationId:i}:{},...c?{model:c}:{},...s?{systemPrompt:s}:{},...l===void 0?{}:{stream:l}},prepareSendMessagesRequest:({id:e,body:t,messages:n,trigger:r,messageId:i})=>{let a=z({id:e,body:t,messages:n,trigger:r,messageId:i});return x.current&&(a.body.model=x.current),a}})},[y,n,u,d,c,s,l,i]),messages:y&&b.length>0?b:void 0,onError:y?e=>{p?.(e)}:void 0}),[C,w]=(0,t.useState)(()=>ae(r)),[T,E]=(0,t.useState)(!1),[O,k]=(0,t.useState)(``),[A,j]=(0,t.useState)(``),M=(0,t.useRef)(null);if((0,t.useEffect)(()=>()=>{M.current&&=(clearTimeout(M.current),null)},[]),y){let{messages:e,status:n,error:r,sendMessage:i,regenerate:a,stop:o,setMessages:s}=S,c=n===`submitted`||n===`streaming`,l=ie(e,{isStreaming:c}).map((t,n)=>({...t,metadata:e[n]?.metadata}));return{messages:l,isLoading:c,error:r,sendMessage:(0,t.useCallback)(e=>{let t=e.trim();if(!t)return;let n=[...l,{id:D(`msg`),role:`user`,content:t}];i({text:t}),j(``),v?.(t,n)},[i,v,l]),stop:o,reload:a,clear:(0,t.useCallback)(()=>{s([])},[s]),setMessages:s,isApiMode:!0,input:A,setInput:j,handleInputChange:(0,t.useCallback)(e=>{j(e.target.value)},[])}}let N=(0,t.useCallback)(()=>{M.current&&=(clearTimeout(M.current),null),E(!1)},[]);return{messages:C,isLoading:T,error:void 0,sendMessage:(0,t.useCallback)(e=>{if(!e.trim())return;let t={id:D(`msg`),role:`user`,content:e.trim(),timestamp:m?new Date().toLocaleTimeString():void 0};w(n=>{let r=[...n,t];return v?.(e.trim(),r),r}),k(``),h&&(E(!0),M.current=setTimeout(()=>{let e={id:D(`msg`),role:`assistant`,content:g||`Thank you for your message!`,timestamp:m?new Date().toLocaleTimeString():void 0};w(t=>[...t,e]),E(!1)},_))},[m,h,g,_,v]),stop:N,reload:(0,t.useCallback)(()=>{},[]),clear:(0,t.useCallback)(()=>{N(),w([])},[N]),isApiMode:!1,input:O,setInput:k,handleInputChange:(0,t.useCallback)(e=>{k(e.target.value)},[])}}var V=[[`build`,`metadata_assistant`],[`ask`,`data_chat`]];function H(e){return V.find(t=>t.includes(e))??[e]}function U(e){return H(e)[0]}function W(e,t){if(e){if(t.includes(e))return e;for(let n of H(e))if(t.includes(n))return n}}function oe(e){return e!=null&&V.some(t=>t.includes(e))}function se(e){return e!=null&&U(e)===`build`}function ce(e){return e!=null&&U(e)===`ask`}var le=`ask`;function ue(e,t){if(e.length===0)return;let n=e.map(e=>e.name);if(t){let e=W(t,n);if(e)return e}return W(`ask`,n)||e[0].name}function de(e){return e.filter(e=>typeof e?.name==`string`&&e.name.length>0).map(e=>({name:e.name,label:e.label||e.name,description:e.description,role:e.role,active:e.active!==!1}))}function fe(e={}){let{apiBase:n,headers:r,enabled:i=!0,fallback:a=[]}=e,[o,s]=(0,t.useState)(a),[c,l]=(0,t.useState)(!1),[u,d]=(0,t.useState)(void 0),[f,p]=(0,t.useState)(0),m=(0,t.useRef)(r);return m.current=r,(0,t.useEffect)(()=>{if(!i||!n)return;let e=new AbortController,t=!1;l(!0),d(void 0);let r=`${n.replace(/\/$/,``)}/agents`;return fetch(r,{method:`GET`,headers:{Accept:`application/json`,...m.current??{}},credentials:`include`,signal:e.signal}).then(async e=>{if(!e.ok)throw Error(`Failed to load agents (${e.status})`);return e.json()}).then(e=>{if(t)return;let n=de(Array.isArray(e)?e:e?.agents??[]);s(n.length>0?n:a)}).catch(e=>{t||e.name===`AbortError`||(d(e),s(a))}).finally(()=>{t||l(!1)}),()=>{t=!0,e.abort()}},[n,i,f]),{agents:o,isLoading:c,error:u,refetch:(0,t.useCallback)(()=>p(e=>e+1),[])}}function pe(e){return e.filter(e=>typeof e?.id==`string`&&e.id.length>0).map(e=>({id:e.id,label:e.label||e.id}))}function me(e={}){let{apiBase:n,headers:r,enabled:i=!0}=e,[a,o]=(0,t.useState)([]),[s,c]=(0,t.useState)(void 0),[l,u]=(0,t.useState)(!1),[d,f]=(0,t.useState)(void 0),[p,m]=(0,t.useState)(0),h=(0,t.useRef)(r);return h.current=r,(0,t.useEffect)(()=>{if(!i||!n)return;let e=new AbortController,t=!1,r=`${n.replace(/\/$/,``)}/models`,a=0,s=async()=>{if(!t){u(!0),f(void 0);try{let n=await fetch(r,{method:`GET`,headers:{Accept:`application/json`,...h.current??{}},credentials:`include`,signal:e.signal});if(!n.ok)throw Error(`Failed to load AI models (${n.status})`);let i=await n.json();if(t)return;let l=Array.isArray(i)?i:i?.models??[],d=Array.isArray(i)?void 0:i?.defaultModel,f=pe(l);o(f),c(d??l.find(e=>e?.default)?.id??l[0]?.id),u(!1),f.length===0&&a<5&&!t&&(a+=1,setTimeout(()=>{s()},1200))}catch(e){if(t||e?.name===`AbortError`)return;a<5?(a+=1,setTimeout(()=>{s()},1200)):(f(e),o([]),c(void 0),u(!1))}}};return s(),()=>{t=!0,e.abort()}},[n,i,p]),{models:a,defaultModelId:s,isLoading:l,error:d,refetch:(0,t.useCallback)(()=>m(e=>e+1),[])}}var he=t.createContext(null);function ge({defaultOpen:e=!1,children:n}){let[r,a]=t.useState(e),[o,s]=t.useState(!1),c=t.useMemo(()=>({isOpen:r,isFullscreen:o,open:()=>a(!0),close:()=>{a(!1),s(!1)},toggle:()=>a(e=>!e),toggleFullscreen:()=>s(e=>!e)}),[r,o]);return(0,i.jsx)(he.Provider,{value:c,children:n})}function _e(){let e=t.useContext(he);if(!e)throw Error(`useFloatingChatbot must be used within a <FloatingChatbotProvider>`);return e}function ve(){try{let{t:e}=(0,c.useObjectTranslation)();return(t,n)=>{let r=e(`common.${t}`);return!r||r===`common.${t}`?n:r}}catch{return(e,t)=>t}}var G={32:`size-8`,36:`size-9`,40:`size-10`,44:`size-11`,48:`size-12`,52:`size-[52px]`,56:`size-14`,60:`size-[60px]`,64:`size-16`,72:`size-[72px]`,80:`size-20`};function ye(e,t){return t.reduce((t,n)=>Math.abs(n-e)<Math.abs(t-e)?n:t)}function K(e){return G[e]??G[ye(e,Object.keys(G).map(Number))]}function be({position:e=`bottom-right`,size:t=56,className:a}){let{isOpen:o,toggle:s}=_e(),c=ve();return(0,i.jsx)(n.Button,{onClick:s,className:(0,n.cn)(`fixed z-50 rounded-full shadow-lg transition-transform hover:scale-105`,K(t),o&&`hidden`,e===`bottom-right`?`right-6 bottom-20 sm:bottom-6`:`left-6 bottom-20 sm:bottom-6`,a),size:`icon`,"aria-label":o?c(`closeChat`,`Close chat`):c(`openChat`,`Open chat`),"data-testid":`floating-chatbot-trigger`,children:o?(0,i.jsx)(r.X,{className:`h-6 w-6`}):(0,i.jsx)(r.Bot,{className:`h-6 w-6`})})}var q={300:`sm:w-[300px]`,320:`sm:w-[320px]`,340:`sm:w-[340px]`,360:`sm:w-[360px]`,380:`sm:w-[380px]`,400:`sm:w-[400px]`,420:`sm:w-[420px]`,440:`sm:w-[440px]`,450:`sm:w-[450px]`,460:`sm:w-[460px]`,480:`sm:w-[480px]`,500:`sm:w-[500px]`,520:`sm:w-[520px]`,560:`sm:w-[560px]`,600:`sm:w-[600px]`,640:`sm:w-[640px]`,720:`sm:w-[720px]`,800:`sm:w-[800px]`},xe={360:`h-[min(360px,calc(100svh_-_6rem_-_env(safe-area-inset-bottom)))] sm:h-[360px]`,400:`h-[min(400px,calc(100svh_-_6rem_-_env(safe-area-inset-bottom)))] sm:h-[400px]`,420:`h-[min(420px,calc(100svh_-_6rem_-_env(safe-area-inset-bottom)))] sm:h-[420px]`,440:`h-[min(440px,calc(100svh_-_6rem_-_env(safe-area-inset-bottom)))] sm:h-[440px]`,480:`h-[min(480px,calc(100svh_-_6rem_-_env(safe-area-inset-bottom)))] sm:h-[480px]`,500:`h-[min(500px,calc(100svh_-_6rem_-_env(safe-area-inset-bottom)))] sm:h-[500px]`,520:`h-[min(520px,calc(100svh_-_6rem_-_env(safe-area-inset-bottom)))] sm:h-[520px]`,560:`h-[min(560px,calc(100svh_-_6rem_-_env(safe-area-inset-bottom)))] sm:h-[560px]`,600:`h-[min(600px,calc(100svh_-_6rem_-_env(safe-area-inset-bottom)))] sm:h-[600px]`,640:`h-[min(640px,calc(100svh_-_6rem_-_env(safe-area-inset-bottom)))] sm:h-[640px]`,720:`h-[min(720px,calc(100svh_-_6rem_-_env(safe-area-inset-bottom)))] sm:h-[720px]`,800:`h-[min(800px,calc(100svh_-_6rem_-_env(safe-area-inset-bottom)))] sm:h-[800px]`};function Se(e,t){return t.reduce((t,n)=>Math.abs(n-e)<Math.abs(t-e)?n:t)}function Ce(e){return q[e]??q[Se(e,Object.keys(q).map(Number))]}function J(e){return xe[e]??xe[Se(e,Object.keys(xe).map(Number))]}function Y({title:e=`Chat`,position:t=`bottom-right`,width:a=400,height:o=520,children:s,className:c,headerExtra:l,headerActions:u}){let{isOpen:d,isFullscreen:f,close:p,toggleFullscreen:m}=_e();return d?(0,i.jsxs)(`div`,{className:(0,n.cn)(`fixed z-50 flex flex-col overflow-hidden border bg-background shadow-xl transition-all`,f?`inset-0 h-svh w-screen rounded-none`:t===`bottom-right`?(0,n.cn)(`left-3 right-3 bottom-[calc(4rem_+_env(safe-area-inset-bottom))] rounded-lg`,`sm:left-auto sm:right-6 sm:bottom-20 sm:max-h-[calc(100vh_-_100px)]`,Ce(a),J(o)):(0,n.cn)(`left-3 right-3 bottom-[calc(4rem_+_env(safe-area-inset-bottom))] rounded-lg`,`sm:right-auto sm:left-6 sm:bottom-20 sm:max-h-[calc(100vh_-_100px)]`,Ce(a),J(o)),c),role:`dialog`,"aria-label":e,"data-testid":`floating-chatbot-panel`,children:[(0,i.jsxs)(`div`,{className:`flex min-h-10 items-center justify-between gap-2 border-b bg-muted/40 px-4 py-2`,children:[(0,i.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-sm font-medium`,children:e}),l?(0,i.jsx)(`div`,{className:`mr-1 flex min-w-0 items-center justify-end`,"data-testid":`floating-chatbot-header-extra`,children:l}):null,(0,i.jsxs)(`div`,{className:`flex items-center gap-1 shrink-0`,children:[u,(0,i.jsx)(n.Button,{variant:`ghost`,size:`icon`,className:`h-7 w-7`,onClick:m,"aria-label":f?`Exit fullscreen`:`Fullscreen`,"data-testid":`floating-chatbot-fullscreen`,children:f?(0,i.jsx)(r.Minimize2,{className:`h-4 w-4`}):(0,i.jsx)(r.Maximize2,{className:`h-4 w-4`})}),(0,i.jsx)(n.Button,{variant:`ghost`,size:`icon`,className:`h-7 w-7`,onClick:p,"aria-label":`Close chat`,"data-testid":`floating-chatbot-close`,children:(0,i.jsx)(r.X,{className:`h-4 w-4`})})]})]}),(0,i.jsx)(`div`,{className:`min-h-0 flex-1 overflow-hidden`,children:s})]}):null}var X={ai:`AI`,api:`API`,crm:`CRM`,hitl:`HITL`,id:`ID`,ids:`IDs`,rag:`RAG`,sql:`SQL`,url:`URL`,utc:`UTC`};function we(e){if(!e)return``;let t=String(e).trim();if(!t)return``;let n=t.replace(/[_-]+/g,` `).replace(/([a-z])([A-Z])/g,`$1 $2`).split(/\s+/).filter(Boolean);return n.length===0?t:n.map((e,t)=>{let n=e.toLowerCase();return X[n]?X[n]:t===0?n.charAt(0).toUpperCase()+n.slice(1):n}).join(` `)}function Te(e){if(e==null)return e;let t=e;for(let e=0;e<2;e++){if(typeof t==`object`&&t&&!Array.isArray(t)&&t.type===`text`&&typeof t.value==`string`){t=t.value;continue}break}if(typeof t==`string`){let e=t.trim();if(e.startsWith(`{`)&&e.endsWith(`}`)||e.startsWith(`[`)&&e.endsWith(`]`))try{return JSON.parse(e)}catch{}}return t}function Ee(e){let t=(e instanceof Error?e.message:String(e??``)).replace(/\s+/g,` `).trim();if(!t)return{summary:`Something went wrong. Please try again.`};let n=t.replace(/^Failed after \d+ attempts?\.\s*Last error:\s*/i,``),r=n.match(/^Invalid error response format:\s*(.+)$/i)?.[1]?.trim()??n,i=r.match(/^([^:]{8,80}):\s+(.+)$/)?.[1]?.trim()??r.match(/^([^.;!?]+[.;!?])\s/)?.[1]?.trim()??(r.length>140?`${r.slice(0,137).trimEnd()}…`:r);return{summary:i.replace(/:$/,``),details:n.length>i.length?n:void 0}}var Z=new Set([`ai_design_quota_exhausted`,`ai_data_chat_trial_exhausted`,`ai_allowance_exhausted`]);function De(e){let t=e instanceof Error?e.message:String(e??``);if(!t)return null;let n=t.replace(/^Failed after \d+ attempts?\.\s*Last error:\s*/i,``).replace(/^Invalid error response format:\s*/i,``).trim(),r=n.indexOf(`{`),i=n.lastIndexOf(`}`);if(r<0||i<=r)return null;let a;try{a=JSON.parse(n.slice(r,i+1))}catch{return null}return!a||typeof a.error!=`string`||!Z.has(a.error)?null:{code:a.error,message:typeof a.message==`string`?a.message:``,messageEn:typeof a.messageEn==`string`?a.messageEn:void 0,upgrade:a.upgrade===!0,topUp:a.topUp===!0}}var Oe=({className:e,...t})=>(0,i.jsx)(l.StickToBottom,{className:(0,n.cn)(`relative flex-1 overflow-y-hidden`,e),initial:`smooth`,resize:`smooth`,role:`log`,...t}),ke=({className:e,...t})=>(0,i.jsx)(l.StickToBottom.Content,{className:(0,n.cn)(`flex flex-col gap-8 p-4`,e),...t}),Ae=({className:e,title:t=`No messages yet`,description:r=`Start a conversation to see messages here`,icon:a,children:o,...s})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`flex size-full flex-col items-center justify-center gap-3 p-8 text-center`,e),...s,children:o??(0,i.jsxs)(i.Fragment,{children:[a&&(0,i.jsx)(`div`,{className:`text-muted-foreground`,children:a}),(0,i.jsxs)(`div`,{className:`space-y-1`,children:[(0,i.jsx)(`h3`,{className:`font-medium text-sm`,children:t}),r&&(0,i.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:r})]})]})}),je=({className:e,...a})=>{let{isAtBottom:o,scrollToBottom:s}=(0,l.useStickToBottomContext)(),c=(0,t.useCallback)(()=>{s()},[s]);return!o&&(0,i.jsx)(n.Button,{className:(0,n.cn)(`absolute bottom-4 left-[50%] translate-x-[-50%] rounded-full`,e),onClick:c,size:`icon`,type:`button`,variant:`outline`,...a,children:(0,i.jsx)(r.ArrowDownIcon,{className:`size-4`})})},Me=(0,u.cva)(`flex w-fit items-stretch has-[>[data-slot=button-group]]:gap-2 [&>*]:focus-visible:relative [&>*]:focus-visible:z-10 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-md [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1`,{variants:{orientation:{horizontal:`[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none`,vertical:`flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none`}},defaultVariants:{orientation:`horizontal`}});function Ne({className:e,orientation:t,...r}){return(0,i.jsx)(`div`,{role:`group`,"data-slot":`button-group`,"data-orientation":t,className:(0,n.cn)(Me({orientation:t}),e),...r})}function Pe({className:e,asChild:t=!1,...r}){return(0,i.jsx)(t?d.Slot:`div`,{className:(0,n.cn)(`flex items-center gap-2 rounded-md border bg-muted px-4 text-sm font-medium shadow-xs [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4`,e),...r})}var Fe=({className:e,from:t,...r})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`group flex w-full max-w-[95%] flex-col gap-2`,t===`user`?`is-user ml-auto justify-end`:`is-assistant`,e),...r}),Ie=({children:e,className:t,...r})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`is-user:dark flex w-fit max-w-full min-w-0 flex-col gap-2 overflow-hidden text-sm`,`group-[.is-user]:ml-auto group-[.is-user]:rounded-lg group-[.is-user]:bg-secondary group-[.is-user]:px-4 group-[.is-user]:py-3 group-[.is-user]:text-foreground`,`group-[.is-assistant]:text-foreground`,t),...r,children:e}),Le=({className:e,children:t,...r})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`flex items-center gap-1`,e),...r,children:t}),Re=({tooltip:e,children:t,label:r,variant:a=`ghost`,size:o=`icon`,...s})=>{let c=(0,i.jsxs)(n.Button,{size:o,type:`button`,variant:a,...s,children:[t,(0,i.jsx)(`span`,{className:`sr-only`,children:r||e})]});return e?(0,i.jsx)(n.TooltipProvider,{children:(0,i.jsxs)(n.Tooltip,{children:[(0,i.jsx)(n.TooltipTrigger,{asChild:!0,children:c}),(0,i.jsx)(n.TooltipContent,{children:(0,i.jsx)(`p`,{children:e})})]})}):c},ze=(0,t.createContext)(null),Q=()=>{let e=(0,t.useContext)(ze);if(!e)throw Error(`MessageBranch components must be used within MessageBranch`);return e},Be=({defaultBranch:e=0,onBranchChange:r,className:a,...o})=>{let[s,c]=(0,t.useState)(e),[l,u]=(0,t.useState)([]),d=e=>{c(e),r?.(e)},f={currentBranch:s,totalBranches:l.length,goToPrevious:()=>{d(s>0?s-1:l.length-1)},goToNext:()=>{d(s<l.length-1?s+1:0)},branches:l,setBranches:u};return(0,i.jsx)(ze.Provider,{value:f,children:(0,i.jsx)(`div`,{className:(0,n.cn)(`grid w-full gap-2 [&>div]:pb-0`,a),...o})})},$=({children:e,...r})=>{let{currentBranch:a,setBranches:o,branches:s}=Q(),c=Array.isArray(e)?e:[e];return(0,t.useEffect)(()=>{s.length!==c.length&&o(c)},[c,s,o]),c.map((e,t)=>(0,i.jsx)(`div`,{className:(0,n.cn)(`grid gap-2 overflow-hidden [&>div]:pb-0`,t===a?`block`:`hidden`),...r,children:e},e.key))},Ve=({className:e,from:t,...n})=>{let{totalBranches:r}=Q();return r<=1?null:(0,i.jsx)(Ne,{className:`[&>*:not(:first-child)]:rounded-l-md [&>*:not(:last-child)]:rounded-r-md`,orientation:`horizontal`,...n})},He=({children:e,...t})=>{let{goToPrevious:a,totalBranches:o}=Q();return(0,i.jsx)(n.Button,{"aria-label":`Previous branch`,disabled:o<=1,onClick:a,size:`icon`,type:`button`,variant:`ghost`,...t,children:e??(0,i.jsx)(r.ChevronLeftIcon,{size:14})})},Ue=({children:e,className:t,...a})=>{let{goToNext:o,totalBranches:s}=Q();return(0,i.jsx)(n.Button,{"aria-label":`Next branch`,disabled:s<=1,onClick:o,size:`icon`,type:`button`,variant:`ghost`,...a,children:e??(0,i.jsx)(r.ChevronRightIcon,{size:14})})},We=({className:e,...t})=>{let{currentBranch:r,totalBranches:a}=Q();return(0,i.jsxs)(Pe,{className:(0,n.cn)(`border-none bg-transparent text-muted-foreground shadow-none`,e),...t,children:[r+1,` of `,a]})},Ge=(0,t.memo)(({className:e,...t})=>(0,i.jsx)(f.Streamdown,{className:(0,n.cn)(`size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0`,e),...t}),(e,t)=>e.children===t.children);Ge.displayName=`MessageResponse`;function Ke({data:e,className:t,onRemove:a,...o}){let s=e.filename||``,c=(e.mediaType?.startsWith(`image/`)&&e.url?`image`:`file`)==`image`,l=s||(c?`Image`:`Attachment`);return(0,i.jsx)(`div`,{className:(0,n.cn)(`group relative size-24 overflow-hidden rounded-lg`,t),...o,children:c?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(`img`,{alt:s||`attachment`,className:`size-full object-cover`,height:100,src:e.url,width:100}),a&&(0,i.jsxs)(n.Button,{"aria-label":`Remove attachment`,className:`absolute top-2 right-2 size-6 rounded-full bg-background/80 p-0 opacity-0 backdrop-blur-sm transition-opacity hover:bg-background group-hover:opacity-100 [&>svg]:size-3`,onClick:e=>{e.stopPropagation(),a()},type:`button`,variant:`ghost`,children:[(0,i.jsx)(r.XIcon,{}),(0,i.jsx)(`span`,{className:`sr-only`,children:`Remove`})]})]}):(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)(n.Tooltip,{children:[(0,i.jsx)(n.TooltipTrigger,{asChild:!0,children:(0,i.jsx)(`div`,{className:`flex size-full shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground`,children:(0,i.jsx)(r.PaperclipIcon,{className:`size-4`})})}),(0,i.jsx)(n.TooltipContent,{children:(0,i.jsx)(`p`,{children:l})})]}),a&&(0,i.jsxs)(n.Button,{"aria-label":`Remove attachment`,className:`size-6 shrink-0 rounded-full p-0 opacity-0 transition-opacity hover:bg-accent group-hover:opacity-100 [&>svg]:size-3`,onClick:e=>{e.stopPropagation(),a()},type:`button`,variant:`ghost`,children:[(0,i.jsx)(r.XIcon,{}),(0,i.jsx)(`span`,{className:`sr-only`,children:`Remove`})]})]})})}function qe({children:e,className:t,...r}){return e?(0,i.jsx)(`div`,{className:(0,n.cn)(`ml-auto flex w-fit flex-wrap items-start gap-2`,t),...r,children:e}):null}var Je=({className:e,children:t,...r})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`mt-4 flex w-full items-center justify-between gap-4`,e),...r,children:t});function Ye({className:e,...t}){return(0,i.jsx)(`div`,{"data-slot":`input-group`,role:`group`,className:(0,n.cn)(`group/input-group relative flex w-full items-center rounded-md border border-input shadow-xs transition-[color,box-shadow] outline-none dark:bg-input/30`,`h-9 min-w-0 has-[>textarea]:h-auto`,`has-[>[data-align=inline-start]]:[&>input]:pl-2`,`has-[>[data-align=inline-end]]:[&>input]:pr-2`,`has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>[data-align=block-start]]:[&>input]:pb-3`,`has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-end]]:[&>input]:pt-3`,`has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-[3px] has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50`,`has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-destructive/20 dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40`,e),...t})}var Xe=(0,u.cva)(`flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium text-muted-foreground select-none group-data-[disabled=true]/input-group:opacity-50 [&>kbd]:rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-4`,{variants:{align:{"inline-start":`order-first pl-3 has-[>button]:ml-[-0.45rem] has-[>kbd]:ml-[-0.35rem]`,"inline-end":`order-last pr-3 has-[>button]:mr-[-0.45rem] has-[>kbd]:mr-[-0.35rem]`,"block-start":`order-first w-full justify-start px-3 pt-3 group-has-[>input]/input-group:pt-2.5 [.border-b]:pb-3`,"block-end":`order-last w-full justify-start px-3 pb-3 group-has-[>input]/input-group:pb-2.5 [.border-t]:pt-3`}},defaultVariants:{align:`inline-start`}});function Ze({className:e,align:t=`inline-start`,...r}){return(0,i.jsx)(`div`,{role:`group`,"data-slot":`input-group-addon`,"data-align":t,className:(0,n.cn)(Xe({align:t}),e),onClick:e=>{e.target.closest(`button`)||e.currentTarget.parentElement?.querySelector(`input`)?.focus()},...r})}var Qe=(0,u.cva)(`flex items-center gap-2 text-sm shadow-none`,{variants:{size:{xs:`h-6 gap-1 rounded-[calc(var(--radius)-5px)] px-2 has-[>svg]:px-2 [&>svg:not([class*='size-'])]:size-3.5`,sm:`h-8 gap-1.5 rounded-md px-2.5 has-[>svg]:px-2.5`,"icon-xs":`size-6 rounded-[calc(var(--radius)-5px)] p-0 has-[>svg]:p-0`,"icon-sm":`size-8 p-0 has-[>svg]:p-0`}},defaultVariants:{size:`xs`}});function $e({className:e,type:t=`button`,variant:r=`ghost`,size:a=`xs`,...o}){return(0,i.jsx)(n.Button,{type:t,"data-size":a,variant:r,className:(0,n.cn)(Qe({size:a}),e),...o})}function et({className:e,...t}){return(0,i.jsx)(n.Textarea,{"data-slot":`input-group-control`,className:(0,n.cn)(`flex-1 resize-none rounded-none border-0 bg-transparent py-3 shadow-none focus-visible:ring-0 dark:bg-transparent`,e),...t})}var tt=(0,t.createContext)(null),nt=(0,t.createContext)(null),rt=()=>{let e=(0,t.useContext)(tt);if(!e)throw Error(`Wrap your component inside <PromptInputProvider> to use usePromptInputController().`);return e},it=()=>(0,t.useContext)(tt),at=()=>{let e=(0,t.useContext)(nt);if(!e)throw Error(`Wrap your component inside <PromptInputProvider> to use useProviderAttachments().`);return e},ot=()=>(0,t.useContext)(nt);function st({initialInput:e=``,children:n}){let[r,a]=(0,t.useState)(e),o=(0,t.useCallback)(()=>a(``),[]),[s,c]=(0,t.useState)([]),l=(0,t.useRef)(null),u=(0,t.useRef)(()=>{}),d=(0,t.useCallback)(e=>{let t=Array.from(e);t.length!==0&&c(e=>e.concat(t.map(e=>({id:(0,p.nanoid)(),type:`file`,url:URL.createObjectURL(e),mediaType:e.type,filename:e.name}))))},[]),f=(0,t.useCallback)(e=>{c(t=>{let n=t.find(t=>t.id===e);return n?.url&&URL.revokeObjectURL(n.url),t.filter(t=>t.id!==e)})},[]),m=(0,t.useCallback)(()=>{c(e=>{for(let t of e)t.url&&URL.revokeObjectURL(t.url);return[]})},[]),h=(0,t.useRef)(s);h.current=s,(0,t.useEffect)(()=>()=>{for(let e of h.current)e.url&&URL.revokeObjectURL(e.url)},[]);let g=(0,t.useCallback)(()=>{u.current?.()},[]),_=(0,t.useMemo)(()=>({files:s,add:d,remove:f,clear:m,openFileDialog:g,fileInputRef:l}),[s,d,f,m,g]),v=(0,t.useCallback)((e,t)=>{l.current=e.current,u.current=t},[]),y=(0,t.useMemo)(()=>({textInput:{value:r,setInput:a,clear:o},attachments:_,__registerFileInput:v}),[r,o,_,v]);return(0,i.jsx)(tt.Provider,{value:y,children:(0,i.jsx)(nt.Provider,{value:_,children:n})})}var ct=(0,t.createContext)(null),lt=()=>{let e=ot(),n=(0,t.useContext)(ct),r=e??n;if(!r)throw Error(`usePromptInputAttachments must be used within a PromptInput or PromptInputProvider`);return r};function ut({data:e,className:t,...a}){let o=lt(),s=e.filename||``,c=(e.mediaType?.startsWith(`image/`)&&e.url?`image`:`file`)==`image`,l=s||(c?`Image`:`Attachment`);return(0,i.jsxs)(jt,{children:[(0,i.jsx)(n.HoverCardTrigger,{asChild:!0,children:(0,i.jsxs)(`div`,{className:(0,n.cn)(`group relative flex h-8 cursor-pointer select-none items-center gap-1.5 rounded-md border border-border px-1.5 font-medium text-sm transition-all hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50`,t),...a,children:[(0,i.jsxs)(`div`,{className:`relative size-5 shrink-0`,children:[(0,i.jsx)(`div`,{className:`absolute inset-0 flex size-5 items-center justify-center overflow-hidden rounded bg-background transition-opacity group-hover:opacity-0`,children:c?(0,i.jsx)(`img`,{alt:s||`attachment`,className:`size-5 object-cover`,height:20,src:e.url,width:20}):(0,i.jsx)(`div`,{className:`flex size-5 items-center justify-center text-muted-foreground`,children:(0,i.jsx)(r.PaperclipIcon,{className:`size-3`})})}),(0,i.jsxs)(n.Button,{"aria-label":`Remove attachment`,className:`absolute inset-0 size-5 cursor-pointer rounded p-0 opacity-0 transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 [&>svg]:size-2.5`,onClick:t=>{t.stopPropagation(),o.remove(e.id)},type:`button`,variant:`ghost`,children:[(0,i.jsx)(r.XIcon,{}),(0,i.jsx)(`span`,{className:`sr-only`,children:`Remove`})]})]}),(0,i.jsx)(`span`,{className:`flex-1 truncate`,children:l})]},e.id)}),(0,i.jsx)(Nt,{className:`w-auto p-2`,children:(0,i.jsxs)(`div`,{className:`w-auto space-y-3`,children:[c&&(0,i.jsx)(`div`,{className:`flex max-h-96 w-96 items-center justify-center overflow-hidden rounded-md border`,children:(0,i.jsx)(`img`,{alt:s||`attachment preview`,className:`max-h-full max-w-full object-contain`,height:384,src:e.url,width:448})}),(0,i.jsx)(`div`,{className:`flex items-center gap-2.5`,children:(0,i.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1 px-0.5`,children:[(0,i.jsx)(`h4`,{className:`truncate font-semibold text-sm leading-none`,children:s||(c?`Image`:`Attachment`)}),e.mediaType&&(0,i.jsx)(`p`,{className:`truncate font-mono text-muted-foreground text-xs`,children:e.mediaType})]})})]})})]})}function dt({children:e,className:r,...a}){let o=lt();return o.files.length?(0,i.jsx)(`div`,{className:(0,n.cn)(`flex flex-wrap items-center gap-2 p-3 w-full`,r),...a,children:o.files.map(n=>(0,i.jsx)(t.Fragment,{children:e(n)},n.id))}):null}var ft=({label:e=`Add photos or files`,...t})=>{let a=lt();return(0,i.jsxs)(n.DropdownMenuItem,{...t,onSelect:e=>{e.preventDefault(),a.openFileDialog()},children:[(0,i.jsx)(r.ImageIcon,{className:`mr-2 size-4`}),` `,e]})},pt=({className:e,accept:r,multiple:a,fileInputLabel:o=`Upload files`,globalDrop:s,syncHiddenInput:c,maxFiles:l,maxFileSize:u,onError:d,onSubmit:f,children:m,...h})=>{let g=it(),_=!!g,v=(0,t.useRef)(null),y=(0,t.useRef)(null),[b,x]=(0,t.useState)([]),S=_?g.attachments.files:b,C=(0,t.useRef)(S);C.current=S;let w=(0,t.useCallback)(()=>{v.current?.click()},[]),T=(0,t.useCallback)(e=>!r||r.trim()===``?!0:r.split(`,`).map(e=>e.trim()).filter(Boolean).some(t=>{if(t.endsWith(`/*`)){let n=t.slice(0,-1);return e.type.startsWith(n)}return e.type===t}),[r]),E=(0,t.useCallback)(e=>{let t=Array.from(e),n=t.filter(e=>T(e));if(t.length&&n.length===0){d?.({code:`accept`,message:`No files match the accepted types.`});return}let r=n.filter(e=>u?e.size<=u:!0);if(n.length>0&&r.length===0){d?.({code:`max_file_size`,message:`All files exceed the maximum size.`});return}x(e=>{let t=typeof l==`number`?Math.max(0,l-e.length):void 0,n=typeof t==`number`?r.slice(0,t):r;typeof t==`number`&&r.length>t&&d?.({code:`max_files`,message:`Too many files. Some were not added.`});let i=[];for(let e of n)i.push({id:(0,p.nanoid)(),type:`file`,url:URL.createObjectURL(e),mediaType:e.type,filename:e.name});return e.concat(i)})},[T,l,u,d]),D=(0,t.useCallback)(e=>x(t=>{let n=t.find(t=>t.id===e);return n?.url&&URL.revokeObjectURL(n.url),t.filter(t=>t.id!==e)}),[]),O=(0,t.useCallback)(()=>x(e=>{for(let t of e)t.url&&URL.revokeObjectURL(t.url);return[]}),[]),k=_?g.attachments.add:E,A=_?g.attachments.remove:D,j=_?g.attachments.clear:O,M=_?g.attachments.openFileDialog:w;(0,t.useEffect)(()=>{_&&g.__registerFileInput(v,()=>v.current?.click())},[_,g]),(0,t.useEffect)(()=>{c&&v.current&&S.length===0&&(v.current.value=``)},[S,c]),(0,t.useEffect)(()=>{let e=y.current;if(!e||s)return;let t=e=>{e.dataTransfer?.types?.includes(`Files`)&&e.preventDefault()},n=e=>{e.dataTransfer?.types?.includes(`Files`)&&e.preventDefault(),e.dataTransfer?.files&&e.dataTransfer.files.length>0&&k(e.dataTransfer.files)};return e.addEventListener(`dragover`,t),e.addEventListener(`drop`,n),()=>{e.removeEventListener(`dragover`,t),e.removeEventListener(`drop`,n)}},[k,s]),(0,t.useEffect)(()=>{if(!s)return;let e=e=>{e.dataTransfer?.types?.includes(`Files`)&&e.preventDefault()},t=e=>{e.dataTransfer?.types?.includes(`Files`)&&e.preventDefault(),e.dataTransfer?.files&&e.dataTransfer.files.length>0&&k(e.dataTransfer.files)};return document.addEventListener(`dragover`,e),document.addEventListener(`drop`,t),()=>{document.removeEventListener(`dragover`,e),document.removeEventListener(`drop`,t)}},[k,s]),(0,t.useEffect)(()=>()=>{if(!_)for(let e of C.current)e.url&&URL.revokeObjectURL(e.url)},[_]);let N=e=>{e.currentTarget.files&&k(e.currentTarget.files),e.currentTarget.value=``},P=async e=>{try{let t=await(await fetch(e)).blob();return new Promise(e=>{let n=new FileReader;n.onloadend=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}catch{return null}},F=(0,t.useMemo)(()=>({files:S.map(e=>({...e,id:e.id})),add:k,remove:A,clear:j,openFileDialog:M,fileInputRef:v}),[S,k,A,j,M]),I=(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(`input`,{accept:r,"aria-label":o,className:`hidden`,multiple:a,onChange:N,ref:v,title:o,type:`file`}),(0,i.jsx)(`form`,{className:(0,n.cn)(`w-full`,e),onSubmit:e=>{e.preventDefault();let t=e.currentTarget,n=_?g.textInput.value:new FormData(t).get(`message`)||``;_||t.reset(),Promise.all(S.map(async({id:e,...t})=>{if(t.url&&t.url.startsWith(`blob:`)){let e=await P(t.url);return{...t,url:e??t.url}}return t})).then(t=>{try{let r=f({text:n,files:t},e);r instanceof Promise?r.then(()=>{j(),_&&g.textInput.clear()}).catch(()=>{}):(j(),_&&g.textInput.clear())}catch{}}).catch(()=>{})},ref:y,...h,children:(0,i.jsx)(Ye,{className:`overflow-hidden`,children:m})})]});return _?I:(0,i.jsx)(ct.Provider,{value:F,children:I})},mt=({className:e,...t})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`contents`,e),...t}),ht=({onChange:e,className:r,placeholder:a=`What would you like to know?`,...o})=>{let s=it(),c=lt(),[l,u]=(0,t.useState)(!1),d=e=>{if(e.key===`Enter`){if(l||e.nativeEvent.isComposing||e.shiftKey)return;e.preventDefault();let t=e.currentTarget.form;if(t?.querySelector(`button[type="submit"]`)?.disabled)return;t?.requestSubmit()}if(e.key===`Backspace`&&e.currentTarget.value===``&&c.files.length>0){e.preventDefault();let t=c.files[c.files.length-1];t&&c.remove(t.id)}},f=e=>{let t=e.clipboardData?.items;if(!t)return;let n=[];for(let e of t)if(e.kind===`file`){let t=e.getAsFile();t&&n.push(t)}n.length>0&&(e.preventDefault(),c.add(n))},p=s?{value:s.textInput.value,onChange:t=>{s.textInput.setInput(t.currentTarget.value),e?.(t)}}:{onChange:e};return(0,i.jsx)(et,{className:(0,n.cn)(`field-sizing-content max-h-48 min-h-16`,r),name:`message`,onCompositionEnd:()=>u(!1),onCompositionStart:()=>u(!0),onKeyDown:d,onPaste:f,placeholder:a,...o,...p})},gt=({className:e,...t})=>(0,i.jsx)(Ze,{align:`block-end`,className:(0,n.cn)(`order-first flex-wrap gap-1`,e),...t}),_t=({className:e,...t})=>(0,i.jsx)(Ze,{align:`block-end`,className:(0,n.cn)(`justify-between gap-1`,e),...t}),vt=({className:e,...t})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`flex items-center gap-1`,e),...t}),yt=({variant:e=`ghost`,className:r,size:a,...o})=>{let s=a??(t.Children.count(o.children)>1?`sm`:`icon-sm`);return(0,i.jsx)($e,{className:(0,n.cn)(r),size:s,type:`button`,variant:e,...o})},bt=e=>(0,i.jsx)(n.DropdownMenu,{...e}),xt=({className:e,children:t,...a})=>(0,i.jsx)(n.DropdownMenuTrigger,{asChild:!0,children:(0,i.jsx)(yt,{className:e,...a,children:t??(0,i.jsx)(r.PlusIcon,{className:`size-4`})})}),St=({className:e,...t})=>(0,i.jsx)(n.DropdownMenuContent,{align:`start`,className:(0,n.cn)(e),...t}),Ct=({className:e,...t})=>(0,i.jsx)(n.DropdownMenuItem,{className:(0,n.cn)(e),...t}),wt=({className:e,variant:t=`default`,size:a=`icon-sm`,status:o,children:s,...c})=>{let l=(0,i.jsx)(r.CornerDownLeftIcon,{className:`size-4`});return o===`submitted`?l=(0,i.jsx)(r.Loader2Icon,{className:`size-4 animate-spin`}):o===`streaming`?l=(0,i.jsx)(r.SquareIcon,{className:`size-4`}):o===`error`&&(l=(0,i.jsx)(r.XIcon,{className:`size-4`})),(0,i.jsx)($e,{"aria-label":`Submit`,className:(0,n.cn)(e),size:a,type:`submit`,variant:t,...c,children:s??l})},Tt=({className:e,textareaRef:a,onTranscriptionChange:o,...s})=>{let[c,l]=(0,t.useState)(!1),[u,d]=(0,t.useState)(null),f=(0,t.useRef)(null);(0,t.useEffect)(()=>{if(typeof window<`u`&&(`SpeechRecognition`in window||`webkitSpeechRecognition`in window)){let e=new(window.SpeechRecognition||window.webkitSpeechRecognition);e.continuous=!0,e.interimResults=!0,e.lang=`en-US`,e.onstart=()=>{l(!0)},e.onend=()=>{l(!1)},e.onresult=e=>{let t=``;for(let n=e.resultIndex;n<e.results.length;n++){let r=e.results[n];r.isFinal&&(t+=r[0]?.transcript??``)}if(t&&a?.current){let e=a.current,n=e.value,r=n+(n?` `:``)+t;e.value=r,e.dispatchEvent(new Event(`input`,{bubbles:!0})),o?.(r)}},e.onerror=e=>{console.error(`Speech recognition error:`,e.error),l(!1)},f.current=e,d(e)}return()=>{f.current&&f.current.stop()}},[a,o]);let p=(0,t.useCallback)(()=>{u&&(c?u.stop():u.start())},[u,c]);return(0,i.jsx)(yt,{className:(0,n.cn)(`relative transition-all duration-200`,c&&`animate-pulse bg-accent text-accent-foreground`,e),disabled:!u,onClick:p,...s,children:(0,i.jsx)(r.MicIcon,{className:`size-4`})})},Et=e=>(0,i.jsx)(n.Select,{...e}),Dt=({className:e,...t})=>(0,i.jsx)(n.SelectTrigger,{className:(0,n.cn)(`border-none bg-transparent font-medium text-muted-foreground shadow-none transition-colors`,`hover:bg-accent hover:text-foreground aria-expanded:bg-accent aria-expanded:text-foreground`,e),...t}),Ot=({className:e,...t})=>(0,i.jsx)(n.SelectContent,{className:(0,n.cn)(e),...t}),kt=({className:e,...t})=>(0,i.jsx)(n.SelectItem,{className:(0,n.cn)(e),...t}),At=({className:e,...t})=>(0,i.jsx)(n.SelectValue,{className:(0,n.cn)(e),...t}),jt=({openDelay:e=0,closeDelay:t=0,...r})=>(0,i.jsx)(n.HoverCard,{closeDelay:t,openDelay:e,...r}),Mt=e=>(0,i.jsx)(n.HoverCardTrigger,{...e}),Nt=({align:e=`start`,...t})=>(0,i.jsx)(n.HoverCardContent,{align:e,...t}),Pt=({className:e,...t})=>(0,i.jsx)(`div`,{className:(0,n.cn)(e),...t}),Ft=({className:e,...t})=>(0,i.jsx)(`div`,{className:(0,n.cn)(e),...t}),It=({className:e,...t})=>(0,i.jsx)(`h3`,{className:(0,n.cn)(`mb-2 px-3 font-medium text-muted-foreground text-xs`,e),...t}),Lt=({className:e,...t})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`space-y-1`,e),...t}),Rt=({className:e,...t})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`flex items-center gap-2 px-3 py-2 text-xs hover:bg-accent`,e),...t}),zt=({className:e,...t})=>(0,i.jsx)(n.Command,{className:(0,n.cn)(e),...t}),Bt=({className:e,...t})=>(0,i.jsx)(n.CommandInput,{className:(0,n.cn)(e),...t}),Vt=({className:e,...t})=>(0,i.jsx)(n.CommandList,{className:(0,n.cn)(e),...t}),Ht=({className:e,...t})=>(0,i.jsx)(n.CommandEmpty,{className:(0,n.cn)(e),...t}),Ut=({className:e,...t})=>(0,i.jsx)(n.CommandGroup,{className:(0,n.cn)(e),...t}),Wt=({className:e,...t})=>(0,i.jsx)(n.CommandItem,{className:(0,n.cn)(e),...t}),Gt=({className:e,...t})=>(0,i.jsx)(n.CommandSeparator,{className:(0,n.cn)(e),...t}),Kt=({className:e,children:t,...r})=>(0,i.jsxs)(n.ScrollArea,{className:`w-full overflow-x-auto whitespace-nowrap`,...r,children:[(0,i.jsx)(`div`,{className:(0,n.cn)(`flex w-max flex-nowrap items-center gap-2`,e),children:t}),(0,i.jsx)(n.ScrollBar,{className:`hidden`,orientation:`horizontal`})]}),qt=({suggestion:e,onClick:t,className:r,variant:a=`outline`,size:o=`sm`,children:s,...c})=>(0,i.jsx)(n.Button,{className:(0,n.cn)(`cursor-pointer rounded-full px-4`,r),onClick:()=>{t?.(e)},size:o,type:`button`,variant:a,...c,children:s||e}),Jt=(0,t.createContext)({code:``}),Yt={name:`line-numbers`,line(e,t){e.children.unshift({type:`element`,tagName:`span`,properties:{className:[`inline-block`,`min-w-10`,`mr-4`,`text-right`,`select-none`,`text-muted-foreground`]},children:[{type:`text`,value:String(t)}]})}};async function Xt(e,t,n=!1){let r=n?[Yt]:[];return await Promise.all([(0,m.codeToHtml)(e,{lang:t,theme:`one-light`,transformers:r}),(0,m.codeToHtml)(e,{lang:t,theme:`one-dark-pro`,transformers:r})])}var Zt=({code:e,language:r,showLineNumbers:a=!1,className:o,children:s,...c})=>{let[l,u]=(0,t.useState)(``),[d,f]=(0,t.useState)(``),p=(0,t.useRef)(!1);return(0,t.useEffect)(()=>(Xt(e,r,a).then(([e,t])=>{p.current||=(u(e),f(t),!0)}),()=>{p.current=!1}),[e,r,a]),(0,i.jsx)(Jt.Provider,{value:{code:e},children:(0,i.jsx)(`div`,{className:(0,n.cn)(`group relative w-full overflow-hidden rounded-md border bg-background text-foreground`,o),...c,children:(0,i.jsxs)(`div`,{className:`relative`,children:[(0,i.jsx)(`div`,{className:`overflow-auto dark:hidden [&>pre]:m-0 [&>pre]:bg-background! [&>pre]:p-4 [&>pre]:text-foreground! [&>pre]:text-sm [&_code]:font-mono [&_code]:text-sm`,dangerouslySetInnerHTML:{__html:l}}),(0,i.jsx)(`div`,{className:`hidden overflow-auto dark:block [&>pre]:m-0 [&>pre]:bg-background! [&>pre]:p-4 [&>pre]:text-foreground! [&>pre]:text-sm [&_code]:font-mono [&_code]:text-sm`,dangerouslySetInnerHTML:{__html:d}}),s&&(0,i.jsx)(`div`,{className:`absolute top-2 right-2 flex items-center gap-2`,children:s})]})})})},Qt=({onCopy:e,onError:a,timeout:o=2e3,children:s,className:c,...l})=>{let[u,d]=(0,t.useState)(!1),{code:f}=(0,t.useContext)(Jt),p=async()=>{if(typeof window>`u`||!navigator?.clipboard?.writeText){a?.(Error(`Clipboard API not available`));return}try{await navigator.clipboard.writeText(f),d(!0),e?.(),setTimeout(()=>d(!1),o)}catch(e){a?.(e)}},m=u?r.CheckIcon:r.CopyIcon;return(0,i.jsx)(n.Button,{className:(0,n.cn)(`shrink-0`,c),onClick:p,size:`icon`,variant:`ghost`,...l,children:s??(0,i.jsx)(m,{size:14})})},$t=({className:e,...t})=>(0,i.jsx)(n.Collapsible,{className:(0,n.cn)(`not-prose mb-4 w-full rounded-md border`,e),...t}),en=e=>(0,i.jsxs)(n.Badge,{className:`gap-1.5 rounded-full text-xs`,variant:`secondary`,children:[{"input-streaming":(0,i.jsx)(r.CircleIcon,{className:`size-4`}),"input-available":(0,i.jsx)(r.ClockIcon,{className:`size-4 animate-pulse`}),"approval-requested":(0,i.jsx)(r.ClockIcon,{className:`size-4 text-yellow-600`}),"approval-responded":(0,i.jsx)(r.CheckCircleIcon,{className:`size-4 text-blue-600`}),"output-available":(0,i.jsx)(r.CheckCircleIcon,{className:`size-4 text-green-600`}),"output-error":(0,i.jsx)(r.XCircleIcon,{className:`size-4 text-red-600`}),"output-denied":(0,i.jsx)(r.XCircleIcon,{className:`size-4 text-orange-600`})}[e],{"input-streaming":`Pending`,"input-available":`Running`,"approval-requested":`Awaiting Approval`,"approval-responded":`Responded`,"output-available":`Completed`,"output-error":`Error`,"output-denied":`Denied`}[e]]}),tn=({className:e,title:t,type:a,state:o,...s})=>(0,i.jsxs)(n.CollapsibleTrigger,{className:(0,n.cn)(`flex w-full items-center justify-between gap-4 p-3`,e),...s,children:[(0,i.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,i.jsx)(r.WrenchIcon,{className:`size-4 text-muted-foreground`}),(0,i.jsx)(`span`,{className:`font-medium text-sm`,children:t??a.split(`-`).slice(1).join(`-`)}),en(o)]}),(0,i.jsx)(r.ChevronDownIcon,{className:`size-4 text-muted-foreground transition-transform group-data-[state=open]:rotate-180`})]}),nn=({className:e,...t})=>(0,i.jsx)(n.CollapsibleContent,{className:(0,n.cn)(`data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-popover-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in`,e),...t}),rn=({className:e,input:t,...r})=>(0,i.jsxs)(`div`,{className:(0,n.cn)(`space-y-2 overflow-hidden p-4`,e),...r,children:[(0,i.jsx)(`h4`,{className:`font-medium text-muted-foreground text-xs uppercase tracking-wide`,children:`Parameters`}),(0,i.jsx)(`div`,{className:`rounded-md bg-muted/50`,children:(0,i.jsx)(Zt,{code:JSON.stringify(t,null,2),language:`json`})})]}),an=({className:e,output:r,errorText:a,...o})=>{if(!(r||a))return null;let s=(0,i.jsx)(`div`,{children:r});return typeof r==`object`&&!(0,t.isValidElement)(r)?s=(0,i.jsx)(Zt,{code:JSON.stringify(r,null,2),language:`json`}):typeof r==`string`&&(s=(0,i.jsx)(Zt,{code:r,language:`json`})),(0,i.jsxs)(`div`,{className:(0,n.cn)(`space-y-2 p-4`,e),...o,children:[(0,i.jsx)(`h4`,{className:`font-medium text-muted-foreground text-xs uppercase tracking-wide`,children:a?`Error`:`Result`}),(0,i.jsxs)(`div`,{className:(0,n.cn)(`overflow-x-auto rounded-md text-xs [&_table]:w-full`,a?`bg-destructive/10 text-destructive`:`bg-muted/50 text-foreground`),children:[a&&(0,i.jsx)(`div`,{children:a}),s]})]})},on=(0,t.memo)(({children:e,as:r=`p`,className:a,duration:o=2,spread:s=2})=>{let c=g.motion.create(r),l=(0,t.useMemo)(()=>(e?.length??0)*s,[e,s]);return(0,i.jsx)(c,{animate:{backgroundPosition:`0% center`},className:(0,n.cn)(`relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent`,`[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]`,a),initial:{backgroundPosition:`100% center`},style:{"--spread":`${l}px`,backgroundImage:`var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))`},transition:{repeat:1/0,duration:o,ease:`linear`},children:e})}),sn=(0,t.createContext)(null),cn=()=>{let e=(0,t.useContext)(sn);if(!e)throw Error(`Reasoning components must be used within Reasoning`);return e},ln=1e3,un=1e3,dn=(0,t.memo)(({className:e,isStreaming:r=!1,open:a,defaultOpen:o=!0,onOpenChange:s,duration:c,children:l,...u})=>{let[d,f]=(0,h.useControllableState)({prop:a,defaultProp:o,onChange:s}),[p,m]=(0,h.useControllableState)({prop:c,defaultProp:void 0}),[g,_]=(0,t.useState)(!1),[v,y]=(0,t.useState)(null);return(0,t.useEffect)(()=>{r?v===null&&y(Date.now()):v!==null&&(m(Math.ceil((Date.now()-v)/un)),y(null))},[r,v,m]),(0,t.useEffect)(()=>{if(o&&!r&&d&&!g){let e=setTimeout(()=>{f(!1),_(!0)},ln);return()=>clearTimeout(e)}},[r,d,o,f,g]),(0,i.jsx)(sn.Provider,{value:{isStreaming:r,isOpen:d,setIsOpen:f,duration:p},children:(0,i.jsx)(n.Collapsible,{className:(0,n.cn)(`not-prose mb-4`,e),onOpenChange:e=>{f(e)},open:d,...u,children:l})})}),fn=(e,t)=>e||t===0?(0,i.jsx)(on,{duration:1,children:`Thinking...`}):t===void 0?(0,i.jsx)(`p`,{children:`Thought for a few seconds`}):(0,i.jsxs)(`p`,{children:[`Thought for `,t,` seconds`]}),pn=(0,t.memo)(({className:e,children:t,getThinkingMessage:a=fn,...o})=>{let{isStreaming:s,isOpen:c,duration:l}=cn();return(0,i.jsx)(n.CollapsibleTrigger,{className:(0,n.cn)(`flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground`,e),...o,children:t??(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(r.BrainIcon,{className:`size-4`}),a(s,l),(0,i.jsx)(r.ChevronDownIcon,{className:(0,n.cn)(`size-4 transition-transform`,c?`rotate-180`:`rotate-0`)})]})})}),mn=(0,t.memo)(({className:e,children:t,...r})=>(0,i.jsx)(n.CollapsibleContent,{className:(0,n.cn)(`mt-4 text-sm`,`data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in`,e),...r,children:(0,i.jsx)(f.Streamdown,{children:t})}));dn.displayName=`Reasoning`,pn.displayName=`ReasoningTrigger`,mn.displayName=`ReasoningContent`;var hn=({className:e,...t})=>(0,i.jsx)(n.Collapsible,{className:(0,n.cn)(`not-prose mb-4 text-primary text-xs`,e),...t}),gn=({className:e,count:t,children:a,...o})=>(0,i.jsx)(n.CollapsibleTrigger,{className:(0,n.cn)(`flex items-center gap-2`,e),...o,children:a??(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)(`p`,{className:`font-medium`,children:[`Used `,t,` sources`]}),(0,i.jsx)(r.ChevronDownIcon,{className:`h-4 w-4`})]})}),_n=({className:e,...t})=>(0,i.jsx)(n.CollapsibleContent,{className:(0,n.cn)(`mt-3 flex w-fit flex-col gap-2`,`data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 outline-none data-[state=closed]:animate-out data-[state=open]:animate-in`,e),...t}),vn=({href:e,title:t,children:n,...a})=>(0,i.jsx)(`a`,{className:`flex items-center gap-2`,href:e,rel:`noreferrer`,target:`_blank`,...a,children:n??(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(r.BookIcon,{className:`h-4 w-4`}),(0,i.jsx)(`span`,{className:`block font-medium`,children:t})]})});function yn(e){let t=e??{},n=t.data&&typeof t.data==`object`?t.data:t,r=n.seedApplied,i=n.probes;if(!r&&!i)return;let a={};return r&&(r.success===!1?a.seedError=r.error??(Array.isArray(r.errors)&&r.errors.length?String(r.errors[0]):`Sample data failed to load.`):a.seededRows=(r.inserted??0)+(r.updated??0)),i&&(a.checked={seeds:i.checked?.seeds??0,views:i.checked?.views??0,widgets:i.checked?.widgets??0},a.issues=(i.issues??[]).filter(e=>e&&typeof e.message==`string`).map(e=>({severity:e.severity===`error`?`error`:`warning`,code:String(e.code??`runtime_issue`),message:String(e.message)}))),a}function bn(e){return e===`user`?`user`:`assistant`}function xn(e){let t=e.trim();if(t.length<2||!(t.startsWith(`{`)||t.startsWith(`[`))||!(t.endsWith(`}`)||t.endsWith(`]`)))return!1;try{return JSON.parse(t),!0}catch{return!1}}function Sn(e){let t=e.state??(e.errorText?`output-error`:e.result===void 0?`input-available`:`output-available`);return t===`output-error`||t===`output-denied`?`failed`:t===`approval-requested`||t===`approval-responded`?`awaiting`:t===`output-available`?`completed`:`running`}function Cn(e){return[{create_object:`新建对象`,add_field:`新增字段`,modify_field:`修改字段`,delete_field:`删除字段`,create_metadata:`新建`,update_metadata:`修改`,create_seed:`生成示例数据`,create_package:`新建应用包`}[e.verb]??e.verb,`${e.field?`${e.object?`${e.object}.`:``}${e.field}`:e.object??e.name??``}${e.type?`(${e.type})`:``}`,e.details].filter(Boolean).join(` `)}function wn(e){let t=Sn(e);return t===`awaiting`||t===`failed`||!!e.pendingActionId||!!e.draftReview?.items.length||!!e.proposedPlan||!!e.proposedChanges}function Tn(e){switch(e){case`failed`:return 4;case`awaiting`:return 3;case`running`:return 2;case`completed`:return 1}}function En(e){let t=new Map;for(let n of e){let e=Sn(n),r=`${n.toolName}:${e}`,i=t.get(r);if(i){i.count+=1,i.errorText=i.errorText??n.errorText;continue}t.set(r,{key:r,title:we(n.toolName)||n.toolName,rawName:n.toolName,count:1,state:e,errorText:n.errorText})}return Array.from(t.values()).sort((e,t)=>{let n=Tn(t.state)-Tn(e.state);return n===0?e.title.localeCompare(t.title):n})}function Dn({health:e}){if(!e)return null;let t=e.issues??[],n=t.filter(e=>e.severity===`error`),a=t.filter(e=>e.severity!==`error`),o=e.checked,s=!!o&&o.seeds+o.views+o.widgets>0,c=[];if(typeof e.seededRows==`number`&&e.seededRows>0&&!e.seedError&&c.push(`${e.seededRows} sample row${e.seededRows===1?``:`s`} live`),s&&n.length===0){let e=[];o.views>0&&e.push(`${o.views} view${o.views===1?``:`s`}`),o.widgets>0&&e.push(`${o.widgets} widget${o.widgets===1?``:`s`}`),o.seeds>0&&e.push(`${o.seeds} seed${o.seeds===1?``:`s`}`),e.length&&c.push(`${e.join(` · `)} verified`)}return c.length===0&&!e.seedError&&t.length===0?null:(0,i.jsxs)(`div`,{className:`flex flex-col gap-1 border-t bg-muted/20 px-3 py-2`,"data-testid":`publish-health`,children:[c.length>0?(0,i.jsxs)(`div`,{className:`flex items-center gap-1.5 text-xs text-emerald-700`,children:[(0,i.jsx)(r.CheckCircle2,{className:`size-3.5 shrink-0`}),(0,i.jsx)(`span`,{children:c.join(` · `)})]}):null,e.seedError?(0,i.jsxs)(`div`,{className:`flex items-start gap-1.5 text-xs text-red-600`,children:[(0,i.jsx)(r.XCircle,{className:`mt-0.5 size-3.5 shrink-0`}),(0,i.jsx)(`span`,{children:e.seedError})]}):null,n.map((e,t)=>(0,i.jsxs)(`div`,{className:`flex items-start gap-1.5 text-xs text-red-600`,children:[(0,i.jsx)(r.XCircle,{className:`mt-0.5 size-3.5 shrink-0`}),(0,i.jsx)(`span`,{children:e.message})]},`e${t}`)),a.map((e,t)=>(0,i.jsxs)(`div`,{className:`flex items-start gap-1.5 text-xs text-amber-600`,children:[(0,i.jsx)(r.AlertCircle,{className:`mt-0.5 size-3.5 shrink-0`}),(0,i.jsx)(`span`,{children:e.message})]},`w${t}`))]})}var On=t.forwardRef(({className:e,messages:a=[],placeholder:o=`Type your message...`,onSendMessage:s,onClear:l,onStop:u,onReload:d,onUpgrade:f,disabled:p=!1,readOnly:m=!1,isLoading:h=!1,error:g,showTimestamp:_=!1,showAvatars:v=!1,userAvatarUrl:y,userAvatarFallback:b=`You`,assistantAvatarUrl:x,assistantAvatarFallback:S=`AI`,hideClearBar:C=!1,maxHeight:w=`500px`,enableMarkdown:T=!0,enableFileUpload:E=!1,acceptedFileTypes:D=`image/*,.pdf,.doc,.docx,.txt`,maxFileSize:O=10*1024*1024,suggestions:k,labels:A,models:j,selectedModelId:M,onModelChange:N,headerSlot:P,promptOverlaySlot:F,onInputChange:I,onToolApprove:L,toolApproveLabel:ee=`Approve`,toolDenyLabel:te=`Deny`,toolDenyReason:ne=`User denied the operation`,toolDecisions:re,onReviewDraft:R,toolReviewLabel:ie=e=>`Review ${e} change${e===1?``:`s`}`,onPublishDrafts:z,onOpenBuiltApp:ae,openBuiltAppLabel:B=`Open app`,onPreviewDraftApp:V,previewDraftLabel:H=`Preview`,onDraftArtifacts:U,onBuildMaterialized:W,publishDraftsLabel:oe=`Publish`,publishedLabel:se=`Published`,verifiedLabel:ce=`Verified`,nextStepsLabel:le=`What's next`,planTitleLabel:ue=`Proposed plan`,planExtendLabel:de=`Adding to existing app`,planQuestionsLabel:fe=`Confirm before building`,planAssumptionsLabel:pe=`Assumptions`,planApproveHintLabel:me=`Reply to approve or adjust this plan.`,planApproveLabel:he=`Build it`,planAdjustLabel:ge=`Adjust`,planBuiltLabel:_e=`Built`,planApproveMessage:ve=`Looks good — build it as proposed.`,planApproveDefaultsMessage:G=`Build it with your best assumptions; use sensible defaults for the open questions.`,planAnswerMessage:ye=(e,t)=>`For "${e}", go with: ${t}.`,fetchPendingDraftCount:K,autoPublishDrafts:be=!1,processVisibility:q=`summary`,surface:xe=`card`,...Se},Ce)=>{let J=h?`streaming`:`ready`,Y=xe===`plain`,[X,Ee]=t.useState(null),Z=t.useMemo(()=>({emptyTitle:A?.emptyTitle??`Start a conversation`,emptyDescription:A?.emptyDescription??`Ask anything — the assistant has access to your current app context.`,clear:A?.clear??`Clear`,sendHint:A?.sendHint??`to send`,agentActivity:A?.agentActivity??`Agent activity`,toolCompleted:A?.toolCompleted??`Completed`,toolRunning:A?.toolRunning??`Running`,toolAwaitingApproval:A?.toolAwaitingApproval??`Awaiting approval`,toolFailed:A?.toolFailed??`Failed`,toolDetailsHidden:A?.toolDetailsHidden??`Detailed tool inputs and outputs are hidden in this view.`,copy:A?.copy??`Copy`,copied:A?.copied??`Copied`,regenerate:A?.regenerate??`Regenerate`,model:A?.model??`Model`,submit:A?.submit??`Submit`,uploadFiles:A?.uploadFiles??`Upload files`,stopResponse:A?.stopResponse??`Stop response`,trace:A?.trace??`trace`,viewTrace:A?.viewTrace??`View trace`,connectionWaiting:A?.connectionWaiting??`Waiting for server…`,connectionStalledLabel:A?.connectionStalledLabel??`Still working…`,connectionOfflineLabel:A?.connectionOfflineLabel??`Connection lost — reconnecting…`}),[A]),[De,Me]=t.useState(()=>new Set),[Ne,Pe]=t.useState(()=>new Map),[ze,Q]=t.useState(()=>new Map),Be=t.useRef(new Set),$=t.useCallback(async e=>{if(K)try{let t=await K(e);Q(n=>{if(n.get(e)===t)return n;let r=new Map(n);return r.set(e,t),r})}catch{}},[K]);t.useEffect(()=>{if(!K||h)return;let e=new Set;for(let t of a)for(let n of t.toolInvocations??[]){let t=n.draftReview?.packageId,r=n.toolCallId;t&&r&&!Be.current.has(r)&&(Be.current.add(r),e.add(t))}for(let t of e)$(t)},[a,h,K,$]);let Ve=t.useCallback(async e=>{if(!z)return;let t=[];for(let n of a)for(let r of n.toolInvocations??[])r.draftReview?.packageId===e&&r.toolCallId&&t.push(r.toolCallId);let n=await z(e),r=n&&typeof n==`object`?n:void 0;if((r?r.ok!==!1:n!==!1)&&t.length>0){Me(e=>{let n=new Set(e);for(let e of t)n.add(e);return n});let e=r?.health;e&&Pe(n=>{let r=new Map(n);for(let n of t)r.set(n,e);return r})}$(e)},[z,a,$]),He=t.useRef(new Set),Ue=t.useRef(!1);t.useEffect(()=>{let e=[];for(let t of a)for(let n of t.toolInvocations??[]){let t=n.draftReview;t?.autoPublishable&&t.packageId&&n.toolCallId&&t.items.length>0&&e.push({key:n.toolCallId,packageId:t.packageId})}if(!Ue.current){Ue.current=!0;for(let t of e)He.current.add(t.key);return}if(!be||!z||h)return;let t=e.filter(e=>!He.current.has(e.key));if(t.length!==0){for(let e of t)He.current.add(e.key);for(let e of[...new Set(t.map(e=>e.packageId))])Ve(e)}},[a,h,be,z,Ve]);let We=t.useRef(new Set);t.useEffect(()=>{if(!U)return;let e=new Map,t;for(let n of a){for(let t of n.buildProgress?.items??[])t?.type&&t?.name&&e.set(`${t.type}:${t.name}`,t);for(let r of n.toolInvocations??[]){let n=r.draftReview;for(let t of n?.items??[])t?.type&&t?.name&&e.set(`${t.type}:${t.name}`,t);n?.packageId&&n.items?.some(e=>e.type===`app`)&&(t=n.packageId)}}let n=We.current,r=!1;for(let t of e.keys())n.has(t)||(n.add(t),r=!0);r&&U([...e.values()],t)},[a,U]);let Ke=t.useRef(new Set);t.useEffect(()=>{if(W)for(let e of a)for(let t of e.toolInvocations??[]){let e=t.draftReview;if(!e?.materialized||!t.toolCallId)continue;let n=e.items.find(e=>e.type===`app`);!n||Ke.current.has(t.toolCallId)||(Ke.current.add(t.toolCallId),W(n.name))}},[a,W]);let qe=t.useCallback(e=>{let t=!!e.text?.trim(),n=e.files?.map(e=>e.file).filter(Boolean),r=!!(n&&n.length>0);(t||r)&&s?.(e.text?.trim()??``,n)},[s]),Je=t.useCallback(e=>{s?.(e)},[s]),Ye=t.useRef(null),Xe=t.useCallback(e=>{s?.(e?G:ve)},[s,ve,G]),Ze=t.useCallback(()=>{let e=Ye.current?.querySelector(`textarea`);e&&(e.focus(),e.scrollIntoView({block:`nearest`}))},[]),Qe=t.useCallback(e=>{navigator.clipboard?.writeText(e.content),Ee(e.id),window.setTimeout(()=>Ee(t=>t===e.id?null:t),1500)},[]),$e=t.useMemo(()=>{let e=new Set,t=[],n=-1,r=0;for(let e of a)for(let i of e.toolInvocations??[])i.proposedPlan&&i.toolCallId&&t.push({id:i.toolCallId,order:r}),i.toolName===`apply_blueprint`&&(n=r),r+=1;for(let r of t)r.order<n&&e.add(r.id);return e},[a]),et=t.useMemo(()=>{let e=new Set,t=[],n=new Map,r=0;for(let e of a)for(let i of e.toolInvocations??[])i.proposedChanges&&i.toolCallId?t.push({id:i.toolCallId,toolName:i.toolName??``,order:r}):i.toolName&&n.set(i.toolName,r),r+=1;for(let r of t){let t=n.get(r.toolName);t!==void 0&&t>r.order&&e.add(r.id)}return e},[a]),tt=e=>{let t=e.state??(e.errorText?`output-error`:e.result===void 0?`input-available`:`output-available`),n=`tool-${e.toolName}`,a=re?.[e.toolCallId],o=t===`approval-requested`&&!!L&&!a,c=t===`approval-requested`&&!!e.pendingActionId,l=we(e.toolName),u=Te(e.result),d=q===`debug`&&l&&l.toLowerCase()!==e.toolName.toLowerCase(),f=q===`debug`||o,p=e.draftReview?.packageId,m=p===void 0?void 0:ze.get(p),h=m===void 0?De.has(e.toolCallId):m===0,g=t===`input-streaming`||t===`input-available`,_=(0,i.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[(0,i.jsx)(`span`,{children:l||e.toolName}),d?(0,i.jsx)(`code`,{className:`rounded bg-muted px-1 py-px text-[10px] font-mono text-muted-foreground`,children:e.toolName}):null,g?(0,i.jsx)(Ln,{offlineLabel:Z.connectionOfflineLabel}):null]});return(0,i.jsxs)($t,{defaultOpen:t===`output-error`||t===`approval-requested`||!!(e.draftReview&&e.draftReview.items.length>0)||!!e.proposedPlan||!!e.proposedChanges,children:[(0,i.jsx)(tn,{type:n,state:t,title:_}),(0,i.jsxs)(nn,{children:[f&&e.args!==void 0?(0,i.jsx)(rn,{input:e.args}):null,c?null:f||t===`output-error`?(0,i.jsx)(Gn,{output:u,errorText:e.errorText}):null,a?(0,i.jsxs)(`div`,{className:`flex items-center gap-2 p-3 border-t text-xs `+(a.state===`error`?`bg-destructive/10 text-destructive`:a.state===`success`?`bg-emerald-500/10 text-emerald-700 dark:text-emerald-400`:`bg-muted/30 text-muted-foreground`),children:[(0,i.jsx)(`span`,{"aria-hidden":`true`,children:a.state===`pending`?`...`:a.state===`success`?`OK`:`X`}),(0,i.jsx)(`span`,{children:a.message??(a.state===`pending`?`Submitting decision...`:a.state===`success`?`Action approved and executed.`:`Decision failed.`)})]}):null,o?(0,i.jsxs)(`div`,{className:`flex gap-2 p-3 border-t bg-muted/30`,children:[(0,i.jsx)(`button`,{type:`button`,onClick:()=>L?.(e.toolCallId,!0),className:`inline-flex h-7 items-center rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground hover:bg-primary/90`,children:ee}),(0,i.jsx)(`button`,{type:`button`,onClick:()=>L?.(e.toolCallId,!1,ne),className:`inline-flex h-7 items-center rounded-md border bg-background px-3 text-xs font-medium hover:bg-accent`,children:te})]}):null,e.draftReview&&e.draftReview.items.length>0&&(R||z&&e.draftReview.packageId)?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)(`div`,{className:`flex items-center gap-2 p-3 border-t bg-muted/30`,children:[z&&e.draftReview.packageId?h?(0,i.jsxs)(`span`,{className:`inline-flex h-7 items-center gap-1.5 rounded-md border border-emerald-200 bg-emerald-50 px-3 text-xs font-medium text-emerald-700`,children:[(0,i.jsx)(r.CheckCircle2,{className:`size-3.5`}),se,e.draftReview.failedCount?` · ${e.draftReview.failedCount} need${e.draftReview.failedCount===1?`s`:``} attention`:``]}):(0,i.jsxs)(`button`,{type:`button`,onClick:()=>void Ve(e.draftReview.packageId),className:`inline-flex h-7 items-center gap-1.5 rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground hover:bg-primary/90`,"data-testid":`draft-publish`,children:[(0,i.jsx)(r.Rocket,{className:`size-3.5`}),oe,typeof m==`number`&&m>0?` (${m})`:``]}):null,R?(0,i.jsxs)(`button`,{type:`button`,onClick:()=>R(e.draftReview.items),className:z&&e.draftReview.packageId?`inline-flex h-7 items-center gap-1.5 rounded-md border px-3 text-xs font-medium hover:bg-muted`:`inline-flex h-7 items-center gap-1.5 rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground hover:bg-primary/90`,children:[(0,i.jsx)(r.GitCompareArrows,{className:`size-3.5`}),ie(e.draftReview.items.length)]}):null,V&&!h?(()=>{let t=e.draftReview.items.find(e=>e.type===`app`);return t?(0,i.jsxs)(`button`,{type:`button`,onClick:()=>V(t.name,{materialized:e.draftReview.materialized===!0,appSegment:e.draftReview.packageId}),className:`inline-flex h-7 items-center gap-1.5 rounded-md border px-3 text-xs font-medium hover:bg-muted`,"data-testid":`draft-preview-app`,children:[(0,i.jsx)(r.Eye,{className:`size-3.5`}),H]}):null})():null,e.draftReview.verification?e.draftReview.verification.errors>0?(0,i.jsxs)(`span`,{className:`inline-flex h-7 shrink-0 items-center gap-1.5 rounded-md border border-amber-200 bg-amber-50 px-2.5 text-xs font-medium text-amber-700`,"data-testid":`draft-verification-chip`,children:[(0,i.jsx)(r.TriangleAlert,{className:`size-3.5`}),`${e.draftReview.verification.errors} issue${e.draftReview.verification.errors===1?``:`s`}`]}):(0,i.jsxs)(`span`,{className:`inline-flex h-7 shrink-0 items-center gap-1.5 rounded-md border border-emerald-200 bg-emerald-50 px-2.5 text-xs font-medium text-emerald-700`,"data-testid":`draft-verification-chip`,children:[(0,i.jsx)(r.ShieldCheck,{className:`size-3.5`}),ce]}):null,e.draftReview.summary?(0,i.jsx)(`span`,{className:`truncate text-xs text-muted-foreground`,children:e.draftReview.summary}):null]}),e.draftReview.issues&&e.draftReview.issues.length>0?(0,i.jsxs)(`div`,{className:`flex flex-col gap-1 border-t bg-muted/20 px-3 py-2`,"data-testid":`draft-issues`,children:[e.draftReview.issues.filter(e=>e.severity===`error`).map((e,t)=>(0,i.jsxs)(`div`,{className:`flex items-start gap-1.5 text-xs text-red-600`,children:[(0,i.jsx)(r.XCircle,{className:`mt-0.5 size-3.5 shrink-0`}),(0,i.jsx)(`span`,{children:e.fix?`${e.message} — ${e.fix}`:e.message})]},`e${t}`)),e.draftReview.issues.filter(e=>e.severity!==`error`).map((e,t)=>(0,i.jsxs)(`div`,{className:`flex items-start gap-1.5 text-xs text-amber-600`,children:[(0,i.jsx)(r.AlertCircle,{className:`mt-0.5 size-3.5 shrink-0`}),(0,i.jsx)(`span`,{children:e.message})]},`w${t}`))]}):null,De.has(e.toolCallId)?(0,i.jsx)(Dn,{health:Ne.get(e.toolCallId)}):null,e.draftReview.nextSteps&&e.draftReview.nextSteps.length>0?(0,i.jsxs)(`div`,{className:`flex flex-col gap-1 border-t bg-muted/20 px-3 py-2`,"data-testid":`draft-next-steps`,children:[(0,i.jsx)(`span`,{className:`text-xs font-medium text-foreground/80`,children:le}),e.draftReview.nextSteps.map((e,t)=>(0,i.jsxs)(`div`,{className:`flex items-start gap-1.5 text-xs text-muted-foreground`,children:[(0,i.jsx)(`span`,{className:`mt-px shrink-0 text-foreground/40`,children:`→`}),(0,i.jsx)(`span`,{children:e})]},t))]}):null]}):null,e.proposedPlan?(0,i.jsxs)(`div`,{className:`flex flex-col gap-2 border-t bg-muted/20 px-3 py-2.5`,"data-testid":`proposed-plan`,children:[(0,i.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-xs font-medium text-foreground/80`,children:[(0,i.jsx)(r.ClipboardList,{className:`size-3.5`}),ue]}),e.proposedPlan.targetApp?(0,i.jsxs)(`span`,{className:`inline-flex w-fit items-center gap-1 rounded-md border border-blue-200 bg-blue-50 px-2 py-0.5 text-[11px] font-medium text-blue-700 dark:border-blue-900/50 dark:bg-blue-950/30 dark:text-blue-300`,"data-testid":`proposed-plan-extend`,children:[`+ `,de,` 「`,e.proposedPlan.targetApp,`」`]}):null,e.proposedPlan.summary?(0,i.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.proposedPlan.summary}):null,e.proposedPlan.objects.length>0?(0,i.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.proposedPlan.objects.map(e=>(0,i.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-md border bg-background px-1.5 py-0.5 text-[11px] text-foreground/80`,title:e.name,children:[(0,i.jsx)(r.Table2,{className:`size-3 text-foreground/40`}),e.label||e.name,e.fieldCount>0?(0,i.jsxs)(`span`,{className:`text-foreground/40`,children:[`· `,e.fieldCount]}):null]},e.name))}):null,(()=>{let t=e.proposedPlan.counts,n=[];return t.objects&&n.push(`${t.objects} object${t.objects===1?``:`s`}`),t.views&&n.push(`${t.views} view${t.views===1?``:`s`}`),t.dashboards&&n.push(`${t.dashboards} dashboard${t.dashboards===1?``:`s`}`),t.seedData&&n.push(`sample data`),n.length?(0,i.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:n.join(` · `)}):null})(),e.proposedPlan.assumptions.length>0?(0,i.jsxs)(`div`,{className:`flex flex-col gap-0.5`,children:[(0,i.jsx)(`span`,{className:`text-[11px] font-medium text-foreground/70`,children:pe}),e.proposedPlan.assumptions.map((e,t)=>(0,i.jsxs)(`div`,{className:`flex items-start gap-1.5 text-[11px] text-muted-foreground`,children:[(0,i.jsx)(`span`,{className:`mt-px shrink-0 text-foreground/40`,children:`·`}),(0,i.jsx)(`span`,{children:e})]},t))]}):null,e.proposedPlan.questions.length>0?(0,i.jsxs)(`div`,{className:`flex flex-col gap-1 rounded-md border border-amber-200 bg-amber-50 px-2 py-1.5 dark:border-amber-900/50 dark:bg-amber-950/30`,"data-testid":`proposed-plan-questions`,children:[(0,i.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-[11px] font-medium text-amber-800 dark:text-amber-300`,children:[(0,i.jsx)(r.HelpCircle,{className:`size-3.5`}),fe]}),e.proposedPlan.questions.map((t,n)=>{let r=e.proposedPlan.questionChoices?.find(e=>e.text===t);return(0,i.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,i.jsxs)(`div`,{className:`flex items-start gap-1.5 text-[11px] text-amber-900/90 dark:text-amber-200/90`,children:[(0,i.jsx)(`span`,{className:`mt-px shrink-0`,children:`?`}),(0,i.jsx)(`span`,{children:t})]}),s&&r&&r.options.length>0?(0,i.jsx)(`div`,{className:`flex flex-wrap gap-1 pl-3.5`,"data-testid":`proposed-plan-choice`,children:r.options.map((e,n)=>(0,i.jsx)(`button`,{type:`button`,onClick:()=>s(ye(t,e)),className:`inline-flex h-6 items-center rounded-full border border-amber-300 bg-background px-2 text-[11px] font-medium text-amber-900 hover:bg-amber-100 dark:border-amber-800 dark:text-amber-200 dark:hover:bg-amber-900/40`,children:e},n))}):null]},n)})]}):null,s?$e.has(e.toolCallId)?(0,i.jsx)(`div`,{className:`flex flex-wrap items-center gap-1.5 pt-0.5`,"data-testid":`proposed-plan-actions`,children:(0,i.jsxs)(`span`,{className:`inline-flex h-7 items-center gap-1.5 rounded-md border border-emerald-200 bg-emerald-50 px-3 text-xs font-medium text-emerald-700 dark:border-emerald-900/50 dark:bg-emerald-950/30 dark:text-emerald-300`,"data-testid":`proposed-plan-built`,children:[(0,i.jsx)(r.CheckCircle2,{className:`size-3.5`}),_e]})}):(0,i.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 pt-0.5`,"data-testid":`proposed-plan-actions`,children:[(0,i.jsxs)(`button`,{type:`button`,onClick:()=>Xe(e.proposedPlan.questions.length>0),className:`inline-flex h-7 items-center gap-1.5 rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground hover:bg-primary/90`,"data-testid":`proposed-plan-approve`,children:[(0,i.jsx)(r.Rocket,{className:`size-3.5`}),he]}),(0,i.jsx)(`button`,{type:`button`,onClick:Ze,className:`inline-flex h-7 items-center rounded-md border bg-background px-3 text-xs font-medium hover:bg-accent`,"data-testid":`proposed-plan-adjust`,children:ge})]}):(0,i.jsx)(`span`,{className:`text-[11px] italic text-muted-foreground/80`,children:me})]}):null,e.proposedChanges?(0,i.jsxs)(`div`,{className:`flex flex-col gap-2 border-t bg-muted/20 px-3 py-2.5`,"data-testid":`proposed-changes`,children:[(0,i.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-xs font-medium text-foreground/80`,children:[(0,i.jsx)(r.ClipboardList,{className:`size-3.5`}),`确认改动`]}),e.proposedChanges.summary?(0,i.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.proposedChanges.summary}):null,(0,i.jsx)(`div`,{className:`flex flex-col gap-1`,children:e.proposedChanges.changes.map((e,t)=>(0,i.jsxs)(`div`,{className:`flex items-start gap-1.5 rounded-md border bg-background px-2 py-1 text-[11px] text-foreground/80`,children:[(0,i.jsx)(r.Table2,{className:`mt-px size-3 shrink-0 text-foreground/40`}),(0,i.jsx)(`span`,{children:Cn(e)})]},t))}),s?et.has(e.toolCallId)?(0,i.jsx)(`div`,{className:`flex flex-wrap items-center gap-1.5 pt-0.5`,"data-testid":`proposed-changes-actions`,children:(0,i.jsxs)(`span`,{className:`inline-flex h-7 items-center gap-1.5 rounded-md border border-emerald-200 bg-emerald-50 px-3 text-xs font-medium text-emerald-700 dark:border-emerald-900/50 dark:bg-emerald-950/30 dark:text-emerald-300`,"data-testid":`proposed-changes-confirmed`,children:[(0,i.jsx)(r.CheckCircle2,{className:`size-3.5`}),`已确认`]})}):(0,i.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 pt-0.5`,"data-testid":`proposed-changes-actions`,children:[(0,i.jsxs)(`button`,{type:`button`,onClick:()=>s(`确认修改,应用你刚才提议的改动。`),className:`inline-flex h-7 items-center gap-1.5 rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground hover:bg-primary/90`,"data-testid":`proposed-changes-confirm`,children:[(0,i.jsx)(r.CheckCircle2,{className:`size-3.5`}),`确认修改`]}),(0,i.jsx)(`button`,{type:`button`,onClick:Ze,className:`inline-flex h-7 items-center rounded-md border bg-background px-3 text-xs font-medium hover:bg-accent`,"data-testid":`proposed-changes-adjust`,children:`调整`})]}):(0,i.jsx)(`span`,{className:`text-[11px] italic text-muted-foreground/80`,children:`回复以确认或调整该改动。`})]}):null]})]},e.toolCallId)};return(0,i.jsxs)(`div`,{ref:Ce,className:(0,n.cn)(Y?`flex min-h-0 flex-col overflow-hidden bg-background`:`flex min-h-0 flex-col overflow-hidden rounded-lg border bg-background`,e),style:{maxHeight:w},...Se,children:[l&&!C&&a.length>0&&(0,i.jsx)(`div`,{className:(0,n.cn)(`flex items-center justify-end px-4 py-2`,Y?`bg-background`:`border-b bg-muted/30`),children:(0,i.jsx)(`button`,{type:`button`,onClick:l,className:`text-xs text-muted-foreground hover:text-foreground transition-colors`,children:Z.clear})}),P?(0,i.jsx)(`div`,{className:(0,n.cn)(`shrink-0`,!Y&&`border-b bg-background/50`),children:P}):null,(0,i.jsxs)(Oe,{className:`flex-1 min-h-0`,children:[(0,i.jsxs)(ke,{className:(0,n.cn)(`space-y-4`,Y?`mx-auto w-full max-w-2xl px-4 py-8 sm:px-0`:`px-4 py-3`),children:[a.length===0?(0,i.jsxs)(Ae,{className:`gap-3 px-0 py-8`,children:[(0,i.jsx)(`div`,{className:`flex size-9 items-center justify-center rounded-md bg-muted/70 text-muted-foreground`,children:x?(0,i.jsx)(`img`,{src:x,alt:``,className:`size-full rounded-md object-cover`}):(0,i.jsx)(r.Bot,{className:`size-4`})}),(0,i.jsxs)(`div`,{className:`space-y-1`,children:[(0,i.jsx)(`h3`,{className:`text-sm font-medium text-foreground/90`,children:Z.emptyTitle}),(0,i.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:Z.emptyDescription})]}),k&&k.length>0?(0,i.jsx)(Kt,{className:`justify-center gap-2`,children:k.map(e=>(0,i.jsx)(qt,{className:`h-8 border-border/60 bg-background/80 px-3 text-xs font-medium text-foreground/90 shadow-none hover:bg-muted/60`,suggestion:e,onClick:Je},e))}):null]}):a.map(e=>{let t=e.role===`user`,a=e.toolInvocations??[],o=e.reasoning?.trim(),s=e.sources??[],l=t?void 0:e.buildProgress,u=!t&&!!e.streaming&&!e.content&&a.length===0&&!o&&!l,f=!t&&q===`summary`?a.filter(e=>!wn(e)):[],p=!t&&q===`debug`?a:!t&&q!==`debug`?a.filter(wn):[];return(0,i.jsx)(Fe,{from:bn(e.role),children:(0,i.jsxs)(`div`,{className:(0,n.cn)(`flex w-full gap-2.5`,v?t?`flex-row-reverse items-start`:`flex-row items-start`:`flex-col`),children:[v?(0,i.jsx)(kn,{isUser:t,url:t?y:x,fallback:t?b:S}):null,(0,i.jsxs)(`div`,{className:(0,n.cn)(`flex min-w-0 flex-col gap-2`,v&&!t&&`flex-1`),children:[(0,i.jsxs)(Ie,{children:[l?(0,i.jsx)(Bn,{progress:l,onOpenBuiltApp:ae,openBuiltAppLabel:B,onPreviewDraftApp:V,previewDraftLabel:H,waitingLabel:Z.connectionWaiting,stalledLabel:Z.connectionStalledLabel,offlineLabel:Z.connectionOfflineLabel}):null,!t&&q===`debug`&&o?(0,i.jsxs)(dn,{isStreaming:!!e.streaming&&!e.content,className:`mb-2`,children:[(0,i.jsx)(pn,{}),(0,i.jsx)(mn,{children:o})]}):null,!t&&q===`summary`&&f.length>0?(0,i.jsx)(Vn,{groups:En(f),labels:Z}):null,!t&&p.length>0?p.map(tt):null,t?e.content?(0,i.jsx)(`div`,{className:`whitespace-pre-wrap break-words`,children:e.content}):null:u?(0,i.jsx)(jn,{}):e.content?(0,i.jsx)(Ge,{children:e.content}):null,e.streaming&&!u?(0,i.jsx)(`span`,{"aria-hidden":!0,className:`ml-0.5 inline-block w-[2px] h-4 align-middle bg-current animate-pulse`}):null,!t&&(e.charts?.length??0)>0?(0,i.jsx)(`div`,{className:`mt-2 flex flex-col gap-3`,"data-testid":`chat-charts`,children:e.charts.map((e,t)=>(0,i.jsxs)(`div`,{className:`rounded-lg border bg-background p-3`,style:{width:`min(520px, 80vw)`},"data-testid":`chat-chart`,children:[e.title?(0,i.jsx)(`div`,{className:`mb-2 text-sm font-medium text-foreground`,children:e.title}):null,(0,i.jsx)(c.SchemaRenderer,{schema:{type:`chart`,chartType:e.chartType??`bar`,data:e.data,xAxisKey:e.xAxisKey,series:e.series}})]},t))}):null,!t&&s.length>0?(0,i.jsxs)(hn,{children:[(0,i.jsx)(gn,{count:s.length}),(0,i.jsx)(_n,{children:s.map((e,t)=>(0,i.jsx)(vn,{href:e.url,title:e.title??e.url},e.id??e.url??t))})]}):null,_&&e.timestamp?(0,i.jsx)(`div`,{className:`text-[10px] opacity-70 mt-1`,children:e.timestamp}):null]}),!t&&!u?(0,i.jsxs)(Le,{className:`opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100`,children:[(0,i.jsx)(Re,{label:X===e.id?Z.copied:Z.copy,tooltip:X===e.id?Z.copied:Z.copy,onClick:()=>Qe(e),children:X===e.id?(0,i.jsx)(r.Check,{className:`size-3.5`}):(0,i.jsx)(r.Copy,{className:`size-3.5`})}),d?(0,i.jsx)(Re,{label:Z.regenerate,tooltip:Z.regenerate,onClick:d,children:(0,i.jsx)(r.RefreshCw,{className:`size-3.5`})}):null,q===`debug`&&e.traceId?(0,i.jsx)(`a`,{href:`#trace/${e.traceId}`,"data-trace-id":e.traceId,className:`text-[10px] text-muted-foreground hover:text-foreground ml-1 underline`,title:Z.viewTrace,children:Z.trace}):null]}):null]})]})},e.id)}),h&&!a.some(e=>e.streaming)?(0,i.jsx)(An,{showAvatar:v,assistantAvatarUrl:x,assistantAvatarFallback:S,waitingLabel:Z.connectionWaiting,stalledLabel:Z.connectionStalledLabel,offlineLabel:Z.connectionOfflineLabel}):null]}),(0,i.jsx)(je,{})]}),g?(0,i.jsx)(Wn,{error:g,onReload:d,onUpgrade:f}):null,m?null:(0,i.jsxs)(`div`,{ref:Ye,className:(0,n.cn)(`relative`,Y&&`mx-auto w-full max-w-2xl px-4 pb-4 sm:px-0`),children:[F?(0,i.jsx)(`div`,{className:`absolute bottom-full left-0 right-0 z-10 px-3 pb-1`,children:F}):null,(0,i.jsxs)(pt,{accept:D,fileInputLabel:Z.uploadFiles,maxFileSize:O,onSubmit:qe,onError:e=>{console.warn(`[plugin-chatbot] prompt-input error`,e)},children:[E?(0,i.jsx)(mt,{children:(0,i.jsx)(dt,{children:e=>(0,i.jsx)(ut,{data:e})})}):null,(0,i.jsx)(ht,{placeholder:o,disabled:p||J===`streaming`,onChange:I?e=>I(e.currentTarget.value):void 0}),(0,i.jsxs)(_t,{children:[(0,i.jsxs)(vt,{children:[E?(0,i.jsxs)(bt,{children:[(0,i.jsx)(xt,{}),(0,i.jsx)(St,{children:(0,i.jsx)(ft,{})})]}):null,j&&j.length>0?(0,i.jsx)(`select`,{"aria-label":Z.model,value:M??j[0].id,onChange:e=>N?.(e.target.value),className:`h-7 rounded-md border bg-background px-2 text-xs text-muted-foreground hover:text-foreground focus:outline-none focus:ring-1 focus:ring-ring`,children:j.map(e=>(0,i.jsxs)(`option`,{value:e.id,children:[e.label??e.id,e.provider?` · ${e.provider}`:``]},e.id))}):null,(0,i.jsxs)(`span`,{className:`hidden items-center gap-1 text-[10px] text-muted-foreground sm:inline-flex`,"aria-hidden":`true`,children:[(0,i.jsx)(`kbd`,{className:`inline-flex h-4 items-center rounded border bg-muted px-1 font-mono text-[10px] leading-none`,children:`⌘`}),(0,i.jsx)(r.CornerDownLeft,{className:`h-3 w-3`}),(0,i.jsx)(`span`,{className:`opacity-70`,children:Z.sendHint})]})]}),(0,i.jsx)(wt,{"aria-label":J===`streaming`?Z.stopResponse:Z.submit,status:J,disabled:p,onClick:J===`streaming`?u:void 0,type:J===`streaming`?`button`:`submit`})]})]})]})]})});On.displayName=`ChatbotEnhanced`;function kn({isUser:e,url:t,fallback:a}){return(0,i.jsx)(`div`,{className:(0,n.cn)(`mt-0.5 flex size-7 shrink-0 items-center justify-center overflow-hidden rounded-full text-[11px] font-medium`,e?`bg-secondary text-secondary-foreground`:`bg-primary/10 text-primary`),"aria-hidden":`true`,children:t?(0,i.jsx)(`img`,{src:t,alt:``,className:`size-full object-cover`}):e?a?.trim()?.charAt(0)?.toUpperCase()||`U`:(0,i.jsx)(r.Bot,{className:`size-4`})})}function An({showAvatar:e,assistantAvatarUrl:t,assistantAvatarFallback:r,waitingLabel:a,stalledLabel:o,offlineLabel:s}){return(0,i.jsx)(Fe,{from:`assistant`,"aria-live":`polite`,children:(0,i.jsxs)(`div`,{className:(0,n.cn)(`flex w-full gap-2.5`,e?`flex-row items-start`:`flex-col`),children:[e?(0,i.jsx)(kn,{isUser:!1,url:t,fallback:r}):null,(0,i.jsx)(Ie,{className:`rounded-lg border bg-muted/30 px-3 py-2 text-muted-foreground`,children:(0,i.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[(0,i.jsx)(jn,{}),(0,i.jsx)(In,{active:!0,pending:!0,activityKey:0,waitingLabel:a,stalledLabel:o,offlineLabel:s})]})})]})})}function jn(){return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(`span`,{className:`sr-only`,children:`Assistant is responding`}),(0,i.jsxs)(`span`,{"aria-hidden":`true`,className:`inline-flex items-center gap-1`,children:[(0,i.jsx)(`span`,{className:`size-1.5 rounded-full bg-current animate-pulse`}),(0,i.jsx)(`span`,{className:`size-1.5 rounded-full bg-current animate-pulse`}),(0,i.jsx)(`span`,{className:`size-1.5 rounded-full bg-current animate-pulse`})]})]})}function Mn(e){let t=Math.floor(e/60),n=e%60;return`${t}:${String(n).padStart(2,`0`)}`}var Nn=6;function Pn(e,n){let r=t.useRef(0),i=t.useRef(0),[a,o]=t.useState({elapsed:0,quiet:0});return t.useEffect(()=>{let e=Date.now();r.current=e,i.current=e},[]),t.useEffect(()=>{let e=Date.now();i.current=e,o({elapsed:Math.floor((e-r.current)/1e3),quiet:0})},[n]),t.useEffect(()=>{if(!e)return;let t=()=>{let e=Date.now();o({elapsed:Math.floor((e-r.current)/1e3),quiet:Math.floor((e-i.current)/1e3)})};t();let n=setInterval(t,1e3);return()=>clearInterval(n)},[e]),{elapsedSeconds:a.elapsed,quietSeconds:a.quiet,live:a.quiet<Nn}}function Fn(){let[e,n]=t.useState(()=>typeof navigator<`u`&&navigator.onLine===!1);return t.useEffect(()=>{if(typeof window>`u`)return;let e=()=>n(!1),t=()=>n(!0);return window.addEventListener(`online`,e),window.addEventListener(`offline`,t),()=>{window.removeEventListener(`online`,e),window.removeEventListener(`offline`,t)}},[]),e}function In({active:e,activityKey:t,pending:a=!1,waitingLabel:o,stalledLabel:s=`Still working…`,offlineLabel:c=`Connection lost — reconnecting…`}){let{elapsedSeconds:l,quietSeconds:u,live:d}=Pn(e,t),f=Fn()?`offline`:d?a?`waiting`:`receiving`:`stalled`,p=Mn(l);return(0,i.jsxs)(`span`,{className:(0,n.cn)(`inline-flex items-center gap-1.5 text-xs tabular-nums`,f===`offline`?`text-red-600 font-medium`:f===`stalled`?`text-amber-600 font-medium`:`font-normal text-muted-foreground`),"aria-live":`polite`,"data-liveness-tier":f,title:f===`offline`?`${c} · ${p} elapsed`:f===`receiving`?`Receiving from server · ${p} elapsed`:f===`stalled`?`${s} (${u}s with no response) · ${p} elapsed`:`${o} · ${p} elapsed`,children:[f===`offline`?(0,i.jsx)(r.WifiOff,{className:`size-3 shrink-0`,"aria-hidden":!0}):(0,i.jsx)(`span`,{"aria-hidden":!0,className:(0,n.cn)(`size-1.5 shrink-0 rounded-full`,f===`receiving`?`bg-emerald-500 animate-pulse`:f===`stalled`?`bg-amber-500`:`bg-muted-foreground/50 animate-pulse`)}),(0,i.jsx)(r.Clock3,{className:`size-3 shrink-0`,"aria-hidden":!0}),(0,i.jsx)(`span`,{children:p}),f===`receiving`?null:(0,i.jsxs)(`span`,{children:[`· `,f===`offline`?c:f===`stalled`?s:o]})]})}function Ln({offlineLabel:e}){let[a,o]=t.useState(0),s=Fn();return t.useEffect(()=>{let e=Date.now(),t=setInterval(()=>o(Math.floor((Date.now()-e)/1e3)),1e3);return()=>clearInterval(t)},[]),(0,i.jsxs)(`span`,{className:(0,n.cn)(`inline-flex items-center gap-1 text-xs tabular-nums`,s?`text-red-600 font-medium`:`text-muted-foreground`),"aria-live":`polite`,"data-tool-running-timer":!0,children:[s?(0,i.jsx)(r.WifiOff,{className:`size-3 shrink-0`,"aria-hidden":!0}):(0,i.jsx)(r.Clock3,{className:`size-3 shrink-0`,"aria-hidden":!0}),(0,i.jsx)(`span`,{children:Mn(a)}),s?(0,i.jsxs)(`span`,{children:[`· `,e]}):null]})}var Rn=[`object`,`view`,`dashboard`,`app`,`seed`],zn={object:`Objects`,view:`Views`,dashboard:`Dashboards`,app:`App`,seed:`Sample data`};function Bn({progress:e,onOpenBuiltApp:t,openBuiltAppLabel:a=`Open app`,onPreviewDraftApp:o,previewDraftLabel:s=`Preview`,waitingLabel:c=`Waiting for server…`,stalledLabel:l=`Still working…`,offlineLabel:u=`Connection lost — reconnecting…`}){let{phase:d,appLabel:f,items:p,done:m,total:h,seq:g}=e,_=d===`done`,v=g??`${d}:${m}:${p.length}`,y=p.find(e=>e.type===`app`),b=h>0?Math.min(100,Math.round(m/h*100)):_?100:6,x=new Map;for(let e of p){let t=x.get(e.type)??[];t.push(e.name.replace(/_sample$/,``)),x.set(e.type,t)}let S=[...Rn.filter(e=>x.has(e)),...[...x.keys()].filter(e=>!Rn.includes(e))];return(0,i.jsxs)(`div`,{className:`rounded-lg border bg-muted/30 p-3 text-sm`,"data-testid":`build-progress`,children:[(0,i.jsxs)(`div`,{className:`mb-2 flex items-center gap-2 font-medium`,children:[_?(0,i.jsx)(r.CheckCircle2,{className:`size-4 shrink-0 text-emerald-600`}):(0,i.jsx)(r.Loader2,{className:`size-4 shrink-0 animate-spin text-primary`}),(0,i.jsx)(`span`,{children:_?`Built ${f??`your app`}`:`Building ${f??`your app`}…`}),!_&&d===`data`?(0,i.jsx)(`span`,{className:`text-xs font-normal text-muted-foreground`,children:`adding sample data`}):null,_?null:(0,i.jsx)(`span`,{className:`ml-auto`,children:(0,i.jsx)(In,{active:!0,activityKey:v,waitingLabel:c,stalledLabel:l,offlineLabel:u})})]}),(0,i.jsx)(`div`,{className:`mb-2 h-1.5 w-full overflow-hidden rounded-full bg-muted`,children:(0,i.jsx)(`div`,{className:(0,n.cn)(`h-full rounded-full transition-all duration-500`,_?`bg-emerald-500`:`bg-primary`),style:{width:`${b}%`}})}),(0,i.jsx)(`ul`,{className:`space-y-1`,children:S.map(e=>{let t=x.get(e);return(0,i.jsxs)(`li`,{className:`flex items-start gap-2`,children:[(0,i.jsx)(r.CheckCircle2,{className:`mt-0.5 size-3.5 shrink-0 text-emerald-600`}),(0,i.jsxs)(`span`,{className:`min-w-0 text-muted-foreground`,children:[(0,i.jsx)(`span`,{className:`font-medium text-foreground`,children:zn[e]??e}),` `,t.slice(0,6).join(`, `),t.length>6?` +${t.length-6} more`:``]})]},e)})}),_&&y&&(t||o)?(0,i.jsxs)(`div`,{className:`mt-3 flex items-center gap-2`,children:[t?(0,i.jsxs)(`button`,{type:`button`,onClick:()=>t(y.name),className:`inline-flex h-7 items-center gap-1.5 rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground hover:bg-primary/90`,"data-testid":`build-progress-open-app`,children:[a,(0,i.jsx)(r.ArrowRight,{className:`size-3.5`})]}):null,o?(0,i.jsxs)(`button`,{type:`button`,onClick:()=>o(y.name),className:`inline-flex h-7 items-center gap-1.5 rounded-md border px-3 text-xs font-medium hover:bg-muted`,"data-testid":`build-progress-preview-app`,children:[(0,i.jsx)(r.Eye,{className:`size-3.5`}),s]}):null]}):null]})}function Vn({groups:e,labels:t}){return e.length===0?null:(0,i.jsx)(`div`,{className:`not-prose mb-2 border-l border-border/70 pl-3`,children:(0,i.jsx)(`div`,{className:`space-y-1`,children:e.map(e=>(0,i.jsxs)(`div`,{className:`flex min-h-6 items-center justify-between gap-3 text-xs`,children:[(0,i.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,i.jsx)(Hn,{state:e.state}),(0,i.jsx)(`span`,{className:`truncate font-medium text-foreground`,children:e.title}),e.count>1?(0,i.jsxs)(`span`,{className:`shrink-0 text-[10px] text-muted-foreground`,children:[`x`,e.count]}):null]}),e.state===`running`?(0,i.jsx)(Ln,{offlineLabel:t.connectionOfflineLabel}):(0,i.jsx)(`span`,{className:(0,n.cn)(`shrink-0 text-[10px] font-medium`,e.state===`failed`?`text-destructive`:e.state===`completed`?`text-emerald-700 dark:text-emerald-400`:`text-muted-foreground`),children:Un(e.state,t)})]},e.key))})})}function Hn({state:e}){return e===`failed`?(0,i.jsx)(r.XCircle,{className:`size-3.5 shrink-0 text-destructive`}):e===`completed`?(0,i.jsx)(r.CheckCircle2,{className:`size-3.5 shrink-0 text-emerald-600`}):(0,i.jsx)(r.Clock3,{className:`size-3.5 shrink-0 text-muted-foreground`})}function Un(e,t){switch(e){case`failed`:return t.toolFailed;case`awaiting`:return t.toolAwaitingApproval;case`running`:return t.toolRunning;case`completed`:return t.toolCompleted}}function Wn({error:e,onReload:n,onUpgrade:a}){let o=t.useMemo(()=>De(e),[e]),{summary:s,details:c}=t.useMemo(()=>Ee(e),[e]),[l,u]=t.useState(!1);if(o){let e=typeof navigator<`u`&&!!navigator.language?.toLowerCase().startsWith(`zh`),t=(e?o.message:o.messageEn??o.message)||(e?`AI 额度已用完。`:`You have reached your AI quota.`),n=o.topUp?e?`购买额度包`:`Buy a credit pack`:e?`升级方案`:`Upgrade plan`;return(0,i.jsx)(`div`,{className:`border-t bg-background px-3 py-2 text-sm`,role:`alert`,children:(0,i.jsx)(`div`,{className:`rounded-md border border-amber-300/40 bg-amber-50/60 px-3 py-2 text-foreground dark:bg-amber-950/20`,children:(0,i.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,i.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,i.jsx)(`div`,{className:`font-medium leading-snug text-foreground`,children:e?`需要升级`:`Upgrade needed`}),(0,i.jsx)(`div`,{className:`mt-0.5 break-words leading-snug text-muted-foreground`,children:t})]}),a?(0,i.jsx)(`button`,{type:`button`,onClick:a,className:`inline-flex h-7 shrink-0 items-center rounded-md border border-amber-400/50 bg-background px-2 text-xs font-medium text-amber-700 hover:bg-amber-100/60 dark:text-amber-300`,children:n}):null]})})})}return(0,i.jsx)(`div`,{className:`border-t bg-background px-3 py-2 text-sm`,role:`alert`,children:(0,i.jsxs)(`div`,{className:`rounded-md border border-destructive/20 bg-destructive/5 px-3 py-2 text-foreground`,children:[(0,i.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,i.jsx)(r.AlertCircle,{className:`mt-0.5 h-4 w-4 shrink-0 text-destructive`}),(0,i.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,i.jsx)(`div`,{className:`font-medium leading-snug text-destructive`,children:`Response failed`}),(0,i.jsx)(`div`,{className:`mt-0.5 break-words leading-snug text-muted-foreground`,children:s||`Something went wrong. Please try again.`})]}),(0,i.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[c?(0,i.jsx)(`button`,{type:`button`,onClick:()=>u(e=>!e),className:`inline-flex h-7 items-center rounded-md px-2 text-xs font-medium text-muted-foreground hover:bg-destructive/10 hover:text-foreground`,"aria-expanded":l,children:l?`Hide`:`Details`}):null,n?(0,i.jsxs)(`button`,{type:`button`,onClick:n,className:`inline-flex h-7 items-center rounded-md border border-destructive/30 bg-background px-2 text-xs font-medium text-destructive hover:bg-destructive/10`,children:[(0,i.jsx)(r.RefreshCw,{className:`mr-1 h-3 w-3`}),`Retry`]}):null]})]}),l&&c?(0,i.jsx)(`pre`,{className:`mt-2 max-h-28 overflow-auto whitespace-pre-wrap break-words rounded border bg-background px-2 py-1 font-mono text-[11px] leading-snug text-muted-foreground`,children:c}):null]})})}function Gn({output:e,errorText:t}){return t?(0,i.jsx)(an,{output:void 0,errorText:t}):e==null||e===``?null:typeof e==`string`&&!xn(e)?(0,i.jsxs)(`div`,{className:`space-y-2 p-4`,children:[(0,i.jsx)(`h4`,{className:`font-medium text-muted-foreground text-xs uppercase tracking-wide`,children:`Result`}),(0,i.jsx)(`div`,{className:`overflow-x-auto rounded-md bg-muted/40 px-3 py-2 text-sm text-foreground`,children:(0,i.jsx)(Ge,{children:e})})]}):(0,i.jsx)(an,{output:e,errorText:void 0})}function Kn({floatingConfig:e,headerExtra:n,headerActions:r,...a}){let{position:o=`bottom-right`,defaultOpen:c=!1,panelWidth:l=400,panelHeight:u=520,title:d=`Chat`,triggerSize:f=56}=e??{},[p,m]=t.useState(null);t.useEffect(()=>{let e=document.getElementById(`floating-chatbot-portal`);return e||(e=document.createElement(`div`),e.id=`floating-chatbot-portal`,document.body.appendChild(e)),m(e),()=>{e&&e.parentNode&&!e.hasChildNodes()&&e.parentNode.removeChild(e)}},[]);let h=(0,i.jsxs)(ge,{defaultOpen:c,children:[(0,i.jsx)(be,{position:o,size:f}),(0,i.jsx)(Y,{title:d,position:o,width:l,height:u,headerExtra:n,headerActions:r,children:(0,i.jsx)(On,{...a,maxHeight:`100%`,className:`h-full border-0 rounded-none`})})]});return p?s.createPortal(h,p):h}_.ComponentRegistry.register(`chatbot`,({schema:e,className:t,...n})=>{let{messages:r,isLoading:a,sendMessage:o}=B({api:e.api,initialMessages:e.messages,conversationId:e.conversationId,systemPrompt:e.systemPrompt,model:e.model,streamingEnabled:e.streamingEnabled,headers:e.headers,body:e.requestBody,maxToolRoundtrips:e.maxToolRoundtrips,onError:e.onError,showTimestamp:e.showTimestamp,autoResponse:e.autoResponse,autoResponseText:e.autoResponseText,autoResponseDelay:e.autoResponseDelay,onSend:e.onSend});return(0,i.jsx)(pr,{messages:r,placeholder:e.placeholder,onSendMessage:e=>{o(e)},disabled:e.disabled||a,showTimestamp:e.showTimestamp,userAvatarUrl:e.userAvatarUrl,userAvatarFallback:e.userAvatarFallback,assistantAvatarUrl:e.assistantAvatarUrl,assistantAvatarFallback:e.assistantAvatarFallback,maxHeight:e.maxHeight,className:t,...n})},{namespace:`plugin-chatbot`,label:`Chatbot`,inputs:[{name:`messages`,type:`array`,label:`Initial Messages`,description:`Array of message objects with id, role, content, and optional timestamp`},{name:`placeholder`,type:`string`,label:`Input Placeholder`,defaultValue:`Type your message...`},{name:`showTimestamp`,type:`boolean`,label:`Show Timestamps`,defaultValue:!1},{name:`disabled`,type:`boolean`,label:`Disabled`,defaultValue:!1},{name:`userAvatarUrl`,type:`string`,label:`User Avatar URL`,description:`URL of the user avatar image`},{name:`userAvatarFallback`,type:`string`,label:`User Avatar Fallback`,defaultValue:`You`,description:`Fallback text shown when user avatar image is not available`},{name:`assistantAvatarUrl`,type:`string`,label:`Assistant Avatar URL`,description:`URL of the assistant avatar image`},{name:`assistantAvatarFallback`,type:`string`,label:`Assistant Avatar Fallback`,defaultValue:`AI`,description:`Fallback text shown when assistant avatar image is not available`},{name:`maxHeight`,type:`string`,label:`Max Height`,defaultValue:`500px`},{name:`api`,type:`string`,label:`API Endpoint`,description:`Backend SSE endpoint (e.g., /api/v1/ai/chat). When set, enables streaming AI mode.`},{name:`conversationId`,type:`string`,label:`Conversation ID`,description:`Multi-turn conversation identifier`},{name:`systemPrompt`,type:`string`,label:`System Prompt`,description:`System prompt to configure assistant behavior`},{name:`model`,type:`string`,label:`AI Model`,description:`AI model identifier (e.g., gpt-4o)`},{name:`streamingEnabled`,type:`boolean`,label:`Enable Streaming`,defaultValue:!0},{name:`autoResponse`,type:`boolean`,label:`Enable Auto Response (Demo)`,defaultValue:!1,description:`Automatically send a response after user message (for demo purposes, ignored when API is set)`},{name:`autoResponseText`,type:`string`,label:`Auto Response Text`,defaultValue:`Thank you for your message!`},{name:`autoResponseDelay`,type:`number`,label:`Auto Response Delay (ms)`,defaultValue:1e3},{name:`className`,type:`string`,label:`CSS Class`}],defaultProps:{messages:[{id:`welcome`,role:`assistant`,content:`Hello! How can I help you today?`}],placeholder:`Type your message...`,showTimestamp:!1,disabled:!1,userAvatarFallback:`You`,assistantAvatarFallback:`AI`,maxHeight:`500px`,autoResponse:!0,autoResponseText:`Thank you for your message! This is an automated response.`,autoResponseDelay:1e3,className:`w-full max-w-2xl`}}),_.ComponentRegistry.register(`chatbot-enhanced`,({schema:e,className:t,...n})=>{let{messages:r,isLoading:a,error:o,sendMessage:s,stop:c,reload:l,clear:u,isApiMode:d}=B({api:e.api,initialMessages:e.messages,conversationId:e.conversationId,systemPrompt:e.systemPrompt,model:e.model,streamingEnabled:e.streamingEnabled,headers:e.headers,body:e.requestBody,maxToolRoundtrips:e.maxToolRoundtrips,onError:e.onError,showTimestamp:e.showTimestamp,autoResponse:e.autoResponse,autoResponseText:e.autoResponseText,autoResponseDelay:e.autoResponseDelay,onSend:e.onSend});return(0,i.jsx)(On,{messages:r,placeholder:e.placeholder,onSendMessage:(e,t)=>{s(e,t)},onClear:()=>{u(),e.onClear?.()},onStop:d&&a?c:void 0,onReload:d?l:void 0,disabled:e.disabled,isLoading:a,error:o,showTimestamp:e.showTimestamp,userAvatarUrl:e.userAvatarUrl,userAvatarFallback:e.userAvatarFallback,assistantAvatarUrl:e.assistantAvatarUrl,assistantAvatarFallback:e.assistantAvatarFallback,maxHeight:e.maxHeight,enableMarkdown:e.enableMarkdown??!0,enableFileUpload:e.enableFileUpload??!1,processVisibility:e.processVisibility,className:t,...n})},{namespace:`plugin-chatbot`,label:`Chatbot (Enhanced)`,inputs:[{name:`messages`,type:`array`,label:`Initial Messages`},{name:`placeholder`,type:`string`,label:`Input Placeholder`,defaultValue:`Type your message...`},{name:`showTimestamp`,type:`boolean`,label:`Show Timestamps`,defaultValue:!1},{name:`disabled`,type:`boolean`,label:`Disabled`,defaultValue:!1},{name:`enableMarkdown`,type:`boolean`,label:`Enable Markdown`,defaultValue:!0},{name:`enableFileUpload`,type:`boolean`,label:`Enable File Upload`,defaultValue:!1},{name:`processVisibility`,type:`enum`,label:`Agent Process Visibility`,defaultValue:`summary`},{name:`userAvatarUrl`,type:`string`,label:`User Avatar URL`},{name:`userAvatarFallback`,type:`string`,label:`User Avatar Fallback`,defaultValue:`You`},{name:`assistantAvatarUrl`,type:`string`,label:`Assistant Avatar URL`},{name:`assistantAvatarFallback`,type:`string`,label:`Assistant Avatar Fallback`,defaultValue:`AI`},{name:`maxHeight`,type:`string`,label:`Max Height`,defaultValue:`500px`},{name:`api`,type:`string`,label:`API Endpoint`,description:`Backend SSE endpoint for streaming AI mode`},{name:`conversationId`,type:`string`,label:`Conversation ID`},{name:`systemPrompt`,type:`string`,label:`System Prompt`},{name:`model`,type:`string`,label:`AI Model`},{name:`streamingEnabled`,type:`boolean`,label:`Enable Streaming`,defaultValue:!0},{name:`autoResponse`,type:`boolean`,label:`Enable Auto Response (Demo)`,defaultValue:!1},{name:`autoResponseText`,type:`string`,label:`Auto Response Text`,defaultValue:`Thank you for your message!`},{name:`autoResponseDelay`,type:`number`,label:`Auto Response Delay (ms)`,defaultValue:1e3},{name:`className`,type:`string`,label:`CSS Class`}],defaultProps:{messages:[{id:`welcome`,role:`assistant`,content:`Hello! How can I help you today?`}],placeholder:`Type your message...`,showTimestamp:!1,disabled:!1,enableMarkdown:!0,enableFileUpload:!1,userAvatarFallback:`You`,assistantAvatarFallback:`AI`,maxHeight:`500px`,autoResponse:!0,autoResponseText:`Thank you for your message! This is an automated response.`,autoResponseDelay:1e3,className:`w-full max-w-2xl`}}),_.ComponentRegistry.register(`chatbot-floating`,({schema:e,className:t,...n})=>{let{messages:r,isLoading:a,error:o,sendMessage:s,stop:c,reload:l,clear:u,isApiMode:d}=B({api:e.api,initialMessages:e.messages,conversationId:e.conversationId,systemPrompt:e.systemPrompt,model:e.model,streamingEnabled:e.streamingEnabled,headers:e.headers,body:e.requestBody,maxToolRoundtrips:e.maxToolRoundtrips,onError:e.onError,showTimestamp:e.showTimestamp,autoResponse:e.autoResponse,autoResponseText:e.autoResponseText,autoResponseDelay:e.autoResponseDelay,onSend:e.onSend});return(0,i.jsx)(Kn,{floatingConfig:e.floatingConfig,messages:r,placeholder:e.placeholder,onSendMessage:(e,t)=>{s(e,t)},onClear:()=>{u(),e.onClear?.()},onStop:d&&a?c:void 0,onReload:d?l:void 0,disabled:e.disabled,isLoading:a,error:o,showTimestamp:e.showTimestamp,userAvatarUrl:e.userAvatarUrl,userAvatarFallback:e.userAvatarFallback,assistantAvatarUrl:e.assistantAvatarUrl,assistantAvatarFallback:e.assistantAvatarFallback,enableMarkdown:e.enableMarkdown??!0,enableFileUpload:e.enableFileUpload??!1,className:t,...n})},{namespace:`plugin-chatbot`,label:`Chatbot (Floating)`,inputs:[{name:`displayMode`,type:`string`,label:`Display Mode`,defaultValue:`floating`,description:`Set to "floating" for FAB widget`},{name:`floatingConfig.position`,type:`string`,label:`FAB Position`,defaultValue:`bottom-right`,description:`bottom-right or bottom-left`},{name:`floatingConfig.defaultOpen`,type:`boolean`,label:`Default Open`,defaultValue:!1},{name:`floatingConfig.panelWidth`,type:`number`,label:`Panel Width`,defaultValue:400},{name:`floatingConfig.panelHeight`,type:`number`,label:`Panel Height`,defaultValue:520},{name:`floatingConfig.title`,type:`string`,label:`Panel Title`,defaultValue:`Chat`},{name:`floatingConfig.triggerSize`,type:`number`,label:`Trigger Size`,defaultValue:56},{name:`messages`,type:`array`,label:`Initial Messages`},{name:`placeholder`,type:`string`,label:`Input Placeholder`,defaultValue:`Type your message...`},{name:`enableMarkdown`,type:`boolean`,label:`Enable Markdown`,defaultValue:!0},{name:`enableFileUpload`,type:`boolean`,label:`Enable File Upload`,defaultValue:!1},{name:`api`,type:`string`,label:`API Endpoint`,description:`Backend SSE endpoint for streaming AI mode`},{name:`conversationId`,type:`string`,label:`Conversation ID`},{name:`systemPrompt`,type:`string`,label:`System Prompt`},{name:`model`,type:`string`,label:`AI Model`},{name:`streamingEnabled`,type:`boolean`,label:`Enable Streaming`,defaultValue:!0},{name:`autoResponse`,type:`boolean`,label:`Enable Auto Response (Demo)`,defaultValue:!1},{name:`autoResponseText`,type:`string`,label:`Auto Response Text`,defaultValue:`Thank you for your message!`},{name:`autoResponseDelay`,type:`number`,label:`Auto Response Delay (ms)`,defaultValue:1e3},{name:`className`,type:`string`,label:`CSS Class`}],defaultProps:{displayMode:`floating`,floatingConfig:{position:`bottom-right`,defaultOpen:!1,panelWidth:400,panelHeight:520,title:`Chat`,triggerSize:56},messages:[{id:`welcome`,role:`assistant`,content:`Hello! How can I help you today?`}],placeholder:`Type your message...`,enableMarkdown:!0,enableFileUpload:!1,autoResponse:!0,autoResponseText:`Thank you for your message! This is an automated response.`,autoResponseDelay:1e3}});var qn=({size:e=16})=>(0,i.jsxs)(`svg`,{height:e,strokeLinejoin:`round`,style:{color:`currentcolor`},viewBox:`0 0 16 16`,width:e,children:[(0,i.jsx)(`title`,{children:`Loader`}),(0,i.jsxs)(`g`,{clipPath:`url(#clip0_2393_1490)`,children:[(0,i.jsx)(`path`,{d:`M8 0V4`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,i.jsx)(`path`,{d:`M8 16V12`,opacity:`0.5`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,i.jsx)(`path`,{d:`M3.29773 1.52783L5.64887 4.7639`,opacity:`0.9`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,i.jsx)(`path`,{d:`M12.7023 1.52783L10.3511 4.7639`,opacity:`0.1`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,i.jsx)(`path`,{d:`M12.7023 14.472L10.3511 11.236`,opacity:`0.4`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,i.jsx)(`path`,{d:`M3.29773 14.472L5.64887 11.236`,opacity:`0.6`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,i.jsx)(`path`,{d:`M15.6085 5.52783L11.8043 6.7639`,opacity:`0.2`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,i.jsx)(`path`,{d:`M0.391602 10.472L4.19583 9.23598`,opacity:`0.7`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,i.jsx)(`path`,{d:`M15.6085 10.4722L11.8043 9.2361`,opacity:`0.3`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,i.jsx)(`path`,{d:`M0.391602 5.52783L4.19583 6.7639`,opacity:`0.8`,stroke:`currentColor`,strokeWidth:`1.5`})]}),(0,i.jsx)(`defs`,{children:(0,i.jsx)(`clipPath`,{id:`clip0_2393_1490`,children:(0,i.jsx)(`rect`,{fill:`white`,height:`16`,width:`16`})})})]}),Jn=({className:e,size:t=16,...r})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`inline-flex animate-spin items-center justify-center`,e),...r,children:(0,i.jsx)(qn,{size:t})}),Yn=w({CodeBlock:()=>Zt,CodeBlockCopyButton:()=>Qt,Conversation:()=>Oe,ConversationContent:()=>ke,ConversationEmptyState:()=>Ae,ConversationScrollButton:()=>je,Loader:()=>Jn,Message:()=>Fe,MessageAction:()=>Re,MessageActions:()=>Le,MessageAttachment:()=>Ke,MessageAttachments:()=>qe,MessageBranch:()=>Be,MessageBranchContent:()=>$,MessageBranchNext:()=>Ue,MessageBranchPage:()=>We,MessageBranchPrevious:()=>He,MessageBranchSelector:()=>Ve,MessageContent:()=>Ie,MessageResponse:()=>Ge,MessageToolbar:()=>Je,PromptInput:()=>pt,PromptInputActionAddAttachments:()=>ft,PromptInputActionMenu:()=>bt,PromptInputActionMenuContent:()=>St,PromptInputActionMenuItem:()=>Ct,PromptInputActionMenuTrigger:()=>xt,PromptInputAttachment:()=>ut,PromptInputAttachments:()=>dt,PromptInputBody:()=>mt,PromptInputButton:()=>yt,PromptInputCommand:()=>zt,PromptInputCommandEmpty:()=>Ht,PromptInputCommandGroup:()=>Ut,PromptInputCommandInput:()=>Bt,PromptInputCommandItem:()=>Wt,PromptInputCommandList:()=>Vt,PromptInputCommandSeparator:()=>Gt,PromptInputFooter:()=>_t,PromptInputHeader:()=>gt,PromptInputHoverCard:()=>jt,PromptInputHoverCardContent:()=>Nt,PromptInputHoverCardTrigger:()=>Mt,PromptInputProvider:()=>st,PromptInputSelect:()=>Et,PromptInputSelectContent:()=>Ot,PromptInputSelectItem:()=>kt,PromptInputSelectTrigger:()=>Dt,PromptInputSelectValue:()=>At,PromptInputSpeechButton:()=>Tt,PromptInputSubmit:()=>wt,PromptInputTab:()=>Ft,PromptInputTabBody:()=>Lt,PromptInputTabItem:()=>Rt,PromptInputTabLabel:()=>It,PromptInputTabsList:()=>Pt,PromptInputTextarea:()=>ht,PromptInputTools:()=>vt,Reasoning:()=>dn,ReasoningContent:()=>mn,ReasoningTrigger:()=>pn,Shimmer:()=>on,Source:()=>vn,Sources:()=>hn,SourcesContent:()=>_n,SourcesTrigger:()=>gn,Suggestion:()=>qt,Suggestions:()=>Kt,Tool:()=>$t,ToolContent:()=>nn,ToolHeader:()=>tn,ToolInput:()=>rn,ToolOutput:()=>an,highlightCode:()=>Xt,usePromptInputAttachments:()=>lt,usePromptInputController:()=>rt,useProviderAttachments:()=>at,useReasoning:()=>cn}),Xn=`/api/v1/ai`;function Zn(e,t,n){let r=e.replace(/\/$/,``),i=new URLSearchParams;if(n)for(let[e,t]of Object.entries(n))t==null||t===``||i.set(e,String(t));let a=i.toString();return`${r}${t}${a?`?${a}`:``}`}async function Qn(e,t,n){let r=await fetch(e,{credentials:`include`,...t,headers:{Accept:`application/json`,"Content-Type":`application/json`,...n??{},...t.headers??{}}}),i=null;try{i=await r.json()}catch{}if(!r.ok){let e=i?.error?.message??i?.message??i?.error??`${r.status} ${r.statusText}`,t=Error(typeof e==`string`?e:JSON.stringify(e));throw t.status=r.status,t.body=i,t}return i}function $n(e={}){let{apiBase:n=Xn,status:r=`pending`,conversationId:i,limit:a,headers:o,pollInterval:s=5e3,enabled:c=!0}=e,[l,u]=t.useState([]),[d,f]=t.useState(0),[p,m]=t.useState(!1),[h,g]=t.useState(void 0),_=t.useRef({apiBase:n,status:r,conversationId:i,limit:a,headers:o});_.current={apiBase:n,status:r,conversationId:i,limit:a,headers:o};let v=t.useCallback(async()=>{let{apiBase:e,status:t,conversationId:n,limit:r,headers:i}=_.current;m(!0),g(void 0);try{let a=await Qn(Zn(e,`/pending-actions`,{status:t&&t!==`all`?t:void 0,conversationId:n,limit:r}),{method:`GET`},i);u(Array.isArray(a.items)?a.items:[]),f(typeof a.total==`number`?a.total:a.items?.length??0)}catch(e){g(e instanceof Error?e:Error(String(e)))}finally{m(!1)}},[]),y=t.useCallback(async e=>{let{apiBase:t,headers:n}=_.current,r=Zn(t,`/pending-actions/${encodeURIComponent(e)}/approve`);try{return await Qn(r,{method:`POST`,body:`{}`},n)}finally{v()}},[v]),b=t.useCallback(async(e,t)=>{let{apiBase:n,headers:r}=_.current,i=Zn(n,`/pending-actions/${encodeURIComponent(e)}/reject`);try{return await Qn(i,{method:`POST`,body:JSON.stringify(t?{reason:t}:{})},r)}finally{v()}},[v]);return t.useEffect(()=>{if(!c||(v(),!s||s<=0))return;let e=setInterval(()=>{v()},s);return()=>clearInterval(e)},[c,s,v,n,r,i,a]),{items:l,total:d,isLoading:p,error:h,refresh:v,approve:y,reject:b}}var er={pending:{variant:`secondary`,label:`Pending`},approved:{variant:`default`,label:`Approved`},executed:{variant:`default`,label:`Executed`},failed:{variant:`destructive`,label:`Failed`},rejected:{variant:`outline`,label:`Rejected`}};function tr({status:e}){let t=er[e]??{variant:`outline`,label:e};return(0,i.jsx)(n.Badge,{variant:t.variant,children:t.label})}function nr(e){if(!e)return`—`;let t=Date.parse(e);if(Number.isNaN(t))return e;let n=Date.now()-t,r=Math.round(n/1e3);if(r<45)return`just now`;let i=Math.round(r/60);if(i<60)return`${i}m ago`;let a=Math.round(i/60);if(a<24)return`${a}h ago`;let o=Math.round(a/24);if(o<30)return`${o}d ago`;try{return new Date(e).toLocaleDateString()}catch{return e}}function rr(e){if(!e)return null;try{return JSON.parse(e)}catch{return e}}function ir({value:e,max:t=320}){let n=typeof e==`string`?e:JSON.stringify(e,null,2);return n==null||n===``?(0,i.jsx)(`span`,{className:`text-muted-foreground text-xs`,children:`—`}):(0,i.jsx)(`pre`,{className:`bg-muted/40 rounded text-xs p-2 overflow-auto whitespace-pre-wrap break-all`,style:{maxHeight:t},children:n})}function ar(e){switch(e){case`pending`:return`pending`;case`all`:return`all`;case`decided`:return`all`}}function or({apiBase:e,headers:a,pollInterval:o=5e3,conversationId:s,variant:c=`card`,title:l=`AI Approvals`,description:u=`Actions an AI agent proposed that need a human review before execution.`,className:d}){let[f,p]=t.useState(`pending`),[m,h]=t.useState(null),[g,_]=t.useState(null),[v,y]=t.useState(``),[b,x]=t.useState(null),[S,C]=t.useState(null),[w,T]=t.useState(null),{items:E,isLoading:D,error:O,refresh:k,approve:A,reject:j}=$n({apiBase:e,headers:a,pollInterval:o,conversationId:s,status:ar(f)}),M=t.useMemo(()=>f===`decided`?E.filter(e=>e.status!==`pending`):E,[E,f]),N=t.useMemo(()=>m?E.find(e=>e.id===m)??null:null,[m,E]),P=t.useCallback(async e=>{x(e),C(null);try{let t=await A(e),n=t.status===`executed`;T({id:e,kind:`approve`,ok:n,message:n?`Executed`:t.error??`Action failed during execution`})}catch(t){let n=t instanceof Error?t.message:String(t);C(n),T({id:e,kind:`approve`,ok:!1,message:n})}finally{x(null)}},[A]),F=t.useCallback(async(e,t)=>{x(e),C(null);try{await j(e,t.trim()||void 0),T({id:e,kind:`reject`,ok:!0,message:`Rejected`}),_(null),y(``)}catch(t){let n=t instanceof Error?t.message:String(t);C(n),T({id:e,kind:`reject`,ok:!1,message:n})}finally{x(null)}},[j]),I=(0,i.jsxs)(`div`,{className:`space-y-3`,children:[(0,i.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,i.jsx)(n.Tabs,{value:f,onValueChange:e=>p(e),children:(0,i.jsxs)(n.TabsList,{children:[(0,i.jsx)(n.TabsTrigger,{value:`pending`,children:`Pending`}),(0,i.jsx)(n.TabsTrigger,{value:`decided`,children:`Decided`}),(0,i.jsx)(n.TabsTrigger,{value:`all`,children:`All`})]})}),(0,i.jsxs)(n.Button,{variant:`outline`,size:`sm`,onClick:()=>void k(),disabled:D,"data-testid":`ai-inbox-refresh`,children:[(0,i.jsx)(r.RefreshCw,{className:`h-3.5 w-3.5 mr-1.5 ${D?`animate-spin`:``}`}),`Refresh`]})]}),O?(0,i.jsxs)(n.Alert,{variant:`destructive`,children:[(0,i.jsx)(r.AlertCircle,{className:`h-4 w-4`}),(0,i.jsx)(n.AlertDescription,{children:O.message})]}):null,S?(0,i.jsxs)(n.Alert,{variant:`destructive`,children:[(0,i.jsx)(r.AlertCircle,{className:`h-4 w-4`}),(0,i.jsx)(n.AlertDescription,{children:S})]}):null,w&&!S?(0,i.jsxs)(n.Alert,{variant:w.ok?`default`:`destructive`,children:[w.ok?(0,i.jsx)(r.CheckCircle2,{className:`h-4 w-4`}):(0,i.jsx)(r.XCircle,{className:`h-4 w-4`}),(0,i.jsxs)(n.AlertDescription,{children:[w.kind===`approve`?`Approve`:`Reject`,` for`,` `,(0,i.jsxs)(`code`,{className:`text-xs`,children:[w.id.slice(0,8),`…`]}),`:`,` `,w.message??(w.ok?`OK`:`Failed`)]})]}):null,D&&M.length===0?(0,i.jsxs)(`div`,{className:`space-y-2`,children:[(0,i.jsx)(n.Skeleton,{className:`h-10 w-full`}),(0,i.jsx)(n.Skeleton,{className:`h-10 w-full`}),(0,i.jsx)(n.Skeleton,{className:`h-10 w-full`})]}):M.length===0?(0,i.jsx)(n.Empty,{children:(0,i.jsxs)(n.EmptyHeader,{children:[(0,i.jsx)(n.EmptyMedia,{children:(0,i.jsx)(r.Inbox,{className:`h-8 w-8 text-muted-foreground`})}),(0,i.jsx)(n.EmptyTitle,{children:`No actions waiting`}),(0,i.jsx)(n.EmptyDescription,{children:`When the AI proposes a sensitive action it will appear here for review.`})]})}):(0,i.jsx)(`div`,{className:`rounded-md border`,children:(0,i.jsxs)(n.Table,{children:[(0,i.jsx)(n.TableHeader,{children:(0,i.jsxs)(n.TableRow,{children:[(0,i.jsx)(n.TableHead,{className:`w-[140px]`,children:`Tool`}),(0,i.jsx)(n.TableHead,{className:`w-[140px]`,children:`Action`}),(0,i.jsx)(n.TableHead,{className:`w-[120px]`,children:`Object`}),(0,i.jsx)(n.TableHead,{className:`w-[110px]`,children:`Status`}),(0,i.jsx)(n.TableHead,{className:`w-[110px]`,children:`Proposed`}),(0,i.jsx)(n.TableHead,{className:`w-[260px] text-right`,children:`Decision`})]})}),(0,i.jsx)(n.TableBody,{children:M.map(e=>{let t=e.status===`pending`,a=b===e.id;return(0,i.jsxs)(n.TableRow,{children:[(0,i.jsx)(n.TableCell,{className:`font-mono text-xs`,children:e.tool_name}),(0,i.jsx)(n.TableCell,{className:`text-sm`,children:e.action_name}),(0,i.jsx)(n.TableCell,{className:`text-sm`,children:e.object_name}),(0,i.jsx)(n.TableCell,{children:(0,i.jsx)(tr,{status:e.status})}),(0,i.jsx)(n.TableCell,{className:`text-xs text-muted-foreground`,children:(0,i.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,i.jsx)(r.Clock,{className:`h-3 w-3`}),` `,nr(e.proposed_at)]})}),(0,i.jsx)(n.TableCell,{className:`text-right`,children:(0,i.jsxs)(`div`,{className:`inline-flex gap-1.5`,children:[(0,i.jsxs)(n.Button,{size:`sm`,variant:`ghost`,onClick:()=>h(e.id),"data-testid":`ai-inbox-view-${e.id}`,children:[(0,i.jsx)(r.Eye,{className:`h-3.5 w-3.5 mr-1`}),` View`]}),t?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)(n.Button,{size:`sm`,variant:`default`,disabled:a,onClick:()=>void P(e.id),"data-testid":`ai-inbox-approve-${e.id}`,children:[(0,i.jsx)(r.CheckCircle2,{className:`h-3.5 w-3.5 mr-1`}),a?`Working…`:`Approve`]}),(0,i.jsxs)(n.Button,{size:`sm`,variant:`destructive`,disabled:a,onClick:()=>{_(e.id),y(``)},"data-testid":`ai-inbox-reject-${e.id}`,children:[(0,i.jsx)(r.XCircle,{className:`h-3.5 w-3.5 mr-1`}),`Reject`]})]}):null]})})]},e.id)})})]})})]});return(0,i.jsxs)(i.Fragment,{children:[c===`card`?(0,i.jsxs)(n.Card,{className:d,children:[(0,i.jsxs)(n.CardHeader,{className:`pb-3`,children:[(0,i.jsxs)(n.CardTitle,{className:`flex items-center gap-2`,children:[(0,i.jsx)(r.Bot,{className:`h-4 w-4`}),` `,l]}),u?(0,i.jsx)(n.CardDescription,{children:u}):null]}),(0,i.jsx)(n.CardContent,{children:I})]}):(0,i.jsx)(`div`,{className:d,children:I}),(0,i.jsx)(n.Sheet,{open:!!m,onOpenChange:e=>{e||h(null)},children:(0,i.jsxs)(n.SheetContent,{className:`sm:max-w-[560px] overflow-y-auto`,children:[(0,i.jsxs)(n.SheetHeader,{children:[(0,i.jsxs)(n.SheetTitle,{className:`flex items-center gap-2`,children:[(0,i.jsx)(r.Bot,{className:`h-4 w-4`}),N?N.action_name:`Pending action`]}),(0,i.jsx)(n.SheetDescription,{children:N?(0,i.jsxs)(i.Fragment,{children:[`Tool `,(0,i.jsx)(`code`,{className:`text-xs`,children:N.tool_name}),` on`,` `,(0,i.jsx)(`code`,{className:`text-xs`,children:N.object_name})]}):`Loading…`})]}),N?(0,i.jsxs)(`div`,{className:`px-4 space-y-4 mt-4`,children:[(0,i.jsxs)(`div`,{className:`grid grid-cols-2 gap-3 text-sm`,children:[(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs text-muted-foreground`,children:`Status`}),(0,i.jsx)(`div`,{className:`mt-1`,children:(0,i.jsx)(tr,{status:N.status})})]}),(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs text-muted-foreground`,children:`Proposed`}),(0,i.jsx)(`div`,{className:`mt-1 text-xs`,children:nr(N.proposed_at)})]}),(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs text-muted-foreground`,children:`Proposed by`}),(0,i.jsx)(`div`,{className:`mt-1 text-xs font-mono break-all`,children:N.proposed_by??`—`})]}),(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs text-muted-foreground`,children:`Decided by`}),(0,i.jsx)(`div`,{className:`mt-1 text-xs font-mono break-all`,children:N.decided_by??`—`})]}),N.conversation_id?(0,i.jsxs)(`div`,{className:`col-span-2`,children:[(0,i.jsx)(n.Label,{className:`text-xs text-muted-foreground`,children:`Conversation`}),(0,i.jsx)(`div`,{className:`mt-1 text-xs font-mono break-all`,children:N.conversation_id})]}):null]}),(0,i.jsx)(n.Separator,{}),(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs`,children:`Tool input`}),(0,i.jsx)(`div`,{className:`mt-1.5`,children:(0,i.jsx)(ir,{value:rr(N.tool_input)})})]}),N.result?(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs`,children:`Result`}),(0,i.jsx)(`div`,{className:`mt-1.5`,children:(0,i.jsx)(ir,{value:rr(N.result)})})]}):null,N.error?(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs text-destructive`,children:`Error`}),(0,i.jsx)(`div`,{className:`mt-1.5`,children:(0,i.jsx)(ir,{value:N.error})})]}):null,N.rejection_reason?(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs`,children:`Rejection reason`}),(0,i.jsx)(`div`,{className:`mt-1.5 text-sm`,children:N.rejection_reason})]}):null,N.status===`pending`?(0,i.jsxs)(`div`,{className:`pt-2 flex gap-2`,children:[(0,i.jsxs)(n.Button,{size:`sm`,onClick:()=>void P(N.id),disabled:b===N.id,children:[(0,i.jsx)(r.CheckCircle2,{className:`h-3.5 w-3.5 mr-1`}),`Approve & Execute`]}),(0,i.jsxs)(n.Button,{size:`sm`,variant:`destructive`,onClick:()=>{_(N.id),y(``)},disabled:b===N.id,children:[(0,i.jsx)(r.XCircle,{className:`h-3.5 w-3.5 mr-1`}),`Reject`]})]}):null]}):null]})}),(0,i.jsx)(n.Sheet,{open:!!g,onOpenChange:e=>{e||(_(null),y(``))},children:(0,i.jsxs)(n.SheetContent,{side:`bottom`,className:`max-h-[40vh]`,children:[(0,i.jsxs)(n.SheetHeader,{children:[(0,i.jsx)(n.SheetTitle,{children:`Reject this action?`}),(0,i.jsx)(n.SheetDescription,{children:`The reason is shown back to the AI so it can adjust its next response.`})]}),(0,i.jsxs)(`div`,{className:`px-4 mt-3 space-y-3`,children:[(0,i.jsx)(n.Textarea,{value:v,onChange:e=>y(e.target.value),placeholder:`Optional reason (e.g. 'Wrong record id — please confirm with the user first.')`,rows:4,"data-testid":`ai-inbox-reject-reason`}),(0,i.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,i.jsx)(n.Button,{variant:`outline`,size:`sm`,onClick:()=>{_(null),y(``)},children:`Cancel`}),(0,i.jsxs)(n.Button,{variant:`destructive`,size:`sm`,onClick:()=>g&&void F(g,v),disabled:!g||b===g,"data-testid":`ai-inbox-reject-confirm`,children:[(0,i.jsx)(r.XCircle,{className:`h-3.5 w-3.5 mr-1`}),`Reject`]})]})]})]})})]})}function sr(e){return!e||e.length===0?`/api/v1/ai`:e.endsWith(`/`)?e.slice(0,-1):e}function cr(e,t){let n={...e??{}};return t&&(n[`Content-Type`]=`application/json`),n}async function lr(e){let t=await e.text();if(!t)return null;try{return JSON.parse(t)}catch{return{raw:t}}}function ur(e){let{messages:n,apiBase:r,headers:i,onDecided:a,continueConversation:o}=e,s=sr(r),c=t.useMemo(()=>{let e=new Map;for(let t of n){let n=t.toolInvocations??[];for(let t of n)t.pendingActionId&&t.toolCallId&&e.set(t.toolCallId,{pendingActionId:t.pendingActionId,toolName:t.toolName})}return e},[n]),[l,u]=t.useState({}),d=t.useRef(0),[f,p]=t.useState(!1),m=t.useCallback((e,t)=>{u(n=>{if(!t){if(!(e in n))return n;let{[e]:t,...r}=n;return r}return{...n,[e]:t}})},[]);return{decisions:l,decide:t.useCallback(async(e,t,n)=>{let r=c.get(e);if(!r){m(e,{state:`error`,message:`No pending-action id found for this tool call. The tool result may not be a HITL proposal.`});return}let{pendingActionId:l,toolName:u}=r;m(e,{state:`pending`,message:t?`Approving…`:`Rejecting…`}),d.current+=1,p(!0);try{let r=`${s}/pending-actions/${encodeURIComponent(l)}/${t?`approve`:`reject`}`,c=t?`{}`:JSON.stringify({reason:n??``}),d=await fetch(r,{method:`POST`,credentials:`include`,headers:cr(i,!0),body:c}),f=await lr(d)??{};if(!d.ok){let t=typeof f.error==`string`?f.error:`Approval failed: HTTP ${d.status}`;m(e,{state:`error`,message:t}),a?.(e,{id:l,status:`failed`,error:t});return}let p=f.status??(t?`executed`:`rejected`),h=!1;if(p===`executed`?(m(e,{state:`success`,message:`Approved — action executed.`}),h=!0):p===`rejected`?(m(e,{state:`success`,message:n?`Rejected: ${n}`:`Rejected.`}),h=!0):p===`failed`?m(e,{state:`error`,message:f.error??`Action approved but execution failed.`}):(m(e,{state:`success`,message:`Status: ${p}`}),h=!0),a?.(e,f),h&&o){let r=dr({approved:t,status:p,toolName:u,pendingActionId:l,outcome:f,reason:n});r&&o(r,{toolCallId:e,pendingActionId:l,decision:t?`approved`:`rejected`,outcome:f,toolName:u})}}catch(t){m(e,{state:`error`,message:t instanceof Error?t.message:String(t)})}finally{--d.current,d.current<=0&&(d.current=0,p(!1))}},[s,i,c,a,o,m]),isDeciding:f}}function dr(e){let{approved:t,status:n,toolName:r,pendingActionId:i,outcome:a,reason:o}=e,s=`[HITL ${i}]`;if(t&&n===`executed`){let e=a.result;return`${s} The operator approved the \`${r}\` call. It executed successfully with result: ${e==null?`(no payload)`:typeof e==`string`?e:fr(JSON.stringify(e),800)}. Acknowledge the outcome concisely and continue the user's task.`}if(!t&&n===`rejected`)return`${s} The operator rejected the \`${r}\` call.${o&&o.trim().length>0?` Reason: ${o}.`:``} Acknowledge the rejection and ask whether to try a different approach.`;if(n===`failed`){let e=a.error;return`${s} The \`${r}\` call was approved but execution failed: ${typeof e==`string`?e:fr(JSON.stringify(e??{}),400)}. Apologize concisely and offer alternatives.`}}function fr(e,t){return e.length<=t?e:`${e.slice(0,t-1)}…`}var pr=t.forwardRef(({className:e,messages:a=[],placeholder:o=`Type your message...`,onSendMessage:s,disabled:c=!1,showTimestamp:l=!1,userAvatarUrl:u,userAvatarFallback:d=`You`,assistantAvatarUrl:f,assistantAvatarFallback:p=`AI`,maxHeight:m=`500px`,...h},g)=>{let[_,v]=t.useState(``),y=t.useRef(null),b=t.useRef(null);t.useEffect(()=>{if(y.current){let e=y.current.querySelector(`[data-radix-scroll-area-viewport]`);e&&(e.scrollTop=e.scrollHeight)}},[a]);let x=()=>{_.trim()&&s&&(s(_.trim()),v(``),b.current?.focus())},S=e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),x())};return(0,i.jsxs)(`div`,{ref:g,className:(0,n.cn)(`flex flex-col border rounded-lg bg-background overflow-hidden`,e),style:{maxHeight:m},...h,children:[(0,i.jsx)(n.ScrollArea,{ref:y,className:`flex-1 p-4`,children:(0,i.jsx)(`div`,{className:`space-y-4`,children:a.length===0?(0,i.jsx)(`div`,{className:`flex items-center justify-center h-32 text-muted-foreground text-sm`,children:`No messages yet. Start a conversation!`}):a.map(e=>(0,i.jsx)(mr,{message:e,showTimestamp:l,userAvatarUrl:u,userAvatarFallback:d,assistantAvatarUrl:f,assistantAvatarFallback:p},e.id))})}),(0,i.jsx)(`div`,{className:`border-t p-4`,children:(0,i.jsxs)(`div`,{className:`flex gap-2`,children:[(0,i.jsx)(n.Input,{ref:b,value:_,onChange:e=>v(e.target.value),onKeyDown:S,placeholder:o,disabled:c,className:`flex-1`}),(0,i.jsx)(n.Button,{onClick:x,disabled:c||!_.trim(),size:`icon`,children:(0,i.jsx)(r.Send,{className:`h-4 w-4`})})]})})]})});pr.displayName=`Chatbot`;var mr=({message:e,showTimestamp:t,userAvatarUrl:r,userAvatarFallback:a,assistantAvatarUrl:o,assistantAvatarFallback:s})=>{let c=e.role===`user`;if(e.role===`system`)return(0,i.jsx)(`div`,{className:`flex justify-center`,children:(0,i.jsx)(`div`,{className:`text-xs text-muted-foreground bg-muted px-3 py-1 rounded-full`,children:e.content})});let l=c?e.avatar||r:e.avatar||o,u=c?e.avatarFallback||a:e.avatarFallback||s;return(0,i.jsxs)(`div`,{className:(0,n.cn)(`flex gap-3`,c?`flex-row-reverse`:`flex-row`),children:[(0,i.jsxs)(n.Avatar,{className:`h-8 w-8`,children:[(0,i.jsx)(n.AvatarImage,{src:l}),(0,i.jsx)(n.AvatarFallback,{className:`text-xs`,children:u})]}),(0,i.jsxs)(`div`,{className:(0,n.cn)(`flex flex-col gap-1`,c?`items-end`:`items-start`),children:[(0,i.jsx)(`div`,{className:(0,n.cn)(`rounded-lg px-4 py-2 max-w-[70%] break-words`,c?`bg-primary text-primary-foreground`:`bg-muted`),children:(0,i.jsx)(`p`,{className:`text-sm whitespace-pre-wrap`,children:e.content})}),t&&e.timestamp&&(0,i.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.timestamp})]})]})},hr=t.forwardRef(({className:e,avatarSrc:t,avatarFallback:r=`AI`,...a},o)=>(0,i.jsxs)(`div`,{ref:o,className:(0,n.cn)(`flex gap-3`,e),...a,children:[(0,i.jsxs)(n.Avatar,{className:`h-8 w-8`,children:[(0,i.jsx)(n.AvatarImage,{src:t}),(0,i.jsx)(n.AvatarFallback,{className:`text-xs`,children:r})]}),(0,i.jsx)(`div`,{className:`flex items-center bg-muted rounded-lg px-4 py-2`,children:(0,i.jsxs)(`div`,{className:`flex gap-1`,children:[(0,i.jsx)(`span`,{className:`w-2 h-2 bg-muted-foreground rounded-full animate-bounce [animation-delay:-0.3s]`}),(0,i.jsx)(`span`,{className:`w-2 h-2 bg-muted-foreground rounded-full animate-bounce [animation-delay:-0.15s]`}),(0,i.jsx)(`span`,{className:`w-2 h-2 bg-muted-foreground rounded-full animate-bounce`})]})})]}));hr.displayName=`TypingIndicator`,e.AGENT_ALIAS_GROUPS=V,Object.defineProperty(e,"AIElements",{enumerable:!0,get:function(){return Yn}}),e.AiPendingActionsInbox=or,e.Chatbot=pr,e.ChatbotEnhanced=On,e.FloatingChatbot=Kn,e.FloatingChatbotPanel=Y,e.FloatingChatbotProvider=ge,e.FloatingChatbotTrigger=be,e.PLATFORM_DEFAULT_AGENT=le,e.TypingIndicator=hr,e.agentAliasGroup=H,e.agentRouteName=U,e.buildProgressFromDraftReview=L,e.detectDraftResult=F,e.detectProposedPlan=N,e.humanizeToolName=we,e.isAskAgent=ce,e.isBuildAgent=se,e.isBuiltinAgentName=oe,e.publishHealthFromResponse=yn,e.resolveAgentParam=W,e.resolveDefaultAgentName=ue,e.summarizeChatError=Ee,e.uiMessageToChatMessage=R,e.uiMessagesToChatMessages=ie,e.unwrapToolResult=Te,e.useAgents=fe,e.useAiModels=me,e.useFloatingChatbot=_e,e.useHitlInChat=ur,e.useObjectChat=B,e.usePendingActions=$n});
|
|
2
|
+
`).trim();return t.length>0?t:void 0}function A(e){let t=e=>{if(e&&typeof e==`object`)return e;if(typeof e!=`string`)return;let t=e.trim();if(t.startsWith(`{`))try{let e=JSON.parse(t);return e&&typeof e==`object`?e:void 0}catch{return}},n=[e];e&&typeof e==`object`&&`value`in e&&n.push(e.value);let r;for(let e of n){let n=t(e);if(n){if(typeof n.status==`string`)return n;r??=n}}return r}function j(e){let t=A(e);if(!t)return;let n=t.pendingActionId;if(t.status===`pending_approval`&&typeof n==`string`&&n.length>0)return{pendingActionId:n,raw:t}}function M(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.trim().length>0):[]}function N(e){let t=A(e);if(!t||t.status!==`blueprint_proposed`)return;let n=t.blueprint,r=n&&typeof n==`object`?n:{},i=(Array.isArray(r.objects)?r.objects:[]).flatMap(e=>{let t=e;return typeof t?.name!=`string`||!t.name?[]:[{name:t.name,...typeof t.label==`string`&&t.label?{label:t.label}:{},fieldCount:Array.isArray(t.fields)?t.fields.length:0}]});if(i.length===0)return;let a=(e,t)=>typeof e==`number`&&Number.isFinite(e)?e:t,o=t.counts??{},s={objects:a(o.objects,i.length),views:a(o.views,Array.isArray(r.views)?r.views.length:0),dashboards:a(o.dashboards,Array.isArray(r.dashboards)?r.dashboards.length:0),seedData:a(o.seedData,Array.isArray(r.seedData)?r.seedData.length:0)},c=M(t.questions),l=t.questionChoices,u=Array.isArray(l)?l.flatMap(e=>{let t=e;if(typeof t?.text!=`string`||!t.text)return[];let n=Array.isArray(t.options)?t.options.filter(e=>typeof e==`string`&&e.trim().length>0):[];return n.length>=2?[{text:t.text,options:n}]:[]}):[],d=typeof t.summary==`string`&&t.summary?t.summary:typeof r.summary==`string`&&r.summary?r.summary:void 0,f=t.targetApp;return{...d?{summary:d}:{},objects:i,counts:s,questions:c.length?c:M(r.questions),...u.length?{questionChoices:u}:{},assumptions:M(r.assumptions),...typeof f==`string`&&f?{targetApp:f}:{}}}function P(e){let t=A(e);if(!t||t.status!==`changes_proposed`)return;let n=e=>typeof e==`string`&&e?e:void 0,r=t.changes,i=(Array.isArray(r)?r:[]).flatMap(e=>{let t=e;return typeof t?.verb!=`string`||!t.verb?[]:[{verb:t.verb,...n(t.object)?{object:n(t.object)}:{},...n(t.field)?{field:n(t.field)}:{},...n(t.type)?{type:n(t.type)}:{},...n(t.name)?{name:n(t.name)}:{},...n(t.details)?{details:n(t.details)}:{}}]});if(i.length!==0)return{...n(t.summary)?{summary:n(t.summary)}:{},changes:i}}function F(e){let t=A(e);if(!t||t.status!==`drafted`)return;let n=[];if(Array.isArray(t.drafted)){for(let e of t.drafted)if(e&&typeof e==`object`){let{type:t,name:r}=e;typeof t==`string`&&typeof r==`string`&&n.push({type:t,name:r})}}else typeof t.type==`string`&&typeof t.name==`string`&&n.push({type:t.type,name:t.name});if(n.length===0)return;let r=Array.isArray(t.failed)?t.failed.length:0,i=t.verification,a=i&&typeof i==`object`&&typeof i.errors==`number`&&typeof i.warnings==`number`?{errors:i.errors,warnings:i.warnings}:void 0,o=t.issues,s=Array.isArray(o)?o.flatMap(e=>{let t=e;return typeof t?.message!=`string`||!t.message?[]:[{severity:t.severity===`error`?`error`:`warning`,code:typeof t.code==`string`?t.code:`issue`,message:t.message,...typeof t.fix==`string`&&t.fix?{fix:t.fix}:{}}]}):[],c=t.nextSteps,l=Array.isArray(c)?c.filter(e=>typeof e==`string`&&e.trim().length>0):[];return{items:n,summary:typeof t.summary==`string`?t.summary:void 0,...typeof t.packageId==`string`&&t.packageId?{packageId:t.packageId}:{},...t.autoPublishable===!0?{autoPublishable:!0}:{},...r>0?{failedCount:r}:{},...l.length?{nextSteps:l}:{},...t.materialized===!0?{materialized:!0}:{},...a?{verification:a}:{},...s.length?{issues:s}:{}}}function I(e){return e.replace(/[._-]+/g,` `).replace(/\s+/g,` `).trim().replace(/\b\w/g,e=>e.toUpperCase())}function L(e){if(!e||!Array.isArray(e.items)||e.items.length===0)return;let t=e.items.find(e=>e.type===`app`);if(t)return{phase:`done`,appLabel:I(t.name),items:e.items,done:e.items.length,total:e.items.length}}function ee(e,t={}){return e.filter(e=>e.type===`dynamic-tool`?!0:typeof e.type==`string`&&e.type.startsWith(`tool-`)).map(e=>{let n=e.type===`dynamic-tool`?e.toolName??`tool`:typeof e.type==`string`?e.type.replace(/^tool-/,``):`tool`,r=e.output??e.result,i=j(r),a=F(r),o=N(r),s=P(r),c=e.state,l=(c===`input-available`||c===`input-streaming`)&&(r!==void 0||!t.liveTail)?`output-available`:c,u=i&&l!==`output-error`?`approval-requested`:l;return{toolCallId:e.toolCallId??e.id??`${e.type??`tool`}-${Math.random().toString(36).slice(2,8)}`,toolName:n,args:e.input??e.args,result:r,errorText:e.errorText,state:u,pendingActionId:i?.pendingActionId,draftReview:a,proposedPlan:o,proposedChanges:s}})}function te(e){let t=e.filter(e=>e.type===`source-url`||e.type===`source`).map(e=>({id:e.id,title:e.title,url:e.url??e.href})).filter(e=>!!e.url);return t.length>0?t:void 0}function ne(e){let t=e.filter(e=>e.type===`data-build-progress`).pop()?.data;if(!t||typeof t!=`object`)return;let n=t,r=Array.isArray(n.items)?n.items.filter(e=>typeof e?.type==`string`&&typeof e?.name==`string`).map(e=>({type:e.type,name:e.name})):[];return{phase:n.phase===`data`||n.phase===`done`?n.phase:`structure`,...typeof n.appLabel==`string`?{appLabel:n.appLabel}:{},items:r,done:typeof n.done==`number`?n.done:r.length,total:typeof n.total==`number`?n.total:r.length,...typeof n.seq==`number`?{seq:n.seq}:{}}}function re(e){let t=e.filter(e=>e.type===`data-blueprint-progress`).pop()?.data;if(!t||typeof t!=`object`)return;let n=t,r=Array.isArray(n.objects)?n.objects.filter(e=>typeof e?.name==`string`).map(e=>({name:e.name,...typeof e.label==`string`?{label:e.label}:{},...typeof e.fields==`number`?{fields:e.fields}:{}})):[],i=n.phase===`done`?`done`:`designing`,a;if(n.counts&&typeof n.counts==`object`){let e=n.counts,t={};typeof e.objects==`number`&&(t.objects=e.objects),typeof e.views==`number`&&(t.views=e.views),typeof e.dashboards==`number`&&(t.dashboards=e.dashboards),Object.keys(t).length>0&&(a=t)}return{phase:i,...typeof n.summary==`string`?{summary:n.summary}:{},...typeof n.appLabel==`string`?{appLabel:n.appLabel}:{},...typeof n.targetApp==`string`?{targetApp:n.targetApp}:{},objects:r,...a?{counts:a}:{},...typeof n.seq==`number`?{seq:n.seq}:{}}}function ie(e){let t=[];for(let n of e){if(n.type!==`data-chart`)continue;let e=n.data;if(!e||typeof e!=`object`)continue;let r=e,i=Array.isArray(r.data)?r.data:[],a=Array.isArray(r.series)?r.series.filter(e=>e&&typeof e.dataKey==`string`).map(e=>({dataKey:e.dataKey,...typeof e.label==`string`?{label:e.label}:{}})):[];a.length!==0&&t.push({...typeof r.chartType==`string`?{chartType:r.chartType}:{},...typeof r.title==`string`?{title:r.title}:{},data:i,...typeof r.xAxisKey==`string`?{xAxisKey:r.xAxisKey}:{},series:a})}return t.length>0?t:void 0}function ae(e,t={}){let n=Array.isArray(e.parts)?e.parts:[],r=ee(n,{liveTail:t.streaming}),i=Array.isArray(e.toolInvocations)?e.toolInvocations:[],a=r.length>0?r:i,o=ne(n)??a.map(e=>L(e.draftReview)).find(e=>!!e);return{id:e.id??`msg-${Math.random().toString(36).slice(2,8)}`,role:e.role??`assistant`,content:O(e,n),reasoning:k(n),toolInvocations:a,sources:te(n),buildProgress:o,blueprintProgress:re(n),charts:ie(n),streaming:t.streaming}}function R(e,t={}){if(!Array.isArray(e)||e.length===0)return[];let n=e.length-1;return e.map((e,r)=>ae(e,{streaming:!!t.isStreaming&&r===n&&e.role===`assistant`}))}async function oe(e,t){let n;try{n=await fetch(e,t)}catch(e){let t=e instanceof Error?e:Error(String(e));throw t.notSent=!0,t}if(!n.ok){let e=``;try{e=await n.text()}catch{}let t=Error(e||n.statusText||`Request failed with status ${n.status}`);throw t.status=n.status,t.notSent=!0,t}return n}function se(e){let t=[...e.messages].reverse().find(e=>e.role===`user`);return{body:{...e.body??{},id:e.id,messages:e.messages,trigger:e.trigger,messageId:e.messageId,...t?{turnId:t.id}:{}}}}function z(e){return(e??[]).map((e,t)=>({id:e.id||`msg-${t}`,role:e.role||`user`,content:e.content||``,timestamp:typeof e.timestamp==`string`?e.timestamp:e.timestamp instanceof Date?e.timestamp.toISOString():void 0,metadata:e.metadata,streaming:e.streaming,toolInvocations:e.toolInvocations}))}function B(e={}){let{api:n,initialMessages:r,conversationId:i,systemPrompt:s,model:c,streamingEnabled:l=!0,headers:u,body:d,maxToolRoundtrips:f=5,onError:p,showTimestamp:m,autoResponse:h,autoResponseText:g,autoResponseDelay:_=1e3,onSend:v}=e,y=(0,t.useRef)(n?`api`:`local`).current===`api`,b=(0,t.useMemo)(()=>(r??[]).map((e,t)=>{if(Array.isArray(e.parts)&&e.parts.length>0)return{id:e.id||`msg-${t}`,role:e.role||`user`,parts:e.parts};let n=z([e])[0],r=[];n.content&&r.push({type:`text`,text:n.content}),e.reasoning&&r.push({type:`reasoning`,text:e.reasoning});for(let e of n.toolInvocations??[])r.push({type:`tool-${e.toolName}`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.args,output:e.result,errorText:e.errorText,state:e.state});return{id:n.id||`msg-${t}`,role:n.role,parts:r.length>0?r:[{type:`text`,text:``}]}}),[]),x=(0,t.useRef)(c);x.current=c;let S=(0,t.useMemo)(()=>{if(y)return new o.DefaultChatTransport({api:n,fetch:oe,headers:{...u},body:{...d,...i?{conversationId:i}:{},...c?{model:c}:{},...s?{systemPrompt:s}:{},...l===void 0?{}:{stream:l}},prepareSendMessagesRequest:({id:e,body:t,messages:n,trigger:r,messageId:i})=>{let a=se({id:e,body:t,messages:n,trigger:r,messageId:i});return x.current&&(a.body.model=x.current),a}})},[y,n,u,d,c,s,l,i]),C=(0,t.useRef)(null),w=(0,a.useChat)({transport:S,messages:y&&b.length>0?b:void 0,onError:y?e=>{if(e.notSent){let e=C.current,t=e?.messages;e?.setMessages&&t&&t.length>0&&t[t.length-1]?.role===`user`&&e.setMessages(t.slice(0,-1))}p?.(e)}:void 0});C.current=w;let[T,E]=(0,t.useState)(()=>z(r)),[O,k]=(0,t.useState)(!1),[A,j]=(0,t.useState)(``),[M,N]=(0,t.useState)(``),P=(0,t.useRef)(null);if((0,t.useEffect)(()=>()=>{P.current&&=(clearTimeout(P.current),null)},[]),y){let{messages:e,status:n,error:r,sendMessage:i,regenerate:a,stop:o,setMessages:s}=w,c=n===`submitted`||n===`streaming`,l=R(e,{isStreaming:c}).map((t,n)=>({...t,metadata:e[n]?.metadata}));return{messages:l,isLoading:c,error:r,sendMessage:(0,t.useCallback)(e=>{let t=e.trim();if(!t)return;let n=[...l,{id:D(`msg`),role:`user`,content:t}];i({text:t}),N(``),v?.(t,n)},[i,v,l]),stop:o,reload:a,clear:(0,t.useCallback)(()=>{s([])},[s]),setMessages:s,isApiMode:!0,input:M,setInput:N,handleInputChange:(0,t.useCallback)(e=>{N(e.target.value)},[])}}let F=(0,t.useCallback)(()=>{P.current&&=(clearTimeout(P.current),null),k(!1)},[]);return{messages:T,isLoading:O,error:void 0,sendMessage:(0,t.useCallback)(e=>{if(!e.trim())return;let t={id:D(`msg`),role:`user`,content:e.trim(),timestamp:m?new Date().toLocaleTimeString():void 0};E(n=>{let r=[...n,t];return v?.(e.trim(),r),r}),j(``),h&&(k(!0),P.current=setTimeout(()=>{let e={id:D(`msg`),role:`assistant`,content:g||`Thank you for your message!`,timestamp:m?new Date().toLocaleTimeString():void 0};E(t=>[...t,e]),k(!1)},_))},[m,h,g,_,v]),stop:F,reload:(0,t.useCallback)(()=>{},[]),clear:(0,t.useCallback)(()=>{F(),E([])},[F]),isApiMode:!1,input:A,setInput:j,handleInputChange:(0,t.useCallback)(e=>{j(e.target.value)},[])}}var V=[[`build`,`metadata_assistant`],[`ask`,`data_chat`]];function H(e){return V.find(t=>t.includes(e))??[e]}function ce(e){return H(e)[0]}function le(e,t){if(e){if(t.includes(e))return e;for(let n of H(e))if(t.includes(n))return n}}function ue(e){return e!=null&&V.some(t=>t.includes(e))}function de(e){return e!=null&&ce(e)===`build`}function fe(e){return e!=null&&ce(e)===`ask`}var pe=`ask`;function me(e,t){if(e.length===0)return;let n=e.map(e=>e.name);if(t){let e=le(t,n);if(e)return e}return le(`ask`,n)||e[0].name}function he(e){return e.filter(e=>typeof e?.name==`string`&&e.name.length>0).map(e=>({name:e.name,label:e.label||e.name,description:e.description,role:e.role,active:e.active!==!1}))}function ge(e={}){let{apiBase:n,headers:r,enabled:i=!0,fallback:a=[]}=e,[o,s]=(0,t.useState)(a),[c,l]=(0,t.useState)(!1),[u,d]=(0,t.useState)(void 0),[f,p]=(0,t.useState)(0),m=(0,t.useRef)(r);return m.current=r,(0,t.useEffect)(()=>{if(!i||!n)return;let e=new AbortController,t=!1;l(!0),d(void 0);let r=`${n.replace(/\/$/,``)}/agents`;return fetch(r,{method:`GET`,headers:{Accept:`application/json`,...m.current??{}},credentials:`include`,signal:e.signal}).then(async e=>{if(!e.ok)throw Error(`Failed to load agents (${e.status})`);return e.json()}).then(e=>{if(t)return;let n=he(Array.isArray(e)?e:e?.agents??[]);s(n.length>0?n:a)}).catch(e=>{t||e.name===`AbortError`||(d(e),s(a))}).finally(()=>{t||l(!1)}),()=>{t=!0,e.abort()}},[n,i,f]),{agents:o,isLoading:c,error:u,refetch:(0,t.useCallback)(()=>p(e=>e+1),[])}}function _e(e){return e.filter(e=>typeof e?.id==`string`&&e.id.length>0).map(e=>({id:e.id,label:e.label||e.id}))}function ve(e={}){let{apiBase:n,headers:r,enabled:i=!0}=e,[a,o]=(0,t.useState)([]),[s,c]=(0,t.useState)(void 0),[l,u]=(0,t.useState)(!1),[d,f]=(0,t.useState)(void 0),[p,m]=(0,t.useState)(0),h=(0,t.useRef)(r);return h.current=r,(0,t.useEffect)(()=>{if(!i||!n)return;let e=new AbortController,t=!1,r=`${n.replace(/\/$/,``)}/models`,a=0,s=async()=>{if(!t){u(!0),f(void 0);try{let n=await fetch(r,{method:`GET`,headers:{Accept:`application/json`,...h.current??{}},credentials:`include`,signal:e.signal});if(!n.ok)throw Error(`Failed to load AI models (${n.status})`);let i=await n.json();if(t)return;let l=Array.isArray(i)?i:i?.models??[],d=Array.isArray(i)?void 0:i?.defaultModel,f=_e(l);o(f),c(d??l.find(e=>e?.default)?.id??l[0]?.id),u(!1),f.length===0&&a<5&&!t&&(a+=1,setTimeout(()=>{s()},1200))}catch(e){if(t||e?.name===`AbortError`)return;a<5?(a+=1,setTimeout(()=>{s()},1200)):(f(e),o([]),c(void 0),u(!1))}}};return s(),()=>{t=!0,e.abort()}},[n,i,p]),{models:a,defaultModelId:s,isLoading:l,error:d,refetch:(0,t.useCallback)(()=>m(e=>e+1),[])}}var ye=t.createContext(null);function be({defaultOpen:e=!1,children:n}){let[r,a]=t.useState(e),[o,s]=t.useState(!1),c=t.useMemo(()=>({isOpen:r,isFullscreen:o,open:()=>a(!0),close:()=>{a(!1),s(!1)},toggle:()=>a(e=>!e),toggleFullscreen:()=>s(e=>!e)}),[r,o]);return(0,i.jsx)(ye.Provider,{value:c,children:n})}function xe(){let e=t.useContext(ye);if(!e)throw Error(`useFloatingChatbot must be used within a <FloatingChatbotProvider>`);return e}function Se(){try{let{t:e}=(0,c.useObjectTranslation)();return(t,n)=>{let r=e(`common.${t}`);return!r||r===`common.${t}`?n:r}}catch{return(e,t)=>t}}var U={32:`size-8`,36:`size-9`,40:`size-10`,44:`size-11`,48:`size-12`,52:`size-[52px]`,56:`size-14`,60:`size-[60px]`,64:`size-16`,72:`size-[72px]`,80:`size-20`};function Ce(e,t){return t.reduce((t,n)=>Math.abs(n-e)<Math.abs(t-e)?n:t)}function W(e){return U[e]??U[Ce(e,Object.keys(U).map(Number))]}function we({position:e=`bottom-right`,size:t=56,className:a}){let{isOpen:o,toggle:s}=xe(),c=Se();return(0,i.jsx)(n.Button,{onClick:s,className:(0,n.cn)(`fixed z-50 rounded-full shadow-lg transition-transform hover:scale-105`,W(t),o&&`hidden`,e===`bottom-right`?`right-6 bottom-20 sm:bottom-6`:`left-6 bottom-20 sm:bottom-6`,a),size:`icon`,"aria-label":o?c(`closeChat`,`Close chat`):c(`openChat`,`Open chat`),"data-testid":`floating-chatbot-trigger`,children:o?(0,i.jsx)(r.X,{className:`h-6 w-6`}):(0,i.jsx)(r.Bot,{className:`h-6 w-6`})})}var G={300:`sm:w-[300px]`,320:`sm:w-[320px]`,340:`sm:w-[340px]`,360:`sm:w-[360px]`,380:`sm:w-[380px]`,400:`sm:w-[400px]`,420:`sm:w-[420px]`,440:`sm:w-[440px]`,450:`sm:w-[450px]`,460:`sm:w-[460px]`,480:`sm:w-[480px]`,500:`sm:w-[500px]`,520:`sm:w-[520px]`,560:`sm:w-[560px]`,600:`sm:w-[600px]`,640:`sm:w-[640px]`,720:`sm:w-[720px]`,800:`sm:w-[800px]`},Te={360:`h-[min(360px,calc(100svh_-_6rem_-_env(safe-area-inset-bottom)))] sm:h-[360px]`,400:`h-[min(400px,calc(100svh_-_6rem_-_env(safe-area-inset-bottom)))] sm:h-[400px]`,420:`h-[min(420px,calc(100svh_-_6rem_-_env(safe-area-inset-bottom)))] sm:h-[420px]`,440:`h-[min(440px,calc(100svh_-_6rem_-_env(safe-area-inset-bottom)))] sm:h-[440px]`,480:`h-[min(480px,calc(100svh_-_6rem_-_env(safe-area-inset-bottom)))] sm:h-[480px]`,500:`h-[min(500px,calc(100svh_-_6rem_-_env(safe-area-inset-bottom)))] sm:h-[500px]`,520:`h-[min(520px,calc(100svh_-_6rem_-_env(safe-area-inset-bottom)))] sm:h-[520px]`,560:`h-[min(560px,calc(100svh_-_6rem_-_env(safe-area-inset-bottom)))] sm:h-[560px]`,600:`h-[min(600px,calc(100svh_-_6rem_-_env(safe-area-inset-bottom)))] sm:h-[600px]`,640:`h-[min(640px,calc(100svh_-_6rem_-_env(safe-area-inset-bottom)))] sm:h-[640px]`,720:`h-[min(720px,calc(100svh_-_6rem_-_env(safe-area-inset-bottom)))] sm:h-[720px]`,800:`h-[min(800px,calc(100svh_-_6rem_-_env(safe-area-inset-bottom)))] sm:h-[800px]`};function Ee(e,t){return t.reduce((t,n)=>Math.abs(n-e)<Math.abs(t-e)?n:t)}function De(e){return G[e]??G[Ee(e,Object.keys(G).map(Number))]}function K(e){return Te[e]??Te[Ee(e,Object.keys(Te).map(Number))]}function q({title:e=`Chat`,position:t=`bottom-right`,width:a=400,height:o=520,children:s,className:c,headerExtra:l,headerActions:u}){let{isOpen:d,isFullscreen:f,close:p,toggleFullscreen:m}=xe();return d?(0,i.jsxs)(`div`,{className:(0,n.cn)(`fixed z-50 flex flex-col overflow-hidden border bg-background shadow-xl transition-all`,f?`inset-0 h-svh w-screen rounded-none`:t===`bottom-right`?(0,n.cn)(`left-3 right-3 bottom-[calc(4rem_+_env(safe-area-inset-bottom))] rounded-lg`,`sm:left-auto sm:right-6 sm:bottom-20 sm:max-h-[calc(100vh_-_100px)]`,De(a),K(o)):(0,n.cn)(`left-3 right-3 bottom-[calc(4rem_+_env(safe-area-inset-bottom))] rounded-lg`,`sm:right-auto sm:left-6 sm:bottom-20 sm:max-h-[calc(100vh_-_100px)]`,De(a),K(o)),c),role:`dialog`,"aria-label":e,"data-testid":`floating-chatbot-panel`,children:[(0,i.jsxs)(`div`,{className:`flex min-h-10 items-center justify-between gap-2 border-b bg-muted/40 px-4 py-2`,children:[(0,i.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-sm font-medium`,children:e}),l?(0,i.jsx)(`div`,{className:`mr-1 flex min-w-0 items-center justify-end`,"data-testid":`floating-chatbot-header-extra`,children:l}):null,(0,i.jsxs)(`div`,{className:`flex items-center gap-1 shrink-0`,children:[u,(0,i.jsx)(n.Button,{variant:`ghost`,size:`icon`,className:`h-7 w-7`,onClick:m,"aria-label":f?`Exit fullscreen`:`Fullscreen`,"data-testid":`floating-chatbot-fullscreen`,children:f?(0,i.jsx)(r.Minimize2,{className:`h-4 w-4`}):(0,i.jsx)(r.Maximize2,{className:`h-4 w-4`})}),(0,i.jsx)(n.Button,{variant:`ghost`,size:`icon`,className:`h-7 w-7`,onClick:p,"aria-label":`Close chat`,"data-testid":`floating-chatbot-close`,children:(0,i.jsx)(r.X,{className:`h-4 w-4`})})]})]}),(0,i.jsx)(`div`,{className:`min-h-0 flex-1 overflow-hidden`,children:s})]}):null}var J={ai:`AI`,api:`API`,crm:`CRM`,hitl:`HITL`,id:`ID`,ids:`IDs`,rag:`RAG`,sql:`SQL`,url:`URL`,utc:`UTC`};function Oe(e){if(!e)return``;let t=String(e).trim();if(!t)return``;let n=t.replace(/[_-]+/g,` `).replace(/([a-z])([A-Z])/g,`$1 $2`).split(/\s+/).filter(Boolean);return n.length===0?t:n.map((e,t)=>{let n=e.toLowerCase();return J[n]?J[n]:t===0?n.charAt(0).toUpperCase()+n.slice(1):n}).join(` `)}function ke(e){if(e==null)return e;let t=e;for(let e=0;e<2;e++){if(typeof t==`object`&&t&&!Array.isArray(t)&&t.type===`text`&&typeof t.value==`string`){t=t.value;continue}break}if(typeof t==`string`){let e=t.trim();if(e.startsWith(`{`)&&e.endsWith(`}`)||e.startsWith(`[`)&&e.endsWith(`]`))try{return JSON.parse(e)}catch{}}return t}function Ae(e){let t=(e instanceof Error?e.message:String(e??``)).replace(/\s+/g,` `).trim();if(!t)return{summary:`Something went wrong. Please try again.`};let n=t.replace(/^Failed after \d+ attempts?\.\s*Last error:\s*/i,``),r=n.match(/^Invalid error response format:\s*(.+)$/i)?.[1]?.trim()??n,i=r.match(/^([^:]{8,80}):\s+(.+)$/)?.[1]?.trim()??r.match(/^([^.;!?]+[.;!?])\s/)?.[1]?.trim()??(r.length>140?`${r.slice(0,137).trimEnd()}…`:r);return{summary:i.replace(/:$/,``),details:n.length>i.length?n:void 0}}var je=new Set([`ai_design_quota_exhausted`,`ai_data_chat_trial_exhausted`,`ai_allowance_exhausted`]);function Me(e){let t=e instanceof Error?e.message:String(e??``);if(!t)return null;let n=t.replace(/^Failed after \d+ attempts?\.\s*Last error:\s*/i,``).replace(/^Invalid error response format:\s*/i,``).trim(),r=n.indexOf(`{`),i=n.lastIndexOf(`}`);if(r<0||i<=r)return null;let a;try{a=JSON.parse(n.slice(r,i+1))}catch{return null}return!a||typeof a.error!=`string`||!je.has(a.error)?null:{code:a.error,message:typeof a.message==`string`?a.message:``,messageEn:typeof a.messageEn==`string`?a.messageEn:void 0,upgrade:a.upgrade===!0,topUp:a.topUp===!0}}function Ne(e){return!!(e&&typeof e==`object`&&e.notSent===!0)}function Pe(e){let t=e&&typeof e==`object`?e.status:void 0;return typeof t==`number`?t:void 0}function Y(e){if(Pe(e)===429)return!0;let t=e instanceof Error?e.message:typeof e==`string`?e:``;return/\b429\b|too many requests|rate[\s_-]?limit/i.test(t)}var Fe=({className:e,...t})=>(0,i.jsx)(l.StickToBottom,{className:(0,n.cn)(`relative flex-1 overflow-y-hidden`,e),initial:`smooth`,resize:`smooth`,role:`log`,...t}),Ie=({className:e,...t})=>(0,i.jsx)(l.StickToBottom.Content,{className:(0,n.cn)(`flex flex-col gap-8 p-4`,e),...t}),Le=({className:e,title:t=`No messages yet`,description:r=`Start a conversation to see messages here`,icon:a,children:o,...s})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`flex size-full flex-col items-center justify-center gap-3 p-8 text-center`,e),...s,children:o??(0,i.jsxs)(i.Fragment,{children:[a&&(0,i.jsx)(`div`,{className:`text-muted-foreground`,children:a}),(0,i.jsxs)(`div`,{className:`space-y-1`,children:[(0,i.jsx)(`h3`,{className:`font-medium text-sm`,children:t}),r&&(0,i.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:r})]})]})}),Re=({className:e,...a})=>{let{isAtBottom:o,scrollToBottom:s}=(0,l.useStickToBottomContext)(),c=(0,t.useCallback)(()=>{s()},[s]);return!o&&(0,i.jsx)(n.Button,{className:(0,n.cn)(`absolute bottom-4 left-[50%] translate-x-[-50%] rounded-full`,e),onClick:c,size:`icon`,type:`button`,variant:`outline`,...a,children:(0,i.jsx)(r.ArrowDownIcon,{className:`size-4`})})},ze=(0,u.cva)(`flex w-fit items-stretch has-[>[data-slot=button-group]]:gap-2 [&>*]:focus-visible:relative [&>*]:focus-visible:z-10 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-md [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1`,{variants:{orientation:{horizontal:`[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none`,vertical:`flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none`}},defaultVariants:{orientation:`horizontal`}});function Be({className:e,orientation:t,...r}){return(0,i.jsx)(`div`,{role:`group`,"data-slot":`button-group`,"data-orientation":t,className:(0,n.cn)(ze({orientation:t}),e),...r})}function Ve({className:e,asChild:t=!1,...r}){return(0,i.jsx)(t?d.Slot:`div`,{className:(0,n.cn)(`flex items-center gap-2 rounded-md border bg-muted px-4 text-sm font-medium shadow-xs [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4`,e),...r})}var He=({className:e,from:t,...r})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`group flex w-full max-w-[95%] flex-col gap-2`,t===`user`?`is-user ml-auto justify-end`:`is-assistant`,e),...r}),Ue=({children:e,className:t,...r})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`is-user:dark flex w-fit max-w-full min-w-0 flex-col gap-2 overflow-hidden text-sm`,`group-[.is-user]:ml-auto group-[.is-user]:rounded-lg group-[.is-user]:bg-secondary group-[.is-user]:px-4 group-[.is-user]:py-3 group-[.is-user]:text-foreground`,`group-[.is-assistant]:text-foreground`,t),...r,children:e}),We=({className:e,children:t,...r})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`flex items-center gap-1`,e),...r,children:t}),Ge=({tooltip:e,children:t,label:r,variant:a=`ghost`,size:o=`icon`,...s})=>{let c=(0,i.jsxs)(n.Button,{size:o,type:`button`,variant:a,...s,children:[t,(0,i.jsx)(`span`,{className:`sr-only`,children:r||e})]});return e?(0,i.jsx)(n.TooltipProvider,{children:(0,i.jsxs)(n.Tooltip,{children:[(0,i.jsx)(n.TooltipTrigger,{asChild:!0,children:c}),(0,i.jsx)(n.TooltipContent,{children:(0,i.jsx)(`p`,{children:e})})]})}):c},Ke=(0,t.createContext)(null),X=()=>{let e=(0,t.useContext)(Ke);if(!e)throw Error(`MessageBranch components must be used within MessageBranch`);return e},qe=({defaultBranch:e=0,onBranchChange:r,className:a,...o})=>{let[s,c]=(0,t.useState)(e),[l,u]=(0,t.useState)([]),d=e=>{c(e),r?.(e)},f={currentBranch:s,totalBranches:l.length,goToPrevious:()=>{d(s>0?s-1:l.length-1)},goToNext:()=>{d(s<l.length-1?s+1:0)},branches:l,setBranches:u};return(0,i.jsx)(Ke.Provider,{value:f,children:(0,i.jsx)(`div`,{className:(0,n.cn)(`grid w-full gap-2 [&>div]:pb-0`,a),...o})})},Je=({children:e,...r})=>{let{currentBranch:a,setBranches:o,branches:s}=X(),c=Array.isArray(e)?e:[e];return(0,t.useEffect)(()=>{s.length!==c.length&&o(c)},[c,s,o]),c.map((e,t)=>(0,i.jsx)(`div`,{className:(0,n.cn)(`grid gap-2 overflow-hidden [&>div]:pb-0`,t===a?`block`:`hidden`),...r,children:e},e.key))},Z=({className:e,from:t,...n})=>{let{totalBranches:r}=X();return r<=1?null:(0,i.jsx)(Be,{className:`[&>*:not(:first-child)]:rounded-l-md [&>*:not(:last-child)]:rounded-r-md`,orientation:`horizontal`,...n})},Ye=({children:e,...t})=>{let{goToPrevious:a,totalBranches:o}=X();return(0,i.jsx)(n.Button,{"aria-label":`Previous branch`,disabled:o<=1,onClick:a,size:`icon`,type:`button`,variant:`ghost`,...t,children:e??(0,i.jsx)(r.ChevronLeftIcon,{size:14})})},Xe=({children:e,className:t,...a})=>{let{goToNext:o,totalBranches:s}=X();return(0,i.jsx)(n.Button,{"aria-label":`Next branch`,disabled:s<=1,onClick:o,size:`icon`,type:`button`,variant:`ghost`,...a,children:e??(0,i.jsx)(r.ChevronRightIcon,{size:14})})},Ze=({className:e,...t})=>{let{currentBranch:r,totalBranches:a}=X();return(0,i.jsxs)(Ve,{className:(0,n.cn)(`border-none bg-transparent text-muted-foreground shadow-none`,e),...t,children:[r+1,` of `,a]})},Qe=(0,t.memo)(({className:e,...t})=>(0,i.jsx)(f.Streamdown,{className:(0,n.cn)(`size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0`,e),...t}),(e,t)=>e.children===t.children);Qe.displayName=`MessageResponse`;function $e({data:e,className:t,onRemove:a,...o}){let s=e.filename||``,c=(e.mediaType?.startsWith(`image/`)&&e.url?`image`:`file`)==`image`,l=s||(c?`Image`:`Attachment`);return(0,i.jsx)(`div`,{className:(0,n.cn)(`group relative size-24 overflow-hidden rounded-lg`,t),...o,children:c?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(`img`,{alt:s||`attachment`,className:`size-full object-cover`,height:100,src:e.url,width:100}),a&&(0,i.jsxs)(n.Button,{"aria-label":`Remove attachment`,className:`absolute top-2 right-2 size-6 rounded-full bg-background/80 p-0 opacity-0 backdrop-blur-sm transition-opacity hover:bg-background group-hover:opacity-100 [&>svg]:size-3`,onClick:e=>{e.stopPropagation(),a()},type:`button`,variant:`ghost`,children:[(0,i.jsx)(r.XIcon,{}),(0,i.jsx)(`span`,{className:`sr-only`,children:`Remove`})]})]}):(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)(n.Tooltip,{children:[(0,i.jsx)(n.TooltipTrigger,{asChild:!0,children:(0,i.jsx)(`div`,{className:`flex size-full shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground`,children:(0,i.jsx)(r.PaperclipIcon,{className:`size-4`})})}),(0,i.jsx)(n.TooltipContent,{children:(0,i.jsx)(`p`,{children:l})})]}),a&&(0,i.jsxs)(n.Button,{"aria-label":`Remove attachment`,className:`size-6 shrink-0 rounded-full p-0 opacity-0 transition-opacity hover:bg-accent group-hover:opacity-100 [&>svg]:size-3`,onClick:e=>{e.stopPropagation(),a()},type:`button`,variant:`ghost`,children:[(0,i.jsx)(r.XIcon,{}),(0,i.jsx)(`span`,{className:`sr-only`,children:`Remove`})]})]})})}function et({children:e,className:t,...r}){return e?(0,i.jsx)(`div`,{className:(0,n.cn)(`ml-auto flex w-fit flex-wrap items-start gap-2`,t),...r,children:e}):null}var tt=({className:e,children:t,...r})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`mt-4 flex w-full items-center justify-between gap-4`,e),...r,children:t});function nt({className:e,...t}){return(0,i.jsx)(`div`,{"data-slot":`input-group`,role:`group`,className:(0,n.cn)(`group/input-group relative flex w-full items-center rounded-md border border-input shadow-xs transition-[color,box-shadow] outline-none dark:bg-input/30`,`h-9 min-w-0 has-[>textarea]:h-auto`,`has-[>[data-align=inline-start]]:[&>input]:pl-2`,`has-[>[data-align=inline-end]]:[&>input]:pr-2`,`has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>[data-align=block-start]]:[&>input]:pb-3`,`has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-end]]:[&>input]:pt-3`,`has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-[3px] has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50`,`has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-destructive/20 dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40`,e),...t})}var rt=(0,u.cva)(`flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium text-muted-foreground select-none group-data-[disabled=true]/input-group:opacity-50 [&>kbd]:rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-4`,{variants:{align:{"inline-start":`order-first pl-3 has-[>button]:ml-[-0.45rem] has-[>kbd]:ml-[-0.35rem]`,"inline-end":`order-last pr-3 has-[>button]:mr-[-0.45rem] has-[>kbd]:mr-[-0.35rem]`,"block-start":`order-first w-full justify-start px-3 pt-3 group-has-[>input]/input-group:pt-2.5 [.border-b]:pb-3`,"block-end":`order-last w-full justify-start px-3 pb-3 group-has-[>input]/input-group:pb-2.5 [.border-t]:pt-3`}},defaultVariants:{align:`inline-start`}});function it({className:e,align:t=`inline-start`,...r}){return(0,i.jsx)(`div`,{role:`group`,"data-slot":`input-group-addon`,"data-align":t,className:(0,n.cn)(rt({align:t}),e),onClick:e=>{e.target.closest(`button`)||e.currentTarget.parentElement?.querySelector(`input`)?.focus()},...r})}var at=(0,u.cva)(`flex items-center gap-2 text-sm shadow-none`,{variants:{size:{xs:`h-6 gap-1 rounded-[calc(var(--radius)-5px)] px-2 has-[>svg]:px-2 [&>svg:not([class*='size-'])]:size-3.5`,sm:`h-8 gap-1.5 rounded-md px-2.5 has-[>svg]:px-2.5`,"icon-xs":`size-6 rounded-[calc(var(--radius)-5px)] p-0 has-[>svg]:p-0`,"icon-sm":`size-8 p-0 has-[>svg]:p-0`}},defaultVariants:{size:`xs`}});function ot({className:e,type:t=`button`,variant:r=`ghost`,size:a=`xs`,...o}){return(0,i.jsx)(n.Button,{type:t,"data-size":a,variant:r,className:(0,n.cn)(at({size:a}),e),...o})}function st({className:e,...t}){return(0,i.jsx)(n.Textarea,{"data-slot":`input-group-control`,className:(0,n.cn)(`flex-1 resize-none rounded-none border-0 bg-transparent py-3 shadow-none focus-visible:ring-0 dark:bg-transparent`,e),...t})}var ct=(0,t.createContext)(null),lt=(0,t.createContext)(null),ut=()=>{let e=(0,t.useContext)(ct);if(!e)throw Error(`Wrap your component inside <PromptInputProvider> to use usePromptInputController().`);return e},dt=()=>(0,t.useContext)(ct),ft=()=>{let e=(0,t.useContext)(lt);if(!e)throw Error(`Wrap your component inside <PromptInputProvider> to use useProviderAttachments().`);return e},pt=()=>(0,t.useContext)(lt);function mt({initialInput:e=``,children:n}){let[r,a]=(0,t.useState)(e),o=(0,t.useCallback)(()=>a(``),[]),[s,c]=(0,t.useState)([]),l=(0,t.useRef)(null),u=(0,t.useRef)(()=>{}),d=(0,t.useCallback)(e=>{let t=Array.from(e);t.length!==0&&c(e=>e.concat(t.map(e=>({id:(0,p.nanoid)(),type:`file`,url:URL.createObjectURL(e),mediaType:e.type,filename:e.name}))))},[]),f=(0,t.useCallback)(e=>{c(t=>{let n=t.find(t=>t.id===e);return n?.url&&URL.revokeObjectURL(n.url),t.filter(t=>t.id!==e)})},[]),m=(0,t.useCallback)(()=>{c(e=>{for(let t of e)t.url&&URL.revokeObjectURL(t.url);return[]})},[]),h=(0,t.useRef)(s);h.current=s,(0,t.useEffect)(()=>()=>{for(let e of h.current)e.url&&URL.revokeObjectURL(e.url)},[]);let g=(0,t.useCallback)(()=>{u.current?.()},[]),_=(0,t.useMemo)(()=>({files:s,add:d,remove:f,clear:m,openFileDialog:g,fileInputRef:l}),[s,d,f,m,g]),v=(0,t.useCallback)((e,t)=>{l.current=e.current,u.current=t},[]),y=(0,t.useMemo)(()=>({textInput:{value:r,setInput:a,clear:o},attachments:_,__registerFileInput:v}),[r,o,_,v]);return(0,i.jsx)(ct.Provider,{value:y,children:(0,i.jsx)(lt.Provider,{value:_,children:n})})}var ht=(0,t.createContext)(null),Q=()=>{let e=pt(),n=(0,t.useContext)(ht),r=e??n;if(!r)throw Error(`usePromptInputAttachments must be used within a PromptInput or PromptInputProvider`);return r};function gt({data:e,className:t,...a}){let o=Q(),s=e.filename||``,c=(e.mediaType?.startsWith(`image/`)&&e.url?`image`:`file`)==`image`,l=s||(c?`Image`:`Attachment`);return(0,i.jsxs)(Lt,{children:[(0,i.jsx)(n.HoverCardTrigger,{asChild:!0,children:(0,i.jsxs)(`div`,{className:(0,n.cn)(`group relative flex h-8 cursor-pointer select-none items-center gap-1.5 rounded-md border border-border px-1.5 font-medium text-sm transition-all hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50`,t),...a,children:[(0,i.jsxs)(`div`,{className:`relative size-5 shrink-0`,children:[(0,i.jsx)(`div`,{className:`absolute inset-0 flex size-5 items-center justify-center overflow-hidden rounded bg-background transition-opacity group-hover:opacity-0`,children:c?(0,i.jsx)(`img`,{alt:s||`attachment`,className:`size-5 object-cover`,height:20,src:e.url,width:20}):(0,i.jsx)(`div`,{className:`flex size-5 items-center justify-center text-muted-foreground`,children:(0,i.jsx)(r.PaperclipIcon,{className:`size-3`})})}),(0,i.jsxs)(n.Button,{"aria-label":`Remove attachment`,className:`absolute inset-0 size-5 cursor-pointer rounded p-0 opacity-0 transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 [&>svg]:size-2.5`,onClick:t=>{t.stopPropagation(),o.remove(e.id)},type:`button`,variant:`ghost`,children:[(0,i.jsx)(r.XIcon,{}),(0,i.jsx)(`span`,{className:`sr-only`,children:`Remove`})]})]}),(0,i.jsx)(`span`,{className:`flex-1 truncate`,children:l})]},e.id)}),(0,i.jsx)(zt,{className:`w-auto p-2`,children:(0,i.jsxs)(`div`,{className:`w-auto space-y-3`,children:[c&&(0,i.jsx)(`div`,{className:`flex max-h-96 w-96 items-center justify-center overflow-hidden rounded-md border`,children:(0,i.jsx)(`img`,{alt:s||`attachment preview`,className:`max-h-full max-w-full object-contain`,height:384,src:e.url,width:448})}),(0,i.jsx)(`div`,{className:`flex items-center gap-2.5`,children:(0,i.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1 px-0.5`,children:[(0,i.jsx)(`h4`,{className:`truncate font-semibold text-sm leading-none`,children:s||(c?`Image`:`Attachment`)}),e.mediaType&&(0,i.jsx)(`p`,{className:`truncate font-mono text-muted-foreground text-xs`,children:e.mediaType})]})})]})})]})}function _t({children:e,className:r,...a}){let o=Q();return o.files.length?(0,i.jsx)(`div`,{className:(0,n.cn)(`flex flex-wrap items-center gap-2 p-3 w-full`,r),...a,children:o.files.map(n=>(0,i.jsx)(t.Fragment,{children:e(n)},n.id))}):null}var vt=({label:e=`Add photos or files`,...t})=>{let a=Q();return(0,i.jsxs)(n.DropdownMenuItem,{...t,onSelect:e=>{e.preventDefault(),a.openFileDialog()},children:[(0,i.jsx)(r.ImageIcon,{className:`mr-2 size-4`}),` `,e]})},yt=({className:e,accept:r,multiple:a,fileInputLabel:o=`Upload files`,globalDrop:s,syncHiddenInput:c,maxFiles:l,maxFileSize:u,onError:d,onSubmit:f,children:m,...h})=>{let g=dt(),_=!!g,v=(0,t.useRef)(null),y=(0,t.useRef)(null),[b,x]=(0,t.useState)([]),S=_?g.attachments.files:b,C=(0,t.useRef)(S);C.current=S;let w=(0,t.useCallback)(()=>{v.current?.click()},[]),T=(0,t.useCallback)(e=>!r||r.trim()===``?!0:r.split(`,`).map(e=>e.trim()).filter(Boolean).some(t=>{if(t.endsWith(`/*`)){let n=t.slice(0,-1);return e.type.startsWith(n)}return e.type===t}),[r]),E=(0,t.useCallback)(e=>{let t=Array.from(e),n=t.filter(e=>T(e));if(t.length&&n.length===0){d?.({code:`accept`,message:`No files match the accepted types.`});return}let r=n.filter(e=>u?e.size<=u:!0);if(n.length>0&&r.length===0){d?.({code:`max_file_size`,message:`All files exceed the maximum size.`});return}x(e=>{let t=typeof l==`number`?Math.max(0,l-e.length):void 0,n=typeof t==`number`?r.slice(0,t):r;typeof t==`number`&&r.length>t&&d?.({code:`max_files`,message:`Too many files. Some were not added.`});let i=[];for(let e of n)i.push({id:(0,p.nanoid)(),type:`file`,url:URL.createObjectURL(e),mediaType:e.type,filename:e.name});return e.concat(i)})},[T,l,u,d]),D=(0,t.useCallback)(e=>x(t=>{let n=t.find(t=>t.id===e);return n?.url&&URL.revokeObjectURL(n.url),t.filter(t=>t.id!==e)}),[]),O=(0,t.useCallback)(()=>x(e=>{for(let t of e)t.url&&URL.revokeObjectURL(t.url);return[]}),[]),k=_?g.attachments.add:E,A=_?g.attachments.remove:D,j=_?g.attachments.clear:O,M=_?g.attachments.openFileDialog:w;(0,t.useEffect)(()=>{_&&g.__registerFileInput(v,()=>v.current?.click())},[_,g]),(0,t.useEffect)(()=>{c&&v.current&&S.length===0&&(v.current.value=``)},[S,c]),(0,t.useEffect)(()=>{let e=y.current;if(!e||s)return;let t=e=>{e.dataTransfer?.types?.includes(`Files`)&&e.preventDefault()},n=e=>{e.dataTransfer?.types?.includes(`Files`)&&e.preventDefault(),e.dataTransfer?.files&&e.dataTransfer.files.length>0&&k(e.dataTransfer.files)};return e.addEventListener(`dragover`,t),e.addEventListener(`drop`,n),()=>{e.removeEventListener(`dragover`,t),e.removeEventListener(`drop`,n)}},[k,s]),(0,t.useEffect)(()=>{if(!s)return;let e=e=>{e.dataTransfer?.types?.includes(`Files`)&&e.preventDefault()},t=e=>{e.dataTransfer?.types?.includes(`Files`)&&e.preventDefault(),e.dataTransfer?.files&&e.dataTransfer.files.length>0&&k(e.dataTransfer.files)};return document.addEventListener(`dragover`,e),document.addEventListener(`drop`,t),()=>{document.removeEventListener(`dragover`,e),document.removeEventListener(`drop`,t)}},[k,s]),(0,t.useEffect)(()=>()=>{if(!_)for(let e of C.current)e.url&&URL.revokeObjectURL(e.url)},[_]);let N=e=>{e.currentTarget.files&&k(e.currentTarget.files),e.currentTarget.value=``},P=async e=>{try{let t=await(await fetch(e)).blob();return new Promise(e=>{let n=new FileReader;n.onloadend=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}catch{return null}},F=(0,t.useMemo)(()=>({files:S.map(e=>({...e,id:e.id})),add:k,remove:A,clear:j,openFileDialog:M,fileInputRef:v}),[S,k,A,j,M]),I=(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(`input`,{accept:r,"aria-label":o,className:`hidden`,multiple:a,onChange:N,ref:v,title:o,type:`file`}),(0,i.jsx)(`form`,{className:(0,n.cn)(`w-full`,e),onSubmit:e=>{e.preventDefault();let t=e.currentTarget,n=_?g.textInput.value:new FormData(t).get(`message`)||``;_||t.reset(),Promise.all(S.map(async({id:e,...t})=>{if(t.url&&t.url.startsWith(`blob:`)){let e=await P(t.url);return{...t,url:e??t.url}}return t})).then(t=>{try{let r=f({text:n,files:t},e);r instanceof Promise?r.then(()=>{j(),_&&g.textInput.clear()}).catch(()=>{}):(j(),_&&g.textInput.clear())}catch{}}).catch(()=>{})},ref:y,...h,children:(0,i.jsx)(nt,{className:`overflow-hidden`,children:m})})]});return _?I:(0,i.jsx)(ht.Provider,{value:F,children:I})},bt=({className:e,...t})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`contents`,e),...t}),xt=({onChange:e,className:r,placeholder:a=`What would you like to know?`,...o})=>{let s=dt(),c=Q(),[l,u]=(0,t.useState)(!1),d=e=>{if(e.key===`Enter`){if(l||e.nativeEvent.isComposing||e.shiftKey)return;e.preventDefault();let t=e.currentTarget.form;if(t?.querySelector(`button[type="submit"]`)?.disabled)return;t?.requestSubmit()}if(e.key===`Backspace`&&e.currentTarget.value===``&&c.files.length>0){e.preventDefault();let t=c.files[c.files.length-1];t&&c.remove(t.id)}},f=e=>{let t=e.clipboardData?.items;if(!t)return;let n=[];for(let e of t)if(e.kind===`file`){let t=e.getAsFile();t&&n.push(t)}n.length>0&&(e.preventDefault(),c.add(n))},p=s?{value:s.textInput.value,onChange:t=>{s.textInput.setInput(t.currentTarget.value),e?.(t)}}:{onChange:e};return(0,i.jsx)(st,{className:(0,n.cn)(`field-sizing-content max-h-48 min-h-16`,r),name:`message`,onCompositionEnd:()=>u(!1),onCompositionStart:()=>u(!0),onKeyDown:d,onPaste:f,placeholder:a,...o,...p})},St=({className:e,...t})=>(0,i.jsx)(it,{align:`block-end`,className:(0,n.cn)(`order-first flex-wrap gap-1`,e),...t}),Ct=({className:e,...t})=>(0,i.jsx)(it,{align:`block-end`,className:(0,n.cn)(`justify-between gap-1`,e),...t}),wt=({className:e,...t})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`flex items-center gap-1`,e),...t}),Tt=({variant:e=`ghost`,className:r,size:a,...o})=>{let s=a??(t.Children.count(o.children)>1?`sm`:`icon-sm`);return(0,i.jsx)(ot,{className:(0,n.cn)(r),size:s,type:`button`,variant:e,...o})},Et=e=>(0,i.jsx)(n.DropdownMenu,{...e}),Dt=({className:e,children:t,...a})=>(0,i.jsx)(n.DropdownMenuTrigger,{asChild:!0,children:(0,i.jsx)(Tt,{className:e,...a,children:t??(0,i.jsx)(r.PlusIcon,{className:`size-4`})})}),Ot=({className:e,...t})=>(0,i.jsx)(n.DropdownMenuContent,{align:`start`,className:(0,n.cn)(e),...t}),kt=({className:e,...t})=>(0,i.jsx)(n.DropdownMenuItem,{className:(0,n.cn)(e),...t}),At=({className:e,variant:t=`default`,size:a=`icon-sm`,status:o,children:s,...c})=>{let l=(0,i.jsx)(r.CornerDownLeftIcon,{className:`size-4`});return o===`submitted`?l=(0,i.jsx)(r.Loader2Icon,{className:`size-4 animate-spin`}):o===`streaming`?l=(0,i.jsx)(r.SquareIcon,{className:`size-4`}):o===`error`&&(l=(0,i.jsx)(r.XIcon,{className:`size-4`})),(0,i.jsx)(ot,{"aria-label":`Submit`,className:(0,n.cn)(e),size:a,type:`submit`,variant:t,...c,children:s??l})},jt=({className:e,textareaRef:a,onTranscriptionChange:o,...s})=>{let[c,l]=(0,t.useState)(!1),[u,d]=(0,t.useState)(null),f=(0,t.useRef)(null);(0,t.useEffect)(()=>{if(typeof window<`u`&&(`SpeechRecognition`in window||`webkitSpeechRecognition`in window)){let e=new(window.SpeechRecognition||window.webkitSpeechRecognition);e.continuous=!0,e.interimResults=!0,e.lang=`en-US`,e.onstart=()=>{l(!0)},e.onend=()=>{l(!1)},e.onresult=e=>{let t=``;for(let n=e.resultIndex;n<e.results.length;n++){let r=e.results[n];r.isFinal&&(t+=r[0]?.transcript??``)}if(t&&a?.current){let e=a.current,n=e.value,r=n+(n?` `:``)+t;e.value=r,e.dispatchEvent(new Event(`input`,{bubbles:!0})),o?.(r)}},e.onerror=e=>{console.error(`Speech recognition error:`,e.error),l(!1)},f.current=e,d(e)}return()=>{f.current&&f.current.stop()}},[a,o]);let p=(0,t.useCallback)(()=>{u&&(c?u.stop():u.start())},[u,c]);return(0,i.jsx)(Tt,{className:(0,n.cn)(`relative transition-all duration-200`,c&&`animate-pulse bg-accent text-accent-foreground`,e),disabled:!u,onClick:p,...s,children:(0,i.jsx)(r.MicIcon,{className:`size-4`})})},Mt=e=>(0,i.jsx)(n.Select,{...e}),Nt=({className:e,...t})=>(0,i.jsx)(n.SelectTrigger,{className:(0,n.cn)(`border-none bg-transparent font-medium text-muted-foreground shadow-none transition-colors`,`hover:bg-accent hover:text-foreground aria-expanded:bg-accent aria-expanded:text-foreground`,e),...t}),Pt=({className:e,...t})=>(0,i.jsx)(n.SelectContent,{className:(0,n.cn)(e),...t}),Ft=({className:e,...t})=>(0,i.jsx)(n.SelectItem,{className:(0,n.cn)(e),...t}),It=({className:e,...t})=>(0,i.jsx)(n.SelectValue,{className:(0,n.cn)(e),...t}),Lt=({openDelay:e=0,closeDelay:t=0,...r})=>(0,i.jsx)(n.HoverCard,{closeDelay:t,openDelay:e,...r}),Rt=e=>(0,i.jsx)(n.HoverCardTrigger,{...e}),zt=({align:e=`start`,...t})=>(0,i.jsx)(n.HoverCardContent,{align:e,...t}),Bt=({className:e,...t})=>(0,i.jsx)(`div`,{className:(0,n.cn)(e),...t}),Vt=({className:e,...t})=>(0,i.jsx)(`div`,{className:(0,n.cn)(e),...t}),Ht=({className:e,...t})=>(0,i.jsx)(`h3`,{className:(0,n.cn)(`mb-2 px-3 font-medium text-muted-foreground text-xs`,e),...t}),Ut=({className:e,...t})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`space-y-1`,e),...t}),Wt=({className:e,...t})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`flex items-center gap-2 px-3 py-2 text-xs hover:bg-accent`,e),...t}),Gt=({className:e,...t})=>(0,i.jsx)(n.Command,{className:(0,n.cn)(e),...t}),Kt=({className:e,...t})=>(0,i.jsx)(n.CommandInput,{className:(0,n.cn)(e),...t}),qt=({className:e,...t})=>(0,i.jsx)(n.CommandList,{className:(0,n.cn)(e),...t}),Jt=({className:e,...t})=>(0,i.jsx)(n.CommandEmpty,{className:(0,n.cn)(e),...t}),Yt=({className:e,...t})=>(0,i.jsx)(n.CommandGroup,{className:(0,n.cn)(e),...t}),Xt=({className:e,...t})=>(0,i.jsx)(n.CommandItem,{className:(0,n.cn)(e),...t}),Zt=({className:e,...t})=>(0,i.jsx)(n.CommandSeparator,{className:(0,n.cn)(e),...t}),Qt=({className:e,children:t,...r})=>(0,i.jsxs)(n.ScrollArea,{className:`w-full overflow-x-auto whitespace-nowrap`,...r,children:[(0,i.jsx)(`div`,{className:(0,n.cn)(`flex w-max flex-nowrap items-center gap-2`,e),children:t}),(0,i.jsx)(n.ScrollBar,{className:`hidden`,orientation:`horizontal`})]}),$t=({suggestion:e,onClick:t,className:r,variant:a=`outline`,size:o=`sm`,children:s,...c})=>(0,i.jsx)(n.Button,{className:(0,n.cn)(`cursor-pointer rounded-full px-4`,r),onClick:()=>{t?.(e)},size:o,type:`button`,variant:a,...c,children:s||e}),en=(0,t.createContext)({code:``}),tn={name:`line-numbers`,line(e,t){e.children.unshift({type:`element`,tagName:`span`,properties:{className:[`inline-block`,`min-w-10`,`mr-4`,`text-right`,`select-none`,`text-muted-foreground`]},children:[{type:`text`,value:String(t)}]})}};async function nn(e,t,n=!1){let r=n?[tn]:[];return await Promise.all([(0,m.codeToHtml)(e,{lang:t,theme:`one-light`,transformers:r}),(0,m.codeToHtml)(e,{lang:t,theme:`one-dark-pro`,transformers:r})])}var $=({code:e,language:r,showLineNumbers:a=!1,className:o,children:s,...c})=>{let[l,u]=(0,t.useState)(``),[d,f]=(0,t.useState)(``),p=(0,t.useRef)(!1);return(0,t.useEffect)(()=>(nn(e,r,a).then(([e,t])=>{p.current||=(u(e),f(t),!0)}),()=>{p.current=!1}),[e,r,a]),(0,i.jsx)(en.Provider,{value:{code:e},children:(0,i.jsx)(`div`,{className:(0,n.cn)(`group relative w-full overflow-hidden rounded-md border bg-background text-foreground`,o),...c,children:(0,i.jsxs)(`div`,{className:`relative`,children:[(0,i.jsx)(`div`,{className:`overflow-auto dark:hidden [&>pre]:m-0 [&>pre]:bg-background! [&>pre]:p-4 [&>pre]:text-foreground! [&>pre]:text-sm [&_code]:font-mono [&_code]:text-sm`,dangerouslySetInnerHTML:{__html:l}}),(0,i.jsx)(`div`,{className:`hidden overflow-auto dark:block [&>pre]:m-0 [&>pre]:bg-background! [&>pre]:p-4 [&>pre]:text-foreground! [&>pre]:text-sm [&_code]:font-mono [&_code]:text-sm`,dangerouslySetInnerHTML:{__html:d}}),s&&(0,i.jsx)(`div`,{className:`absolute top-2 right-2 flex items-center gap-2`,children:s})]})})})},rn=({onCopy:e,onError:a,timeout:o=2e3,children:s,className:c,...l})=>{let[u,d]=(0,t.useState)(!1),{code:f}=(0,t.useContext)(en),p=async()=>{if(typeof window>`u`||!navigator?.clipboard?.writeText){a?.(Error(`Clipboard API not available`));return}try{await navigator.clipboard.writeText(f),d(!0),e?.(),setTimeout(()=>d(!1),o)}catch(e){a?.(e)}},m=u?r.CheckIcon:r.CopyIcon;return(0,i.jsx)(n.Button,{className:(0,n.cn)(`shrink-0`,c),onClick:p,size:`icon`,variant:`ghost`,...l,children:s??(0,i.jsx)(m,{size:14})})},an=({className:e,...t})=>(0,i.jsx)(n.Collapsible,{className:(0,n.cn)(`not-prose mb-4 w-full rounded-md border`,e),...t}),on=e=>(0,i.jsxs)(n.Badge,{className:`gap-1.5 rounded-full text-xs`,variant:`secondary`,children:[{"input-streaming":(0,i.jsx)(r.CircleIcon,{className:`size-4`}),"input-available":(0,i.jsx)(r.ClockIcon,{className:`size-4 animate-pulse`}),"approval-requested":(0,i.jsx)(r.ClockIcon,{className:`size-4 text-yellow-600`}),"approval-responded":(0,i.jsx)(r.CheckCircleIcon,{className:`size-4 text-blue-600`}),"output-available":(0,i.jsx)(r.CheckCircleIcon,{className:`size-4 text-green-600`}),"output-error":(0,i.jsx)(r.XCircleIcon,{className:`size-4 text-red-600`}),"output-denied":(0,i.jsx)(r.XCircleIcon,{className:`size-4 text-orange-600`})}[e],{"input-streaming":`Pending`,"input-available":`Running`,"approval-requested":`Awaiting Approval`,"approval-responded":`Responded`,"output-available":`Completed`,"output-error":`Error`,"output-denied":`Denied`}[e]]}),sn=({className:e,title:t,type:a,state:o,...s})=>(0,i.jsxs)(n.CollapsibleTrigger,{className:(0,n.cn)(`flex w-full items-center justify-between gap-4 p-3`,e),...s,children:[(0,i.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,i.jsx)(r.WrenchIcon,{className:`size-4 text-muted-foreground`}),(0,i.jsx)(`span`,{className:`font-medium text-sm`,children:t??a.split(`-`).slice(1).join(`-`)}),on(o)]}),(0,i.jsx)(r.ChevronDownIcon,{className:`size-4 text-muted-foreground transition-transform group-data-[state=open]:rotate-180`})]}),cn=({className:e,...t})=>(0,i.jsx)(n.CollapsibleContent,{className:(0,n.cn)(`data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-popover-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in`,e),...t}),ln=({className:e,input:t,...r})=>(0,i.jsxs)(`div`,{className:(0,n.cn)(`space-y-2 overflow-hidden p-4`,e),...r,children:[(0,i.jsx)(`h4`,{className:`font-medium text-muted-foreground text-xs uppercase tracking-wide`,children:`Parameters`}),(0,i.jsx)(`div`,{className:`rounded-md bg-muted/50`,children:(0,i.jsx)($,{code:JSON.stringify(t,null,2),language:`json`})})]}),un=({className:e,output:r,errorText:a,...o})=>{if(!(r||a))return null;let s=(0,i.jsx)(`div`,{children:r});return typeof r==`object`&&!(0,t.isValidElement)(r)?s=(0,i.jsx)($,{code:JSON.stringify(r,null,2),language:`json`}):typeof r==`string`&&(s=(0,i.jsx)($,{code:r,language:`json`})),(0,i.jsxs)(`div`,{className:(0,n.cn)(`space-y-2 p-4`,e),...o,children:[(0,i.jsx)(`h4`,{className:`font-medium text-muted-foreground text-xs uppercase tracking-wide`,children:a?`Error`:`Result`}),(0,i.jsxs)(`div`,{className:(0,n.cn)(`overflow-x-auto rounded-md text-xs [&_table]:w-full`,a?`bg-destructive/10 text-destructive`:`bg-muted/50 text-foreground`),children:[a&&(0,i.jsx)(`div`,{children:a}),s]})]})},dn=(0,t.memo)(({children:e,as:r=`p`,className:a,duration:o=2,spread:s=2})=>{let c=g.motion.create(r),l=(0,t.useMemo)(()=>(e?.length??0)*s,[e,s]);return(0,i.jsx)(c,{animate:{backgroundPosition:`0% center`},className:(0,n.cn)(`relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent`,`[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]`,a),initial:{backgroundPosition:`100% center`},style:{"--spread":`${l}px`,backgroundImage:`var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))`},transition:{repeat:1/0,duration:o,ease:`linear`},children:e})}),fn=(0,t.createContext)(null),pn=()=>{let e=(0,t.useContext)(fn);if(!e)throw Error(`Reasoning components must be used within Reasoning`);return e},mn=1e3,hn=1e3,gn=(0,t.memo)(({className:e,isStreaming:r=!1,open:a,defaultOpen:o=!0,onOpenChange:s,duration:c,children:l,...u})=>{let[d,f]=(0,h.useControllableState)({prop:a,defaultProp:o,onChange:s}),[p,m]=(0,h.useControllableState)({prop:c,defaultProp:void 0}),[g,_]=(0,t.useState)(!1),[v,y]=(0,t.useState)(null);return(0,t.useEffect)(()=>{r?v===null&&y(Date.now()):v!==null&&(m(Math.ceil((Date.now()-v)/hn)),y(null))},[r,v,m]),(0,t.useEffect)(()=>{if(o&&!r&&d&&!g){let e=setTimeout(()=>{f(!1),_(!0)},mn);return()=>clearTimeout(e)}},[r,d,o,f,g]),(0,i.jsx)(fn.Provider,{value:{isStreaming:r,isOpen:d,setIsOpen:f,duration:p},children:(0,i.jsx)(n.Collapsible,{className:(0,n.cn)(`not-prose mb-4`,e),onOpenChange:e=>{f(e)},open:d,...u,children:l})})}),_n=(e,t)=>e||t===0?(0,i.jsx)(dn,{duration:1,children:`Thinking...`}):t===void 0?(0,i.jsx)(`p`,{children:`Thought for a few seconds`}):(0,i.jsxs)(`p`,{children:[`Thought for `,t,` seconds`]}),vn=(0,t.memo)(({className:e,children:t,getThinkingMessage:a=_n,...o})=>{let{isStreaming:s,isOpen:c,duration:l}=pn();return(0,i.jsx)(n.CollapsibleTrigger,{className:(0,n.cn)(`flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground`,e),...o,children:t??(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(r.BrainIcon,{className:`size-4`}),a(s,l),(0,i.jsx)(r.ChevronDownIcon,{className:(0,n.cn)(`size-4 transition-transform`,c?`rotate-180`:`rotate-0`)})]})})}),yn=(0,t.memo)(({className:e,children:t,...r})=>(0,i.jsx)(n.CollapsibleContent,{className:(0,n.cn)(`mt-4 text-sm`,`data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in`,e),...r,children:(0,i.jsx)(f.Streamdown,{children:t})}));gn.displayName=`Reasoning`,vn.displayName=`ReasoningTrigger`,yn.displayName=`ReasoningContent`;var bn=({className:e,...t})=>(0,i.jsx)(n.Collapsible,{className:(0,n.cn)(`not-prose mb-4 text-primary text-xs`,e),...t}),xn=({className:e,count:t,children:a,...o})=>(0,i.jsx)(n.CollapsibleTrigger,{className:(0,n.cn)(`flex items-center gap-2`,e),...o,children:a??(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)(`p`,{className:`font-medium`,children:[`Used `,t,` sources`]}),(0,i.jsx)(r.ChevronDownIcon,{className:`h-4 w-4`})]})}),Sn=({className:e,...t})=>(0,i.jsx)(n.CollapsibleContent,{className:(0,n.cn)(`mt-3 flex w-fit flex-col gap-2`,`data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 outline-none data-[state=closed]:animate-out data-[state=open]:animate-in`,e),...t}),Cn=({href:e,title:t,children:n,...a})=>(0,i.jsx)(`a`,{className:`flex items-center gap-2`,href:e,rel:`noreferrer`,target:`_blank`,...a,children:n??(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(r.BookIcon,{className:`h-4 w-4`}),(0,i.jsx)(`span`,{className:`block font-medium`,children:t})]})});function wn(e){let t=e??{},n=t.data&&typeof t.data==`object`?t.data:t,r=n.seedApplied,i=n.probes;if(!r&&!i)return;let a={};return r&&(r.success===!1?a.seedError=r.error??(Array.isArray(r.errors)&&r.errors.length?String(r.errors[0]):`Sample data failed to load.`):a.seededRows=(r.inserted??0)+(r.updated??0)),i&&(a.checked={seeds:i.checked?.seeds??0,views:i.checked?.views??0,widgets:i.checked?.widgets??0},a.issues=(i.issues??[]).filter(e=>e&&typeof e.message==`string`).map(e=>({severity:e.severity===`error`?`error`:`warning`,code:String(e.code??`runtime_issue`),message:String(e.message)}))),a}function Tn(e){return e===`user`?`user`:`assistant`}function En(e){let t=e.trim();if(t.length<2||!(t.startsWith(`{`)||t.startsWith(`[`))||!(t.endsWith(`}`)||t.endsWith(`]`)))return!1;try{return JSON.parse(t),!0}catch{return!1}}function Dn(e){let t=e.state??(e.errorText?`output-error`:e.result===void 0?`input-available`:`output-available`);return t===`output-error`||t===`output-denied`?`failed`:t===`approval-requested`||t===`approval-responded`?`awaiting`:t===`output-available`?`completed`:`running`}function On(e){return[{create_object:`新建对象`,add_field:`新增字段`,modify_field:`修改字段`,delete_field:`删除字段`,create_metadata:`新建`,update_metadata:`修改`,create_seed:`生成示例数据`,create_package:`新建应用包`}[e.verb]??e.verb,`${e.field?`${e.object?`${e.object}.`:``}${e.field}`:e.object??e.name??``}${e.type?`(${e.type})`:``}`,e.details].filter(Boolean).join(` `)}function kn(e){return e.toolName===`propose_blueprint`}function An(e){return kn(e)&&Dn(e)===`completed`&&!e.proposedPlan&&!e.proposedChanges&&!e.draftReview?.items.length}var jn=[`待补`,`后续`,`将在`,`稍后`,`暂不`,`暂未`,`尚未`,`确认后一起补`,`一起补`,`另行`,`日后`,`not yet`,`will be implemented`,`will be added`,`to be added`,`to be implemented`,`later`,`deferred`,`follow-up`,`follow up`,`future`,`subsequent`,`coming soon`,`tbd`];function Mn(e){let t=[],n=[];for(let r of e){if(typeof r!=`string`)continue;let e=r.trim();if(!e)continue;let i=e.toLowerCase();jn.some(e=>i.includes(e))?n.push(e):t.push(e)}return{designNotes:t,deferred:n}}function Nn(e){let t=Dn(e);return t===`awaiting`||t===`failed`||!!e.pendingActionId||!!e.draftReview?.items.length||!!e.proposedPlan||!!e.proposedChanges||An(e)}function Pn(e){switch(e){case`failed`:return 4;case`awaiting`:return 3;case`running`:return 2;case`completed`:return 1}}function Fn(e){let t=new Map;for(let n of e){let e=Dn(n),r=`${n.toolName}:${e}`,i=t.get(r);if(i){i.count+=1,i.errorText=i.errorText??n.errorText;continue}t.set(r,{key:r,title:Oe(n.toolName)||n.toolName,rawName:n.toolName,count:1,state:e,errorText:n.errorText})}return Array.from(t.values()).sort((e,t)=>{let n=Pn(t.state)-Pn(e.state);return n===0?e.title.localeCompare(t.title):n})}function In({health:e}){if(!e)return null;let t=e.issues??[],n=t.filter(e=>e.severity===`error`),a=t.filter(e=>e.severity!==`error`),o=e.checked,s=!!o&&o.seeds+o.views+o.widgets>0,c=[];if(typeof e.seededRows==`number`&&e.seededRows>0&&!e.seedError&&c.push(`${e.seededRows} sample row${e.seededRows===1?``:`s`} live`),s&&n.length===0){let e=[];o.views>0&&e.push(`${o.views} view${o.views===1?``:`s`}`),o.widgets>0&&e.push(`${o.widgets} widget${o.widgets===1?``:`s`}`),o.seeds>0&&e.push(`${o.seeds} seed${o.seeds===1?``:`s`}`),e.length&&c.push(`${e.join(` · `)} verified`)}return c.length===0&&!e.seedError&&t.length===0?null:(0,i.jsxs)(`div`,{className:`flex flex-col gap-1 border-t bg-muted/20 px-3 py-2`,"data-testid":`publish-health`,children:[c.length>0?(0,i.jsxs)(`div`,{className:`flex items-center gap-1.5 text-xs text-emerald-700`,children:[(0,i.jsx)(r.CheckCircle2,{className:`size-3.5 shrink-0`}),(0,i.jsx)(`span`,{children:c.join(` · `)})]}):null,e.seedError?(0,i.jsxs)(`div`,{className:`flex items-start gap-1.5 text-xs text-red-600`,children:[(0,i.jsx)(r.XCircle,{className:`mt-0.5 size-3.5 shrink-0`}),(0,i.jsx)(`span`,{children:e.seedError})]}):null,n.map((e,t)=>(0,i.jsxs)(`div`,{className:`flex items-start gap-1.5 text-xs text-red-600`,children:[(0,i.jsx)(r.XCircle,{className:`mt-0.5 size-3.5 shrink-0`}),(0,i.jsx)(`span`,{children:e.message})]},`e${t}`)),a.map((e,t)=>(0,i.jsxs)(`div`,{className:`flex items-start gap-1.5 text-xs text-amber-600`,children:[(0,i.jsx)(r.AlertCircle,{className:`mt-0.5 size-3.5 shrink-0`}),(0,i.jsx)(`span`,{children:e.message})]},`w${t}`))]})}var Ln=t.forwardRef(({className:e,messages:a=[],placeholder:o=`Type your message...`,onSendMessage:s,onClear:l,onStop:u,onReload:d,onUpgrade:f,disabled:p=!1,readOnly:m=!1,isLoading:h=!1,error:g,showTimestamp:_=!1,showAvatars:v=!1,userAvatarUrl:y,userAvatarFallback:b=`You`,assistantAvatarUrl:x,assistantAvatarFallback:S=`AI`,hideClearBar:C=!1,maxHeight:w=`500px`,enableMarkdown:T=!0,enableFileUpload:E=!1,acceptedFileTypes:D=`image/*,.pdf,.doc,.docx,.txt`,maxFileSize:O=10*1024*1024,suggestions:k,labels:A,models:j,selectedModelId:M,onModelChange:N,headerSlot:P,promptOverlaySlot:F,onInputChange:I,onToolApprove:L,toolApproveLabel:ee=`Approve`,toolDenyLabel:te=`Deny`,toolDenyReason:ne=`User denied the operation`,toolDecisions:re,onReviewDraft:ie,toolReviewLabel:ae=e=>`Review ${e} change${e===1?``:`s`}`,onPublishDrafts:R,onOpenBuiltApp:oe,openBuiltAppLabel:se=`Open app`,onPreviewDraftApp:z,previewDraftLabel:B=`Preview`,onDraftArtifacts:V,onBuildMaterialized:H,publishDraftsLabel:ce=`Publish`,publishedLabel:le=`Published`,verifiedLabel:ue=`Verified`,nextStepsLabel:de=`What's next`,planTitleLabel:fe=`Proposed plan`,planExtendLabel:pe=`Adding to existing app`,planQuestionsLabel:me=`Confirm before building`,planAssumptionsLabel:he=`Assumptions`,planDeferredLabel:ge=`Not yet built`,planApproveHintLabel:_e=`Reply to approve or adjust this plan.`,planApproveLabel:ve=`Build it`,planAdjustLabel:ye=`Adjust`,planBuiltLabel:be=`Built`,planReadyLabel:xe=`The plan is ready. Build it now, or tell me what to adjust.`,planApproveMessage:Se=`Looks good — build it as proposed.`,planApproveDefaultsMessage:U=`Build it with your best assumptions; use sensible defaults for the open questions.`,planAnswerMessage:Ce=(e,t)=>`For "${e}", go with: ${t}.`,fetchPendingDraftCount:W,autoPublishDrafts:we=!1,processVisibility:G=`summary`,surface:Te=`card`,...Ee},De)=>{let K=h?`streaming`:`ready`,q=Te===`plain`,[J,Ae]=t.useState(null),je=t.useRef(``),Pe=t.useRef(null),Y=t.useMemo(()=>({emptyTitle:A?.emptyTitle??`Start a conversation`,emptyDescription:A?.emptyDescription??`Ask anything — the assistant has access to your current app context.`,clear:A?.clear??`Clear`,sendHint:A?.sendHint??`to send`,agentActivity:A?.agentActivity??`Agent activity`,toolCompleted:A?.toolCompleted??`Completed`,toolRunning:A?.toolRunning??`Running`,toolAwaitingApproval:A?.toolAwaitingApproval??`Awaiting approval`,toolFailed:A?.toolFailed??`Failed`,toolDetailsHidden:A?.toolDetailsHidden??`Detailed tool inputs and outputs are hidden in this view.`,copy:A?.copy??`Copy`,copied:A?.copied??`Copied`,regenerate:A?.regenerate??`Regenerate`,model:A?.model??`Model`,submit:A?.submit??`Submit`,uploadFiles:A?.uploadFiles??`Upload files`,stopResponse:A?.stopResponse??`Stop response`,sendFailedRateLimited:A?.sendFailedRateLimited??`You're sending messages too quickly. Your message is kept below — wait a moment and try again.`,sendFailedGeneric:A?.sendFailedGeneric??`Couldn't send your message. It's kept below — please try again.`,trace:A?.trace??`trace`,viewTrace:A?.viewTrace??`View trace`,connectionWaiting:A?.connectionWaiting??`Waiting for server…`,connectionStalledLabel:A?.connectionStalledLabel??`Still working…`,connectionOfflineLabel:A?.connectionOfflineLabel??`Connection lost — reconnecting…`,designingPlanLabel:A?.designingPlanLabel??`Designing your app…`,designingPlanHints:A?.designingPlanHints??Kn}),[A]),[ze,Be]=t.useState(()=>new Set),[Ve,Ke]=t.useState(()=>new Map),[X,qe]=t.useState(()=>new Map),Je=t.useRef(new Set),Z=t.useCallback(async e=>{if(W)try{let t=await W(e);qe(n=>{if(n.get(e)===t)return n;let r=new Map(n);return r.set(e,t),r})}catch{}},[W]);t.useEffect(()=>{if(!W||h)return;let e=new Set;for(let t of a)for(let n of t.toolInvocations??[]){let t=n.draftReview?.packageId,r=n.toolCallId;t&&r&&!Je.current.has(r)&&(Je.current.add(r),e.add(t))}for(let t of e)Z(t)},[a,h,W,Z]);let Ye=t.useCallback(async e=>{if(!R)return;let t=[];for(let n of a)for(let r of n.toolInvocations??[])r.draftReview?.packageId===e&&r.toolCallId&&t.push(r.toolCallId);let n=await R(e),r=n&&typeof n==`object`?n:void 0;if((r?r.ok!==!1:n!==!1)&&t.length>0){Be(e=>{let n=new Set(e);for(let e of t)n.add(e);return n});let e=r?.health;e&&Ke(n=>{let r=new Map(n);for(let n of t)r.set(n,e);return r})}Z(e)},[R,a,Z]),Xe=t.useRef(new Set),Ze=t.useRef(!1);t.useEffect(()=>{let e=[];for(let t of a)for(let n of t.toolInvocations??[]){let t=n.draftReview;t?.autoPublishable&&t.packageId&&n.toolCallId&&t.items.length>0&&e.push({key:n.toolCallId,packageId:t.packageId})}if(!Ze.current){Ze.current=!0;for(let t of e)Xe.current.add(t.key);return}if(!we||!R||h)return;let t=e.filter(e=>!Xe.current.has(e.key));if(t.length!==0){for(let e of t)Xe.current.add(e.key);for(let e of[...new Set(t.map(e=>e.packageId))])Ye(e)}},[a,h,we,R,Ye]);let $e=t.useRef(new Set);t.useEffect(()=>{if(!V)return;let e=new Map,t;for(let n of a){for(let t of n.buildProgress?.items??[])t?.type&&t?.name&&e.set(`${t.type}:${t.name}`,t);for(let r of n.toolInvocations??[]){let n=r.draftReview;for(let t of n?.items??[])t?.type&&t?.name&&e.set(`${t.type}:${t.name}`,t);n?.packageId&&n.items?.some(e=>e.type===`app`)&&(t=n.packageId)}}let n=$e.current,r=!1;for(let t of e.keys())n.has(t)||(n.add(t),r=!0);r&&V([...e.values()],t)},[a,V]);let et=t.useRef(new Set);t.useEffect(()=>{if(H)for(let e of a)for(let t of e.toolInvocations??[]){let e=t.draftReview;if(!e?.materialized||!t.toolCallId)continue;let n=e.items.find(e=>e.type===`app`);!n||et.current.has(t.toolCallId)||(et.current.add(t.toolCallId),H(n.name))}},[a,H]);let tt=t.useCallback(e=>{let t=!!e.text?.trim(),n=e.files?.map(e=>e.file).filter(Boolean),r=!!(n&&n.length>0);if(!(t||r))return;let i=e.text?.trim()??``;je.current=i,Pe.current=null,s?.(i,n)},[s]),nt=t.useCallback(e=>{s?.(e)},[s]),rt=t.useRef(null),it=t.useCallback(e=>{s?.(e?U:Se)},[s,Se,U]),at=t.useCallback(()=>{let e=rt.current?.querySelector(`textarea`);e&&(e.focus(),e.scrollIntoView({block:`nearest`}))},[]);t.useEffect(()=>{if(!g||!Ne(g)||Pe.current===g)return;Pe.current=g;let e=je.current;if(!e)return;let t=rt.current?.querySelector(`textarea`);t&&t.value.trim()===``&&(t.value=e,t.dispatchEvent(new Event(`input`,{bubbles:!0})),t.focus())},[g]);let ot=t.useCallback(e=>{navigator.clipboard?.writeText(e.content),Ae(e.id),window.setTimeout(()=>Ae(t=>t===e.id?null:t),1500)},[]),st=t.useMemo(()=>{let e=new Set,t=[],n=-1,r=0;for(let e of a)for(let i of e.toolInvocations??[])(i.proposedPlan||An(i))&&i.toolCallId&&t.push({id:i.toolCallId,order:r}),i.toolName===`apply_blueprint`&&(n=r),r+=1;for(let r of t)r.order<n&&e.add(r.id);return e},[a]),ct=t.useMemo(()=>{let e=new Set,t=[],n=new Map,r=0;for(let e of a)for(let i of e.toolInvocations??[])i.proposedChanges&&i.toolCallId?t.push({id:i.toolCallId,toolName:i.toolName??``,order:r}):i.toolName&&n.set(i.toolName,r),r+=1;for(let r of t){let t=n.get(r.toolName);t!==void 0&&t>r.order&&e.add(r.id)}return e},[a]),lt=e=>{let t=e.state??(e.errorText?`output-error`:e.result===void 0?`input-available`:`output-available`),n=`tool-${e.toolName}`,a=re?.[e.toolCallId],o=t===`approval-requested`&&!!L&&!a,c=t===`approval-requested`&&!!e.pendingActionId,l=Oe(e.toolName),u=ke(e.result),d=G===`debug`&&l&&l.toLowerCase()!==e.toolName.toLowerCase(),f=G===`debug`||o,p=e.draftReview?.packageId,m=p===void 0?void 0:X.get(p),h=m===void 0?ze.has(e.toolCallId):m===0,g=t===`input-streaming`||t===`input-available`,_=(0,i.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,i.jsx)(`span`,{children:l||e.toolName}),d?(0,i.jsx)(`code`,{className:`rounded bg-muted px-1 py-px text-[10px] font-mono text-muted-foreground`,children:e.toolName}):null,g?kn(e)?(0,i.jsx)(Yn,{label:Y.designingPlanLabel,hints:Y.designingPlanHints,offlineLabel:Y.connectionOfflineLabel}):(0,i.jsx)(Xn,{offlineLabel:Y.connectionOfflineLabel}):null]});return(0,i.jsxs)(an,{defaultOpen:t===`output-error`||t===`approval-requested`||!!(e.draftReview&&e.draftReview.items.length>0)||!!e.proposedPlan||!!e.proposedChanges||An(e),children:[(0,i.jsx)(sn,{type:n,state:t,title:_}),(0,i.jsxs)(cn,{children:[f&&e.args!==void 0?(0,i.jsx)(ln,{input:e.args}):null,c?null:f||t===`output-error`?(0,i.jsx)(or,{output:u,errorText:e.errorText}):null,a?(0,i.jsxs)(`div`,{className:`flex items-center gap-2 p-3 border-t text-xs `+(a.state===`error`?`bg-destructive/10 text-destructive`:a.state===`success`?`bg-emerald-500/10 text-emerald-700 dark:text-emerald-400`:`bg-muted/30 text-muted-foreground`),children:[(0,i.jsx)(`span`,{"aria-hidden":`true`,children:a.state===`pending`?`...`:a.state===`success`?`OK`:`X`}),(0,i.jsx)(`span`,{children:a.message??(a.state===`pending`?`Submitting decision...`:a.state===`success`?`Action approved and executed.`:`Decision failed.`)})]}):null,o?(0,i.jsxs)(`div`,{className:`flex gap-2 p-3 border-t bg-muted/30`,children:[(0,i.jsx)(`button`,{type:`button`,onClick:()=>L?.(e.toolCallId,!0),className:`inline-flex h-7 items-center rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground hover:bg-primary/90`,children:ee}),(0,i.jsx)(`button`,{type:`button`,onClick:()=>L?.(e.toolCallId,!1,ne),className:`inline-flex h-7 items-center rounded-md border bg-background px-3 text-xs font-medium hover:bg-accent`,children:te})]}):null,e.draftReview&&e.draftReview.items.length>0&&(ie||R&&e.draftReview.packageId)?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)(`div`,{className:`flex items-center gap-2 p-3 border-t bg-muted/30`,children:[R&&e.draftReview.packageId?h?(0,i.jsxs)(`span`,{className:`inline-flex h-7 items-center gap-1.5 rounded-md border border-emerald-200 bg-emerald-50 px-3 text-xs font-medium text-emerald-700`,children:[(0,i.jsx)(r.CheckCircle2,{className:`size-3.5`}),le,e.draftReview.failedCount?` · ${e.draftReview.failedCount} need${e.draftReview.failedCount===1?`s`:``} attention`:``]}):(0,i.jsxs)(`button`,{type:`button`,onClick:()=>void Ye(e.draftReview.packageId),className:`inline-flex h-7 items-center gap-1.5 rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground hover:bg-primary/90`,"data-testid":`draft-publish`,children:[(0,i.jsx)(r.Rocket,{className:`size-3.5`}),ce,typeof m==`number`&&m>0?` (${m})`:``]}):null,ie?(0,i.jsxs)(`button`,{type:`button`,onClick:()=>ie(e.draftReview.items),className:R&&e.draftReview.packageId?`inline-flex h-7 items-center gap-1.5 rounded-md border px-3 text-xs font-medium hover:bg-muted`:`inline-flex h-7 items-center gap-1.5 rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground hover:bg-primary/90`,children:[(0,i.jsx)(r.GitCompareArrows,{className:`size-3.5`}),ae(e.draftReview.items.length)]}):null,z&&!h?(()=>{let t=e.draftReview.items.find(e=>e.type===`app`);return t?(0,i.jsxs)(`button`,{type:`button`,onClick:()=>z(t.name,{materialized:e.draftReview.materialized===!0,appSegment:e.draftReview.packageId}),className:`inline-flex h-7 items-center gap-1.5 rounded-md border px-3 text-xs font-medium hover:bg-muted`,"data-testid":`draft-preview-app`,children:[(0,i.jsx)(r.Eye,{className:`size-3.5`}),B]}):null})():null,e.draftReview.verification?e.draftReview.verification.errors>0?(0,i.jsxs)(`span`,{className:`inline-flex h-7 shrink-0 items-center gap-1.5 rounded-md border border-amber-200 bg-amber-50 px-2.5 text-xs font-medium text-amber-700`,"data-testid":`draft-verification-chip`,children:[(0,i.jsx)(r.TriangleAlert,{className:`size-3.5`}),`${e.draftReview.verification.errors} issue${e.draftReview.verification.errors===1?``:`s`}`]}):(0,i.jsxs)(`span`,{className:`inline-flex h-7 shrink-0 items-center gap-1.5 rounded-md border border-emerald-200 bg-emerald-50 px-2.5 text-xs font-medium text-emerald-700`,"data-testid":`draft-verification-chip`,children:[(0,i.jsx)(r.ShieldCheck,{className:`size-3.5`}),ue]}):null,e.draftReview.summary?(0,i.jsx)(`span`,{className:`truncate text-xs text-muted-foreground`,children:e.draftReview.summary}):null]}),e.draftReview.issues&&e.draftReview.issues.length>0?(0,i.jsxs)(`div`,{className:`flex flex-col gap-1 border-t bg-muted/20 px-3 py-2`,"data-testid":`draft-issues`,children:[e.draftReview.issues.filter(e=>e.severity===`error`).map((e,t)=>(0,i.jsxs)(`div`,{className:`flex items-start gap-1.5 text-xs text-red-600`,children:[(0,i.jsx)(r.XCircle,{className:`mt-0.5 size-3.5 shrink-0`}),(0,i.jsx)(`span`,{children:e.fix?`${e.message} — ${e.fix}`:e.message})]},`e${t}`)),e.draftReview.issues.filter(e=>e.severity!==`error`).map((e,t)=>(0,i.jsxs)(`div`,{className:`flex items-start gap-1.5 text-xs text-amber-600`,children:[(0,i.jsx)(r.AlertCircle,{className:`mt-0.5 size-3.5 shrink-0`}),(0,i.jsx)(`span`,{children:e.message})]},`w${t}`))]}):null,ze.has(e.toolCallId)?(0,i.jsx)(In,{health:Ve.get(e.toolCallId)}):null,e.draftReview.nextSteps&&e.draftReview.nextSteps.length>0?(0,i.jsxs)(`div`,{className:`flex flex-col gap-1 border-t bg-muted/20 px-3 py-2`,"data-testid":`draft-next-steps`,children:[(0,i.jsx)(`span`,{className:`text-xs font-medium text-foreground/80`,children:de}),e.draftReview.nextSteps.map((e,t)=>(0,i.jsxs)(`div`,{className:`flex items-start gap-1.5 text-xs text-muted-foreground`,children:[(0,i.jsx)(`span`,{className:`mt-px shrink-0 text-foreground/40`,children:`→`}),(0,i.jsx)(`span`,{children:e})]},t))]}):null]}):null,e.proposedPlan?(0,i.jsxs)(`div`,{className:`flex flex-col gap-2 border-t bg-muted/20 px-3 py-2.5`,"data-testid":`proposed-plan`,children:[(0,i.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-xs font-medium text-foreground/80`,children:[(0,i.jsx)(r.ClipboardList,{className:`size-3.5`}),fe]}),e.proposedPlan.targetApp?(0,i.jsxs)(`span`,{className:`inline-flex w-fit items-center gap-1 rounded-md border border-blue-200 bg-blue-50 px-2 py-0.5 text-[11px] font-medium text-blue-700 dark:border-blue-900/50 dark:bg-blue-950/30 dark:text-blue-300`,"data-testid":`proposed-plan-extend`,children:[`+ `,pe,` 「`,e.proposedPlan.targetApp,`」`]}):null,e.proposedPlan.summary?(0,i.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.proposedPlan.summary}):null,e.proposedPlan.objects.length>0?(0,i.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.proposedPlan.objects.map(e=>(0,i.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-md border bg-background px-1.5 py-0.5 text-[11px] text-foreground/80`,title:e.name,children:[(0,i.jsx)(r.Table2,{className:`size-3 text-foreground/40`}),e.label||e.name,e.fieldCount>0?(0,i.jsxs)(`span`,{className:`text-foreground/40`,children:[`· `,e.fieldCount]}):null]},e.name))}):null,(()=>{let t=e.proposedPlan.counts,n=[];return t.objects&&n.push(`${t.objects} object${t.objects===1?``:`s`}`),t.views&&n.push(`${t.views} view${t.views===1?``:`s`}`),t.dashboards&&n.push(`${t.dashboards} dashboard${t.dashboards===1?``:`s`}`),t.seedData&&n.push(`sample data`),n.length?(0,i.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:n.join(` · `)}):null})(),(()=>{let{designNotes:t,deferred:n}=Mn(e.proposedPlan.assumptions);return(0,i.jsxs)(i.Fragment,{children:[t.length>0?(0,i.jsxs)(`div`,{className:`flex flex-col gap-0.5`,"data-testid":`proposed-plan-assumptions`,children:[(0,i.jsx)(`span`,{className:`text-[11px] font-medium text-foreground/70`,children:he}),t.map((e,t)=>(0,i.jsxs)(`div`,{className:`flex items-start gap-1.5 text-[11px] text-muted-foreground`,children:[(0,i.jsx)(`span`,{className:`mt-px shrink-0 text-foreground/40`,children:`·`}),(0,i.jsx)(`span`,{children:e})]},t))]}):null,n.length>0?(0,i.jsxs)(`div`,{className:`flex flex-col gap-1 rounded-md border border-dashed border-amber-300 bg-amber-50/60 px-2 py-1.5 dark:border-amber-800/60 dark:bg-amber-950/20`,"data-testid":`proposed-plan-deferred`,children:[(0,i.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-[11px] font-medium text-amber-800 dark:text-amber-300`,children:[(0,i.jsx)(r.Hourglass,{className:`size-3.5`}),ge]}),n.map((e,t)=>(0,i.jsxs)(`div`,{className:`flex items-start gap-1.5 text-[11px] text-amber-900/90 dark:text-amber-200/90`,children:[(0,i.jsx)(`span`,{className:`mt-px shrink-0 text-amber-500/80`,children:`·`}),(0,i.jsx)(`span`,{children:e})]},t))]}):null]})})(),e.proposedPlan.questions.length>0?(0,i.jsxs)(`div`,{className:`flex flex-col gap-1 rounded-md border border-amber-200 bg-amber-50 px-2 py-1.5 dark:border-amber-900/50 dark:bg-amber-950/30`,"data-testid":`proposed-plan-questions`,children:[(0,i.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-[11px] font-medium text-amber-800 dark:text-amber-300`,children:[(0,i.jsx)(r.HelpCircle,{className:`size-3.5`}),me]}),e.proposedPlan.questions.map((t,n)=>{let r=e.proposedPlan.questionChoices?.find(e=>e.text===t);return(0,i.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,i.jsxs)(`div`,{className:`flex items-start gap-1.5 text-[11px] text-amber-900/90 dark:text-amber-200/90`,children:[(0,i.jsx)(`span`,{className:`mt-px shrink-0`,children:`?`}),(0,i.jsx)(`span`,{children:t})]}),s&&r&&r.options.length>0?(0,i.jsx)(`div`,{className:`flex flex-wrap gap-1 pl-3.5`,"data-testid":`proposed-plan-choice`,children:r.options.map((e,n)=>(0,i.jsx)(`button`,{type:`button`,onClick:()=>s(Ce(t,e)),className:`inline-flex h-6 items-center rounded-full border border-amber-300 bg-background px-2 text-[11px] font-medium text-amber-900 hover:bg-amber-100 dark:border-amber-800 dark:text-amber-200 dark:hover:bg-amber-900/40`,children:e},n))}):null]},n)})]}):null,s?st.has(e.toolCallId)?(0,i.jsx)(`div`,{className:`flex flex-wrap items-center gap-1.5 pt-0.5`,"data-testid":`proposed-plan-actions`,children:(0,i.jsxs)(`span`,{className:`inline-flex h-7 items-center gap-1.5 rounded-md border border-emerald-200 bg-emerald-50 px-3 text-xs font-medium text-emerald-700 dark:border-emerald-900/50 dark:bg-emerald-950/30 dark:text-emerald-300`,"data-testid":`proposed-plan-built`,children:[(0,i.jsx)(r.CheckCircle2,{className:`size-3.5`}),be]})}):(0,i.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 pt-0.5`,"data-testid":`proposed-plan-actions`,children:[(0,i.jsxs)(`button`,{type:`button`,onClick:()=>it(e.proposedPlan.questions.length>0),className:`inline-flex h-7 items-center gap-1.5 rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground hover:bg-primary/90`,"data-testid":`proposed-plan-approve`,children:[(0,i.jsx)(r.Rocket,{className:`size-3.5`}),ve]}),(0,i.jsx)(`button`,{type:`button`,onClick:at,className:`inline-flex h-7 items-center rounded-md border bg-background px-3 text-xs font-medium hover:bg-accent`,"data-testid":`proposed-plan-adjust`,children:ye})]}):(0,i.jsx)(`span`,{className:`text-[11px] italic text-muted-foreground/80`,children:_e})]}):null,An(e)?(0,i.jsxs)(`div`,{className:`flex flex-col gap-2 border-t bg-muted/20 px-3 py-2.5`,"data-testid":`proposed-plan-fallback`,children:[(0,i.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-xs font-medium text-foreground/80`,children:[(0,i.jsx)(r.ClipboardList,{className:`size-3.5`}),fe]}),(0,i.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:xe}),s?st.has(e.toolCallId)?(0,i.jsx)(`div`,{className:`flex flex-wrap items-center gap-1.5 pt-0.5`,"data-testid":`proposed-plan-actions`,children:(0,i.jsxs)(`span`,{className:`inline-flex h-7 items-center gap-1.5 rounded-md border border-emerald-200 bg-emerald-50 px-3 text-xs font-medium text-emerald-700 dark:border-emerald-900/50 dark:bg-emerald-950/30 dark:text-emerald-300`,"data-testid":`proposed-plan-built`,children:[(0,i.jsx)(r.CheckCircle2,{className:`size-3.5`}),be]})}):(0,i.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 pt-0.5`,"data-testid":`proposed-plan-actions`,children:[(0,i.jsxs)(`button`,{type:`button`,onClick:()=>it(!1),className:`inline-flex h-7 items-center gap-1.5 rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground hover:bg-primary/90`,"data-testid":`proposed-plan-approve`,children:[(0,i.jsx)(r.Rocket,{className:`size-3.5`}),ve]}),(0,i.jsx)(`button`,{type:`button`,onClick:at,className:`inline-flex h-7 items-center rounded-md border bg-background px-3 text-xs font-medium hover:bg-accent`,"data-testid":`proposed-plan-adjust`,children:ye})]}):(0,i.jsx)(`span`,{className:`text-[11px] italic text-muted-foreground/80`,children:_e})]}):null,e.proposedChanges?(0,i.jsxs)(`div`,{className:`flex flex-col gap-2 border-t bg-muted/20 px-3 py-2.5`,"data-testid":`proposed-changes`,children:[(0,i.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-xs font-medium text-foreground/80`,children:[(0,i.jsx)(r.ClipboardList,{className:`size-3.5`}),`确认改动`]}),e.proposedChanges.summary?(0,i.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.proposedChanges.summary}):null,(0,i.jsx)(`div`,{className:`flex flex-col gap-1`,children:e.proposedChanges.changes.map((e,t)=>(0,i.jsxs)(`div`,{className:`flex items-start gap-1.5 rounded-md border bg-background px-2 py-1 text-[11px] text-foreground/80`,children:[(0,i.jsx)(r.Table2,{className:`mt-px size-3 shrink-0 text-foreground/40`}),(0,i.jsx)(`span`,{children:On(e)})]},t))}),s?ct.has(e.toolCallId)?(0,i.jsx)(`div`,{className:`flex flex-wrap items-center gap-1.5 pt-0.5`,"data-testid":`proposed-changes-actions`,children:(0,i.jsxs)(`span`,{className:`inline-flex h-7 items-center gap-1.5 rounded-md border border-emerald-200 bg-emerald-50 px-3 text-xs font-medium text-emerald-700 dark:border-emerald-900/50 dark:bg-emerald-950/30 dark:text-emerald-300`,"data-testid":`proposed-changes-confirmed`,children:[(0,i.jsx)(r.CheckCircle2,{className:`size-3.5`}),`已确认`]})}):(0,i.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 pt-0.5`,"data-testid":`proposed-changes-actions`,children:[(0,i.jsxs)(`button`,{type:`button`,onClick:()=>s(`确认修改,应用你刚才提议的改动。`),className:`inline-flex h-7 items-center gap-1.5 rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground hover:bg-primary/90`,"data-testid":`proposed-changes-confirm`,children:[(0,i.jsx)(r.CheckCircle2,{className:`size-3.5`}),`确认修改`]}),(0,i.jsx)(`button`,{type:`button`,onClick:at,className:`inline-flex h-7 items-center rounded-md border bg-background px-3 text-xs font-medium hover:bg-accent`,"data-testid":`proposed-changes-adjust`,children:`调整`})]}):(0,i.jsx)(`span`,{className:`text-[11px] italic text-muted-foreground/80`,children:`回复以确认或调整该改动。`})]}):null]})]},e.toolCallId)};return(0,i.jsxs)(`div`,{ref:De,className:(0,n.cn)(q?`flex min-h-0 flex-col overflow-hidden bg-background`:`flex min-h-0 flex-col overflow-hidden rounded-lg border bg-background`,e),style:{maxHeight:w},...Ee,children:[l&&!C&&a.length>0&&(0,i.jsx)(`div`,{className:(0,n.cn)(`flex items-center justify-end px-4 py-2`,q?`bg-background`:`border-b bg-muted/30`),children:(0,i.jsx)(`button`,{type:`button`,onClick:l,className:`text-xs text-muted-foreground hover:text-foreground transition-colors`,children:Y.clear})}),P?(0,i.jsx)(`div`,{className:(0,n.cn)(`shrink-0`,!q&&`border-b bg-background/50`),children:P}):null,(0,i.jsxs)(Fe,{className:`flex-1 min-h-0`,children:[(0,i.jsxs)(Ie,{className:(0,n.cn)(`space-y-4`,q?`mx-auto w-full max-w-2xl px-4 py-8 sm:px-0`:`px-4 py-3`),children:[a.length===0?(0,i.jsxs)(Le,{className:`gap-3 px-0 py-8`,children:[(0,i.jsx)(`div`,{className:`flex size-9 items-center justify-center rounded-md bg-muted/70 text-muted-foreground`,children:x?(0,i.jsx)(`img`,{src:x,alt:``,className:`size-full rounded-md object-cover`}):(0,i.jsx)(r.Bot,{className:`size-4`})}),(0,i.jsxs)(`div`,{className:`space-y-1`,children:[(0,i.jsx)(`h3`,{className:`text-sm font-medium text-foreground/90`,children:Y.emptyTitle}),(0,i.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:Y.emptyDescription})]}),k&&k.length>0?(0,i.jsx)(Qt,{className:`justify-center gap-2`,children:k.map(e=>(0,i.jsx)($t,{className:`h-8 border-border/60 bg-background/80 px-3 text-xs font-medium text-foreground/90 shadow-none hover:bg-muted/60`,suggestion:e,onClick:nt},e))}):null]}):a.map(e=>{let t=e.role===`user`,a=e.toolInvocations??[],o=e.reasoning?.trim(),s=e.sources??[],l=t?void 0:e.buildProgress,u=!t&&!a.some(e=>!!e.proposedPlan)?e.blueprintProgress:void 0,f=!t&&!!e.streaming&&!e.content&&a.length===0&&!o&&!l&&!u,p=!t&&G===`summary`?a.filter(e=>!Nn(e)&&!(u&&e.toolName===`propose_blueprint`)):[],m=!t&&G===`debug`?a:!t&&G!==`debug`?a.filter(Nn):[];return(0,i.jsx)(He,{from:Tn(e.role),children:(0,i.jsxs)(`div`,{className:(0,n.cn)(`flex w-full gap-2.5`,v?t?`flex-row-reverse items-start`:`flex-row items-start`:`flex-col`),children:[v?(0,i.jsx)(Rn,{isUser:t,url:t?y:x,fallback:t?b:S}):null,(0,i.jsxs)(`div`,{className:(0,n.cn)(`flex min-w-0 flex-col gap-2`,v&&!t&&`flex-1`),children:[(0,i.jsxs)(Ue,{children:[u?(0,i.jsx)($n,{progress:u,designingLabel:Y.designingPlanLabel,extendLabel:pe,waitingLabel:Y.connectionWaiting,stalledLabel:Y.connectionStalledLabel,offlineLabel:Y.connectionOfflineLabel}):null,l?(0,i.jsx)(er,{progress:l,onOpenBuiltApp:oe,openBuiltAppLabel:se,onPreviewDraftApp:z,previewDraftLabel:B,waitingLabel:Y.connectionWaiting,stalledLabel:Y.connectionStalledLabel,offlineLabel:Y.connectionOfflineLabel}):null,!t&&G===`debug`&&o?(0,i.jsxs)(gn,{isStreaming:!!e.streaming&&!e.content,className:`mb-2`,children:[(0,i.jsx)(vn,{}),(0,i.jsx)(yn,{children:o})]}):null,!t&&G===`summary`&&p.length>0?(0,i.jsx)(tr,{groups:Fn(p),labels:Y}):null,!t&&m.length>0?m.map(lt):null,t?e.content?(0,i.jsx)(`div`,{className:`whitespace-pre-wrap break-words`,children:e.content}):null:f?(0,i.jsx)(Bn,{}):e.content?(0,i.jsx)(Qe,{children:e.content}):null,e.streaming&&!f?(0,i.jsx)(`span`,{"aria-hidden":!0,className:`ml-0.5 inline-block w-[2px] h-4 align-middle bg-current animate-pulse`}):null,!t&&(e.charts?.length??0)>0?(0,i.jsx)(`div`,{className:`mt-2 flex flex-col gap-3`,"data-testid":`chat-charts`,children:e.charts.map((e,t)=>(0,i.jsxs)(`div`,{className:`rounded-lg border bg-background p-3`,style:{width:`min(520px, 80vw)`},"data-testid":`chat-chart`,children:[e.title?(0,i.jsx)(`div`,{className:`mb-2 text-sm font-medium text-foreground`,children:e.title}):null,(0,i.jsx)(c.SchemaRenderer,{schema:{type:`chart`,chartType:e.chartType??`bar`,data:e.data,xAxisKey:e.xAxisKey,series:e.series}})]},t))}):null,!t&&s.length>0?(0,i.jsxs)(bn,{children:[(0,i.jsx)(xn,{count:s.length}),(0,i.jsx)(Sn,{children:s.map((e,t)=>(0,i.jsx)(Cn,{href:e.url,title:e.title??e.url},e.id??e.url??t))})]}):null,_&&e.timestamp?(0,i.jsx)(`div`,{className:`text-[10px] opacity-70 mt-1`,children:e.timestamp}):null]}),!t&&!f?(0,i.jsxs)(We,{className:`opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100`,children:[(0,i.jsx)(Ge,{label:J===e.id?Y.copied:Y.copy,tooltip:J===e.id?Y.copied:Y.copy,onClick:()=>ot(e),children:J===e.id?(0,i.jsx)(r.Check,{className:`size-3.5`}):(0,i.jsx)(r.Copy,{className:`size-3.5`})}),d?(0,i.jsx)(Ge,{label:Y.regenerate,tooltip:Y.regenerate,onClick:d,children:(0,i.jsx)(r.RefreshCw,{className:`size-3.5`})}):null,G===`debug`&&e.traceId?(0,i.jsx)(`a`,{href:`#trace/${e.traceId}`,"data-trace-id":e.traceId,className:`text-[10px] text-muted-foreground hover:text-foreground ml-1 underline`,title:Y.viewTrace,children:Y.trace}):null]}):null]})]})},e.id)}),h&&!a.some(e=>e.streaming)?(0,i.jsx)(zn,{showAvatar:v,assistantAvatarUrl:x,assistantAvatarFallback:S,waitingLabel:Y.connectionWaiting,stalledLabel:Y.connectionStalledLabel,offlineLabel:Y.connectionOfflineLabel}):null]}),(0,i.jsx)(Re,{})]}),g?Ne(g)&&!Me(g)?(0,i.jsx)(ir,{error:g,rateLimitedLabel:Y.sendFailedRateLimited,genericLabel:Y.sendFailedGeneric}):(0,i.jsx)(ar,{error:g,onReload:d,onUpgrade:f}):null,m?null:(0,i.jsxs)(`div`,{ref:rt,className:(0,n.cn)(`relative`,q&&`mx-auto w-full max-w-2xl px-4 pb-4 sm:px-0`),children:[F?(0,i.jsx)(`div`,{className:`absolute bottom-full left-0 right-0 z-10 px-3 pb-1`,children:F}):null,(0,i.jsxs)(yt,{accept:D,fileInputLabel:Y.uploadFiles,maxFileSize:O,onSubmit:tt,onError:e=>{console.warn(`[plugin-chatbot] prompt-input error`,e)},children:[E?(0,i.jsx)(bt,{children:(0,i.jsx)(_t,{children:e=>(0,i.jsx)(gt,{data:e})})}):null,(0,i.jsx)(xt,{placeholder:o,disabled:p||K===`streaming`,onChange:I?e=>I(e.currentTarget.value):void 0}),(0,i.jsxs)(Ct,{children:[(0,i.jsxs)(wt,{children:[E?(0,i.jsxs)(Et,{children:[(0,i.jsx)(Dt,{}),(0,i.jsx)(Ot,{children:(0,i.jsx)(vt,{})})]}):null,j&&j.length>1?(0,i.jsx)(`select`,{"aria-label":Y.model,value:M??j[0].id,onChange:e=>N?.(e.target.value),className:`h-7 rounded-md border bg-background px-2 text-xs text-muted-foreground hover:text-foreground focus:outline-none focus:ring-1 focus:ring-ring`,children:j.map(e=>(0,i.jsxs)(`option`,{value:e.id,children:[e.label??e.id,e.provider?` · ${e.provider}`:``]},e.id))}):null,(0,i.jsxs)(`span`,{className:`hidden items-center gap-1 text-[10px] text-muted-foreground sm:inline-flex`,"aria-hidden":`true`,children:[(0,i.jsx)(`kbd`,{className:`inline-flex h-4 items-center rounded border bg-muted px-1 font-mono text-[10px] leading-none`,children:`⌘`}),(0,i.jsx)(r.CornerDownLeft,{className:`h-3 w-3`}),(0,i.jsx)(`span`,{className:`opacity-70`,children:Y.sendHint})]})]}),(0,i.jsx)(At,{"aria-label":K===`streaming`?Y.stopResponse:Y.submit,status:K,disabled:p,onClick:K===`streaming`?u:void 0,type:K===`streaming`?`button`:`submit`})]})]})]})]})});Ln.displayName=`ChatbotEnhanced`;function Rn({isUser:e,url:t,fallback:a}){return(0,i.jsx)(`div`,{className:(0,n.cn)(`mt-0.5 flex size-7 shrink-0 items-center justify-center overflow-hidden rounded-full text-[11px] font-medium`,e?`bg-secondary text-secondary-foreground`:`bg-primary/10 text-primary`),"aria-hidden":`true`,children:t?(0,i.jsx)(`img`,{src:t,alt:``,className:`size-full object-cover`}):e?a?.trim()?.charAt(0)?.toUpperCase()||`U`:(0,i.jsx)(r.Bot,{className:`size-4`})})}function zn({showAvatar:e,assistantAvatarUrl:t,assistantAvatarFallback:r,waitingLabel:a,stalledLabel:o,offlineLabel:s}){return(0,i.jsx)(He,{from:`assistant`,"aria-live":`polite`,children:(0,i.jsxs)(`div`,{className:(0,n.cn)(`flex w-full gap-2.5`,e?`flex-row items-start`:`flex-col`),children:[e?(0,i.jsx)(Rn,{isUser:!1,url:t,fallback:r}):null,(0,i.jsx)(Ue,{className:`rounded-lg border bg-muted/30 px-3 py-2 text-muted-foreground`,children:(0,i.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[(0,i.jsx)(Bn,{}),(0,i.jsx)(Gn,{active:!0,pending:!0,activityKey:0,waitingLabel:a,stalledLabel:o,offlineLabel:s})]})})]})})}function Bn(){return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(`span`,{className:`sr-only`,children:`Assistant is responding`}),(0,i.jsxs)(`span`,{"aria-hidden":`true`,className:`inline-flex items-center gap-1`,children:[(0,i.jsx)(`span`,{className:`size-1.5 rounded-full bg-current animate-pulse`}),(0,i.jsx)(`span`,{className:`size-1.5 rounded-full bg-current animate-pulse`}),(0,i.jsx)(`span`,{className:`size-1.5 rounded-full bg-current animate-pulse`})]})]})}function Vn(e){let t=Math.floor(e/60),n=e%60;return`${t}:${String(n).padStart(2,`0`)}`}var Hn=6;function Un(e,n){let r=t.useRef(0),i=t.useRef(0),[a,o]=t.useState({elapsed:0,quiet:0});return t.useEffect(()=>{let e=Date.now();r.current=e,i.current=e},[]),t.useEffect(()=>{let e=Date.now();i.current=e,o({elapsed:Math.floor((e-r.current)/1e3),quiet:0})},[n]),t.useEffect(()=>{if(!e)return;let t=()=>{let e=Date.now();o({elapsed:Math.floor((e-r.current)/1e3),quiet:Math.floor((e-i.current)/1e3)})};t();let n=setInterval(t,1e3);return()=>clearInterval(n)},[e]),{elapsedSeconds:a.elapsed,quietSeconds:a.quiet,live:a.quiet<Hn}}function Wn(){let[e,n]=t.useState(()=>typeof navigator<`u`&&navigator.onLine===!1);return t.useEffect(()=>{if(typeof window>`u`)return;let e=()=>n(!1),t=()=>n(!0);return window.addEventListener(`online`,e),window.addEventListener(`offline`,t),()=>{window.removeEventListener(`online`,e),window.removeEventListener(`offline`,t)}},[]),e}function Gn({active:e,activityKey:t,pending:a=!1,waitingLabel:o,stalledLabel:s=`Still working…`,offlineLabel:c=`Connection lost — reconnecting…`}){let{elapsedSeconds:l,quietSeconds:u,live:d}=Un(e,t),f=Wn()?`offline`:d?a?`waiting`:`receiving`:`stalled`,p=Vn(l);return(0,i.jsxs)(`span`,{className:(0,n.cn)(`inline-flex items-center gap-1.5 text-xs tabular-nums`,f===`offline`?`text-red-600 font-medium`:f===`stalled`?`text-amber-600 font-medium`:`font-normal text-muted-foreground`),"aria-live":`polite`,"data-liveness-tier":f,title:f===`offline`?`${c} · ${p} elapsed`:f===`receiving`?`Receiving from server · ${p} elapsed`:f===`stalled`?`${s} (${u}s with no response) · ${p} elapsed`:`${o} · ${p} elapsed`,children:[f===`offline`?(0,i.jsx)(r.WifiOff,{className:`size-3 shrink-0`,"aria-hidden":!0}):(0,i.jsx)(`span`,{"aria-hidden":!0,className:(0,n.cn)(`size-1.5 shrink-0 rounded-full`,f===`receiving`?`bg-emerald-500 animate-pulse`:f===`stalled`?`bg-amber-500`:`bg-muted-foreground/50 animate-pulse`)}),(0,i.jsx)(r.Clock3,{className:`size-3 shrink-0`,"aria-hidden":!0}),(0,i.jsx)(`span`,{children:p}),f===`receiving`?null:(0,i.jsxs)(`span`,{children:[`· `,f===`offline`?c:f===`stalled`?s:o]})]})}var Kn=[`Mapping out the data you’ll track…`,`Shaping objects and their fields…`,`Connecting related records…`,`Setting up relationships and lookups…`,`Planning the screens and views…`,`Laying out forms and lists…`,`Adding sensible defaults and validations…`,`Sketching a dashboard to track it…`,`Double-checking the structure hangs together…`,`Pulling the plan together…`],qn=3500;function Jn(e,t,n=qn){if(t<=0)return-1;if(t===1)return 0;let r=Math.floor((Number.isFinite(e)&&e>0?e:0)/(n>0?n:qn));return Math.min(r,t-1)}function Yn({label:e,hints:a,offlineLabel:o}){let[s,c]=t.useState(0);t.useEffect(()=>{if(a.length<=1)return;let e=Date.now(),t=setInterval(()=>c(Date.now()-e),qn);return()=>clearInterval(t)},[a.length]);let l=Jn(s,a.length),u=l>=0?a[l]:void 0,d=a.length>1&&a.length<=12;return(0,i.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground`,"data-testid":`build-proposal-progress`,"aria-live":`polite`,children:[(0,i.jsx)(r.Sparkles,{className:`size-3 shrink-0 animate-pulse text-primary`,"aria-hidden":!0}),(0,i.jsx)(`span`,{className:`font-medium text-foreground/80`,children:e}),u?(0,i.jsx)(`span`,{className:`truncate animate-in fade-in duration-500`,children:u},u):null,d?(0,i.jsx)(`span`,{className:`hidden shrink-0 items-center gap-0.5 sm:inline-flex`,"data-testid":`build-proposal-progress-dots`,"aria-hidden":!0,children:a.map((e,t)=>(0,i.jsx)(`span`,{className:(0,n.cn)(`size-1 rounded-full transition-colors`,t<=l?`bg-primary/70`:`bg-muted-foreground/25`)},t))}):null,(0,i.jsx)(Xn,{offlineLabel:o})]})}function Xn({offlineLabel:e}){let[a,o]=t.useState(0),s=Wn();return t.useEffect(()=>{let e=Date.now(),t=setInterval(()=>o(Math.floor((Date.now()-e)/1e3)),1e3);return()=>clearInterval(t)},[]),(0,i.jsxs)(`span`,{className:(0,n.cn)(`inline-flex items-center gap-1 text-xs tabular-nums`,s?`text-red-600 font-medium`:`text-muted-foreground`),"aria-live":`polite`,"data-tool-running-timer":!0,children:[s?(0,i.jsx)(r.WifiOff,{className:`size-3 shrink-0`,"aria-hidden":!0}):(0,i.jsx)(r.Clock3,{className:`size-3 shrink-0`,"aria-hidden":!0}),(0,i.jsx)(`span`,{children:Vn(a)}),s?(0,i.jsxs)(`span`,{children:[`· `,e]}):null]})}var Zn=[`object`,`view`,`dashboard`,`app`,`seed`],Qn={object:`Objects`,view:`Views`,dashboard:`Dashboards`,app:`App`,seed:`Sample data`};function $n({progress:e,designingLabel:t=`Designing your app…`,extendLabel:n=`Adding to existing app`,waitingLabel:a=`Waiting for server…`,stalledLabel:o=`Still working…`,offlineLabel:s=`Connection lost — reconnecting…`}){let{phase:c,summary:l,appLabel:u,targetApp:d,objects:f,counts:p,seq:m}=e,h=c===`done`,g=m??`${c}:${f.length}`,_=h&&(l||u)||t,v=[];return p?.objects&&v.push(`${p.objects} object${p.objects===1?``:`s`}`),p?.views&&v.push(`${p.views} view${p.views===1?``:`s`}`),p?.dashboards&&v.push(`${p.dashboards} dashboard${p.dashboards===1?``:`s`}`),(0,i.jsxs)(`div`,{className:`rounded-lg border bg-muted/30 p-3 text-sm`,"data-testid":`blueprint-progress`,children:[(0,i.jsxs)(`div`,{className:`mb-2 flex items-center gap-2 font-medium`,children:[h?(0,i.jsx)(r.CheckCircle2,{className:`size-4 shrink-0 text-emerald-600`}):(0,i.jsx)(r.Loader2,{className:`size-4 shrink-0 animate-spin text-primary`}),(0,i.jsx)(`span`,{className:`min-w-0 truncate`,children:_}),d?(0,i.jsxs)(`span`,{className:`inline-flex shrink-0 items-center gap-1 rounded-md border border-blue-200 bg-blue-50 px-1.5 py-0.5 text-[10px] font-medium text-blue-700 dark:border-blue-900/50 dark:bg-blue-950/30 dark:text-blue-300`,"data-testid":`blueprint-progress-extend`,children:[`+ `,n,` 「`,d,`」`]}):null,h?null:(0,i.jsx)(`span`,{className:`ml-auto shrink-0`,children:(0,i.jsx)(Gn,{active:!0,activityKey:g,waitingLabel:a,stalledLabel:o,offlineLabel:s})})]}),!h&&(l||u)?(0,i.jsx)(`p`,{className:`mb-2 text-xs text-muted-foreground`,children:l||u}):null,f.length>0?(0,i.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,"data-testid":`blueprint-progress-objects`,children:f.map(e=>(0,i.jsxs)(`span`,{className:`inline-flex animate-in fade-in items-center gap-1 rounded-md border bg-background px-1.5 py-0.5 text-[11px] text-foreground/80 duration-500`,title:e.name,children:[(0,i.jsx)(r.Table2,{className:`size-3 text-foreground/40`}),e.label||e.name,e.fields?(0,i.jsxs)(`span`,{className:`text-foreground/40`,children:[`· `,e.fields]}):null]},e.name))}):null,v.length>0?(0,i.jsx)(`span`,{className:`mt-2 block text-[11px] text-muted-foreground`,children:v.join(` · `)}):null]})}function er({progress:e,onOpenBuiltApp:t,openBuiltAppLabel:a=`Open app`,onPreviewDraftApp:o,previewDraftLabel:s=`Preview`,waitingLabel:c=`Waiting for server…`,stalledLabel:l=`Still working…`,offlineLabel:u=`Connection lost — reconnecting…`}){let{phase:d,appLabel:f,items:p,done:m,total:h,seq:g}=e,_=d===`done`,v=g??`${d}:${m}:${p.length}`,y=p.find(e=>e.type===`app`),b=h>0?Math.min(100,Math.round(m/h*100)):_?100:6,x=new Map;for(let e of p){let t=x.get(e.type)??[];t.push(e.name.replace(/_sample$/,``)),x.set(e.type,t)}let S=[...Zn.filter(e=>x.has(e)),...[...x.keys()].filter(e=>!Zn.includes(e))];return(0,i.jsxs)(`div`,{className:`rounded-lg border bg-muted/30 p-3 text-sm`,"data-testid":`build-progress`,children:[(0,i.jsxs)(`div`,{className:`mb-2 flex items-center gap-2 font-medium`,children:[_?(0,i.jsx)(r.CheckCircle2,{className:`size-4 shrink-0 text-emerald-600`}):(0,i.jsx)(r.Loader2,{className:`size-4 shrink-0 animate-spin text-primary`}),(0,i.jsx)(`span`,{children:_?`Built ${f??`your app`}`:`Building ${f??`your app`}…`}),!_&&d===`data`?(0,i.jsx)(`span`,{className:`text-xs font-normal text-muted-foreground`,children:`adding sample data`}):null,_?null:(0,i.jsx)(`span`,{className:`ml-auto`,children:(0,i.jsx)(Gn,{active:!0,activityKey:v,waitingLabel:c,stalledLabel:l,offlineLabel:u})})]}),(0,i.jsx)(`div`,{className:`mb-2 h-1.5 w-full overflow-hidden rounded-full bg-muted`,children:(0,i.jsx)(`div`,{className:(0,n.cn)(`h-full rounded-full transition-all duration-500`,_?`bg-emerald-500`:`bg-primary`),style:{width:`${b}%`}})}),(0,i.jsx)(`ul`,{className:`space-y-1`,children:S.map(e=>{let t=x.get(e);return(0,i.jsxs)(`li`,{className:`flex items-start gap-2`,children:[(0,i.jsx)(r.CheckCircle2,{className:`mt-0.5 size-3.5 shrink-0 text-emerald-600`}),(0,i.jsxs)(`span`,{className:`min-w-0 text-muted-foreground`,children:[(0,i.jsx)(`span`,{className:`font-medium text-foreground`,children:Qn[e]??e}),` `,t.slice(0,6).join(`, `),t.length>6?` +${t.length-6} more`:``]})]},e)})}),_&&y&&(t||o)?(0,i.jsxs)(`div`,{className:`mt-3 flex items-center gap-2`,children:[t?(0,i.jsxs)(`button`,{type:`button`,onClick:()=>t(y.name),className:`inline-flex h-7 items-center gap-1.5 rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground hover:bg-primary/90`,"data-testid":`build-progress-open-app`,children:[a,(0,i.jsx)(r.ArrowRight,{className:`size-3.5`})]}):null,o?(0,i.jsxs)(`button`,{type:`button`,onClick:()=>o(y.name),className:`inline-flex h-7 items-center gap-1.5 rounded-md border px-3 text-xs font-medium hover:bg-muted`,"data-testid":`build-progress-preview-app`,children:[(0,i.jsx)(r.Eye,{className:`size-3.5`}),s]}):null]}):null]})}function tr({groups:e,labels:t}){return e.length===0?null:(0,i.jsx)(`div`,{className:`not-prose mb-2 border-l border-border/70 pl-3`,children:(0,i.jsx)(`div`,{className:`space-y-1`,children:e.map(e=>(0,i.jsxs)(`div`,{className:`flex min-h-6 items-center justify-between gap-3 text-xs`,children:[(0,i.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,i.jsx)(nr,{state:e.state}),(0,i.jsx)(`span`,{className:`truncate font-medium text-foreground`,children:e.title}),e.count>1?(0,i.jsxs)(`span`,{className:`shrink-0 text-[10px] text-muted-foreground`,children:[`x`,e.count]}):null]}),e.state===`running`?e.rawName===`propose_blueprint`?(0,i.jsx)(Yn,{label:t.designingPlanLabel,hints:t.designingPlanHints,offlineLabel:t.connectionOfflineLabel}):(0,i.jsx)(Xn,{offlineLabel:t.connectionOfflineLabel}):(0,i.jsx)(`span`,{className:(0,n.cn)(`shrink-0 text-[10px] font-medium`,e.state===`failed`?`text-destructive`:e.state===`completed`?`text-emerald-700 dark:text-emerald-400`:`text-muted-foreground`),children:rr(e.state,t)})]},e.key))})})}function nr({state:e}){return e===`failed`?(0,i.jsx)(r.XCircle,{className:`size-3.5 shrink-0 text-destructive`}):e===`completed`?(0,i.jsx)(r.CheckCircle2,{className:`size-3.5 shrink-0 text-emerald-600`}):(0,i.jsx)(r.Clock3,{className:`size-3.5 shrink-0 text-muted-foreground`})}function rr(e,t){switch(e){case`failed`:return t.toolFailed;case`awaiting`:return t.toolAwaitingApproval;case`running`:return t.toolRunning;case`completed`:return t.toolCompleted}}function ir({error:e,rateLimitedLabel:n,genericLabel:a}){let o=t.useMemo(()=>Y(e)?n:a,[e,n,a]);return(0,i.jsx)(`div`,{className:`border-t bg-background px-3 py-2 text-sm`,role:`alert`,"data-testid":`chat-send-error`,children:(0,i.jsx)(`div`,{className:`rounded-md border border-amber-300/40 bg-amber-50/60 px-3 py-2 text-foreground dark:bg-amber-950/20`,children:(0,i.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,i.jsx)(r.TriangleAlert,{className:`mt-0.5 h-4 w-4 shrink-0 text-amber-600`}),(0,i.jsx)(`div`,{className:`min-w-0 flex-1 break-words leading-snug`,children:o})]})})})}function ar({error:e,onReload:n,onUpgrade:a}){let o=t.useMemo(()=>Me(e),[e]),{summary:s,details:c}=t.useMemo(()=>Ae(e),[e]),[l,u]=t.useState(!1);if(o){let e=typeof navigator<`u`&&!!navigator.language?.toLowerCase().startsWith(`zh`),t=(e?o.message:o.messageEn??o.message)||(e?`AI 额度已用完。`:`You have reached your AI quota.`),n=o.topUp?e?`购买额度包`:`Buy a credit pack`:e?`升级方案`:`Upgrade plan`;return(0,i.jsx)(`div`,{className:`border-t bg-background px-3 py-2 text-sm`,role:`alert`,children:(0,i.jsx)(`div`,{className:`rounded-md border border-amber-300/40 bg-amber-50/60 px-3 py-2 text-foreground dark:bg-amber-950/20`,children:(0,i.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,i.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,i.jsx)(`div`,{className:`font-medium leading-snug text-foreground`,children:e?`需要升级`:`Upgrade needed`}),(0,i.jsx)(`div`,{className:`mt-0.5 break-words leading-snug text-muted-foreground`,children:t})]}),a?(0,i.jsx)(`button`,{type:`button`,onClick:a,className:`inline-flex h-7 shrink-0 items-center rounded-md border border-amber-400/50 bg-background px-2 text-xs font-medium text-amber-700 hover:bg-amber-100/60 dark:text-amber-300`,children:n}):null]})})})}return(0,i.jsx)(`div`,{className:`border-t bg-background px-3 py-2 text-sm`,role:`alert`,children:(0,i.jsxs)(`div`,{className:`rounded-md border border-destructive/20 bg-destructive/5 px-3 py-2 text-foreground`,children:[(0,i.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,i.jsx)(r.AlertCircle,{className:`mt-0.5 h-4 w-4 shrink-0 text-destructive`}),(0,i.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,i.jsx)(`div`,{className:`font-medium leading-snug text-destructive`,children:`Response failed`}),(0,i.jsx)(`div`,{className:`mt-0.5 break-words leading-snug text-muted-foreground`,children:s||`Something went wrong. Please try again.`})]}),(0,i.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[c?(0,i.jsx)(`button`,{type:`button`,onClick:()=>u(e=>!e),className:`inline-flex h-7 items-center rounded-md px-2 text-xs font-medium text-muted-foreground hover:bg-destructive/10 hover:text-foreground`,"aria-expanded":l,children:l?`Hide`:`Details`}):null,n?(0,i.jsxs)(`button`,{type:`button`,onClick:n,className:`inline-flex h-7 items-center rounded-md border border-destructive/30 bg-background px-2 text-xs font-medium text-destructive hover:bg-destructive/10`,children:[(0,i.jsx)(r.RefreshCw,{className:`mr-1 h-3 w-3`}),`Retry`]}):null]})]}),l&&c?(0,i.jsx)(`pre`,{className:`mt-2 max-h-28 overflow-auto whitespace-pre-wrap break-words rounded border bg-background px-2 py-1 font-mono text-[11px] leading-snug text-muted-foreground`,children:c}):null]})})}function or({output:e,errorText:t}){return t?(0,i.jsx)(un,{output:void 0,errorText:t}):e==null||e===``?null:typeof e==`string`&&!En(e)?(0,i.jsxs)(`div`,{className:`space-y-2 p-4`,children:[(0,i.jsx)(`h4`,{className:`font-medium text-muted-foreground text-xs uppercase tracking-wide`,children:`Result`}),(0,i.jsx)(`div`,{className:`overflow-x-auto rounded-md bg-muted/40 px-3 py-2 text-sm text-foreground`,children:(0,i.jsx)(Qe,{children:e})})]}):(0,i.jsx)(un,{output:e,errorText:void 0})}function sr({floatingConfig:e,headerExtra:n,headerActions:r,...a}){let{position:o=`bottom-right`,defaultOpen:c=!1,panelWidth:l=400,panelHeight:u=520,title:d=`Chat`,triggerSize:f=56}=e??{},[p,m]=t.useState(null);t.useEffect(()=>{let e=document.getElementById(`floating-chatbot-portal`);return e||(e=document.createElement(`div`),e.id=`floating-chatbot-portal`,document.body.appendChild(e)),m(e),()=>{e&&e.parentNode&&!e.hasChildNodes()&&e.parentNode.removeChild(e)}},[]);let h=(0,i.jsxs)(be,{defaultOpen:c,children:[(0,i.jsx)(we,{position:o,size:f}),(0,i.jsx)(q,{title:d,position:o,width:l,height:u,headerExtra:n,headerActions:r,children:(0,i.jsx)(Ln,{...a,maxHeight:`100%`,className:`h-full border-0 rounded-none`})})]});return p?s.createPortal(h,p):h}_.ComponentRegistry.register(`chatbot`,({schema:e,className:t,...n})=>{let{messages:r,isLoading:a,sendMessage:o}=B({api:e.api,initialMessages:e.messages,conversationId:e.conversationId,systemPrompt:e.systemPrompt,model:e.model,streamingEnabled:e.streamingEnabled,headers:e.headers,body:e.requestBody,maxToolRoundtrips:e.maxToolRoundtrips,onError:e.onError,showTimestamp:e.showTimestamp,autoResponse:e.autoResponse,autoResponseText:e.autoResponseText,autoResponseDelay:e.autoResponseDelay,onSend:e.onSend});return(0,i.jsx)(Or,{messages:r,placeholder:e.placeholder,onSendMessage:e=>{o(e)},disabled:e.disabled||a,showTimestamp:e.showTimestamp,userAvatarUrl:e.userAvatarUrl,userAvatarFallback:e.userAvatarFallback,assistantAvatarUrl:e.assistantAvatarUrl,assistantAvatarFallback:e.assistantAvatarFallback,maxHeight:e.maxHeight,className:t,...n})},{namespace:`plugin-chatbot`,label:`Chatbot`,inputs:[{name:`messages`,type:`array`,label:`Initial Messages`,description:`Array of message objects with id, role, content, and optional timestamp`},{name:`placeholder`,type:`string`,label:`Input Placeholder`,defaultValue:`Type your message...`},{name:`showTimestamp`,type:`boolean`,label:`Show Timestamps`,defaultValue:!1},{name:`disabled`,type:`boolean`,label:`Disabled`,defaultValue:!1},{name:`userAvatarUrl`,type:`string`,label:`User Avatar URL`,description:`URL of the user avatar image`},{name:`userAvatarFallback`,type:`string`,label:`User Avatar Fallback`,defaultValue:`You`,description:`Fallback text shown when user avatar image is not available`},{name:`assistantAvatarUrl`,type:`string`,label:`Assistant Avatar URL`,description:`URL of the assistant avatar image`},{name:`assistantAvatarFallback`,type:`string`,label:`Assistant Avatar Fallback`,defaultValue:`AI`,description:`Fallback text shown when assistant avatar image is not available`},{name:`maxHeight`,type:`string`,label:`Max Height`,defaultValue:`500px`},{name:`api`,type:`string`,label:`API Endpoint`,description:`Backend SSE endpoint (e.g., /api/v1/ai/chat). When set, enables streaming AI mode.`},{name:`conversationId`,type:`string`,label:`Conversation ID`,description:`Multi-turn conversation identifier`},{name:`systemPrompt`,type:`string`,label:`System Prompt`,description:`System prompt to configure assistant behavior`},{name:`model`,type:`string`,label:`AI Model`,description:`AI model identifier (e.g., gpt-4o)`},{name:`streamingEnabled`,type:`boolean`,label:`Enable Streaming`,defaultValue:!0},{name:`autoResponse`,type:`boolean`,label:`Enable Auto Response (Demo)`,defaultValue:!1,description:`Automatically send a response after user message (for demo purposes, ignored when API is set)`},{name:`autoResponseText`,type:`string`,label:`Auto Response Text`,defaultValue:`Thank you for your message!`},{name:`autoResponseDelay`,type:`number`,label:`Auto Response Delay (ms)`,defaultValue:1e3},{name:`className`,type:`string`,label:`CSS Class`}],defaultProps:{messages:[{id:`welcome`,role:`assistant`,content:`Hello! How can I help you today?`}],placeholder:`Type your message...`,showTimestamp:!1,disabled:!1,userAvatarFallback:`You`,assistantAvatarFallback:`AI`,maxHeight:`500px`,autoResponse:!0,autoResponseText:`Thank you for your message! This is an automated response.`,autoResponseDelay:1e3,className:`w-full max-w-2xl`}}),_.ComponentRegistry.register(`chatbot-enhanced`,({schema:e,className:t,...n})=>{let{messages:r,isLoading:a,error:o,sendMessage:s,stop:c,reload:l,clear:u,isApiMode:d}=B({api:e.api,initialMessages:e.messages,conversationId:e.conversationId,systemPrompt:e.systemPrompt,model:e.model,streamingEnabled:e.streamingEnabled,headers:e.headers,body:e.requestBody,maxToolRoundtrips:e.maxToolRoundtrips,onError:e.onError,showTimestamp:e.showTimestamp,autoResponse:e.autoResponse,autoResponseText:e.autoResponseText,autoResponseDelay:e.autoResponseDelay,onSend:e.onSend});return(0,i.jsx)(Ln,{messages:r,placeholder:e.placeholder,onSendMessage:(e,t)=>{s(e,t)},onClear:()=>{u(),e.onClear?.()},onStop:d&&a?c:void 0,onReload:d?l:void 0,disabled:e.disabled,isLoading:a,error:o,showTimestamp:e.showTimestamp,userAvatarUrl:e.userAvatarUrl,userAvatarFallback:e.userAvatarFallback,assistantAvatarUrl:e.assistantAvatarUrl,assistantAvatarFallback:e.assistantAvatarFallback,maxHeight:e.maxHeight,enableMarkdown:e.enableMarkdown??!0,enableFileUpload:e.enableFileUpload??!1,processVisibility:e.processVisibility,className:t,...n})},{namespace:`plugin-chatbot`,label:`Chatbot (Enhanced)`,inputs:[{name:`messages`,type:`array`,label:`Initial Messages`},{name:`placeholder`,type:`string`,label:`Input Placeholder`,defaultValue:`Type your message...`},{name:`showTimestamp`,type:`boolean`,label:`Show Timestamps`,defaultValue:!1},{name:`disabled`,type:`boolean`,label:`Disabled`,defaultValue:!1},{name:`enableMarkdown`,type:`boolean`,label:`Enable Markdown`,defaultValue:!0},{name:`enableFileUpload`,type:`boolean`,label:`Enable File Upload`,defaultValue:!1},{name:`processVisibility`,type:`enum`,label:`Agent Process Visibility`,defaultValue:`summary`},{name:`userAvatarUrl`,type:`string`,label:`User Avatar URL`},{name:`userAvatarFallback`,type:`string`,label:`User Avatar Fallback`,defaultValue:`You`},{name:`assistantAvatarUrl`,type:`string`,label:`Assistant Avatar URL`},{name:`assistantAvatarFallback`,type:`string`,label:`Assistant Avatar Fallback`,defaultValue:`AI`},{name:`maxHeight`,type:`string`,label:`Max Height`,defaultValue:`500px`},{name:`api`,type:`string`,label:`API Endpoint`,description:`Backend SSE endpoint for streaming AI mode`},{name:`conversationId`,type:`string`,label:`Conversation ID`},{name:`systemPrompt`,type:`string`,label:`System Prompt`},{name:`model`,type:`string`,label:`AI Model`},{name:`streamingEnabled`,type:`boolean`,label:`Enable Streaming`,defaultValue:!0},{name:`autoResponse`,type:`boolean`,label:`Enable Auto Response (Demo)`,defaultValue:!1},{name:`autoResponseText`,type:`string`,label:`Auto Response Text`,defaultValue:`Thank you for your message!`},{name:`autoResponseDelay`,type:`number`,label:`Auto Response Delay (ms)`,defaultValue:1e3},{name:`className`,type:`string`,label:`CSS Class`}],defaultProps:{messages:[{id:`welcome`,role:`assistant`,content:`Hello! How can I help you today?`}],placeholder:`Type your message...`,showTimestamp:!1,disabled:!1,enableMarkdown:!0,enableFileUpload:!1,userAvatarFallback:`You`,assistantAvatarFallback:`AI`,maxHeight:`500px`,autoResponse:!0,autoResponseText:`Thank you for your message! This is an automated response.`,autoResponseDelay:1e3,className:`w-full max-w-2xl`}}),_.ComponentRegistry.register(`chatbot-floating`,({schema:e,className:t,...n})=>{let{messages:r,isLoading:a,error:o,sendMessage:s,stop:c,reload:l,clear:u,isApiMode:d}=B({api:e.api,initialMessages:e.messages,conversationId:e.conversationId,systemPrompt:e.systemPrompt,model:e.model,streamingEnabled:e.streamingEnabled,headers:e.headers,body:e.requestBody,maxToolRoundtrips:e.maxToolRoundtrips,onError:e.onError,showTimestamp:e.showTimestamp,autoResponse:e.autoResponse,autoResponseText:e.autoResponseText,autoResponseDelay:e.autoResponseDelay,onSend:e.onSend});return(0,i.jsx)(sr,{floatingConfig:e.floatingConfig,messages:r,placeholder:e.placeholder,onSendMessage:(e,t)=>{s(e,t)},onClear:()=>{u(),e.onClear?.()},onStop:d&&a?c:void 0,onReload:d?l:void 0,disabled:e.disabled,isLoading:a,error:o,showTimestamp:e.showTimestamp,userAvatarUrl:e.userAvatarUrl,userAvatarFallback:e.userAvatarFallback,assistantAvatarUrl:e.assistantAvatarUrl,assistantAvatarFallback:e.assistantAvatarFallback,enableMarkdown:e.enableMarkdown??!0,enableFileUpload:e.enableFileUpload??!1,className:t,...n})},{namespace:`plugin-chatbot`,label:`Chatbot (Floating)`,inputs:[{name:`displayMode`,type:`string`,label:`Display Mode`,defaultValue:`floating`,description:`Set to "floating" for FAB widget`},{name:`floatingConfig.position`,type:`string`,label:`FAB Position`,defaultValue:`bottom-right`,description:`bottom-right or bottom-left`},{name:`floatingConfig.defaultOpen`,type:`boolean`,label:`Default Open`,defaultValue:!1},{name:`floatingConfig.panelWidth`,type:`number`,label:`Panel Width`,defaultValue:400},{name:`floatingConfig.panelHeight`,type:`number`,label:`Panel Height`,defaultValue:520},{name:`floatingConfig.title`,type:`string`,label:`Panel Title`,defaultValue:`Chat`},{name:`floatingConfig.triggerSize`,type:`number`,label:`Trigger Size`,defaultValue:56},{name:`messages`,type:`array`,label:`Initial Messages`},{name:`placeholder`,type:`string`,label:`Input Placeholder`,defaultValue:`Type your message...`},{name:`enableMarkdown`,type:`boolean`,label:`Enable Markdown`,defaultValue:!0},{name:`enableFileUpload`,type:`boolean`,label:`Enable File Upload`,defaultValue:!1},{name:`api`,type:`string`,label:`API Endpoint`,description:`Backend SSE endpoint for streaming AI mode`},{name:`conversationId`,type:`string`,label:`Conversation ID`},{name:`systemPrompt`,type:`string`,label:`System Prompt`},{name:`model`,type:`string`,label:`AI Model`},{name:`streamingEnabled`,type:`boolean`,label:`Enable Streaming`,defaultValue:!0},{name:`autoResponse`,type:`boolean`,label:`Enable Auto Response (Demo)`,defaultValue:!1},{name:`autoResponseText`,type:`string`,label:`Auto Response Text`,defaultValue:`Thank you for your message!`},{name:`autoResponseDelay`,type:`number`,label:`Auto Response Delay (ms)`,defaultValue:1e3},{name:`className`,type:`string`,label:`CSS Class`}],defaultProps:{displayMode:`floating`,floatingConfig:{position:`bottom-right`,defaultOpen:!1,panelWidth:400,panelHeight:520,title:`Chat`,triggerSize:56},messages:[{id:`welcome`,role:`assistant`,content:`Hello! How can I help you today?`}],placeholder:`Type your message...`,enableMarkdown:!0,enableFileUpload:!1,autoResponse:!0,autoResponseText:`Thank you for your message! This is an automated response.`,autoResponseDelay:1e3}});var cr=({size:e=16})=>(0,i.jsxs)(`svg`,{height:e,strokeLinejoin:`round`,style:{color:`currentcolor`},viewBox:`0 0 16 16`,width:e,children:[(0,i.jsx)(`title`,{children:`Loader`}),(0,i.jsxs)(`g`,{clipPath:`url(#clip0_2393_1490)`,children:[(0,i.jsx)(`path`,{d:`M8 0V4`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,i.jsx)(`path`,{d:`M8 16V12`,opacity:`0.5`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,i.jsx)(`path`,{d:`M3.29773 1.52783L5.64887 4.7639`,opacity:`0.9`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,i.jsx)(`path`,{d:`M12.7023 1.52783L10.3511 4.7639`,opacity:`0.1`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,i.jsx)(`path`,{d:`M12.7023 14.472L10.3511 11.236`,opacity:`0.4`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,i.jsx)(`path`,{d:`M3.29773 14.472L5.64887 11.236`,opacity:`0.6`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,i.jsx)(`path`,{d:`M15.6085 5.52783L11.8043 6.7639`,opacity:`0.2`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,i.jsx)(`path`,{d:`M0.391602 10.472L4.19583 9.23598`,opacity:`0.7`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,i.jsx)(`path`,{d:`M15.6085 10.4722L11.8043 9.2361`,opacity:`0.3`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,i.jsx)(`path`,{d:`M0.391602 5.52783L4.19583 6.7639`,opacity:`0.8`,stroke:`currentColor`,strokeWidth:`1.5`})]}),(0,i.jsx)(`defs`,{children:(0,i.jsx)(`clipPath`,{id:`clip0_2393_1490`,children:(0,i.jsx)(`rect`,{fill:`white`,height:`16`,width:`16`})})})]}),lr=({className:e,size:t=16,...r})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`inline-flex animate-spin items-center justify-center`,e),...r,children:(0,i.jsx)(cr,{size:t})}),ur=w({CodeBlock:()=>$,CodeBlockCopyButton:()=>rn,Conversation:()=>Fe,ConversationContent:()=>Ie,ConversationEmptyState:()=>Le,ConversationScrollButton:()=>Re,Loader:()=>lr,Message:()=>He,MessageAction:()=>Ge,MessageActions:()=>We,MessageAttachment:()=>$e,MessageAttachments:()=>et,MessageBranch:()=>qe,MessageBranchContent:()=>Je,MessageBranchNext:()=>Xe,MessageBranchPage:()=>Ze,MessageBranchPrevious:()=>Ye,MessageBranchSelector:()=>Z,MessageContent:()=>Ue,MessageResponse:()=>Qe,MessageToolbar:()=>tt,PromptInput:()=>yt,PromptInputActionAddAttachments:()=>vt,PromptInputActionMenu:()=>Et,PromptInputActionMenuContent:()=>Ot,PromptInputActionMenuItem:()=>kt,PromptInputActionMenuTrigger:()=>Dt,PromptInputAttachment:()=>gt,PromptInputAttachments:()=>_t,PromptInputBody:()=>bt,PromptInputButton:()=>Tt,PromptInputCommand:()=>Gt,PromptInputCommandEmpty:()=>Jt,PromptInputCommandGroup:()=>Yt,PromptInputCommandInput:()=>Kt,PromptInputCommandItem:()=>Xt,PromptInputCommandList:()=>qt,PromptInputCommandSeparator:()=>Zt,PromptInputFooter:()=>Ct,PromptInputHeader:()=>St,PromptInputHoverCard:()=>Lt,PromptInputHoverCardContent:()=>zt,PromptInputHoverCardTrigger:()=>Rt,PromptInputProvider:()=>mt,PromptInputSelect:()=>Mt,PromptInputSelectContent:()=>Pt,PromptInputSelectItem:()=>Ft,PromptInputSelectTrigger:()=>Nt,PromptInputSelectValue:()=>It,PromptInputSpeechButton:()=>jt,PromptInputSubmit:()=>At,PromptInputTab:()=>Vt,PromptInputTabBody:()=>Ut,PromptInputTabItem:()=>Wt,PromptInputTabLabel:()=>Ht,PromptInputTabsList:()=>Bt,PromptInputTextarea:()=>xt,PromptInputTools:()=>wt,Reasoning:()=>gn,ReasoningContent:()=>yn,ReasoningTrigger:()=>vn,Shimmer:()=>dn,Source:()=>Cn,Sources:()=>bn,SourcesContent:()=>Sn,SourcesTrigger:()=>xn,Suggestion:()=>$t,Suggestions:()=>Qt,Tool:()=>an,ToolContent:()=>cn,ToolHeader:()=>sn,ToolInput:()=>ln,ToolOutput:()=>un,highlightCode:()=>nn,usePromptInputAttachments:()=>Q,usePromptInputController:()=>ut,useProviderAttachments:()=>ft,useReasoning:()=>pn}),dr=`/api/v1/ai`;function fr(e,t,n){let r=e.replace(/\/$/,``),i=new URLSearchParams;if(n)for(let[e,t]of Object.entries(n))t==null||t===``||i.set(e,String(t));let a=i.toString();return`${r}${t}${a?`?${a}`:``}`}async function pr(e,t,n){let r=await fetch(e,{credentials:`include`,...t,headers:{Accept:`application/json`,"Content-Type":`application/json`,...n??{},...t.headers??{}}}),i=null;try{i=await r.json()}catch{}if(!r.ok){let e=i?.error?.message??i?.message??i?.error??`${r.status} ${r.statusText}`,t=Error(typeof e==`string`?e:JSON.stringify(e));throw t.status=r.status,t.body=i,t}return i}function mr(e={}){let{apiBase:n=dr,status:r=`pending`,conversationId:i,limit:a,headers:o,pollInterval:s=5e3,enabled:c=!0}=e,[l,u]=t.useState([]),[d,f]=t.useState(0),[p,m]=t.useState(!1),[h,g]=t.useState(void 0),_=t.useRef({apiBase:n,status:r,conversationId:i,limit:a,headers:o});_.current={apiBase:n,status:r,conversationId:i,limit:a,headers:o};let v=t.useCallback(async()=>{let{apiBase:e,status:t,conversationId:n,limit:r,headers:i}=_.current;m(!0),g(void 0);try{let a=await pr(fr(e,`/pending-actions`,{status:t&&t!==`all`?t:void 0,conversationId:n,limit:r}),{method:`GET`},i);u(Array.isArray(a.items)?a.items:[]),f(typeof a.total==`number`?a.total:a.items?.length??0)}catch(e){g(e instanceof Error?e:Error(String(e)))}finally{m(!1)}},[]),y=t.useCallback(async e=>{let{apiBase:t,headers:n}=_.current,r=fr(t,`/pending-actions/${encodeURIComponent(e)}/approve`);try{return await pr(r,{method:`POST`,body:`{}`},n)}finally{v()}},[v]),b=t.useCallback(async(e,t)=>{let{apiBase:n,headers:r}=_.current,i=fr(n,`/pending-actions/${encodeURIComponent(e)}/reject`);try{return await pr(i,{method:`POST`,body:JSON.stringify(t?{reason:t}:{})},r)}finally{v()}},[v]);return t.useEffect(()=>{if(!c||(v(),!s||s<=0))return;let e=setInterval(()=>{v()},s);return()=>clearInterval(e)},[c,s,v,n,r,i,a]),{items:l,total:d,isLoading:p,error:h,refresh:v,approve:y,reject:b}}var hr={pending:{variant:`secondary`,label:`Pending`},approved:{variant:`default`,label:`Approved`},executed:{variant:`default`,label:`Executed`},failed:{variant:`destructive`,label:`Failed`},rejected:{variant:`outline`,label:`Rejected`}};function gr({status:e}){let t=hr[e]??{variant:`outline`,label:e};return(0,i.jsx)(n.Badge,{variant:t.variant,children:t.label})}function _r(e){if(!e)return`—`;let t=Date.parse(e);if(Number.isNaN(t))return e;let n=Date.now()-t,r=Math.round(n/1e3);if(r<45)return`just now`;let i=Math.round(r/60);if(i<60)return`${i}m ago`;let a=Math.round(i/60);if(a<24)return`${a}h ago`;let o=Math.round(a/24);if(o<30)return`${o}d ago`;try{return new Date(e).toLocaleDateString()}catch{return e}}function vr(e){if(!e)return null;try{return JSON.parse(e)}catch{return e}}function yr({value:e,max:t=320}){let n=typeof e==`string`?e:JSON.stringify(e,null,2);return n==null||n===``?(0,i.jsx)(`span`,{className:`text-muted-foreground text-xs`,children:`—`}):(0,i.jsx)(`pre`,{className:`bg-muted/40 rounded text-xs p-2 overflow-auto whitespace-pre-wrap break-all`,style:{maxHeight:t},children:n})}function br(e){switch(e){case`pending`:return`pending`;case`all`:return`all`;case`decided`:return`all`}}function xr({apiBase:e,headers:a,pollInterval:o=5e3,conversationId:s,variant:c=`card`,title:l=`AI Approvals`,description:u=`Actions an AI agent proposed that need a human review before execution.`,className:d}){let[f,p]=t.useState(`pending`),[m,h]=t.useState(null),[g,_]=t.useState(null),[v,y]=t.useState(``),[b,x]=t.useState(null),[S,C]=t.useState(null),[w,T]=t.useState(null),{items:E,isLoading:D,error:O,refresh:k,approve:A,reject:j}=mr({apiBase:e,headers:a,pollInterval:o,conversationId:s,status:br(f)}),M=t.useMemo(()=>f===`decided`?E.filter(e=>e.status!==`pending`):E,[E,f]),N=t.useMemo(()=>m?E.find(e=>e.id===m)??null:null,[m,E]),P=t.useCallback(async e=>{x(e),C(null);try{let t=await A(e),n=t.status===`executed`;T({id:e,kind:`approve`,ok:n,message:n?`Executed`:t.error??`Action failed during execution`})}catch(t){let n=t instanceof Error?t.message:String(t);C(n),T({id:e,kind:`approve`,ok:!1,message:n})}finally{x(null)}},[A]),F=t.useCallback(async(e,t)=>{x(e),C(null);try{await j(e,t.trim()||void 0),T({id:e,kind:`reject`,ok:!0,message:`Rejected`}),_(null),y(``)}catch(t){let n=t instanceof Error?t.message:String(t);C(n),T({id:e,kind:`reject`,ok:!1,message:n})}finally{x(null)}},[j]),I=(0,i.jsxs)(`div`,{className:`space-y-3`,children:[(0,i.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,i.jsx)(n.Tabs,{value:f,onValueChange:e=>p(e),children:(0,i.jsxs)(n.TabsList,{children:[(0,i.jsx)(n.TabsTrigger,{value:`pending`,children:`Pending`}),(0,i.jsx)(n.TabsTrigger,{value:`decided`,children:`Decided`}),(0,i.jsx)(n.TabsTrigger,{value:`all`,children:`All`})]})}),(0,i.jsxs)(n.Button,{variant:`outline`,size:`sm`,onClick:()=>void k(),disabled:D,"data-testid":`ai-inbox-refresh`,children:[(0,i.jsx)(r.RefreshCw,{className:`h-3.5 w-3.5 mr-1.5 ${D?`animate-spin`:``}`}),`Refresh`]})]}),O?(0,i.jsxs)(n.Alert,{variant:`destructive`,children:[(0,i.jsx)(r.AlertCircle,{className:`h-4 w-4`}),(0,i.jsx)(n.AlertDescription,{children:O.message})]}):null,S?(0,i.jsxs)(n.Alert,{variant:`destructive`,children:[(0,i.jsx)(r.AlertCircle,{className:`h-4 w-4`}),(0,i.jsx)(n.AlertDescription,{children:S})]}):null,w&&!S?(0,i.jsxs)(n.Alert,{variant:w.ok?`default`:`destructive`,children:[w.ok?(0,i.jsx)(r.CheckCircle2,{className:`h-4 w-4`}):(0,i.jsx)(r.XCircle,{className:`h-4 w-4`}),(0,i.jsxs)(n.AlertDescription,{children:[w.kind===`approve`?`Approve`:`Reject`,` for`,` `,(0,i.jsxs)(`code`,{className:`text-xs`,children:[w.id.slice(0,8),`…`]}),`:`,` `,w.message??(w.ok?`OK`:`Failed`)]})]}):null,D&&M.length===0?(0,i.jsxs)(`div`,{className:`space-y-2`,children:[(0,i.jsx)(n.Skeleton,{className:`h-10 w-full`}),(0,i.jsx)(n.Skeleton,{className:`h-10 w-full`}),(0,i.jsx)(n.Skeleton,{className:`h-10 w-full`})]}):M.length===0?(0,i.jsx)(n.Empty,{children:(0,i.jsxs)(n.EmptyHeader,{children:[(0,i.jsx)(n.EmptyMedia,{children:(0,i.jsx)(r.Inbox,{className:`h-8 w-8 text-muted-foreground`})}),(0,i.jsx)(n.EmptyTitle,{children:`No actions waiting`}),(0,i.jsx)(n.EmptyDescription,{children:`When the AI proposes a sensitive action it will appear here for review.`})]})}):(0,i.jsx)(`div`,{className:`rounded-md border`,children:(0,i.jsxs)(n.Table,{children:[(0,i.jsx)(n.TableHeader,{children:(0,i.jsxs)(n.TableRow,{children:[(0,i.jsx)(n.TableHead,{className:`w-[140px]`,children:`Tool`}),(0,i.jsx)(n.TableHead,{className:`w-[140px]`,children:`Action`}),(0,i.jsx)(n.TableHead,{className:`w-[120px]`,children:`Object`}),(0,i.jsx)(n.TableHead,{className:`w-[110px]`,children:`Status`}),(0,i.jsx)(n.TableHead,{className:`w-[110px]`,children:`Proposed`}),(0,i.jsx)(n.TableHead,{className:`w-[260px] text-right`,children:`Decision`})]})}),(0,i.jsx)(n.TableBody,{children:M.map(e=>{let t=e.status===`pending`,a=b===e.id;return(0,i.jsxs)(n.TableRow,{children:[(0,i.jsx)(n.TableCell,{className:`font-mono text-xs`,children:e.tool_name}),(0,i.jsx)(n.TableCell,{className:`text-sm`,children:e.action_name}),(0,i.jsx)(n.TableCell,{className:`text-sm`,children:e.object_name}),(0,i.jsx)(n.TableCell,{children:(0,i.jsx)(gr,{status:e.status})}),(0,i.jsx)(n.TableCell,{className:`text-xs text-muted-foreground`,children:(0,i.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,i.jsx)(r.Clock,{className:`h-3 w-3`}),` `,_r(e.proposed_at)]})}),(0,i.jsx)(n.TableCell,{className:`text-right`,children:(0,i.jsxs)(`div`,{className:`inline-flex gap-1.5`,children:[(0,i.jsxs)(n.Button,{size:`sm`,variant:`ghost`,onClick:()=>h(e.id),"data-testid":`ai-inbox-view-${e.id}`,children:[(0,i.jsx)(r.Eye,{className:`h-3.5 w-3.5 mr-1`}),` View`]}),t?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)(n.Button,{size:`sm`,variant:`default`,disabled:a,onClick:()=>void P(e.id),"data-testid":`ai-inbox-approve-${e.id}`,children:[(0,i.jsx)(r.CheckCircle2,{className:`h-3.5 w-3.5 mr-1`}),a?`Working…`:`Approve`]}),(0,i.jsxs)(n.Button,{size:`sm`,variant:`destructive`,disabled:a,onClick:()=>{_(e.id),y(``)},"data-testid":`ai-inbox-reject-${e.id}`,children:[(0,i.jsx)(r.XCircle,{className:`h-3.5 w-3.5 mr-1`}),`Reject`]})]}):null]})})]},e.id)})})]})})]});return(0,i.jsxs)(i.Fragment,{children:[c===`card`?(0,i.jsxs)(n.Card,{className:d,children:[(0,i.jsxs)(n.CardHeader,{className:`pb-3`,children:[(0,i.jsxs)(n.CardTitle,{className:`flex items-center gap-2`,children:[(0,i.jsx)(r.Bot,{className:`h-4 w-4`}),` `,l]}),u?(0,i.jsx)(n.CardDescription,{children:u}):null]}),(0,i.jsx)(n.CardContent,{children:I})]}):(0,i.jsx)(`div`,{className:d,children:I}),(0,i.jsx)(n.Sheet,{open:!!m,onOpenChange:e=>{e||h(null)},children:(0,i.jsxs)(n.SheetContent,{className:`sm:max-w-[560px] overflow-y-auto`,children:[(0,i.jsxs)(n.SheetHeader,{children:[(0,i.jsxs)(n.SheetTitle,{className:`flex items-center gap-2`,children:[(0,i.jsx)(r.Bot,{className:`h-4 w-4`}),N?N.action_name:`Pending action`]}),(0,i.jsx)(n.SheetDescription,{children:N?(0,i.jsxs)(i.Fragment,{children:[`Tool `,(0,i.jsx)(`code`,{className:`text-xs`,children:N.tool_name}),` on`,` `,(0,i.jsx)(`code`,{className:`text-xs`,children:N.object_name})]}):`Loading…`})]}),N?(0,i.jsxs)(`div`,{className:`px-4 space-y-4 mt-4`,children:[(0,i.jsxs)(`div`,{className:`grid grid-cols-2 gap-3 text-sm`,children:[(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs text-muted-foreground`,children:`Status`}),(0,i.jsx)(`div`,{className:`mt-1`,children:(0,i.jsx)(gr,{status:N.status})})]}),(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs text-muted-foreground`,children:`Proposed`}),(0,i.jsx)(`div`,{className:`mt-1 text-xs`,children:_r(N.proposed_at)})]}),(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs text-muted-foreground`,children:`Proposed by`}),(0,i.jsx)(`div`,{className:`mt-1 text-xs font-mono break-all`,children:N.proposed_by??`—`})]}),(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs text-muted-foreground`,children:`Decided by`}),(0,i.jsx)(`div`,{className:`mt-1 text-xs font-mono break-all`,children:N.decided_by??`—`})]}),N.conversation_id?(0,i.jsxs)(`div`,{className:`col-span-2`,children:[(0,i.jsx)(n.Label,{className:`text-xs text-muted-foreground`,children:`Conversation`}),(0,i.jsx)(`div`,{className:`mt-1 text-xs font-mono break-all`,children:N.conversation_id})]}):null]}),(0,i.jsx)(n.Separator,{}),(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs`,children:`Tool input`}),(0,i.jsx)(`div`,{className:`mt-1.5`,children:(0,i.jsx)(yr,{value:vr(N.tool_input)})})]}),N.result?(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs`,children:`Result`}),(0,i.jsx)(`div`,{className:`mt-1.5`,children:(0,i.jsx)(yr,{value:vr(N.result)})})]}):null,N.error?(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs text-destructive`,children:`Error`}),(0,i.jsx)(`div`,{className:`mt-1.5`,children:(0,i.jsx)(yr,{value:N.error})})]}):null,N.rejection_reason?(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs`,children:`Rejection reason`}),(0,i.jsx)(`div`,{className:`mt-1.5 text-sm`,children:N.rejection_reason})]}):null,N.status===`pending`?(0,i.jsxs)(`div`,{className:`pt-2 flex gap-2`,children:[(0,i.jsxs)(n.Button,{size:`sm`,onClick:()=>void P(N.id),disabled:b===N.id,children:[(0,i.jsx)(r.CheckCircle2,{className:`h-3.5 w-3.5 mr-1`}),`Approve & Execute`]}),(0,i.jsxs)(n.Button,{size:`sm`,variant:`destructive`,onClick:()=>{_(N.id),y(``)},disabled:b===N.id,children:[(0,i.jsx)(r.XCircle,{className:`h-3.5 w-3.5 mr-1`}),`Reject`]})]}):null]}):null]})}),(0,i.jsx)(n.Sheet,{open:!!g,onOpenChange:e=>{e||(_(null),y(``))},children:(0,i.jsxs)(n.SheetContent,{side:`bottom`,className:`max-h-[40vh]`,children:[(0,i.jsxs)(n.SheetHeader,{children:[(0,i.jsx)(n.SheetTitle,{children:`Reject this action?`}),(0,i.jsx)(n.SheetDescription,{children:`The reason is shown back to the AI so it can adjust its next response.`})]}),(0,i.jsxs)(`div`,{className:`px-4 mt-3 space-y-3`,children:[(0,i.jsx)(n.Textarea,{value:v,onChange:e=>y(e.target.value),placeholder:`Optional reason (e.g. 'Wrong record id — please confirm with the user first.')`,rows:4,"data-testid":`ai-inbox-reject-reason`}),(0,i.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,i.jsx)(n.Button,{variant:`outline`,size:`sm`,onClick:()=>{_(null),y(``)},children:`Cancel`}),(0,i.jsxs)(n.Button,{variant:`destructive`,size:`sm`,onClick:()=>g&&void F(g,v),disabled:!g||b===g,"data-testid":`ai-inbox-reject-confirm`,children:[(0,i.jsx)(r.XCircle,{className:`h-3.5 w-3.5 mr-1`}),`Reject`]})]})]})]})})]})}function Sr(e){return!e||e.length===0?`/api/v1/ai`:e.endsWith(`/`)?e.slice(0,-1):e}function Cr(e,t){let n={...e??{}};return t&&(n[`Content-Type`]=`application/json`),n}async function wr(e){let t=await e.text();if(!t)return null;try{return JSON.parse(t)}catch{return{raw:t}}}function Tr(e){let{messages:n,apiBase:r,headers:i,onDecided:a,continueConversation:o}=e,s=Sr(r),c=t.useMemo(()=>{let e=new Map;for(let t of n){let n=t.toolInvocations??[];for(let t of n)t.pendingActionId&&t.toolCallId&&e.set(t.toolCallId,{pendingActionId:t.pendingActionId,toolName:t.toolName})}return e},[n]),[l,u]=t.useState({}),d=t.useRef(0),[f,p]=t.useState(!1),m=t.useCallback((e,t)=>{u(n=>{if(!t){if(!(e in n))return n;let{[e]:t,...r}=n;return r}return{...n,[e]:t}})},[]);return{decisions:l,decide:t.useCallback(async(e,t,n)=>{let r=c.get(e);if(!r){m(e,{state:`error`,message:`No pending-action id found for this tool call. The tool result may not be a HITL proposal.`});return}let{pendingActionId:l,toolName:u}=r;m(e,{state:`pending`,message:t?`Approving…`:`Rejecting…`}),d.current+=1,p(!0);try{let r=`${s}/pending-actions/${encodeURIComponent(l)}/${t?`approve`:`reject`}`,c=t?`{}`:JSON.stringify({reason:n??``}),d=await fetch(r,{method:`POST`,credentials:`include`,headers:Cr(i,!0),body:c}),f=await wr(d)??{};if(!d.ok){let t=typeof f.error==`string`?f.error:`Approval failed: HTTP ${d.status}`;m(e,{state:`error`,message:t}),a?.(e,{id:l,status:`failed`,error:t});return}let p=f.status??(t?`executed`:`rejected`),h=!1;if(p===`executed`?(m(e,{state:`success`,message:`Approved — action executed.`}),h=!0):p===`rejected`?(m(e,{state:`success`,message:n?`Rejected: ${n}`:`Rejected.`}),h=!0):p===`failed`?m(e,{state:`error`,message:f.error??`Action approved but execution failed.`}):(m(e,{state:`success`,message:`Status: ${p}`}),h=!0),a?.(e,f),h&&o){let r=Er({approved:t,status:p,toolName:u,pendingActionId:l,outcome:f,reason:n});r&&o(r,{toolCallId:e,pendingActionId:l,decision:t?`approved`:`rejected`,outcome:f,toolName:u})}}catch(t){m(e,{state:`error`,message:t instanceof Error?t.message:String(t)})}finally{--d.current,d.current<=0&&(d.current=0,p(!1))}},[s,i,c,a,o,m]),isDeciding:f}}function Er(e){let{approved:t,status:n,toolName:r,pendingActionId:i,outcome:a,reason:o}=e,s=`[HITL ${i}]`;if(t&&n===`executed`){let e=a.result;return`${s} The operator approved the \`${r}\` call. It executed successfully with result: ${e==null?`(no payload)`:typeof e==`string`?e:Dr(JSON.stringify(e),800)}. Acknowledge the outcome concisely and continue the user's task.`}if(!t&&n===`rejected`)return`${s} The operator rejected the \`${r}\` call.${o&&o.trim().length>0?` Reason: ${o}.`:``} Acknowledge the rejection and ask whether to try a different approach.`;if(n===`failed`){let e=a.error;return`${s} The \`${r}\` call was approved but execution failed: ${typeof e==`string`?e:Dr(JSON.stringify(e??{}),400)}. Apologize concisely and offer alternatives.`}}function Dr(e,t){return e.length<=t?e:`${e.slice(0,t-1)}…`}var Or=t.forwardRef(({className:e,messages:a=[],placeholder:o=`Type your message...`,onSendMessage:s,disabled:c=!1,showTimestamp:l=!1,userAvatarUrl:u,userAvatarFallback:d=`You`,assistantAvatarUrl:f,assistantAvatarFallback:p=`AI`,maxHeight:m=`500px`,...h},g)=>{let[_,v]=t.useState(``),y=t.useRef(null),b=t.useRef(null);t.useEffect(()=>{if(y.current){let e=y.current.querySelector(`[data-radix-scroll-area-viewport]`);e&&(e.scrollTop=e.scrollHeight)}},[a]);let x=()=>{_.trim()&&s&&(s(_.trim()),v(``),b.current?.focus())},S=e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),x())};return(0,i.jsxs)(`div`,{ref:g,className:(0,n.cn)(`flex flex-col border rounded-lg bg-background overflow-hidden`,e),style:{maxHeight:m},...h,children:[(0,i.jsx)(n.ScrollArea,{ref:y,className:`flex-1 p-4`,children:(0,i.jsx)(`div`,{className:`space-y-4`,children:a.length===0?(0,i.jsx)(`div`,{className:`flex items-center justify-center h-32 text-muted-foreground text-sm`,children:`No messages yet. Start a conversation!`}):a.map(e=>(0,i.jsx)(kr,{message:e,showTimestamp:l,userAvatarUrl:u,userAvatarFallback:d,assistantAvatarUrl:f,assistantAvatarFallback:p},e.id))})}),(0,i.jsx)(`div`,{className:`border-t p-4`,children:(0,i.jsxs)(`div`,{className:`flex gap-2`,children:[(0,i.jsx)(n.Input,{ref:b,value:_,onChange:e=>v(e.target.value),onKeyDown:S,placeholder:o,disabled:c,className:`flex-1`}),(0,i.jsx)(n.Button,{onClick:x,disabled:c||!_.trim(),size:`icon`,children:(0,i.jsx)(r.Send,{className:`h-4 w-4`})})]})})]})});Or.displayName=`Chatbot`;var kr=({message:e,showTimestamp:t,userAvatarUrl:r,userAvatarFallback:a,assistantAvatarUrl:o,assistantAvatarFallback:s})=>{let c=e.role===`user`;if(e.role===`system`)return(0,i.jsx)(`div`,{className:`flex justify-center`,children:(0,i.jsx)(`div`,{className:`text-xs text-muted-foreground bg-muted px-3 py-1 rounded-full`,children:e.content})});let l=c?e.avatar||r:e.avatar||o,u=c?e.avatarFallback||a:e.avatarFallback||s;return(0,i.jsxs)(`div`,{className:(0,n.cn)(`flex gap-3`,c?`flex-row-reverse`:`flex-row`),children:[(0,i.jsxs)(n.Avatar,{className:`h-8 w-8`,children:[(0,i.jsx)(n.AvatarImage,{src:l}),(0,i.jsx)(n.AvatarFallback,{className:`text-xs`,children:u})]}),(0,i.jsxs)(`div`,{className:(0,n.cn)(`flex flex-col gap-1`,c?`items-end`:`items-start`),children:[(0,i.jsx)(`div`,{className:(0,n.cn)(`rounded-lg px-4 py-2 max-w-[70%] break-words`,c?`bg-primary text-primary-foreground`:`bg-muted`),children:(0,i.jsx)(`p`,{className:`text-sm whitespace-pre-wrap`,children:e.content})}),t&&e.timestamp&&(0,i.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.timestamp})]})]})},Ar=t.forwardRef(({className:e,avatarSrc:t,avatarFallback:r=`AI`,...a},o)=>(0,i.jsxs)(`div`,{ref:o,className:(0,n.cn)(`flex gap-3`,e),...a,children:[(0,i.jsxs)(n.Avatar,{className:`h-8 w-8`,children:[(0,i.jsx)(n.AvatarImage,{src:t}),(0,i.jsx)(n.AvatarFallback,{className:`text-xs`,children:r})]}),(0,i.jsx)(`div`,{className:`flex items-center bg-muted rounded-lg px-4 py-2`,children:(0,i.jsxs)(`div`,{className:`flex gap-1`,children:[(0,i.jsx)(`span`,{className:`w-2 h-2 bg-muted-foreground rounded-full animate-bounce [animation-delay:-0.3s]`}),(0,i.jsx)(`span`,{className:`w-2 h-2 bg-muted-foreground rounded-full animate-bounce [animation-delay:-0.15s]`}),(0,i.jsx)(`span`,{className:`w-2 h-2 bg-muted-foreground rounded-full animate-bounce`})]})})]}));Ar.displayName=`TypingIndicator`,e.AGENT_ALIAS_GROUPS=V,Object.defineProperty(e,"AIElements",{enumerable:!0,get:function(){return ur}}),e.AiPendingActionsInbox=xr,e.Chatbot=Or,e.ChatbotEnhanced=Ln,e.FloatingChatbot=sr,e.FloatingChatbotPanel=q,e.FloatingChatbotProvider=be,e.FloatingChatbotTrigger=we,e.PLATFORM_DEFAULT_AGENT=pe,e.TypingIndicator=Ar,e.agentAliasGroup=H,e.agentRouteName=ce,e.buildProgressFromDraftReview=L,e.detectDraftResult=F,e.detectProposedPlan=N,e.humanizeToolName=Oe,e.isAskAgent=fe,e.isBuildAgent=de,e.isBuiltinAgentName=ue,e.publishHealthFromResponse=wn,e.resolveAgentParam=le,e.resolveDefaultAgentName=me,e.summarizeChatError=Ae,e.uiMessageToChatMessage=ae,e.uiMessagesToChatMessages=R,e.unwrapToolResult=ke,e.useAgents=ge,e.useAiModels=ve,e.useFloatingChatbot=xe,e.useHitlInChat=Tr,e.useObjectChat=B,e.usePendingActions=mr});
|