@object-ui/plugin-chatbot 17.7.0 → 18.0.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 +499 -0
- package/README.md +55 -24
- package/dist/AiPendingActionsInbox.d.ts.map +1 -1
- package/dist/ChatbotEnhanced.d.ts +143 -54
- package/dist/ChatbotEnhanced.d.ts.map +1 -1
- package/dist/chatMessageAdapter.d.ts +2 -2
- package/dist/chatMessageAdapter.d.ts.map +1 -1
- package/dist/elements/conversation.d.ts +1 -1
- package/dist/elements/conversation.d.ts.map +1 -1
- package/dist/elements/message.d.ts +1 -1
- package/dist/elements/message.d.ts.map +1 -1
- package/dist/elements/prompt-input.d.ts +9 -1
- package/dist/elements/prompt-input.d.ts.map +1 -1
- package/dist/index.d.ts +17 -28
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2620 -1580
- package/dist/index.umd.cjs +2 -2
- package/dist/mapMessages.d.ts +215 -3
- package/dist/mapMessages.d.ts.map +1 -1
- package/dist/recordLink.d.ts +34 -0
- package/dist/recordLink.d.ts.map +1 -0
- package/dist/useAgents.d.ts +5 -0
- package/dist/useAgents.d.ts.map +1 -1
- package/dist/useAiModels.d.ts +2 -0
- package/dist/useAiModels.d.ts.map +1 -1
- package/dist/useHitlInChat.d.ts +1 -1
- package/dist/useHitlInChat.d.ts.map +1 -1
- package/dist/usePendingActions.d.ts +5 -0
- package/dist/usePendingActions.d.ts.map +1 -1
- package/package.json +7 -7
package/dist/index.umd.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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("@object-ui/i18n"),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`,`@object-ui/i18n`,`@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._object_ui_i18n,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,_,v){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var y=Object.create,b=Object.defineProperty,x=Object.getOwnPropertyDescriptor,S=Object.getOwnPropertyNames,C=Object.getPrototypeOf,w=Object.prototype.hasOwnProperty,T=(e,t)=>{let n={};for(var r in e)b(n,r,{get:e[r],enumerable:!0});return t||b(n,Symbol.toStringTag,{value:`Module`}),n},E=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=S(t),a=0,o=i.length,s;a<o;a++)s=i[a],!w.call(e,s)&&s!==n&&b(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=x(t,s))||r.enumerable});return e},D=(e,t,n)=>(n=e==null?{}:y(C(e)),E(t||!e||!e.__esModule||!w.call(e,`default`)?b(n,`default`,{value:e,enumerable:!0}):n,e));t=D(t,1),c=D(c,1);function O(e=`msg`){return typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`${e}-${Date.now()}-${Math.random().toString(36).slice(2)}`}var k={"input-streaming":!0,"input-available":!0,"approval-requested":!0,"approval-responded":!0,"output-available":!0,"output-error":!0,"output-denied":!0};function A(e){return e!==void 0&&e in k}function j(e,t){return typeof e.content==`string`?e.content:t.filter(e=>e.type===`text`).map(e=>e.text??``).join(``)}function M(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 N(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,i;for(let e of n){let n=t(e);if(n){if(typeof n.status==`string`)return n;n.type===`text`&&`value`in n?i??=n:r??=n}}return r??i}function
|
|
2
|
+
`).trim();return t.length>0?t:void 0}function N(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,i;for(let e of n){let n=t(e);if(n){if(typeof n.status==`string`)return n;n.type===`text`&&`value`in n?i??=n:r??=n}}return r??i}function P(e){let t=N(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 F(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.trim().length>0):[]}function I(e){return(Array.isArray(e)?e:[]).flatMap(e=>{let t=e;return typeof t?.name!=`string`||!t.name?[]:[{name:t.name,...typeof t.label==`string`&&t.label?{label:t.label}:{}}]})}function L(e){let t=N(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;if(typeof t?.name!=`string`||!t.name)return[];let n=I(t.fields);return[{name:t.name,...typeof t.label==`string`&&t.label?{label:t.label}:{},fieldCount:Array.isArray(t.fields)?t.fields.length:0,...n.length?{fields:n}:{}}]});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=F(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,p=r.app&&typeof r.app==`object`?r.app:void 0,m=typeof p?.label==`string`&&p.label?p.label:void 0,h=I(r.views),g=ee(t.planCard),_=t.viewIntents,v=Array.isArray(_)?B(_):[];return{...d?{summary:d}:{},...m?{appLabel:m}:{},objects:i,...h.length?{views:h}:{},counts:s,questions:c.length?c:F(r.questions),...u.length?{questionChoices:u}:{},assumptions:g?g.assumptions:F(r.assumptions),...typeof f==`string`&&f?{targetApp:f}:{},...g?{planCard:g}:{},...v.length?{viewIntents:v}:{}}}var R=e=>typeof e==`string`&&e.length>0,z=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:void 0;function B(e){return e.flatMap(e=>{let t=z(e);return!t||!R(t.view)||!R(t.object)||!R(t.line)?[]:[{view:t.view,object:t.object,...R(t.label)?{label:t.label}:{},line:t.line}]})}function ee(e){let t=z(e);if(!t||!Array.isArray(t.objects)||!Array.isArray(t.views)||!Array.isArray(t.assumptions))return;let n=t.objects.flatMap(e=>{let t=z(e);if(!t||!R(t.name)||!R(t.label)||!Array.isArray(t.fields))return[];let n=t.fields.flatMap(e=>{let t=z(e);if(!t||!R(t.name)||!R(t.label))return[];let n=z(t.format),r=z(t.lifecycle);return[{name:t.name,label:t.label,...n&&R(n.label)?{format:{label:n.label}}:{},...r&&R(r.label)?{lifecycle:{label:r.label}}:{},...t.suggested===!0?{suggested:!0}:{}}]}),r=z(t.nameField),i=z(r?.generated);return[{name:t.name,label:t.label,fields:n,...r&&R(r.name)&&R(r.label)?{nameField:{name:r.name,label:r.label,...i&&R(i.line)?{generated:{line:i.line}}:{}}}:{}}]}),r=z(t.sampleData);return{objects:n,views:B(t.views),assumptions:F(t.assumptions),...r&&R(r.line)?{sampleData:{line:r.line}}:{}}}var V=e=>e===`passed`||e===`failed`,te=e=>e===`object`||e===`view`||e===`sampleData`,H=e=>typeof e==`number`&&Number.isInteger(e)&&e>=0;function ne(e){let t=z(N(e)?.checklist);if(!t||!V(t.status)||!H(t.passed)||!H(t.total)||!Array.isArray(t.lines))return;let n=t.lines.flatMap(e=>{let t=z(e);return!t||!te(t.kind)||!V(t.status)||!R(t.line)?[]:[{kind:t.kind,status:t.status,line:t.line}]}),r=z(t.app);return{status:t.status,passed:t.passed,total:t.total,lines:n,...r&&R(r.name)?{app:{name:r.name,...R(r.label)?{label:r.label}:{}}}:{},...R(t.packageId)?{packageId:t.packageId}:{}}}function re(e){let t=N(e);if(!t||t.status!==`build_handoff`)return;let n=typeof t.prompt==`string`?t.prompt.trim():``;if(!n)return;let r=t.packageId,i=typeof r==`string`&&r.trim().length>0?r.trim():void 0;return{prompt:n,...i?{packageId:i}:{}}}function ie(e){let t=N(e);if(!t||t.status!==`record_handoff`)return;let n=e=>{let t=typeof e==`string`?e.trim():``;return t.length>0?t:void 0},r=t,i=n(r.objectName),a=n(r.recordId);if(i&&a)return{objectName:i,recordId:a,...n(r.label)?{label:n(r.label)}:{},...n(r.reason)?{reason:n(r.reason)}:{}}}function U(e){let t=N(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;let a=ae(t.posture),o=t.primaryAction===`save_draft`||t.primaryAction===`confirm`?t.primaryAction:void 0;return{...n(t.summary)?{summary:n(t.summary)}:{},changes:i,...a?{posture:a}:{},...o?{primaryAction:o}:{}}}function ae(e){let t=z(e);if(t&&(t.mode===`draft`||t.mode===`publish`)&&H(t.liveRecords))return{mode:t.mode,liveRecords:t.liveRecords,...t.platformPackage===!0?{platformPackage:!0}:{},...H(t.buildTurnRows)?{buildTurnRows:t.buildTurnRows}:{}}}function W(e){let t=z(e);if(!t||!H(t.pending)||!H(t.others))return;let n=(Array.isArray(t.items)?t.items:[]).flatMap(e=>{let t=z(e);return t&&R(t.type)&&R(t.name)?[{type:t.type,name:t.name}]:[]});return{pending:t.pending,items:n,others:t.others}}function oe(e){if(!Array.isArray(e))return;let t=e.flatMap(e=>{let t=z(e);return t&&R(t.object)&&R(t.field)&&R(t.label)&&H(t.rows)?[{object:t.object,field:t.field,label:t.label,rows:t.rows}]:[]});return t.length>0?t:void 0}function se(e){let t=z(e);if(!t||!R(t.title))return;let n=Array.isArray(t.lines)?t.lines.filter(R):[];return{title:t.title,lines:n}}function ce(e){let t=[];if(Array.isArray(e.drafted)){for(let n of e.drafted)if(n&&typeof n==`object`){let{type:e,name:r}=n;typeof e==`string`&&typeof r==`string`&&t.push({type:e,name:r})}}else typeof e.type==`string`&&typeof e.name==`string`&&t.push({type:e.type,name:e.name});return t}function le(e,t){if(!e||!e.startsWith(`replay_`))return;let n=N(t);if(!n)return;if(n.status===`published`)return{kind:`published`};let r=n.error;if(typeof r==`string`&&r.trim()&&n.status===void 0)return{kind:`failed`,dispatchError:!0,error:r.trim().split(`
|
|
3
3
|
`)[0]};if(n.status!==`drafted`)return;let i=n.packageId,a=typeof i==`string`&&i?{packageId:i}:{};if(n.publishFailed===!0){let e=n.publishError,t=typeof e==`string`&&e.trim()?e.trim().split(`
|
|
4
|
-
`)[0]:void 0,r=n.publishOutcome;return{kind:`failed`,...typeof r==`string`&&r?{outcome:r}:{},...t?{error:t}:{},...a}}return{kind:`drafted`,...a}}function z(e){let t=N(e);if(!t)return;if(t.status===`published`)return{kind:`published`};if(t.status!==`drafted`)return;let n=t.packageId,r=typeof n==`string`&&n?{packageId:n}:{};return t.publishFailed===!0?{kind:`failed`,...r}:{kind:`drafted`,...r}}function B(e){let t=N(e);if(!t||t.kind===`edit`||t.status!==`drafted`&&t.status!==`published`)return;let n=t.packageId;if(typeof n!=`string`||!n)return;let r=t.drafted;return Array.isArray(r)&&r.some(e=>e&&typeof e==`object`&&e.type===`app`)?n:void 0}function ne(e){let t=N(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}:{},...t.kind===`edit`?{kind:`edit`}:{}}}function re(e){return e.replace(/[._-]+/g,` `).replace(/\s+/g,` `).trim().replace(/\b\w/g,e=>e.toUpperCase())}function ie(e){if(!e||!Array.isArray(e.items)||e.items.length===0||e.kind===`edit`)return;let t=e.items.find(e=>e.type===`app`);if(t)return{phase:`done`,appLabel:re(t.name),items:e.items,done:e.items.length,total:e.items.length}}function V(e){let{approval:t}=e;if(typeof t!=`object`||!t)return;let n=t,{id:r}=n;if(typeof r==`string`&&r.length!==0)return{id:r,approved:typeof n.approved==`boolean`?n.approved:void 0,reason:typeof n.reason==`string`?n.reason:void 0,isAutomatic:typeof n.isAutomatic==`boolean`?n.isAutomatic:void 0,signature:typeof n.signature==`string`?n.signature:void 0}}function ae(e,t={}){return e.filter(e=>e.type===`dynamic-tool`||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.toolCallId??e.id??`${e.type??`tool`}-${Math.random().toString(36).slice(2,8)}`,i=e.output??e.result,a=ee(i),o=te(r,i),s=o?void 0:ne(i),c=F(i),l=R(i),u=I(i),d=L(i),f=A(e.state)?e.state:void 0,p=(f===`input-available`||f===`input-streaming`)&&(i!==void 0||!t.liveTail)?`output-available`:f,m=a&&p!==`output-error`?`approval-requested`:p;return{toolCallId:r,toolName:n,args:e.input??e.args,result:i,errorText:e.errorText,state:m,approval:V(e),pendingActionId:a?.pendingActionId,draftReview:s,proposedPlan:c,proposedChanges:l,builderHandoff:u,recordHandoff:d,replayOutcome:o}})}function oe(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 se(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 ce(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 le(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 ue(e,t={}){let n=Array.isArray(e.parts)?e.parts:[],r=ae(n,{liveTail:t.streaming}),i=Array.isArray(e.toolInvocations)?e.toolInvocations:[],a=r.length>0?r:i,o=se(n)??a.map(e=>ie(e.draftReview)).find(e=>!!e);return{id:e.id??`msg-${Math.random().toString(36).slice(2,8)}`,role:e.role??`assistant`,content:j(e,n),reasoning:M(n),toolInvocations:a,sources:oe(n),buildProgress:o,blueprintProgress:ce(n),charts:le(n),streaming:t.streaming}}function de(e,t={}){if(!Array.isArray(e)||e.length===0)return[];let n=e.length-1;return e.map((e,r)=>ue(e,{streaming:!!t.isStreaming&&r===n&&e.role===`assistant`}))}function H(e){return typeof e==`string`?e:e instanceof Date?e.toISOString():void 0}function U(e){return e===`tool`?`assistant`:e}function fe(e){switch(e){case`partial-call`:return`input-streaming`;case`call`:return`input-available`;case`result`:return`output-available`;default:return e}}function pe(e){let{state:t,...n}=e;return{...n,state:fe(t)}}function W(e){let{role:t,timestamp:n,toolInvocations:r,...i}=e;return{...i,role:U(t),timestamp:H(n),toolInvocations:r?.map(pe)}}function G(e){return(e??[]).map(W)}var me=`objectui:ai-usage-refresh`;function he(){if(!(typeof window>`u`||typeof window.dispatchEvent!=`function`))try{window.dispatchEvent(new CustomEvent(me))}catch{}}async function ge(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 _e(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 ve(e,t){let n=e.context??{};return{...e,context:{...n,parentConversationId:t}}}function ye(e){return(e??[]).map((e,t)=>({id:e.id||`msg-${t}`,role:e.role||`user`,content:e.content||``,timestamp:H(e.timestamp),metadata:e.metadata,streaming:e.streaming,toolInvocations:e.toolInvocations}))}function be(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&(t.role===`user`||t.role===`assistant`||t.role===`system`)&&Array.isArray(t.parts)}function xe(e){if(!Array.isArray(e))throw TypeError(`useObjectChat: setMessages expects an array of chat messages, received ${typeof e}.`);let t=[];return e.forEach((e,n)=>{if(!be(e))throw TypeError(`useObjectChat: setMessages received a value at index ${n} that is not a chat message (it needs a string \`id\`, a 'user' | 'assistant' | 'system' \`role\` and a \`parts\` array). Nothing was written; the thread is unchanged.`);t.push(e)}),t}var Se=new Set;function Ce(e){e.pendingActionId||we(e.state??`approval`,e.toolName)}function we(e,t){let n=`${e}:${t}`;Se.has(n)||(Se.add(n),console.warn(`[@object-ui/plugin-chatbot] tool invocation \`${t}\` declares state \`${e}\` with no \`approval\` envelope. The chat runtime requires the envelope alongside that state, so the invocation is not representable as authored and its state was derived from the data instead. Fix it at the producer: carry \`approval.id\` (plus \`approved\` for \`approval-responded\` and \`output-denied\`) beside the state (objectui#8426).`))}function Te(e,t){let{toolCallId:n}=e,r=e.args;return e.errorText===void 0?e.result===void 0?{type:t,toolCallId:n,state:`input-available`,input:r}:{type:t,toolCallId:n,state:`output-available`,input:r,output:e.result}:{type:t,toolCallId:n,state:`output-error`,input:r,errorText:e.errorText}}function Ee(e){let t=`tool-${e.toolName}`,{toolCallId:n,approval:r}=e,i=e.args;switch(e.state){case`approval-requested`:if(r)return{type:t,toolCallId:n,state:`approval-requested`,input:i,approval:{id:r.id,isAutomatic:r.isAutomatic,signature:r.signature}};Ce(e);break;case`approval-responded`:if(r&&typeof r.approved==`boolean`)return{type:t,toolCallId:n,state:`approval-responded`,input:i,approval:{id:r.id,approved:r.approved,reason:r.reason,isAutomatic:r.isAutomatic,signature:r.signature}};Ce(e);break;case`output-denied`:if(r&&r.approved===!1)return{type:t,toolCallId:n,state:`output-denied`,input:i,approval:{id:r.id,approved:!1,reason:r.reason,isAutomatic:r.isAutomatic,signature:r.signature}};Ce(e);break;case`input-streaming`:case`partial-call`:return{type:t,toolCallId:n,state:`input-streaming`,input:i};case`input-available`:case`call`:return{type:t,toolCallId:n,state:`input-available`,input:i};case`output-error`:return{type:t,toolCallId:n,state:`output-error`,input:i,errorText:e.errorText??``};case`output-available`:case`result`:return{type:t,toolCallId:n,state:`output-available`,input:i,output:e.result};case void 0:break;default:e.state}return Te(e,t)}function De(e={}){let{api:n,initialMessages:r,conversationId:i,parentConversationId:c,systemPrompt:l,model:u,streamingEnabled:d=!0,headers:f,body:p,onError:m,showTimestamp:h,autoResponse:g,autoResponseText:_,autoResponseDelay:v=1e3,onSend:y}=e,b=(0,a.useDisplayLocale)(),x=(0,t.useRef)(n?`api`:`local`).current===`api`,S=(0,t.useMemo)(()=>(r??[]).map((e,t)=>{if(Array.isArray(e.parts)&&e.parts.length>0)return{id:e.id||`msg-${t}`,role:U(e.role||`user`),parts:e.parts};let n=ye([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(Ee(e));return{id:n.id||`msg-${t}`,role:U(n.role),parts:r.length>0?r:[{type:`text`,text:``}]}}),[]),C=(0,t.useRef)(u);C.current=u;let w=(0,t.useRef)(c),T=(0,t.useRef)(c);(0,t.useEffect)(()=>{let e=T.current;T.current=c,c&&!e&&(w.current=c)},[c]);let E=(0,t.useRef)(p);E.current=p;let D=(0,t.useRef)(f);D.current=f;let k=(0,t.useMemo)(()=>{if(x)return new s.DefaultChatTransport({api:n,fetch:ge,body:{...i?{conversationId:i}:{},...u?{model:u}:{},...l?{systemPrompt:l}:{},...d===void 0?{}:{stream:d}},prepareSendMessagesRequest:({id:e,body:t,messages:n,trigger:r,messageId:i,headers:a})=>{let o=_e({id:e,body:{...E.current,...t},messages:n,trigger:r,messageId:i});C.current&&(o.body.model=C.current),w.current&&=(o.body=ve(o.body,w.current),void 0);let s=new Headers(D.current??{});return new Headers(a??{}).forEach((e,t)=>s.set(t,e)),{...o,headers:s}}})},[x,n,u,l,d,i]),A=(0,t.useRef)(null),j=(0,o.useChat)({transport:k,messages:x&&S.length>0?S:void 0,onError:x?e=>{if(e.notSent){let e=A.current,t=e?.messages;e?.setMessages&&t&&t.length>0&&t[t.length-1]?.role===`user`&&e.setMessages(t.slice(0,-1)),he()}m?.(e)}:void 0});A.current=j;let M=(0,t.useRef)(void 0),N=j?.status;(0,t.useEffect)(()=>{let e=M.current;M.current=N,(e===`streaming`||e===`submitted`)&&N===`ready`&&he()},[N]);let[ee,P]=(0,t.useState)(()=>ye(r)),[F,I]=(0,t.useState)(!1),[L,R]=(0,t.useState)(``),[te,z]=(0,t.useState)(``),B=(0,t.useRef)(null);(0,t.useEffect)(()=>()=>{B.current&&=(clearTimeout(B.current),null)},[]);let{messages:ne,status:re,error:ie,sendMessage:V,regenerate:ae,stop:oe,setMessages:se}=j,ce=re===`submitted`||re===`streaming`,le=de(ne,{isStreaming:ce}).map((e,t)=>({...e,metadata:ne[t]?.metadata})),ue=(0,t.useCallback)(e=>{let t=e.trim();if(!t)return;let n=[...le,{id:O(`msg`),role:`user`,content:t}];V({text:t}),z(``),y?.(t,n)},[V,y,le]),H=(0,t.useCallback)(e=>{se(xe(e))},[se]),fe=(0,t.useCallback)(()=>{H([])},[H]),pe=(0,t.useCallback)(e=>{z(e.target.value)},[]),W=(0,t.useCallback)(()=>{B.current&&=(clearTimeout(B.current),null),I(!1)},[]),G=(0,t.useCallback)(e=>{if(!e.trim())return;let t={id:O(`msg`),role:`user`,content:e.trim(),timestamp:h?new Date().toLocaleTimeString(b):void 0};P(n=>{let r=[...n,t];return y?.(e.trim(),r),r}),R(``),g&&(I(!0),B.current=setTimeout(()=>{let e={id:O(`msg`),role:`assistant`,content:_||`Thank you for your message!`,timestamp:h?new Date().toLocaleTimeString(b):void 0};P(t=>[...t,e]),I(!1)},v))},[h,b,g,_,v,y]),me=(0,t.useCallback)(()=>{},[]),be=(0,t.useCallback)(()=>{W(),P([])},[W]),Se=(0,t.useCallback)(e=>{R(e.target.value)},[]);return x?{messages:le,isLoading:ce,error:ie,sendMessage:ue,stop:oe,reload:ae,clear:fe,setMessages:H,isApiMode:!0,input:te,setInput:z,handleInputChange:pe}:{messages:ee,isLoading:F,error:void 0,sendMessage:G,stop:W,reload:me,clear:be,isApiMode:!1,input:L,setInput:R,handleInputChange:Se}}var Oe=[[`build`,`metadata_assistant`],[`ask`,`data_chat`]];function ke(e){return Oe.find(t=>t.includes(e))??[e]}function Ae(e){return ke(e)[0]}function je(e,t){if(e){if(t.includes(e))return e;for(let n of ke(e))if(t.includes(n))return n}}function Me(e){return e!=null&&Oe.some(t=>t.includes(e))}function Ne(e){return e!=null&&Ae(e)===`build`}function Pe(e){return e!=null&&Ae(e)===`ask`}function Fe(e){if(e&&typeof e==`object`)return{authoring:e.authoring===!0,canvas:e.canvas===!0,debug:e.debug===!0,resume:e.resume===!0}}function Ie(e,t,n){if(!t)return!1;let r=e.find(e=>e.name===t);return r?.capabilities?r.capabilities[n]:Ne(t)}var Le=`ask`;function Re(e,t){if(e.length===0)return;let n=e.map(e=>e.name);if(t){let e=je(t,n);if(e)return e}return je(`ask`,n)||e[0].name}function ze(e){let t=e&&typeof e==`object`&&!Array.isArray(e)&&typeof e.success==`boolean`?e.data:e;if(Array.isArray(t))return t;let n=t?.agents;return Array.isArray(n)?n:[]}function Be(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,capabilities:Fe(e.capabilities)}))}var Ve=3e4,He=new Map,Ue=new Map;function We(e,t,n){if(n)He.delete(e);else{let t=He.get(e);if(t&&Date.now()-t.timestamp<Ve)return Promise.resolve(t.data)}let r=Ue.get(e);if(r&&!n)return r;let i=`${e.replace(/\/$/,``)}/agents`,a=fetch(i,{method:`GET`,headers:{Accept:`application/json`,...t??{}},credentials:`include`}).then(async e=>{if(!e.ok)throw Error(`Failed to load agents (${e.status})`);return Be(ze(await e.json()))}).then(t=>(He.set(e,{data:t,timestamp:Date.now()}),t)).finally(()=>{Ue.delete(e)});return Ue.set(e,a),a}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=!1;return l(!0),d(void 0),We(n,m.current,f>0).then(t=>{e||s(t.length>0?t:a)}).catch(t=>{e||(d(t),s(a))}).finally(()=>{e||l(!1)}),()=>{e=!0}},[n,i,f]),{agents:o,isLoading:c,error:u,refetch:(0,t.useCallback)(()=>p(e=>e+1),[])}}function Ke(e){return e.filter(e=>typeof e?.id==`string`&&e.id.length>0).map(e=>({id:e.id,label:e.label||e.id}))}function qe(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=Ke(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 Je=t.createContext(null);function K({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)(Je.Provider,{value:c,children:n})}function Ye(){let e=t.useContext(Je);if(!e)throw Error(`useFloatingChatbot must be used within a <FloatingChatbotProvider>`);return e}function Xe(){let{t:e}=(0,l.useObjectTranslation)();return(t,n)=>{let r=e(`common.${t}`);return!r||r===`common.${t}`?n:r}}var Ze={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 Qe(e,t){return t.reduce((t,n)=>Math.abs(n-e)<Math.abs(t-e)?n:t)}function $e(e){return Ze[e]??Ze[Qe(e,Object.keys(Ze).map(Number))]}function et({position:e=`bottom-right`,size:t=56,className:a}){let{isOpen:o,toggle:s}=Ye(),c=Xe();return(0,i.jsx)(n.Button,{onClick:s,className:(0,n.cn)(`fixed z-50 rounded-full shadow-lg transition-transform hover:scale-105`,$e(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 tt={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]`},q={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 nt(e,t){return t.reduce((t,n)=>Math.abs(n-e)<Math.abs(t-e)?n:t)}function rt(e){return tt[e]??tt[nt(e,Object.keys(tt).map(Number))]}function J(e){return q[e]??q[nt(e,Object.keys(q).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}=Ye();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)]`,rt(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)]`,rt(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 it={ai:`AI`,api:`API`,crm:`CRM`,hitl:`HITL`,id:`ID`,ids:`IDs`,rag:`RAG`,sql:`SQL`,url:`URL`,utc:`UTC`};function at(e){return`chatbot.tool.${String(e).trim()}`}function ot(e,t){if(!e)return``;let n=String(e).trim();if(!n)return``;let r=n.replace(/[_-]+/g,` `).replace(/([a-z])([A-Z])/g,`$1 $2`).split(/\s+/).filter(Boolean);if(r.length===0)return n;let i=r.map((e,t)=>{let n=e.toLowerCase();return it[n]?it[n]:t===0?n.charAt(0).toUpperCase()+n.slice(1):n}).join(` `);return t?t(at(n),i):i}function st(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 ct(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 lt=new Set([`AI_DESIGN_QUOTA_EXHAUSTED`,`AI_DATA_CHAT_TRIAL_EXHAUSTED`,`AI_ALLOWANCE_EXHAUSTED`,`ai_design_quota_exhausted`,`ai_data_chat_trial_exhausted`,`ai_allowance_exhausted`]);function ut(e){return typeof e==`string`&<.has(e)?e:void 0}function dt(e){return typeof e==`string`&&e.trim()?e:void 0}function ft(...e){for(let t of e)if(typeof t==`boolean`)return t}function pt(...e){return ft(...e)??!1}function mt(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}if(!a||typeof a!=`object`)return null;let o=a.error&&typeof a.error==`object`?a.error:void 0,s=o?.details&&typeof o.details==`object`&&!Array.isArray(o.details)?o.details:void 0,c=ut(a.error),l=ut(o?.code)??c??ut(a.code);return l?{code:l,message:dt(o?.message)??dt(a.message)??(c?void 0:dt(a.error))??``,messageEn:dt(s?.messageEn)??dt(a.messageEn),upgrade:pt(s?.upgrade,a.upgrade),topUp:pt(s?.topUp,a.topUp),resetsTonight:ft(s?.resetsTonight,a.resetsTonight)}:null}function ht(e){return!!(e&&typeof e==`object`&&e.notSent===!0)}function gt(e){let t=e&&typeof e==`object`?e.status:void 0;return typeof t==`number`?t:void 0}function _t(e){if(gt(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 vt=({className:e,...t})=>(0,i.jsx)(u.StickToBottom,{className:(0,n.cn)(`relative flex-1 overflow-y-hidden`,e),initial:`smooth`,resize:`smooth`,role:`log`,...t}),yt=({className:e,...t})=>(0,i.jsx)(u.StickToBottom.Content,{className:(0,n.cn)(`flex flex-col gap-8 p-4`,e),...t}),bt=({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})]})]})}),xt=({className:e,...a})=>{let{isAtBottom:o,scrollToBottom:s}=(0,u.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`})})},St=(0,d.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 Ct({className:e,orientation:t,...r}){return(0,i.jsx)(`div`,{role:`group`,"data-slot":`button-group`,"data-orientation":t,className:(0,n.cn)(St({orientation:t}),e),...r})}function wt({className:e,asChild:t=!1,...r}){return(0,i.jsx)(t?f.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 Tt=({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}),Et=({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}),Dt=({className:e,children:t,...r})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`flex items-center gap-1`,e),...r,children:t}),Ot=({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},kt=(0,t.createContext)(null),X=()=>{let e=(0,t.useContext)(kt);if(!e)throw Error(`MessageBranch components must be used within MessageBranch`);return e},Z=({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:()=>{let e=s>0?s-1:l.length-1;d(e)},goToNext:()=>{let e=s<l.length-1?s+1:0;d(e)},branches:l,setBranches:u};return(0,i.jsx)(kt.Provider,{value:f,children:(0,i.jsx)(`div`,{className:(0,n.cn)(`grid w-full gap-2 [&>div]:pb-0`,a),...o})})},At=({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))},jt=({className:e,from:t,...n})=>{let{totalBranches:r}=X();return r<=1?null:(0,i.jsx)(Ct,{className:`[&>*:not(:first-child)]:rounded-l-md [&>*:not(:last-child)]:rounded-r-md`,orientation:`horizontal`,...n})},Mt=({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})})},Nt=({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})})},Pt=({className:e,...t})=>{let{currentBranch:r,totalBranches:a}=X();return(0,i.jsxs)(wt,{className:(0,n.cn)(`border-none bg-transparent text-muted-foreground shadow-none`,e),...t,children:[r+1,` of `,a]})},Ft=(0,t.memo)(({className:e,...t})=>(0,i.jsx)(p.Streamdown,{className:(0,n.cn)(`size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0`,e),...t}),(e,t)=>e.children===t.children);Ft.displayName=`MessageResponse`;function Q({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 It({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 Lt=({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 Rt({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 zt=(0,d.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 Bt({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)(zt({align:t}),e),onClick:e=>{e.target.closest(`button`)||e.currentTarget.parentElement?.querySelector(`input`)?.focus()},...r})}var Vt=(0,d.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 Ht({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)(Vt({size:a}),e),...o})}function Ut({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 Wt=(0,t.createContext)(null),Gt=(0,t.createContext)(null),Kt=()=>{let e=(0,t.useContext)(Wt);if(!e)throw Error(`Wrap your component inside <PromptInputProvider> to use usePromptInputController().`);return e},qt=()=>(0,t.useContext)(Wt),Jt=()=>{let e=(0,t.useContext)(Gt);if(!e)throw Error(`Wrap your component inside <PromptInputProvider> to use useProviderAttachments().`);return e},$=()=>(0,t.useContext)(Gt);function Yt({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,m.nanoid)(),type:`file`,url:URL.createObjectURL(e),mediaType:e.type,filename:e.name,file:e}))))},[]),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)})},[]),p=(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:p,openFileDialog:g,fileInputRef:l}),[s,d,f,p,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)(Wt.Provider,{value:y,children:(0,i.jsx)(Gt.Provider,{value:_,children:n})})}var Xt=(0,t.createContext)(null),Zt=()=>{let e=$(),n=(0,t.useContext)(Xt),r=e??n;if(!r)throw Error(`usePromptInputAttachments must be used within a PromptInput or PromptInputProvider`);return r};function Qt({data:e,className:t,...a}){let o=Zt(),s=e.filename||``,c=(e.mediaType?.startsWith(`image/`)&&e.url?`image`:`file`)==`image`,l=s||(c?`Image`:`Attachment`);return(0,i.jsxs)(bn,{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)(Sn,{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=Zt();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 en=({label:e=`Add photos or files`,...t})=>{let a=Zt();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]})},tn=({className:e,accept:r,multiple:a,fileInputLabel:o=`Upload files`,globalDrop:s,syncHiddenInput:c,maxFiles:l,maxFileSize:u,onError:d,onSubmit:f,children:p,...h})=>{let g=qt(),_=!!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()===``||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);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,m.nanoid)(),type:`file`,url:URL.createObjectURL(e),mediaType:e.type,filename:e.name,file:e});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=``},ee=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}},P=(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]),F=(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 ee(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)(Rt,{className:`overflow-hidden`,children:p})})]});return _?F:(0,i.jsx)(Xt.Provider,{value:P,children:F})},nn=({className:e,...t})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`contents`,e),...t}),rn=({onChange:e,className:r,placeholder:a=`What would you like to know?`,...o})=>{let s=qt(),c=Zt(),[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)(Ut,{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})},an=({className:e,...t})=>(0,i.jsx)(Bt,{align:`block-end`,className:(0,n.cn)(`order-first flex-wrap gap-1`,e),...t}),on=({className:e,...t})=>(0,i.jsx)(Bt,{align:`block-end`,className:(0,n.cn)(`justify-between gap-1`,e),...t}),sn=({className:e,...t})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`flex items-center gap-1`,e),...t}),cn=({variant:e=`ghost`,className:r,size:a,...o})=>{let s=a??(t.Children.count(o.children)>1?`sm`:`icon-sm`);return(0,i.jsx)(Ht,{className:(0,n.cn)(r),size:s,type:`button`,variant:e,...o})},ln=e=>(0,i.jsx)(n.DropdownMenu,{...e}),un=({className:e,children:t,...a})=>(0,i.jsx)(n.DropdownMenuTrigger,{asChild:!0,children:(0,i.jsx)(cn,{className:e,...a,children:t??(0,i.jsx)(r.PlusIcon,{className:`size-4`})})}),dn=({className:e,...t})=>(0,i.jsx)(n.DropdownMenuContent,{align:`start`,className:(0,n.cn)(e),...t}),fn=({className:e,...t})=>(0,i.jsx)(n.DropdownMenuItem,{className:(0,n.cn)(e),...t}),pn=({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)(Ht,{"aria-label":`Submit`,className:(0,n.cn)(e),size:a,type:`submit`,variant:t,...c,children:s??l})},mn=({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)(cn,{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`})})},hn=e=>(0,i.jsx)(n.Select,{...e}),gn=({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}),_n=({className:e,...t})=>(0,i.jsx)(n.SelectContent,{className:(0,n.cn)(e),...t}),vn=({className:e,...t})=>(0,i.jsx)(n.SelectItem,{className:(0,n.cn)(e),...t}),yn=({className:e,...t})=>(0,i.jsx)(n.SelectValue,{className:(0,n.cn)(e),...t}),bn=({openDelay:e=0,closeDelay:t=0,...r})=>(0,i.jsx)(n.HoverCard,{closeDelay:t,openDelay:e,...r}),xn=e=>(0,i.jsx)(n.HoverCardTrigger,{...e}),Sn=({align:e=`start`,...t})=>(0,i.jsx)(n.HoverCardContent,{align:e,...t}),Cn=({className:e,...t})=>(0,i.jsx)(`div`,{className:(0,n.cn)(e),...t}),wn=({className:e,...t})=>(0,i.jsx)(`div`,{className:(0,n.cn)(e),...t}),Tn=({className:e,...t})=>(0,i.jsx)(`h3`,{className:(0,n.cn)(`mb-2 px-3 font-medium text-muted-foreground text-xs`,e),...t}),En=({className:e,...t})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`space-y-1`,e),...t}),Dn=({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}),On=({className:e,...t})=>(0,i.jsx)(n.Command,{className:(0,n.cn)(e),...t}),kn=({className:e,...t})=>(0,i.jsx)(n.CommandInput,{className:(0,n.cn)(e),...t}),An=({className:e,...t})=>(0,i.jsx)(n.CommandList,{className:(0,n.cn)(e),...t}),jn=({className:e,...t})=>(0,i.jsx)(n.CommandEmpty,{className:(0,n.cn)(e),...t}),Mn=({className:e,...t})=>(0,i.jsx)(n.CommandGroup,{className:(0,n.cn)(e),...t}),Nn=({className:e,...t})=>(0,i.jsx)(n.CommandItem,{className:(0,n.cn)(e),...t}),Pn=({className:e,...t})=>(0,i.jsx)(n.CommandSeparator,{className:(0,n.cn)(e),...t}),Fn=({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`})]}),In=({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}),Ln=(0,t.createContext)({code:``}),Rn={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 zn(e,t,n=!1){let r=n?[Rn]:[];return await Promise.all([(0,h.codeToHtml)(e,{lang:t,theme:`one-light`,transformers:r}),(0,h.codeToHtml)(e,{lang:t,theme:`one-dark-pro`,transformers:r})])}var Bn=({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)(()=>(zn(e,r,a).then(([e,t])=>{p.current||=(u(e),f(t),!0)}),()=>{p.current=!1}),[e,r,a]),(0,i.jsx)(Ln.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})]})})})},Vn=({onCopy:e,onError:a,timeout:o=2e3,children:s,className:c,...l})=>{let[u,d]=(0,t.useState)(!1),{code:f}=(0,t.useContext)(Ln),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})})},Hn=({className:e,...t})=>(0,i.jsx)(n.Collapsible,{className:(0,n.cn)(`not-prose mb-4 w-full rounded-md border`,e),...t}),Un=(e,t)=>(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],t?.[e]??{"input-streaming":`Pending`,"input-available":`Running`,"approval-requested":`Awaiting Approval`,"approval-responded":`Responded`,"output-available":`Completed`,"output-error":`Error`,"output-denied":`Denied`}[e]]}),Wn=({className:e,title:t,type:a,state:o,statusLabels:s,...c})=>(0,i.jsxs)(n.CollapsibleTrigger,{className:(0,n.cn)(`flex w-full items-center justify-between gap-4 p-3`,e),...c,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(`-`)}),Un(o,s)]}),(0,i.jsx)(r.ChevronDownIcon,{className:`size-4 text-muted-foreground transition-transform group-data-[state=open]:rotate-180`})]}),Gn=({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}),Kn=({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)(Bn,{code:JSON.stringify(t,null,2),language:`json`})})]}),qn=({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)(Bn,{code:JSON.stringify(r,null,2),language:`json`}):typeof r==`string`&&(s=(0,i.jsx)(Bn,{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]})]})},Jn=(0,t.memo)(({children:e,as:r=`p`,className:a,duration:o=2,spread:s=2})=>{let c=(0,t.useMemo)(()=>_.motion.create(r),[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})}),Yn=(0,t.createContext)(null),Xn=()=>{let e=(0,t.useContext)(Yn);if(!e)throw Error(`Reasoning components must be used within Reasoning`);return e},Zn=1e3,Qn=1e3,$n=(0,t.memo)(({className:e,isStreaming:r=!1,open:a,defaultOpen:o=!0,onOpenChange:s,duration:c,children:l,...u})=>{let[d,f]=(0,g.useControllableState)({prop:a,defaultProp:o,onChange:s}),[p,m]=(0,g.useControllableState)({prop:c,defaultProp:void 0}),[h,_]=(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)/Qn)),y(null))},[r,v,m]),(0,t.useEffect)(()=>{if(o&&!r&&d&&!h){let e=setTimeout(()=>{f(!1),_(!0)},Zn);return()=>clearTimeout(e)}},[r,d,o,f,h]),(0,i.jsx)(Yn.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})})}),er=(e,t)=>e||t===0?(0,i.jsx)(Jn,{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`]}),tr=(0,t.memo)(({className:e,children:t,getThinkingMessage:a=er,...o})=>{let{isStreaming:s,isOpen:c,duration:l}=Xn();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`)})]})})}),nr=(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)(p.Streamdown,{children:t})}));$n.displayName=`Reasoning`,tr.displayName=`ReasoningTrigger`,nr.displayName=`ReasoningContent`;var rr=({className:e,...t})=>(0,i.jsx)(n.Collapsible,{className:(0,n.cn)(`not-prose mb-4 text-primary text-xs`,e),...t}),ir=({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`})]})}),ar=({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}),or=({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 sr(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 cr(e){return e===`user`?`user`:`assistant`}function lr(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 ur(e){let t=N(e)?.status;return t===`changes_proposed`||t===`blueprint_proposed`||t===`awaiting_confirmation`}function dr(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`?ur(e.result)?`awaiting`:`completed`:`running`}function fr(e){let t=e.replayOutcome?.kind;return t===`failed`?`failed`:t===`published`||t===`drafted`?`settled`:t===`applying`?`in-progress`:e.built||e.confirmed?`settled`:e.approved?`in-progress`:`pending`}var pr={pending:`approval-requested`,"in-progress":`input-available`,settled:`output-available`,failed:`output-error`},mr={create_object:`Create object`,add_field:`Add field`,modify_field:`Modify field`,delete_field:`Delete field`,create_metadata:`Create`,update_metadata:`Modify`,create_seed:`Generate sample data`,create_package:`Create app package`};function hr(e,t=mr){return[t[e.verb]??mr[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 gr(e){return e.toolName===`propose_blueprint`}function _r(e){return gr(e)&&dr(e)===`completed`&&!e.proposedPlan&&!e.proposedChanges&&!e.draftReview?.items.length}var vr=[`待补`,`后续`,`将在`,`稍后`,`暂不`,`暂未`,`尚未`,`确认后一起补`,`一起补`,`另行`,`日后`,`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 yr(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();vr.some(e=>i.includes(e))?n.push(e):t.push(e)}return{designNotes:t,deferred:n}}function br(e){let t=dr(e);return t===`awaiting`||t===`failed`||!!e.pendingActionId||!!e.draftReview?.items.length||!!e.proposedPlan||!!e.proposedChanges||!!e.builderHandoff||!!e.recordHandoff||_r(e)}function xr(e){switch(e){case`failed`:return 4;case`awaiting`:return 3;case`running`:return 2;case`completed`:return 1}}function Sr(e){return/^\((?:called [^)]*|tool call|no content)\)$/.test(e.trim())}function Cr(){let{t:e}=(0,a.useObjectTranslation)();return t.useCallback(t=>{let n=[];return t?.objects&&n.push(e(`chatbot.plan.countObjects`,{count:t.objects,defaultValue:`{{count}} objects`})),t?.views&&n.push(e(`chatbot.plan.countViews`,{count:t.views,defaultValue:`{{count}} views`})),t?.dashboards&&n.push(e(`chatbot.plan.countDashboards`,{count:t.dashboards,defaultValue:`{{count}} dashboards`})),t?.seedData&&n.push(e(`chatbot.plan.countSeedData`,{defaultValue:`sample data`})),n},[e])}function wr(e,t){let n=new Map;for(let r of e){let e=dr(r),i=`${r.toolName}:${e}`,a=n.get(i);if(a){a.count+=1,a.errorText=a.errorText??r.errorText;continue}n.set(i,{key:i,title:ot(r.toolName,t)||r.toolName,rawName:r.toolName,count:1,state:e,errorText:r.errorText})}return Array.from(n.values()).sort((e,t)=>{let n=xr(t.state)-xr(e.state);return n===0?e.title.localeCompare(t.title):n})}function Tr({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 Er=t.forwardRef(({className:e,messages:o=[],placeholder:s=`Type your message...`,onSendMessage:c,onClear:u,onStop:d,onReload:f,onUpgrade:p,disabled:m=!1,readOnly:h=!1,isLoading:g=!1,error:_,showTimestamp:v=!1,showAvatars:y=!1,userAvatarUrl:b,userAvatarFallback:x=`You`,assistantAvatarUrl:S,assistantAvatarFallback:C=`AI`,hideClearBar:w=!1,maxHeight:T=`500px`,enableMarkdown:E=!0,enableFileUpload:D=!1,acceptedFileTypes:O=`image/*,.pdf,.doc,.docx,.txt,.csv,.tsv,.xlsx,.xlsm`,maxFileSize:k=10485760,suggestions:A,labels:j,models:M,selectedModelId:N,onModelChange:ee,headerSlot:P,promptOverlaySlot:F,onInputChange:I,onToolApprove:L,toolApproveLabel:R=`Approve`,toolDenyLabel:te=`Deny`,toolDenyReason:B=`User denied the operation`,toolDecisions:ne,onReviewDraft:re,toolReviewLabel:ie=e=>`Review ${e} change${e===1?``:`s`}`,onPublishDrafts:V,onOpenBuiltApp:ae,openBuiltAppLabel:oe=`Open app`,onDesignBuiltApp:se,designBuiltAppLabel:ce=`Design in Studio`,getArtifactAction:le,onPreviewDraftApp:ue,previewDraftLabel:de=`Preview`,onDraftArtifacts:H,onBuildMaterialized:U,publishDraftsLabel:fe=`Publish`,publishedLabel:pe=`Published`,verifiedLabel:W=`Verified`,nextStepsLabel:G=`What's next`,planTitleLabel:me=`Proposed plan`,builderHandoffTitleLabel:he=`Build this in the Builder`,builderHandoffOpenLabel:ge=`Open in Builder →`,recordHandoffTitleLabel:_e=`Open this record`,recordHandoffOpenLabel:ve=`Open record →`,builderHandoffSupersededTitle:ye=`A newer request is available`,onOpenBuilder:be,onOpenRecord:xe,planExtendLabel:Se=`Adding to existing app`,planQuestionsLabel:Ce=`Confirm before building`,planAssumptionsLabel:we=`Assumptions`,planDeferredLabel:Te=`Not yet built`,planApproveHintLabel:Ee=`Reply to approve or adjust this plan.`,planApproveLabel:De=`Build it`,planAdjustLabel:Oe=`Adjust`,planBuiltLabel:ke=`Built`,planBuildingLabel:Ae=`Building…`,planReadyLabel:je=`The plan is ready. Build it now, or tell me what to adjust.`,planApproveMessage:Me=`Looks good — build it as proposed.`,planApproveDefaultsMessage:Ne=`Build it with your best assumptions; use sensible defaults for the open questions.`,planAnswerMessage:Pe=(e,t)=>`For "${e}", go with: ${t}.`,changesTitleLabel:Fe=`Confirm changes`,changesConfirmedLabel:Ie=`Confirmed`,changesConfirmLabel:Le=`Confirm`,changesConfirmHintLabel:Re=`Reply to confirm or adjust this change.`,changesConfirmMessage:ze=`Confirm — apply the change you just proposed.`,changeVerbLabels:Be=mr,changesApplyingLabel:Ve=`Applying…`,changesAppliedLabel:He=`Applied`,changesDraftedLabel:Ue=`Saved as draft`,changesFailedLabel:We=`Not applied`,surfaceContextLabel:Ge,surfaceContextTitle:Ke,fetchPendingDraftCount:qe,autoPublishDrafts:Je=!1,processVisibility:K=`summary`,surface:Ye=`card`,...Xe},Ze)=>{let Qe=g?`streaming`:`ready`,$e=Ye===`plain`,[et,tt]=t.useState(null),q=t.useRef(``),nt=t.useRef(null),rt=Cr(),J=(0,a.useSafeTranslate)(),Y=t.useMemo(()=>({emptyTitle:j?.emptyTitle??`Start a conversation`,emptyDescription:j?.emptyDescription??`Ask anything — the assistant has access to your current app context.`,clear:j?.clear??`Clear`,sendHint:j?.sendHint??`to send`,agentActivity:j?.agentActivity??J(`chatbot.toolState.agentActivity`,`Agent activity`),toolCompleted:j?.toolCompleted??J(`chatbot.toolState.completed`,`Completed`),toolRunning:j?.toolRunning??J(`chatbot.toolState.running`,`Running`),toolAwaitingApproval:j?.toolAwaitingApproval??J(`chatbot.toolState.awaitingApproval`,`Awaiting approval`),toolFailed:j?.toolFailed??J(`chatbot.toolState.failed`,`Failed`),toolPending:J(`chatbot.toolState.pending`,`Pending`),toolResponded:J(`chatbot.toolState.responded`,`Responded`),toolDenied:J(`chatbot.toolState.denied`,`Denied`),toolError:J(`chatbot.toolState.error`,`Error`),toolDetailsHidden:j?.toolDetailsHidden??`Detailed tool inputs and outputs are hidden in this view.`,copy:j?.copy??`Copy`,copied:j?.copied??`Copied`,regenerate:j?.regenerate??`Regenerate`,model:j?.model??`Model`,submit:j?.submit??`Submit`,uploadFiles:j?.uploadFiles??`Upload files`,stopResponse:j?.stopResponse??`Stop response`,sendFailedRateLimited:j?.sendFailedRateLimited??`You're sending messages too quickly. Your message is kept below — wait a moment and try again.`,sendFailedGeneric:j?.sendFailedGeneric??`Couldn't send your message. It's kept below — please try again.`,trace:j?.trace??`trace`,viewTrace:j?.viewTrace??`View trace`,connectionWaiting:j?.connectionWaiting??`Waiting for server…`,connectionStalledLabel:j?.connectionStalledLabel??`Still working…`,connectionOfflineLabel:j?.connectionOfflineLabel??`Connection lost — reconnecting…`,designingPlanLabel:j?.designingPlanLabel??`Designing your app…`,designingPlanHints:j?.designingPlanHints??Fr}),[j,J]),it=t.useMemo(()=>({"input-streaming":Y.toolPending,"input-available":Y.toolRunning,"approval-requested":Y.toolAwaitingApproval,"approval-responded":Y.toolResponded,"output-available":Y.toolCompleted,"output-error":Y.toolError,"output-denied":Y.toolDenied}),[Y]),[at,ct]=t.useState(()=>new Set),[lt,ut]=t.useState(()=>new Map),[dt,ft]=t.useState(()=>new Map),pt=t.useRef(new Set),gt=t.useCallback(async e=>{if(qe)try{let t=await qe(e);ft(n=>{if(n.get(e)===t)return n;let r=new Map(n);return r.set(e,t),r})}catch{}},[qe]);t.useEffect(()=>{if(!qe||g)return;let e=new Set;for(let t of o)for(let n of t.toolInvocations??[]){let t=n.draftReview?.packageId,r=n.toolCallId;t&&r&&!pt.current.has(r)&&(pt.current.add(r),e.add(t))}for(let t of e)gt(t)},[o,g,qe,gt]);let _t=t.useCallback(async e=>{if(!V)return;let t=[];for(let n of o)for(let r of n.toolInvocations??[])r.draftReview?.packageId===e&&r.toolCallId&&t.push(r.toolCallId);let n=await V(e),r=n&&typeof n==`object`?n:void 0;if((r?r.ok!==!1:n!==!1)&&t.length>0){ct(e=>{let n=new Set(e);for(let e of t)n.add(e);return n});let e=r?.health;e&&ut(n=>{let r=new Map(n);for(let n of t)r.set(n,e);return r})}gt(e)},[V,o,gt]),St=t.useRef(new Set),Ct=t.useRef(!1);t.useEffect(()=>{let e=[];for(let t of o)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(!Ct.current){Ct.current=!0;for(let t of e)St.current.add(t.key);return}if(!Je||!V||g)return;let t=e.filter(e=>!St.current.has(e.key));if(t.length!==0){for(let e of t)St.current.add(e.key);for(let e of[...new Set(t.map(e=>e.packageId))])_t(e)}},[o,g,Je,V,_t]);let wt=t.useRef(new Set);t.useEffect(()=>{if(!H)return;let e=new Map,t;for(let n of o){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=wt.current,r=!1;for(let t of e.keys())n.has(t)||(n.add(t),r=!0);r&&H([...e.values()],t)},[o,H]);let kt=t.useRef(new Set);t.useEffect(()=>{if(U)for(let e of o)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&&!kt.current.has(t.toolCallId)&&(kt.current.add(t.toolCallId),U(n.name))}},[o,U]);let X=t.useRef(null),Z=t.useCallback(()=>{X.current?.scrollToBottom({animation:`smooth`})},[]),At=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()??``;q.current=i,nt.current=null,Q.current=null,c?.(i,n),Z()},[c,Z]),jt=t.useCallback(e=>{Q.current=null,q.current=``,c?.(e),Z()},[c,Z]),Mt=t.useRef(null),[Nt,Pt]=t.useState(()=>new Set),Q=t.useRef(null),It=t.useCallback((e,t)=>{q.current=``,t&&(Q.current=t,Pt(e=>{let n=new Set(e);return n.add(t),n})),c?.(e?Ne:Me),Z()},[c,Me,Ne,Z]),[Lt,Rt]=t.useState(()=>new Set),zt=t.useRef(null),[Bt,Vt]=t.useState(()=>new Map),Ht=t.useCallback(e=>{q.current=``,e&&(zt.current=e,Rt(t=>{let n=new Set(t);return n.add(e),n})),c?.(ze),Z()},[c,ze,Z]),Ut=t.useCallback(()=>{let e=Mt.current?.querySelector(`textarea`);e&&(e.focus(),e.scrollIntoView({block:`nearest`}))},[]);t.useEffect(()=>{if(!_||!ht(_)||nt.current===_)return;if(nt.current=_,Q.current){let e=Q.current;Q.current=null,Pt(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})}if(zt.current){let e=zt.current;zt.current=null,Rt(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),mt(_)&&Vt(t=>{if(t.has(e))return t;let n=new Map(t);return n.set(e,_),n})}let e=q.current;if(!e)return;let t=Mt.current?.querySelector(`textarea`);t&&t.value.trim()===``&&(t.value=e,t.dispatchEvent(new Event(`input`,{bubbles:!0})),t.focus())},[_]);let Wt=t.useCallback(e=>{navigator.clipboard?.writeText(e.content),tt(e.id),window.setTimeout(()=>tt(t=>t===e.id?null:t),1500)},[]),Gt=t.useMemo(()=>{let e=new Set,t=[],n=-1,r=0;for(let e of o)for(let i of e.toolInvocations??[])(i.proposedPlan||_r(i))&&i.toolCallId&&t.push({id:i.toolCallId,order:r}),i.toolName===`apply_blueprint`&&!ur(i.result)&&(n=r),r+=1;for(let r of t)r.order<n&&e.add(r.id);return e},[o]),Kt=t.useMemo(()=>{let e;for(let t of o)for(let n of t.toolInvocations??[])n.builderHandoff&&n.toolCallId&&(e=n.toolCallId);return e},[o]),qt=t.useMemo(()=>{let e=new Set,t=[],n=new Map,r=0;for(let e of o)for(let i of e.toolInvocations??[])i.proposedChanges&&i.toolCallId?t.push({id:i.toolCallId,toolName:i.toolName??``,order:r}):i.toolName&&!ur(i.result)&&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},[o]),Jt=t.useMemo(()=>{let e=new Map,t=new Map,n=[],r=0;for(let i of o)for(let a of i.toolInvocations??[]){if(a.proposedChanges&&a.toolCallId)n.push({id:a.toolCallId,toolName:a.toolName??``,order:r}),t.delete(a.toolCallId);else if(a.toolCallId?.startsWith(`replay_`)){let i;for(let e of n)e.order<r&&e.toolName===(a.toolName??``)&&(i=e);i&&(a.replayOutcome?(e.set(i.id,a.replayOutcome),a.replayOutcome.dispatchError?t.set(i.id,r):t.delete(i.id)):a.result===void 0&&!a.errorText&&e.set(i.id,{kind:`applying`}))}else if(a.result!==void 0&&t.size>0){let n=z(a.result);if(n)for(let[i,a]of t)r>a&&e.set(i,n)}r+=1}return e},[o]),$=g,Yt=e=>{let t=e.state??(e.errorText?`output-error`:e.result===void 0?`input-available`:`output-available`),n=`tool-${e.toolName}`,a=ne?.[e.toolCallId],o=t===`approval-requested`&&!!L&&!a,s=t===`approval-requested`&&!!e.pendingActionId,l=ot(e.toolName,J),u=st(e.result),d=K===`debug`&&l&&l.toLowerCase()!==e.toolName.toLowerCase(),f=K===`debug`||o,m=e.draftReview?.packageId,h=m===void 0?void 0:dt.get(m),g=h===void 0?at.has(e.toolCallId):h===0,_=t===`input-streaming`||t===`input-available`,v=fr({replayOutcome:Jt.get(e.toolCallId),built:Gt.has(e.toolCallId),confirmed:qt.has(e.toolCallId),approved:Nt.has(e.toolCallId)}),y=t===`output-available`&&ur(e.result)?pr[v]:t,b=(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,_?gr(e)?(0,i.jsx)(Rr,{label:Y.designingPlanLabel,hints:Y.designingPlanHints,offlineLabel:Y.connectionOfflineLabel}):(0,i.jsx)(zr,{offlineLabel:Y.connectionOfflineLabel}):null]});return(0,i.jsxs)(Hn,{defaultOpen:t===`output-error`||t===`approval-requested`||!!(e.draftReview&&e.draftReview.items.length>0)||!!e.proposedPlan||!!e.proposedChanges||!!e.builderHandoff||!!e.recordHandoff||_r(e),children:[(0,i.jsx)(Wn,{type:n,state:y,title:b,statusLabels:it}),(0,i.jsxs)(Gn,{children:[f&&e.args!==void 0?(0,i.jsx)(Kn,{input:e.args}):null,s?null:f||t===`output-error`?(0,i.jsx)(Zr,{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:R}),(0,i.jsx)(`button`,{type:`button`,onClick:()=>L?.(e.toolCallId,!1,B),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&&(re||V&&e.draftReview.packageId)?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 p-3 border-t bg-muted/30`,children:[V&&e.draftReview.packageId?g?(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`}),pe,e.draftReview.failedCount?` · ${e.draftReview.failedCount} need${e.draftReview.failedCount===1?`s`:``} attention`:``]}):(0,i.jsxs)(`button`,{type:`button`,onClick:()=>void _t(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`}),fe,typeof h==`number`&&h>0?` (${h})`:``]}):null,re?(0,i.jsxs)(`button`,{type:`button`,onClick:()=>re(e.draftReview.items),className:V&&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,ue&&!g?(()=>{let t=e.draftReview.items.find(e=>e.type===`app`);return t?(0,i.jsxs)(`button`,{type:`button`,onClick:()=>ue(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`}),de]}):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`}),W]}):null,e.draftReview.summary?(0,i.jsx)(`span`,{className:`min-w-0 flex-1 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,at.has(e.toolCallId)?(0,i.jsx)(Tr,{health:lt.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:G}),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.builderHandoff?(0,i.jsxs)(`div`,{className:`flex flex-col gap-2 border-t bg-muted/20 px-3 py-2.5`,"data-testid":`builder-handoff`,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.Sparkles,{className:`size-3.5`}),he]}),(0,i.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.builderHandoff.prompt}),(()=>{let t=!!Kt&&e.toolCallId!==Kt;return(0,i.jsx)(`button`,{type:`button`,onClick:()=>be?.(e.builderHandoff),disabled:!be||t,"data-testid":t?`builder-handoff-superseded`:`builder-handoff-open`,title:t?ye:void 0,className:`inline-flex w-fit items-center gap-1 rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-50`,children:ge})})()]}):null,e.recordHandoff?(0,i.jsxs)(`div`,{className:`flex flex-col gap-2 border-t bg-muted/20 px-3 py-2.5`,"data-testid":`record-handoff`,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.Sparkles,{className:`size-3.5`}),_e]}),(0,i.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[e.recordHandoff.label??e.recordHandoff.objectName,e.recordHandoff.reason?` — ${e.recordHandoff.reason}`:``]}),(0,i.jsx)(`button`,{type:`button`,onClick:()=>xe?.(e.recordHandoff),disabled:!xe,"data-testid":`record-handoff-open`,className:`inline-flex w-fit items-center gap-1 rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-50`,children:ve})]}):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`}),me]}),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:[`+ `,Se,` "`,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=rt(e.proposedPlan.counts);return t.length?(0,i.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:t.join(` · `)}):null})(),(()=>{let{designNotes:t,deferred:n}=yr(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:we}),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`}),Te]}),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`}),Ce]}),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})]}),c&&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:()=>c(Pe(t,e)),disabled:$,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 disabled:cursor-not-allowed disabled:opacity-50 dark:border-amber-800 dark:text-amber-200 dark:hover:bg-amber-900/40`,children:e},n))}):null]},n)})]}):null,c?Gt.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`}),ke]})}):Nt.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 bg-muted/40 px-3 text-xs font-medium text-muted-foreground`,"data-testid":`proposed-plan-building`,children:[(0,i.jsx)(r.Loader2,{className:`size-3.5 animate-spin`}),Ae]})}):(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,e.toolCallId),disabled:$,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 disabled:cursor-not-allowed disabled:opacity-50`,"data-testid":`proposed-plan-approve`,children:[(0,i.jsx)(r.Rocket,{className:`size-3.5`}),De]}),(0,i.jsx)(`button`,{type:`button`,onClick:Ut,disabled:$,className:`inline-flex h-7 items-center rounded-md border bg-background px-3 text-xs font-medium hover:bg-accent disabled:cursor-not-allowed disabled:opacity-50`,"data-testid":`proposed-plan-adjust`,children:Oe})]}):(0,i.jsx)(`span`,{className:`text-[11px] italic text-muted-foreground/80`,children:Ee})]}):null,_r(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`}),me]}),(0,i.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:je}),c?Gt.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`}),ke]})}):Nt.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 bg-muted/40 px-3 text-xs font-medium text-muted-foreground`,"data-testid":`proposed-plan-building`,children:[(0,i.jsx)(r.Loader2,{className:`size-3.5 animate-spin`}),Ae]})}):(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,e.toolCallId),disabled:$,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 disabled:cursor-not-allowed disabled:opacity-50`,"data-testid":`proposed-plan-approve`,children:[(0,i.jsx)(r.Rocket,{className:`size-3.5`}),De]}),(0,i.jsx)(`button`,{type:`button`,onClick:Ut,disabled:$,className:`inline-flex h-7 items-center rounded-md border bg-background px-3 text-xs font-medium hover:bg-accent disabled:cursor-not-allowed disabled:opacity-50`,"data-testid":`proposed-plan-adjust`,children:Oe})]}):(0,i.jsx)(`span`,{className:`text-[11px] italic text-muted-foreground/80`,children:Ee})]}):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`}),Fe]}),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:hr(e,Be)})]},t))}),(()=>{let t=Jt.get(e.toolCallId);return t?.kind===`published`?(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-applied`,children:[(0,i.jsx)(r.CheckCircle2,{className:`size-3.5`}),He]})}):t?.kind===`failed`?(0,i.jsxs)(`div`,{className:`flex flex-col gap-1 pt-0.5`,"data-testid":`proposed-changes-actions`,children:[(0,i.jsxs)(`span`,{className:`inline-flex h-7 w-fit items-center gap-1.5 rounded-md border border-red-200 bg-red-50 px-3 text-xs font-medium text-red-700 dark:border-red-900/50 dark:bg-red-950/30 dark:text-red-300`,"data-testid":`proposed-changes-failed`,children:[(0,i.jsx)(r.XCircle,{className:`size-3.5`}),We]}),t.error?(0,i.jsx)(`span`,{className:`text-[11px] text-red-700/80 dark:text-red-300/80`,"data-testid":`proposed-changes-failed-reason`,children:t.error}):null]}):t?.kind===`drafted`?(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)(`span`,{className:`inline-flex h-7 items-center gap-1.5 rounded-md border border-amber-200 bg-amber-50 px-3 text-xs font-medium text-amber-800 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-300`,"data-testid":`proposed-changes-drafted`,children:[(0,i.jsx)(r.Clock3,{className:`size-3.5`}),Ue]}),V&&t.packageId?(0,i.jsxs)(`button`,{type:`button`,onClick:()=>void _t(t.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":`proposed-changes-publish`,children:[(0,i.jsx)(r.Rocket,{className:`size-3.5`}),fe]}):null]}):Bt.has(e.toolCallId)?(0,i.jsxs)(`div`,{className:`flex flex-col items-start gap-1 pt-0.5`,"data-testid":`proposed-changes-actions`,children:[(0,i.jsxs)(`span`,{className:`inline-flex h-7 w-fit items-center gap-1.5 rounded-md border border-amber-200 bg-amber-50 px-3 text-xs font-medium text-amber-800 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-300`,"data-testid":`proposed-changes-quota-blocked`,children:[(0,i.jsx)(r.XCircle,{className:`size-3.5`}),We]}),(0,i.jsx)(Yr,{error:Bt.get(e.toolCallId),onUpgrade:p})]}):t?.kind===`applying`||Lt.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 bg-muted/40 px-3 text-xs font-medium text-foreground/70`,"data-testid":`proposed-changes-applying`,children:[(0,i.jsx)(r.Loader2,{className:`size-3.5 animate-spin`}),Ve]})}):c?qt.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`}),Ie]})}):(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:()=>Ht(e.toolCallId),disabled:$,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 disabled:cursor-not-allowed disabled:opacity-50`,"data-testid":`proposed-changes-confirm`,children:[(0,i.jsx)(r.CheckCircle2,{className:`size-3.5`}),Le]}),(0,i.jsx)(`button`,{type:`button`,onClick:Ut,disabled:$,className:`inline-flex h-7 items-center rounded-md border bg-background px-3 text-xs font-medium hover:bg-accent disabled:cursor-not-allowed disabled:opacity-50`,"data-testid":`proposed-changes-adjust`,children:Oe})]}):(0,i.jsx)(`span`,{className:`text-[11px] italic text-muted-foreground/80`,children:Re})})()]}):null]})]},e.toolCallId)};return(0,i.jsxs)(`div`,{ref:Ze,className:(0,n.cn)($e?`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:T},...Xe,children:[u&&!w&&o.length>0&&(0,i.jsx)(`div`,{className:(0,n.cn)(`flex items-center justify-end px-4 py-2`,$e?`bg-background`:`border-b bg-muted/30`),children:(0,i.jsx)(`button`,{type:`button`,onClick:u,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`,!$e&&`border-b bg-background/50`),children:P}):null,(0,i.jsxs)(vt,{className:`flex-1 min-h-0`,contextRef:X,children:[(0,i.jsxs)(yt,{className:(0,n.cn)(`space-y-4`,$e?`mx-auto w-full max-w-2xl px-4 py-8 sm:px-0`:`px-4 py-3`),children:[o.length===0?(0,i.jsxs)(bt,{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:S?(0,i.jsx)(`img`,{src:S,alt:``,className:`size-full rounded-md object-cover`}):(0,i.jsx)(r.Bot,{className:`size-4`})}),(0,i.jsxs)(`div`,{className:`w-full max-w-full space-y-1`,children:[(0,i.jsx)(`h3`,{className:`text-sm font-medium text-foreground/90 break-words`,children:Y.emptyTitle}),(0,i.jsx)(`p`,{className:`text-sm text-muted-foreground break-words`,children:Y.emptyDescription})]}),A&&A.length>0?(0,i.jsx)(`div`,{className:`flex w-full max-w-full flex-wrap justify-center gap-2`,children:A.map(e=>(0,i.jsx)(In,{className:`h-auto min-h-8 min-w-0 max-w-full whitespace-normal break-words rounded-full border-border/60 bg-background/80 px-3 py-1 text-left text-xs font-medium text-foreground/90 shadow-none hover:bg-muted/60`,suggestion:e,onClick:jt},e))}):null]}):o.map(e=>{let t=e.role===`user`,a=e.toolInvocations??[],o=e.reasoning?.trim(),s=e.sources??[],c=t?void 0:e.buildProgress,u=!t&&!a.some(e=>!!e.proposedPlan)?e.blueprintProgress:void 0,d=!t&&K===`summary`?a.filter(e=>!br(e)&&!(u&&e.toolName===`propose_blueprint`)):[],p=!t&&K===`debug`?a:!t&&K!==`debug`?a.filter(br):[],m=!t&&e.content.trim().length>0&&!Sr(e.content),h=K===`debug`&&!!o,g=!t&&!!e.streaming&&!m&&d.length===0&&p.length===0&&!h&&!c&&!u,_=d.length>0||p.length>0||!!c||!!u;return(0,i.jsx)(Tt,{from:cr(e.role),children:(0,i.jsxs)(`div`,{className:(0,n.cn)(`flex w-full gap-2.5`,y?t?`flex-row-reverse items-start`:`flex-row items-start`:`flex-col`),children:[y?(0,i.jsx)(Dr,{isUser:t,url:t?b:S,fallback:t?x:C}):null,(0,i.jsxs)(`div`,{className:(0,n.cn)(`flex min-w-0 flex-col gap-2`,y&&!t&&`flex-1`),children:[(0,i.jsxs)(Et,{children:[u?(0,i.jsx)(Hr,{progress:u,designingLabel:Y.designingPlanLabel,extendLabel:Se,waitingLabel:Y.connectionWaiting,stalledLabel:Y.connectionStalledLabel,offlineLabel:Y.connectionOfflineLabel}):null,c?(0,i.jsx)(Ur,{progress:c,appSegment:e.toolInvocations?.map(e=>e.draftReview).find(e=>e?.packageId&&e.items?.some(e=>e.type===`app`))?.packageId,onOpenBuiltApp:ae,openBuiltAppLabel:oe,onDesignBuiltApp:se,designBuiltAppLabel:ce,getArtifactAction:le,onPreviewDraftApp:ue,previewDraftLabel:de,waitingLabel:Y.connectionWaiting,stalledLabel:Y.connectionStalledLabel,offlineLabel:Y.connectionOfflineLabel}):null,!t&&K===`debug`&&o?(0,i.jsxs)($n,{isStreaming:!!e.streaming&&!e.content,className:`mb-2`,children:[(0,i.jsx)(tr,{}),(0,i.jsx)(nr,{children:o})]}):null,!t&&K===`summary`&&d.length>0?(0,i.jsx)(Wr,{groups:wr(d,J),labels:Y}):null,!t&&p.length>0?p.map(Yt):null,t?e.content?(0,i.jsx)(`div`,{className:`whitespace-pre-wrap break-words`,children:e.content}):null:g?(0,i.jsx)(kr,{}):m?(0,i.jsx)(Ft,{children:e.content}):!e.streaming&&!_&&Sr(e.content)?(0,i.jsx)(`span`,{className:`text-xs italic text-muted-foreground/70`,title:e.content,children:Y.agentActivity}):null,e.streaming&&m?(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)(l.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)(rr,{children:[(0,i.jsx)(ir,{count:s.length}),(0,i.jsx)(ar,{children:s.map((e,t)=>(0,i.jsx)(or,{href:e.url,title:e.title??e.url},e.id??e.url??t))})]}):null,v&&e.timestamp?(0,i.jsx)(`div`,{className:`text-[10px] opacity-70 mt-1`,children:e.timestamp}):null]}),!t&&!g&&m?(0,i.jsxs)(Dt,{className:`opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100`,children:[(0,i.jsx)(Ot,{label:et===e.id?Y.copied:Y.copy,tooltip:et===e.id?Y.copied:Y.copy,onClick:()=>Wt(e),children:et===e.id?(0,i.jsx)(r.Check,{className:`size-3.5`}):(0,i.jsx)(r.Copy,{className:`size-3.5`})}),f?(0,i.jsx)(Ot,{label:Y.regenerate,tooltip:Y.regenerate,onClick:f,children:(0,i.jsx)(r.RefreshCw,{className:`size-3.5`})}):null,K===`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)}),g&&!o.some(e=>e.streaming)?(0,i.jsx)(Or,{showAvatar:y,assistantAvatarUrl:S,assistantAvatarFallback:C,waitingLabel:Y.connectionWaiting,stalledLabel:Y.connectionStalledLabel,offlineLabel:Y.connectionOfflineLabel}):null]}),(0,i.jsx)(xt,{})]}),_?ht(_)&&!mt(_)?(0,i.jsx)(qr,{error:_,rateLimitedLabel:Y.sendFailedRateLimited,genericLabel:Y.sendFailedGeneric}):(0,i.jsx)(Xr,{error:_,onReload:f,onUpgrade:p}):null,h?null:(0,i.jsxs)(`div`,{ref:Mt,className:(0,n.cn)(`relative`,$e&&`mx-auto w-full max-w-2xl px-4 pb-4 sm:px-0`),children:[Ge?(0,i.jsx)(`div`,{className:`mb-1 flex`,"data-testid":`surface-context-chip`,children:(0,i.jsx)(`span`,{className:`inline-flex items-center gap-1 rounded-full border bg-muted/40 px-2 py-0.5 text-[11px] text-muted-foreground`,title:Ke,children:Ge})}):null,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)(tn,{accept:O,fileInputLabel:Y.uploadFiles,maxFileSize:k,onSubmit:At,onError:e=>{console.warn(`[plugin-chatbot] prompt-input error`,e)},children:[D?(0,i.jsx)(nn,{children:(0,i.jsx)($t,{children:e=>(0,i.jsx)(Qt,{data:e})})}):null,(0,i.jsx)(rn,{placeholder:s,disabled:m||Qe===`streaming`,onChange:I?e=>I(e.currentTarget.value):void 0}),(0,i.jsxs)(on,{children:[(0,i.jsxs)(sn,{children:[D?(0,i.jsxs)(ln,{children:[(0,i.jsx)(un,{}),(0,i.jsx)(dn,{children:(0,i.jsx)(en,{})})]}):null,M&&M.length>1?(0,i.jsx)(`select`,{"aria-label":Y.model,value:N??M[0].id,onChange:e=>ee?.(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:M.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)(r.CornerDownLeft,{className:`h-3 w-3`}),(0,i.jsx)(`span`,{className:`opacity-70`,children:Y.sendHint})]})]}),(0,i.jsx)(pn,{"aria-label":Qe===`streaming`?Y.stopResponse:Y.submit,status:Qe,disabled:m,onClick:Qe===`streaming`?d:void 0,type:Qe===`streaming`?`button`:`submit`})]})]})]})]})});Er.displayName=`ChatbotEnhanced`;function Dr({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 Or({showAvatar:e,assistantAvatarUrl:t,assistantAvatarFallback:r,waitingLabel:a,stalledLabel:o,offlineLabel:s}){return(0,i.jsx)(Tt,{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)(Dr,{isUser:!1,url:t,fallback:r}):null,(0,i.jsx)(Et,{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)(kr,{}),(0,i.jsx)(Pr,{active:!0,pending:!0,activityKey:0,waitingLabel:a,stalledLabel:o,offlineLabel:s})]})})]})})}function kr(){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 Ar(e){let t=Math.floor(e/60),n=e%60;return`${t}:${String(n).padStart(2,`0`)}`}var jr=6;function Mr(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<jr}}function Nr(){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 Pr({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}=Mr(e,t),f=Nr()?`offline`:d?a?`waiting`:`receiving`:`stalled`,p=Ar(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 Fr=[`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…`],Ir=3500;function Lr(e,t,n=Ir){if(t<=0)return-1;if(t===1)return 0;let r=Math.floor((Number.isFinite(e)&&e>0?e:0)/(n>0?n:Ir));return Math.min(r,t-1)}function Rr({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),Ir);return()=>clearInterval(t)},[a.length]);let l=Lr(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)(zr,{offlineLabel:o})]})}function zr({offlineLabel:e}){let[a,o]=t.useState(0),s=Nr();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:Ar(a)}),s?(0,i.jsxs)(`span`,{children:[`· `,e]}):null]})}var Br=[`object`,`view`,`dashboard`,`app`,`seed`];function Vr(){let{t:e}=(0,a.useObjectTranslation)();return t.useCallback(t=>{switch(t){case`object`:return e(`chatbot.build.group.object`,{defaultValue:`Objects`});case`view`:return e(`chatbot.build.group.view`,{defaultValue:`Views`});case`dashboard`:return e(`chatbot.build.group.dashboard`,{defaultValue:`Dashboards`});case`app`:return e(`chatbot.build.group.app`,{defaultValue:`App`});case`seed`:return e(`chatbot.build.group.seed`,{defaultValue:`Sample data`});default:return t}},[e])}function Hr({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=Cr(),g=c===`done`,_=m??`${c}:${f.length}`,v=g&&(l||u)||t,y=h(p??{});return(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:[g?(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:v}),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,g?null:(0,i.jsx)(`span`,{className:`ml-auto shrink-0`,children:(0,i.jsx)(Pr,{active:!0,activityKey:_,waitingLabel:a,stalledLabel:o,offlineLabel:s})})]}),!g&&(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,y.length>0?(0,i.jsx)(`span`,{className:`mt-2 block text-[11px] text-muted-foreground`,children:y.join(` · `)}):null]})}function Ur({progress:e,appSegment:o,onOpenBuiltApp:s,openBuiltAppLabel:c=`Open app`,onDesignBuiltApp:l,designBuiltAppLabel:u=`Design in Studio`,getArtifactAction:d,onPreviewDraftApp:f,previewDraftLabel:p=`Preview`,waitingLabel:m=`Waiting for server…`,stalledLabel:h=`Still working…`,offlineLabel:g=`Connection lost — reconnecting…`}){let{phase:_,appLabel:v,items:y,done:b,total:x,seq:S}=e,{t:C}=(0,a.useObjectTranslation)(),w=Vr(),T=_===`done`,E=v??C(`chatbot.build.appFallback`,{defaultValue:`your app`}),D=S??`${_}:${b}:${y.length}`,O=y.find(e=>e.type===`app`),k=x>0?Math.min(100,Math.round(b/x*100)):T?100:6,A=new Map;for(let e of y){let t=A.get(e.type)??[];t.push({name:e.name,display:e.name.replace(/_sample$/,``)}),A.set(e.type,t)}let j=[...Br.filter(e=>A.has(e)),...[...A.keys()].filter(e=>!Br.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:[T?(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:T?C(`chatbot.build.built`,{app:E,defaultValue:`Built {{app}}`}):C(`chatbot.build.building`,{app:E,defaultValue:`Building {{app}}…`})}),!T&&_===`data`?(0,i.jsx)(`span`,{className:`text-xs font-normal text-muted-foreground`,children:C(`chatbot.build.addingSampleData`,{defaultValue:`adding sample data`})}):null,T?null:(0,i.jsx)(`span`,{className:`ml-auto`,children:(0,i.jsx)(Pr,{active:!0,activityKey:D,waitingLabel:m,stalledLabel:h,offlineLabel:g})})]}),(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`,T?`bg-emerald-500`:`bg-primary`),style:{width:`${k}%`}})}),(0,i.jsx)(`ul`,{className:`space-y-1`,children:j.map(e=>{let n=A.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:w(e)}),` `,n.slice(0,6).map((n,r)=>{let a=T?d?.({type:e,name:n.name},o):null;return(0,i.jsxs)(t.Fragment,{children:[r>0?`, `:null,a?(0,i.jsx)(`button`,{type:`button`,onClick:a,className:`rounded-sm text-primary underline decoration-primary/40 underline-offset-2 hover:decoration-primary`,"data-testid":`build-artifact-link-${e}-${n.name}`,children:n.display}):n.display]},n.name)}),n.length>6?` ${C(`chatbot.build.moreArtifacts`,{n:n.length-6,defaultValue:`+{{n}} more`})}`:``]})]},e)})}),T&&O&&(l||s||f)?(0,i.jsxs)(`div`,{className:`mt-3 flex items-center gap-2`,children:[l?(0,i.jsxs)(`button`,{type:`button`,onClick:()=>l(O.name,o),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-design-app`,children:[u,(0,i.jsx)(r.ArrowRight,{className:`size-3.5`})]}):null,s?(0,i.jsxs)(`button`,{type:`button`,onClick:()=>s(O.name),className:(0,n.cn)(`inline-flex h-7 items-center gap-1.5 rounded-md px-3 text-xs font-medium`,l?`border hover:bg-muted`:`bg-primary text-primary-foreground hover:bg-primary/90`),"data-testid":`build-progress-open-app`,children:[c,(0,i.jsx)(r.ArrowRight,{className:`size-3.5`})]}):null,f?(0,i.jsxs)(`button`,{type:`button`,onClick:()=>f(O.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`}),p]}):null]}):null]})}function Wr({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)(Gr,{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)(Rr,{label:t.designingPlanLabel,hints:t.designingPlanHints,offlineLabel:t.connectionOfflineLabel}):(0,i.jsx)(zr,{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:Kr(e.state,t)})]},e.key))})})}function Gr({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 Kr(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 qr({error:e,rateLimitedLabel:n,genericLabel:a}){let o=t.useMemo(()=>_t(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 Jr(e){let{language:n}=(0,a.useObjectTranslation)(),r=(0,a.useSafeTranslate)(),i=t.useMemo(()=>mt(e),[e]);return i?{text:(n.toLowerCase().startsWith(`zh`)?i.message:i.messageEn??i.message)||r(`chatbotQuota.fallbackMessage`,`You have reached your AI quota.`),cta:i.topUp?r(`chatbotQuota.buyCredits`,`Buy a credit pack`):r(`chatbotQuota.upgradePlan`,`Upgrade plan`)}:null}function Yr({error:e,onUpgrade:t}){let n=Jr(e);return n?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(`span`,{className:`text-[11px] leading-snug text-muted-foreground`,"data-testid":`proposed-changes-quota-reason`,children:n.text}),t?(0,i.jsx)(`button`,{type:`button`,onClick:t,className:`inline-flex h-7 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`,"data-testid":`proposed-changes-quota-upgrade`,children:n.cta}):null]}):null}function Xr({error:e,onReload:n,onUpgrade:o}){let s=(0,a.useSafeTranslate)(),c=Jr(e),{summary:l,details:u}=t.useMemo(()=>ct(e),[e]),[d,f]=t.useState(!1);if(c){let{text:e,cta:t}=c,n=s(`chatbotQuota.title`,`Upgrade needed`);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:n}),(0,i.jsx)(`div`,{className:`mt-0.5 break-words leading-snug text-muted-foreground`,children:e})]}),o?(0,i.jsx)(`button`,{type:`button`,onClick:o,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:t}):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:s(`chatbotError.title`,`Response failed`)}),(0,i.jsx)(`div`,{className:`mt-0.5 break-words leading-snug text-muted-foreground`,children:l||s(`chatbotError.fallbackDetail`,`Something went wrong. Please try again.`)})]}),(0,i.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[u?(0,i.jsx)(`button`,{type:`button`,onClick:()=>f(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":d,children:d?s(`chatbotError.hide`,`Hide`):s(`chatbotError.details`,`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`}),s(`chatbotError.retry`,`Retry`)]}):null]})]}),d&&u?(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:u}):null]})})}function Zr({output:e,errorText:t}){return t?(0,i.jsx)(qn,{output:void 0,errorText:t}):e==null||e===``?null:typeof e==`string`&&!lr(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)(Ft,{children:e})})]}):(0,i.jsx)(qn,{output:e,errorText:void 0})}function Qr({floatingConfig:e,headerExtra:r,headerActions:a,...o}){let{position:s=`bottom-right`,defaultOpen:l=!1,panelWidth:u=400,panelHeight:d=520,title:f=`Chat`,triggerSize:p=56}=e??{},[m,h]=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)),h(e),()=>{e&&e.parentNode&&!e.hasChildNodes()&&e.parentNode.removeChild(e)}},[]);let g=(0,i.jsxs)(K,{defaultOpen:l,children:[(0,i.jsx)(et,{position:s,size:p}),(0,i.jsx)(Y,{title:f,position:s,width:u,height:d,headerExtra:r,headerActions:a,children:(0,i.jsx)(Er,{...o,maxHeight:`100%`,className:(0,n.cn)(`h-full border-0 rounded-none`,o.className)})})]});return m?c.createPortal(g,m):g}v.ComponentRegistry.register(`chatbot`,({schema:e,className:n,disabled:r,...a})=>{let{messages:o,isLoading:s,sendMessage:c}=De({api:e.api,initialMessages:e.messages,conversationId:e.conversationId,systemPrompt:e.systemPrompt,model:e.model,streamingEnabled:e.streamingEnabled,headers:e.headers,body:e.requestBody,onError:e.onError,showTimestamp:e.showTimestamp,autoResponse:e.autoResponse,autoResponseText:e.autoResponseText,autoResponseDelay:e.autoResponseDelay,onSend:e.onSend}),l=e=>{c(e)},u=(0,t.useMemo)(()=>G(o),[o]);return(0,i.jsx)(xi,{...(0,v.toDomProps)(a),messages:u,placeholder:e.placeholder,onSendMessage:l,disabled:r||s,showTimestamp:e.showTimestamp,userAvatarUrl:e.userAvatarUrl,userAvatarFallback:e.userAvatarFallback,assistantAvatarUrl:e.assistantAvatarUrl,assistantAvatarFallback:e.assistantAvatarFallback,maxHeight:e.maxHeight,className:n})},{namespace:`plugin-chatbot`,label:`Chatbot`,inputs:[{name:`messages`,type:`array`,description:`Array of message objects with id, role, content, and optional timestamp`},{name:`placeholder`,type:`string`},{name:`showTimestamp`,type:`boolean`},{name:`disabled`,type:`boolean`},{name:`userAvatarUrl`,type:`string`,description:`URL of the user avatar image`},{name:`userAvatarFallback`,type:`string`,description:`Fallback text shown when user avatar image is not available`},{name:`assistantAvatarUrl`,type:`string`,description:`URL of the assistant avatar image`},{name:`assistantAvatarFallback`,type:`string`,description:`Fallback text shown when assistant avatar image is not available`},{name:`maxHeight`,type:`string`},{name:`api`,type:`string`,description:`Backend SSE endpoint (e.g., /api/v1/ai/chat). When set, enables streaming AI mode.`},{name:`conversationId`,type:`string`,description:`Multi-turn conversation identifier`},{name:`systemPrompt`,type:`string`,description:`System prompt to configure assistant behavior`},{name:`model`,type:`string`,description:`AI model identifier (e.g., gpt-4o)`},{name:`streamingEnabled`,type:`boolean`},{name:`autoResponse`,type:`boolean`,description:`Automatically send a response after user message (for demo purposes, ignored when API is set)`},{name:`autoResponseText`,type:`string`},{name:`autoResponseDelay`,type:`number`},{name:`className`,type:`string`}],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`}}),v.ComponentRegistry.register(`chatbot-enhanced`,({schema:e,className:n,disabled:r,...a})=>{let{messages:o,isLoading:s,error:c,sendMessage:l,stop:u,reload:d,clear:f,isApiMode:p}=De({api:e.api,initialMessages:e.messages,conversationId:e.conversationId,systemPrompt:e.systemPrompt,model:e.model,streamingEnabled:e.streamingEnabled,headers:e.headers,body:e.requestBody,onError:e.onError,showTimestamp:e.showTimestamp,autoResponse:e.autoResponse,autoResponseText:e.autoResponseText,autoResponseDelay:e.autoResponseDelay,onSend:e.onSend}),m=(e,t)=>{l(e,t)},h=()=>{f(),e.onClear?.()},g=(0,t.useMemo)(()=>G(o),[o]);return(0,i.jsx)(Er,{...(0,v.toDomProps)(a),messages:g,placeholder:e.placeholder,onSendMessage:m,onClear:h,onStop:p&&s?u:void 0,onReload:p?d:void 0,disabled:r,isLoading:s,error:c,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,surface:e.surface,className:n})},{namespace:`plugin-chatbot`,label:`Chatbot (Enhanced)`,inputs:[{name:`messages`,type:`array`},{name:`placeholder`,type:`string`},{name:`showTimestamp`,type:`boolean`},{name:`disabled`,type:`boolean`},{name:`enableMarkdown`,type:`boolean`},{name:`enableFileUpload`,type:`boolean`},{name:`processVisibility`,type:`enum`},{name:`surface`,type:`enum`,description:`'card' bordered panel, or 'plain' frameless full-page workspace`},{name:`userAvatarUrl`,type:`string`},{name:`userAvatarFallback`,type:`string`},{name:`assistantAvatarUrl`,type:`string`},{name:`assistantAvatarFallback`,type:`string`},{name:`maxHeight`,type:`string`},{name:`api`,type:`string`,description:`Backend SSE endpoint for streaming AI mode`},{name:`conversationId`,type:`string`},{name:`systemPrompt`,type:`string`},{name:`model`,type:`string`},{name:`streamingEnabled`,type:`boolean`},{name:`autoResponse`,type:`boolean`},{name:`autoResponseText`,type:`string`},{name:`autoResponseDelay`,type:`number`},{name:`className`,type:`string`}],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`}}),v.ComponentRegistry.register(`chatbot-floating`,({schema:e,className:n,disabled:r,...a})=>{let{messages:o,isLoading:s,error:c,sendMessage:l,stop:u,reload:d,clear:f,isApiMode:p}=De({api:e.api,initialMessages:e.messages,conversationId:e.conversationId,systemPrompt:e.systemPrompt,model:e.model,streamingEnabled:e.streamingEnabled,headers:e.headers,body:e.requestBody,onError:e.onError,showTimestamp:e.showTimestamp,autoResponse:e.autoResponse,autoResponseText:e.autoResponseText,autoResponseDelay:e.autoResponseDelay,onSend:e.onSend}),m=(e,t)=>{l(e,t)},h=()=>{f(),e.onClear?.()},g=(0,t.useMemo)(()=>G(o),[o]);return(0,i.jsx)(Qr,{...(0,v.toDomProps)(a),floatingConfig:e.floatingConfig,messages:g,placeholder:e.placeholder,onSendMessage:m,onClear:h,onStop:p&&s?u:void 0,onReload:p?d:void 0,disabled:r,isLoading:s,error:c,showTimestamp:e.showTimestamp,userAvatarUrl:e.userAvatarUrl,userAvatarFallback:e.userAvatarFallback,assistantAvatarUrl:e.assistantAvatarUrl,assistantAvatarFallback:e.assistantAvatarFallback,enableMarkdown:e.enableMarkdown??!0,enableFileUpload:e.enableFileUpload??!1,className:n})},{namespace:`plugin-chatbot`,label:`Chatbot (Floating)`,inputs:[{name:`floatingConfig.position`,type:`string`,description:`bottom-right or bottom-left`},{name:`floatingConfig.defaultOpen`,type:`boolean`},{name:`floatingConfig.panelWidth`,type:`number`},{name:`floatingConfig.panelHeight`,type:`number`},{name:`floatingConfig.title`,type:`string`},{name:`floatingConfig.triggerSize`,type:`number`},{name:`messages`,type:`array`},{name:`placeholder`,type:`string`},{name:`enableMarkdown`,type:`boolean`},{name:`enableFileUpload`,type:`boolean`},{name:`api`,type:`string`,description:`Backend SSE endpoint for streaming AI mode`},{name:`conversationId`,type:`string`},{name:`systemPrompt`,type:`string`},{name:`model`,type:`string`},{name:`streamingEnabled`,type:`boolean`},{name:`autoResponse`,type:`boolean`},{name:`autoResponseText`,type:`string`},{name:`autoResponseDelay`,type:`number`},{name:`className`,type:`string`}],defaultProps:{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 $r=({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`})})})]}),ei=({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)($r,{size:t})}),ti=T({CodeBlock:()=>Bn,CodeBlockCopyButton:()=>Vn,Conversation:()=>vt,ConversationContent:()=>yt,ConversationEmptyState:()=>bt,ConversationScrollButton:()=>xt,Loader:()=>ei,Message:()=>Tt,MessageAction:()=>Ot,MessageActions:()=>Dt,MessageAttachment:()=>Q,MessageAttachments:()=>It,MessageBranch:()=>Z,MessageBranchContent:()=>At,MessageBranchNext:()=>Nt,MessageBranchPage:()=>Pt,MessageBranchPrevious:()=>Mt,MessageBranchSelector:()=>jt,MessageContent:()=>Et,MessageResponse:()=>Ft,MessageToolbar:()=>Lt,PromptInput:()=>tn,PromptInputActionAddAttachments:()=>en,PromptInputActionMenu:()=>ln,PromptInputActionMenuContent:()=>dn,PromptInputActionMenuItem:()=>fn,PromptInputActionMenuTrigger:()=>un,PromptInputAttachment:()=>Qt,PromptInputAttachments:()=>$t,PromptInputBody:()=>nn,PromptInputButton:()=>cn,PromptInputCommand:()=>On,PromptInputCommandEmpty:()=>jn,PromptInputCommandGroup:()=>Mn,PromptInputCommandInput:()=>kn,PromptInputCommandItem:()=>Nn,PromptInputCommandList:()=>An,PromptInputCommandSeparator:()=>Pn,PromptInputFooter:()=>on,PromptInputHeader:()=>an,PromptInputHoverCard:()=>bn,PromptInputHoverCardContent:()=>Sn,PromptInputHoverCardTrigger:()=>xn,PromptInputProvider:()=>Yt,PromptInputSelect:()=>hn,PromptInputSelectContent:()=>_n,PromptInputSelectItem:()=>vn,PromptInputSelectTrigger:()=>gn,PromptInputSelectValue:()=>yn,PromptInputSpeechButton:()=>mn,PromptInputSubmit:()=>pn,PromptInputTab:()=>wn,PromptInputTabBody:()=>En,PromptInputTabItem:()=>Dn,PromptInputTabLabel:()=>Tn,PromptInputTabsList:()=>Cn,PromptInputTextarea:()=>rn,PromptInputTools:()=>sn,Reasoning:()=>$n,ReasoningContent:()=>nr,ReasoningTrigger:()=>tr,Shimmer:()=>Jn,Source:()=>or,Sources:()=>rr,SourcesContent:()=>ar,SourcesTrigger:()=>ir,Suggestion:()=>In,Suggestions:()=>Fn,Tool:()=>Hn,ToolContent:()=>Gn,ToolHeader:()=>Wn,ToolInput:()=>Kn,ToolOutput:()=>qn,highlightCode:()=>zn,usePromptInputAttachments:()=>Zt,usePromptInputController:()=>Kt,useProviderAttachments:()=>Jt,useReasoning:()=>Xn}),ni=`/api/v1/ai`;function ri(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 ii(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 ai(e={}){let{apiBase:n=ni,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 ii(ri(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=ri(t,`/pending-actions/${encodeURIComponent(e)}/approve`);try{return await ii(r,{method:`POST`,body:`{}`},n)}finally{v()}},[v]),b=t.useCallback(async(e,t)=>{let{apiBase:n,headers:r}=_.current,i=ri(n,`/pending-actions/${encodeURIComponent(e)}/reject`);try{return await ii(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 oi=(0,a.createSafeTranslation)({"aiApprovals.title":`AI Approvals`,"aiApprovals.description":`Actions an AI agent proposed that need a human review before execution.`,"aiApprovals.tabPending":`Pending`,"aiApprovals.tabDecided":`Decided`,"aiApprovals.tabAll":`All`,"aiApprovals.statusPending":`Pending`,"aiApprovals.statusApproved":`Approved`,"aiApprovals.statusExecuted":`Executed`,"aiApprovals.statusFailed":`Failed`,"aiApprovals.statusRejected":`Rejected`,"aiApprovals.colTool":`Tool`,"aiApprovals.colAction":`Action`,"aiApprovals.colObject":`Object`,"aiApprovals.colStatus":`Status`,"aiApprovals.colProposed":`Proposed`,"aiApprovals.colDecision":`Decision`,"aiApprovals.emptyTitle":`No actions waiting`,"aiApprovals.emptyDescription":`When the AI proposes a sensitive action it will appear here for review.`,"aiApprovals.view":`View`,"aiApprovals.approve":`Approve`,"aiApprovals.reject":`Reject`,"aiApprovals.working":`Working…`,"aiApprovals.approveAndExecute":`Approve & Execute`,"aiApprovals.outcomeApprove":`Approve for {{id}}: {{message}}`,"aiApprovals.outcomeReject":`Reject for {{id}}: {{message}}`,"aiApprovals.outcomeExecuteFailed":`Action failed during execution`,"aiApprovals.drawerFallbackTitle":`Pending action`,"aiApprovals.drawerSubtitle":`Tool {{tool}} on {{object}}`,"aiApprovals.fieldProposedBy":`Proposed by`,"aiApprovals.fieldDecidedBy":`Decided by`,"aiApprovals.fieldConversation":`Conversation`,"aiApprovals.fieldToolInput":`Tool input`,"aiApprovals.fieldResult":`Result`,"aiApprovals.fieldError":`Error`,"aiApprovals.fieldRejectionReason":`Rejection reason`,"aiApprovals.rejectTitle":`Reject this action?`,"aiApprovals.rejectBody":`The reason is shown back to the AI so it can adjust its next response.`,"aiApprovals.rejectPlaceholder":`Optional reason (e.g. 'Wrong record id — please confirm with the user first.')`,"detail.justNow":`just now`,"detail.minutesAgo":`{{count}}m ago`,"detail.hoursAgo":`{{count}}h ago`,"detail.daysAgo":`{{count}}d ago`,"common.refresh":`Refresh`,"common.cancel":`Cancel`,"common.loading":`Loading…`,"common.ok":`OK`},`aiApprovals.title`),si={pending:`secondary`,approved:`default`,executed:`default`,failed:`destructive`,rejected:`outline`};function ci(e,t){switch(e){case`pending`:return t(`aiApprovals.statusPending`);case`approved`:return t(`aiApprovals.statusApproved`);case`executed`:return t(`aiApprovals.statusExecuted`);case`failed`:return t(`aiApprovals.statusFailed`);case`rejected`:return t(`aiApprovals.statusRejected`);default:return null}}function li({status:e,t}){let r=ci(e,t);return r===null?(0,i.jsx)(n.Badge,{variant:`outline`,children:e}):(0,i.jsx)(n.Badge,{variant:si[e]??`outline`,children:r})}function ui(e,t,n){if(!e)return`—`;let r=Date.parse(e);if(Number.isNaN(r))return e;let i=Date.now()-r,a=Math.round(i/1e3);if(a<45)return t(`detail.justNow`);let o=Math.round(a/60);if(o<60)return t(`detail.minutesAgo`,{count:o});let s=Math.round(o/60);if(s<24)return t(`detail.hoursAgo`,{count:s});let c=Math.round(s/24);if(c<30)return t(`detail.daysAgo`,{count:c});try{return new Date(e).toLocaleDateString(n)}catch{return e}}function di(e){if(!e)return null;try{return JSON.parse(e)}catch{return e}}function fi({value:e,max:t=320}){let r=typeof e==`string`?e:JSON.stringify(e,null,2);return r==null||r===``?(0,i.jsx)(n.EmptyValue,{className:`text-xs`}):(0,i.jsx)(`pre`,{className:`bg-muted/40 rounded text-xs p-2 overflow-auto whitespace-pre-wrap break-all`,style:{maxHeight:t},children:r})}function pi(e){switch(e){case`pending`:return`pending`;case`all`:return`all`;case`decided`:return`all`}}function mi({apiBase:e,headers:o,pollInterval:s=5e3,conversationId:c,variant:l=`card`,title:u,description:d,className:f}){let{t:p}=oi(),m=(0,a.useDisplayLocale)(),h=u??p(`aiApprovals.title`),g=d??p(`aiApprovals.description`),[_,v]=t.useState(`pending`),[y,b]=t.useState(null),[x,S]=t.useState(null),[C,w]=t.useState(``),[T,E]=t.useState(null),[D,O]=t.useState(null),[k,A]=t.useState(null),{items:j,isLoading:M,error:N,refresh:ee,approve:P,reject:F}=ai({apiBase:e,headers:o,pollInterval:s,conversationId:c,status:pi(_)}),I=t.useMemo(()=>_===`decided`?j.filter(e=>e.status!==`pending`):j,[j,_]),L=t.useMemo(()=>y?j.find(e=>e.id===y)??null:null,[y,j]),R=t.useCallback(async e=>{E(e),O(null);try{let t=await P(e),n=t.status===`executed`;A({id:e,kind:`approve`,ok:n,message:n?p(`aiApprovals.statusExecuted`):t.error??p(`aiApprovals.outcomeExecuteFailed`)})}catch(t){let n=t instanceof Error?t.message:String(t);O(n),A({id:e,kind:`approve`,ok:!1,message:n})}finally{E(null)}},[P,p]),te=t.useCallback(async(e,t)=>{E(e),O(null);try{await F(e,t.trim()||void 0),A({id:e,kind:`reject`,ok:!0,message:p(`aiApprovals.statusRejected`)}),S(null),w(``)}catch(t){let n=t instanceof Error?t.message:String(t);O(n),A({id:e,kind:`reject`,ok:!1,message:n})}finally{E(null)}},[F,p]),z=(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:_,onValueChange:e=>v(e),children:(0,i.jsxs)(n.TabsList,{children:[(0,i.jsx)(n.TabsTrigger,{value:`pending`,children:p(`aiApprovals.tabPending`)}),(0,i.jsx)(n.TabsTrigger,{value:`decided`,children:p(`aiApprovals.tabDecided`)}),(0,i.jsx)(n.TabsTrigger,{value:`all`,children:p(`aiApprovals.tabAll`)})]})}),(0,i.jsxs)(n.Button,{variant:`outline`,size:`sm`,onClick:()=>void ee(),disabled:M,"data-testid":`ai-inbox-refresh`,children:[(0,i.jsx)(r.RefreshCw,{className:`h-3.5 w-3.5 mr-1.5 ${M?`animate-spin`:``}`}),p(`common.refresh`)]})]}),N?(0,i.jsxs)(n.Alert,{variant:`destructive`,children:[(0,i.jsx)(r.AlertCircle,{className:`h-4 w-4`}),(0,i.jsx)(n.AlertDescription,{children:N.message})]}):null,D?(0,i.jsxs)(n.Alert,{variant:`destructive`,children:[(0,i.jsx)(r.AlertCircle,{className:`h-4 w-4`}),(0,i.jsx)(n.AlertDescription,{children:D})]}):null,k&&!D?(0,i.jsxs)(n.Alert,{variant:k.ok?`default`:`destructive`,children:[k.ok?(0,i.jsx)(r.CheckCircle2,{className:`h-4 w-4`}):(0,i.jsx)(r.XCircle,{className:`h-4 w-4`}),(0,i.jsx)(n.AlertDescription,{children:p(k.kind===`approve`?`aiApprovals.outcomeApprove`:`aiApprovals.outcomeReject`,{id:`${k.id.slice(0,8)}…`,message:k.message??(k.ok?p(`common.ok`):p(`aiApprovals.statusFailed`))})})]}):null,M&&I.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`})]}):I.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:p(`aiApprovals.emptyTitle`)}),(0,i.jsx)(n.EmptyDescription,{children:p(`aiApprovals.emptyDescription`)})]})}):(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:p(`aiApprovals.colTool`)}),(0,i.jsx)(n.TableHead,{className:`w-[140px]`,children:p(`aiApprovals.colAction`)}),(0,i.jsx)(n.TableHead,{className:`w-[120px]`,children:p(`aiApprovals.colObject`)}),(0,i.jsx)(n.TableHead,{className:`w-[110px]`,children:p(`aiApprovals.colStatus`)}),(0,i.jsx)(n.TableHead,{className:`w-[110px]`,children:p(`aiApprovals.colProposed`)}),(0,i.jsx)(n.TableHead,{className:`w-[260px] text-right`,children:p(`aiApprovals.colDecision`)})]})}),(0,i.jsx)(n.TableBody,{children:I.map(e=>{let t=e.status===`pending`,a=T===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)(li,{status:e.status,t:p})}),(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`}),` `,ui(e.proposed_at,p,m)]})}),(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:()=>b(e.id),"data-testid":`ai-inbox-view-${e.id}`,children:[(0,i.jsx)(r.Eye,{className:`h-3.5 w-3.5 mr-1`}),` `,p(`aiApprovals.view`)]}),t?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)(n.Button,{size:`sm`,variant:`default`,disabled:a,onClick:()=>void R(e.id),"data-testid":`ai-inbox-approve-${e.id}`,children:[(0,i.jsx)(r.CheckCircle2,{className:`h-3.5 w-3.5 mr-1`}),p(a?`aiApprovals.working`:`aiApprovals.approve`)]}),(0,i.jsxs)(n.Button,{size:`sm`,variant:`destructive`,disabled:a,onClick:()=>{S(e.id),w(``)},"data-testid":`ai-inbox-reject-${e.id}`,children:[(0,i.jsx)(r.XCircle,{className:`h-3.5 w-3.5 mr-1`}),p(`aiApprovals.reject`)]})]}):null]})})]},e.id)})})]})})]});return(0,i.jsxs)(i.Fragment,{children:[l===`card`?(0,i.jsxs)(n.Card,{className:f,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`}),` `,h]}),g?(0,i.jsx)(n.CardDescription,{children:g}):null]}),(0,i.jsx)(n.CardContent,{children:z})]}):(0,i.jsx)(`div`,{className:f,children:z}),(0,i.jsx)(n.Sheet,{open:!!y,onOpenChange:e=>{e||b(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`}),L?L.action_name:p(`aiApprovals.drawerFallbackTitle`)]}),(0,i.jsx)(n.SheetDescription,{children:L?p(`aiApprovals.drawerSubtitle`,{tool:L.tool_name,object:L.object_name}):p(`common.loading`)})]}),L?(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:p(`aiApprovals.colStatus`)}),(0,i.jsx)(`div`,{className:`mt-1`,children:(0,i.jsx)(li,{status:L.status,t:p})})]}),(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs text-muted-foreground`,children:p(`aiApprovals.colProposed`)}),(0,i.jsx)(`div`,{className:`mt-1 text-xs`,children:ui(L.proposed_at,p,m)})]}),(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs text-muted-foreground`,children:p(`aiApprovals.fieldProposedBy`)}),(0,i.jsx)(`div`,{className:`mt-1 text-xs font-mono break-all`,children:L.proposed_by??(0,i.jsx)(n.EmptyValue,{})})]}),(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs text-muted-foreground`,children:p(`aiApprovals.fieldDecidedBy`)}),(0,i.jsx)(`div`,{className:`mt-1 text-xs font-mono break-all`,children:L.decided_by??(0,i.jsx)(n.EmptyValue,{})})]}),L.conversation_id?(0,i.jsxs)(`div`,{className:`col-span-2`,children:[(0,i.jsx)(n.Label,{className:`text-xs text-muted-foreground`,children:p(`aiApprovals.fieldConversation`)}),(0,i.jsx)(`div`,{className:`mt-1 text-xs font-mono break-all`,children:L.conversation_id})]}):null]}),(0,i.jsx)(n.Separator,{}),(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs`,children:p(`aiApprovals.fieldToolInput`)}),(0,i.jsx)(`div`,{className:`mt-1.5`,children:(0,i.jsx)(fi,{value:di(L.tool_input)})})]}),L.result?(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs`,children:p(`aiApprovals.fieldResult`)}),(0,i.jsx)(`div`,{className:`mt-1.5`,children:(0,i.jsx)(fi,{value:di(L.result)})})]}):null,L.error?(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs text-destructive`,children:p(`aiApprovals.fieldError`)}),(0,i.jsx)(`div`,{className:`mt-1.5`,children:(0,i.jsx)(fi,{value:L.error})})]}):null,L.rejection_reason?(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs`,children:p(`aiApprovals.fieldRejectionReason`)}),(0,i.jsx)(`div`,{className:`mt-1.5 text-sm`,children:L.rejection_reason})]}):null,L.status===`pending`?(0,i.jsxs)(`div`,{className:`pt-2 flex gap-2`,children:[(0,i.jsxs)(n.Button,{size:`sm`,onClick:()=>void R(L.id),disabled:T===L.id,children:[(0,i.jsx)(r.CheckCircle2,{className:`h-3.5 w-3.5 mr-1`}),p(`aiApprovals.approveAndExecute`)]}),(0,i.jsxs)(n.Button,{size:`sm`,variant:`destructive`,onClick:()=>{S(L.id),w(``)},disabled:T===L.id,children:[(0,i.jsx)(r.XCircle,{className:`h-3.5 w-3.5 mr-1`}),p(`aiApprovals.reject`)]})]}):null]}):null]})}),(0,i.jsx)(n.Sheet,{open:!!x,onOpenChange:e=>{e||(S(null),w(``))},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:p(`aiApprovals.rejectTitle`)}),(0,i.jsx)(n.SheetDescription,{children:p(`aiApprovals.rejectBody`)})]}),(0,i.jsxs)(`div`,{className:`px-4 mt-3 space-y-3`,children:[(0,i.jsx)(n.Textarea,{value:C,onChange:e=>w(e.target.value),placeholder:p(`aiApprovals.rejectPlaceholder`),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:()=>{S(null),w(``)},children:p(`common.cancel`)}),(0,i.jsxs)(n.Button,{variant:`destructive`,size:`sm`,onClick:()=>x&&void te(x,C),disabled:!x||T===x,"data-testid":`ai-inbox-reject-confirm`,children:[(0,i.jsx)(r.XCircle,{className:`h-3.5 w-3.5 mr-1`}),p(`aiApprovals.reject`)]})]})]})]})})]})}function hi(e){return!e||e.length===0?`/api/v1/ai`:e.endsWith(`/`)?e.slice(0,-1):e}function gi(e,t){let n={...e??{}};return t&&(n[`Content-Type`]=`application/json`),n}async function _i(e){let t=await e.text();if(!t)return null;try{return JSON.parse(t)}catch{return{raw:t}}}function vi(e){let{messages:n,apiBase:r,headers:i,onDecided:a,continueConversation:o}=e,s=hi(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:gi(i,!0),body:c}),f=await _i(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;else if(p===`rejected`)m(e,{state:`success`,message:n?`Rejected: ${n}`:`Rejected.`}),h=!0;else if(p===`failed`){let t=f.error??`Action approved but execution failed.`;m(e,{state:`error`,message:t})}else m(e,{state:`success`,message:`Status: ${p}`}),h=!0;if(a?.(e,f),h&&o){let r=yi({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){let n=t instanceof Error?t.message:String(t);m(e,{state:`error`,message:n})}finally{--d.current,d.current<=0&&(d.current=0,p(!1))}},[s,i,c,a,o,m]),isDeciding:f}}function yi(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:bi(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:bi(JSON.stringify(e??{}),400)}. Apologize concisely and offer alternatives.`}}function bi(e,t){return e.length<=t?e:`${e.slice(0,t-1)}…`}var xi=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)(Si,{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`})})]})})]})});xi.displayName=`Chatbot`;var Si=({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})]})]})},Ci=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`})]})})]}));Ci.displayName=`TypingIndicator`,e.AGENT_ALIAS_GROUPS=Oe,Object.defineProperty(e,"AIElements",{enumerable:!0,get:function(){return ti}}),e.AI_USAGE_REFRESH_EVENT=me,e.AiPendingActionsInbox=mi,e.Chatbot=xi,e.ChatbotEnhanced=Er,e.FloatingChatbot=Qr,e.FloatingChatbotPanel=Y,e.FloatingChatbotProvider=K,e.FloatingChatbotTrigger=et,e.PLATFORM_DEFAULT_AGENT=Le,e.TypingIndicator=Ci,e.agentAliasGroup=ke,e.agentHasCapability=Ie,e.agentRouteName=Ae,e.authoredToRuntimeMessage=W,e.buildProgressFromDraftReview=ie,e.detectAuthoringVerdict=z,e.detectBuilderHandoff=I,e.detectBuiltAppPackage=B,e.detectDraftResult=ne,e.detectPendingApproval=ee,e.detectProposedChanges=R,e.detectProposedPlan=F,e.detectRecordHandoff=L,e.detectReplayOutcome=te,e.emitAiUsageRefresh=he,e.humanizeToolName=ot,e.isAskAgent=Pe,e.isBuildAgent=Ne,e.isBuiltinAgentName=Me,e.publishHealthFromResponse=sr,e.resolveAgentParam=je,e.resolveDefaultAgentName=Re,e.summarizeChatError=ct,e.toRuntimeMessages=G,e.toRuntimeRole=U,e.toRuntimeTimestamp=H,e.toRuntimeToolInvocation=pe,e.toRuntimeToolState=fe,e.uiMessageToChatMessage=ue,e.uiMessagesToChatMessages=de,e.unwrapToolResult=st,e.useAgents=Ge,e.useAiModels=qe,e.useFloatingChatbot=Ye,e.useHitlInChat=vi,e.useObjectChat=De,e.usePendingActions=ai});
|
|
4
|
+
`)[0]:void 0,r=n.publishOutcome;return{kind:`failed`,...typeof r==`string`&&r?{outcome:r}:{},...t?{error:t}:{},...a}}let o=W(n.draftState),s=oe(n.existingRows),c=se(n.appliedCard),l=ce(n);return{kind:`drafted`,...a,...l.length>0?{items:l}:{},...o?{draftState:o}:{},...s?{existingRows:s}:{},...c?{appliedCard:c}:{}}}function ue(e){let t=N(e);if(!t)return;if(t.status===`published`)return{kind:`published`};if(t.status!==`drafted`)return;let n=t.packageId,r=typeof n==`string`&&n?{packageId:n}:{};return t.publishFailed===!0?{kind:`failed`,...r}:{kind:`drafted`,...r}}function de(e){let t=N(e);if(!t||t.kind===`edit`||t.status!==`drafted`&&t.status!==`published`)return;let n=t.packageId;if(typeof n!=`string`||!n)return;let r=t.drafted;return Array.isArray(r)&&r.some(e=>e&&typeof e==`object`&&e.type===`app`)?n:void 0}function fe(e){let t=N(e);if(!t||t.status!==`drafted`)return;let n=ce(t);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}:{},...t.kind===`edit`?{kind:`edit`}:{}}}function pe(e){return e.replace(/[._-]+/g,` `).replace(/\s+/g,` `).trim().replace(/\b\w/g,e=>e.toUpperCase())}function me(e){if(!e||!Array.isArray(e.items)||e.items.length===0||e.kind===`edit`)return;let t=e.items.find(e=>e.type===`app`);if(t)return{phase:`done`,appLabel:pe(t.name),items:e.items,done:e.items.length,total:e.items.length}}function he(e){let{approval:t}=e;if(typeof t!=`object`||!t)return;let n=t,{id:r}=n;if(typeof r==`string`&&r.length!==0)return{id:r,approved:typeof n.approved==`boolean`?n.approved:void 0,reason:typeof n.reason==`string`?n.reason:void 0,isAutomatic:typeof n.isAutomatic==`boolean`?n.isAutomatic:void 0,signature:typeof n.signature==`string`?n.signature:void 0}}function ge(e,t={}){return e.filter(e=>e.type===`dynamic-tool`||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.toolCallId??e.id??`${e.type??`tool`}-${Math.random().toString(36).slice(2,8)}`,i=e.output??e.result,a=P(i),o=le(r,i),s=o?void 0:fe(i),c=L(i),l=U(i),u=re(i),d=ie(i),f=A(e.state)?e.state:void 0,p=(f===`input-available`||f===`input-streaming`)&&(i!==void 0||!t.liveTail)?`output-available`:f,m=a&&p!==`output-error`?`approval-requested`:p;return{toolCallId:r,toolName:n,args:e.input??e.args,result:i,errorText:e.errorText,state:m,approval:he(e),pendingActionId:a?.pendingActionId,draftReview:s,proposedPlan:c,proposedChanges:l,builderHandoff:u,recordHandoff:d,replayOutcome:o}})}function _e(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}var ve=`data-build-progress`,ye={structure:!0,data:!0,verify:!0,done:!0},be=`build-verify`;function xe(e){return typeof e==`string`&&Object.prototype.hasOwnProperty.call(ye,e)?e:`unknown`}function Se(e,t){let n=e.filter(e=>e.type===ve&&t(e.id)).pop()?.data;return n&&typeof n==`object`?n:void 0}function Ce(e){let t=Se(e,e=>e===be);if(t)return{phase:xe(t.phase),...typeof t.hop==`number`?{hop:t.hop}:{},...typeof t.tool==`string`?{tool:t.tool}:{}}}function we(e){let t=Se(e,e=>e!==be);if(!t)return;let n=Array.isArray(t.items)?t.items.filter(e=>typeof e?.type==`string`&&typeof e?.name==`string`).map(e=>({type:e.type,name:e.name})):[];return{phase:xe(t.phase),...typeof t.appLabel==`string`?{appLabel:t.appLabel}:{},items:n,done:typeof t.done==`number`?t.done:n.length,total:typeof t.total==`number`?t.total:n.length,...typeof t.seq==`number`?{seq:t.seq}:{}}}function Te(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 Ee(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 De(e,t={}){let n=Array.isArray(e.parts)?e.parts:[],r=ge(n,{liveTail:t.streaming}),i=Array.isArray(e.toolInvocations)?e.toolInvocations:[],a=r.length>0?r:i,o=we(n)??a.map(e=>me(e.draftReview)).find(e=>!!e),s=Ce(n),c=o&&s?{...o,verify:s}:o;return{id:e.id??`msg-${Math.random().toString(36).slice(2,8)}`,role:e.role??`assistant`,content:j(e,n),reasoning:M(n),toolInvocations:a,sources:_e(n),buildProgress:c,blueprintProgress:Te(n),charts:Ee(n),streaming:t.streaming}}function Oe(e,t={}){if(!Array.isArray(e)||e.length===0)return[];let n=e.length-1;return e.map((e,r)=>De(e,{streaming:!!t.isStreaming&&r===n&&e.role===`assistant`}))}function ke(e){return typeof e==`string`?e:e instanceof Date?e.toISOString():void 0}function Ae(e){return e===`tool`?`assistant`:e}function je(e){switch(e){case`partial-call`:return`input-streaming`;case`call`:return`input-available`;case`result`:return`output-available`;default:return e}}function Me(e){let{state:t,...n}=e;return{...n,state:je(t)}}function Ne(e){let{role:t,timestamp:n,toolInvocations:r,...i}=e;return{...i,role:Ae(t),timestamp:ke(n),toolInvocations:r?.map(Me)}}function Pe(e){return(e??[]).map(Ne)}var Fe=`objectui:ai-usage-refresh`;function Ie(){if(!(typeof window>`u`||typeof window.dispatchEvent!=`function`))try{window.dispatchEvent(new CustomEvent(Fe))}catch{}}async function Le(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 Re(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 ze(e,t){let n=e.context??{};return{...e,context:{...n,parentConversationId:t}}}function Be(e){return(e??[]).map((e,t)=>({id:e.id||`msg-${t}`,role:e.role||`user`,content:e.content||``,timestamp:ke(e.timestamp),metadata:e.metadata,streaming:e.streaming,toolInvocations:e.toolInvocations}))}function Ve(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&(t.role===`user`||t.role===`assistant`||t.role===`system`)&&Array.isArray(t.parts)}function He(e){if(!Array.isArray(e))throw TypeError(`useObjectChat: setMessages expects an array of chat messages, received ${typeof e}.`);let t=[];return e.forEach((e,n)=>{if(!Ve(e))throw TypeError(`useObjectChat: setMessages received a value at index ${n} that is not a chat message (it needs a string \`id\`, a 'user' | 'assistant' | 'system' \`role\` and a \`parts\` array). Nothing was written; the thread is unchanged.`);t.push(e)}),t}var Ue=new Set;function We(e){e.pendingActionId||Ge(e.state??`approval`,e.toolName)}function Ge(e,t){let n=`${e}:${t}`;Ue.has(n)||(Ue.add(n),console.warn(`[@object-ui/plugin-chatbot] tool invocation \`${t}\` declares state \`${e}\` with no \`approval\` envelope. The chat runtime requires the envelope alongside that state, so the invocation is not representable as authored and its state was derived from the data instead. Fix it at the producer: carry \`approval.id\` (plus \`approved\` for \`approval-responded\` and \`output-denied\`) beside the state (objectui#8426).`))}function Ke(e,t){let{toolCallId:n}=e,r=e.args;return e.errorText===void 0?e.result===void 0?{type:t,toolCallId:n,state:`input-available`,input:r}:{type:t,toolCallId:n,state:`output-available`,input:r,output:e.result}:{type:t,toolCallId:n,state:`output-error`,input:r,errorText:e.errorText}}function qe(e){let t=`tool-${e.toolName}`,{toolCallId:n,approval:r}=e,i=e.args;switch(e.state){case`approval-requested`:if(r)return{type:t,toolCallId:n,state:`approval-requested`,input:i,approval:{id:r.id,isAutomatic:r.isAutomatic,signature:r.signature}};We(e);break;case`approval-responded`:if(r&&typeof r.approved==`boolean`)return{type:t,toolCallId:n,state:`approval-responded`,input:i,approval:{id:r.id,approved:r.approved,reason:r.reason,isAutomatic:r.isAutomatic,signature:r.signature}};We(e);break;case`output-denied`:if(r&&r.approved===!1)return{type:t,toolCallId:n,state:`output-denied`,input:i,approval:{id:r.id,approved:!1,reason:r.reason,isAutomatic:r.isAutomatic,signature:r.signature}};We(e);break;case`input-streaming`:case`partial-call`:return{type:t,toolCallId:n,state:`input-streaming`,input:i};case`input-available`:case`call`:return{type:t,toolCallId:n,state:`input-available`,input:i};case`output-error`:return{type:t,toolCallId:n,state:`output-error`,input:i,errorText:e.errorText??``};case`output-available`:case`result`:return{type:t,toolCallId:n,state:`output-available`,input:i,output:e.result};case void 0:break;default:e.state}return Ke(e,t)}function Je(e={}){let{api:n,initialMessages:r,conversationId:i,parentConversationId:c,systemPrompt:l,model:u,streamingEnabled:d=!0,headers:f,body:p,onError:m,showTimestamp:h,autoResponse:g,autoResponseText:_,autoResponseDelay:v=1e3,onSend:y}=e,b=(0,a.useDisplayLocale)(),x=(0,t.useRef)(n?`api`:`local`).current===`api`,S=(0,t.useMemo)(()=>(r??[]).map((e,t)=>{if(Array.isArray(e.parts)&&e.parts.length>0)return{id:e.id||`msg-${t}`,role:Ae(e.role||`user`),parts:e.parts};let n=Be([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(qe(e));return{id:n.id||`msg-${t}`,role:Ae(n.role),parts:r.length>0?r:[{type:`text`,text:``}]}}),[]),C=(0,t.useRef)(u);C.current=u;let w=(0,t.useRef)(c),T=(0,t.useRef)(c);(0,t.useEffect)(()=>{let e=T.current;T.current=c,c&&!e&&(w.current=c)},[c]);let E=(0,t.useRef)(p);E.current=p;let D=(0,t.useRef)(f);D.current=f;let k=(0,t.useMemo)(()=>{if(x)return new s.DefaultChatTransport({api:n,fetch:Le,body:{...i?{conversationId:i}:{},...u?{model:u}:{},...l?{systemPrompt:l}:{},...d===void 0?{}:{stream:d}},prepareSendMessagesRequest:({id:e,body:t,messages:n,trigger:r,messageId:i,headers:a})=>{let o=Re({id:e,body:{...E.current,...t},messages:n,trigger:r,messageId:i});C.current&&(o.body.model=C.current),w.current&&=(o.body=ze(o.body,w.current),void 0);let s=new Headers(D.current??{});return new Headers(a??{}).forEach((e,t)=>s.set(t,e)),{...o,headers:s}}})},[x,n,u,l,d,i]),A=(0,t.useRef)(null),j=(0,o.useChat)({transport:k,messages:x&&S.length>0?S:void 0,onError:x?e=>{if(e.notSent){let e=A.current,t=e?.messages;e?.setMessages&&t&&t.length>0&&t[t.length-1]?.role===`user`&&e.setMessages(t.slice(0,-1)),Ie()}m?.(e)}:void 0});A.current=j;let M=(0,t.useRef)(void 0),N=j?.status;(0,t.useEffect)(()=>{let e=M.current;M.current=N,(e===`streaming`||e===`submitted`)&&N===`ready`&&Ie()},[N]);let[P,F]=(0,t.useState)(()=>Be(r)),[I,L]=(0,t.useState)(!1),[R,z]=(0,t.useState)(``),[B,ee]=(0,t.useState)(``),V=(0,t.useRef)(null);(0,t.useEffect)(()=>()=>{V.current&&=(clearTimeout(V.current),null)},[]);let{messages:te,status:H,error:ne,sendMessage:re,regenerate:ie,stop:U,setMessages:ae}=j,W=H===`submitted`||H===`streaming`,oe=Oe(te,{isStreaming:W}).map((e,t)=>({...e,metadata:te[t]?.metadata})),se=(0,t.useCallback)(e=>{let t=e.trim();if(!t)return;let n=[...oe,{id:O(`msg`),role:`user`,content:t}];re({text:t}),ee(``),y?.(t,n)},[re,y,oe]),ce=(0,t.useCallback)(e=>{ae(He(e))},[ae]),le=(0,t.useCallback)(()=>{ce([])},[ce]),ue=(0,t.useCallback)(e=>{ee(e.target.value)},[]),de=(0,t.useCallback)(()=>{V.current&&=(clearTimeout(V.current),null),L(!1)},[]),fe=(0,t.useCallback)(e=>{if(!e.trim())return;let t={id:O(`msg`),role:`user`,content:e.trim(),timestamp:h?new Date().toLocaleTimeString(b):void 0};F(n=>{let r=[...n,t];return y?.(e.trim(),r),r}),z(``),g&&(L(!0),V.current=setTimeout(()=>{let e={id:O(`msg`),role:`assistant`,content:_||`Thank you for your message!`,timestamp:h?new Date().toLocaleTimeString(b):void 0};F(t=>[...t,e]),L(!1)},v))},[h,b,g,_,v,y]),pe=(0,t.useCallback)(()=>{},[]),me=(0,t.useCallback)(()=>{de(),F([])},[de]),he=(0,t.useCallback)(e=>{z(e.target.value)},[]);return x?{messages:oe,isLoading:W,error:ne,sendMessage:se,stop:U,reload:ie,clear:le,setMessages:ce,isApiMode:!0,input:B,setInput:ee,handleInputChange:ue}:{messages:P,isLoading:I,error:void 0,sendMessage:fe,stop:de,reload:pe,clear:me,isApiMode:!1,input:R,setInput:z,handleInputChange:he}}var Ye=[[`build`,`metadata_assistant`],[`ask`,`data_chat`]];function Xe(e){return Ye.find(t=>t.includes(e))??[e]}function Ze(e){return Xe(e)[0]}function Qe(e,t){if(e){if(t.includes(e))return e;for(let n of Xe(e))if(t.includes(n))return n}}function $e(e){return e!=null&&Ye.some(t=>t.includes(e))}function et(e){return e!=null&&Ze(e)===`build`}function tt(e){return e!=null&&Ze(e)===`ask`}function nt(e){if(e&&typeof e==`object`)return{authoring:e.authoring===!0,canvas:e.canvas===!0,debug:e.debug===!0,resume:e.resume===!0}}function rt(e,t,n){if(!t)return!1;let r=e.find(e=>e.name===t);return r?.capabilities?r.capabilities[n]:et(t)}var G=`ask`;function it(e,t){if(e.length===0)return;let n=e.map(e=>e.name);if(t){let e=Qe(t,n);if(e)return e}return Qe(`ask`,n)||e[0].name}function K(e){let t=e&&typeof e==`object`&&!Array.isArray(e)&&typeof e.success==`boolean`?e.data:e;if(Array.isArray(t))return t;let n=t?.agents;return Array.isArray(n)?n:[]}function at(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,capabilities:nt(e.capabilities)}))}var ot=3e4,st=new Map,q=new Map;function ct(e,t,n){if(n)st.delete(e);else{let t=st.get(e);if(t&&Date.now()-t.timestamp<ot)return Promise.resolve(t.data)}let r=q.get(e);if(r&&!n)return r;let i=`${e.replace(/\/$/,``)}/agents`,a=fetch(i,{method:`GET`,headers:{Accept:`application/json`,...t??{}},credentials:`include`}).then(async e=>{if(!e.ok)throw Error(`Failed to load agents (${e.status})`);return at(K(await e.json()))}).then(t=>(st.set(e,{data:t,timestamp:Date.now()}),t)).finally(()=>{q.delete(e)});return q.set(e,a),a}var lt=!1;function ut(e){if(lt)return e(),()=>{};let t=!0,n,r=()=>{t&&(lt=!0,e())},i=typeof requestAnimationFrame==`function`?requestAnimationFrame(()=>{n=setTimeout(r,0)}):void 0;return i===void 0&&(n=setTimeout(r,0)),()=>{t=!1,i!==void 0&&typeof cancelAnimationFrame==`function`&&cancelAnimationFrame(i),n!==void 0&&clearTimeout(n)}}function dt(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=!1,t=ut(()=>{e||(l(!0),d(void 0),ct(n,m.current,f>0).then(t=>{e||s(t.length>0?t:a)}).catch(t=>{e||(d(t),s(a))}).finally(()=>{e||l(!1)}))});return()=>{e=!0,t()}},[n,i,f]),{agents:o,isLoading:c,error:u,refetch:(0,t.useCallback)(()=>p(e=>e+1),[])}}var ft=new Set;function pt(e){return e.filter(e=>typeof e?.id==`string`&&e.id.length>0).map(e=>({id:e.id,label:e.label||e.id}))}function mt(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`;if(ft.has(r))return;let 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.status===501){if(ft.add(r),t)return;o([]),c(void 0),u(!1);return}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=pt(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 J=t.createContext(null);function ht({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)(J.Provider,{value:c,children:n})}function gt(){let e=t.useContext(J);if(!e)throw Error(`useFloatingChatbot must be used within a <FloatingChatbotProvider>`);return e}function _t(){let{t:e}=(0,l.useObjectTranslation)();return(t,n)=>{let r=e(`common.${t}`);return!r||r===`common.${t}`?n:r}}var vt={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 Y(e,t){return t.reduce((t,n)=>Math.abs(n-e)<Math.abs(t-e)?n:t)}function yt(e){return vt[e]??vt[Y(e,Object.keys(vt).map(Number))]}function bt({position:e=`bottom-right`,size:t=56,className:a}){let{isOpen:o,toggle:s}=gt(),c=_t();return(0,i.jsx)(n.Button,{onClick:s,className:(0,n.cn)(`fixed z-50 rounded-full shadow-lg transition-transform hover:scale-105`,yt(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 xt={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]`},St={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 Ct(e,t){return t.reduce((t,n)=>Math.abs(n-e)<Math.abs(t-e)?n:t)}function wt(e){return xt[e]??xt[Ct(e,Object.keys(xt).map(Number))]}function Tt(e){return St[e]??St[Ct(e,Object.keys(St).map(Number))]}function Et({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}=gt();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)]`,wt(a),Tt(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)]`,wt(a),Tt(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 Dt(e){return`chatbot.tool.${String(e).trim()}`}function Ot(e,t){if(!e)return``;let n=String(e).trim();if(!n)return``;let r=n.replace(/[_-]+/g,` `).replace(/([a-z])([A-Z])/g,`$1 $2`).split(/\s+/).filter(Boolean);if(r.length===0)return n;let i=r.map((e,t)=>{let n=e.toLowerCase();return X[n]?X[n]:t===0?n.charAt(0).toUpperCase()+n.slice(1):n}).join(` `);return t?t(Dt(n),i):i}function kt(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 At(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 jt=new Set([`AI_DESIGN_QUOTA_EXHAUSTED`,`AI_DATA_CHAT_TRIAL_EXHAUSTED`,`AI_ALLOWANCE_EXHAUSTED`,`ai_design_quota_exhausted`,`ai_data_chat_trial_exhausted`,`ai_allowance_exhausted`]);function Z(e){return typeof e==`string`&&jt.has(e)?e:void 0}function Q(e){return typeof e==`string`&&e.trim()?e:void 0}function Mt(...e){for(let t of e)if(typeof t==`boolean`)return t}function Nt(...e){return Mt(...e)??!1}function Pt(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}if(!a||typeof a!=`object`)return null;let o=a.error&&typeof a.error==`object`?a.error:void 0,s=o?.details&&typeof o.details==`object`&&!Array.isArray(o.details)?o.details:void 0,c=Z(a.error),l=Z(o?.code)??c??Z(a.code);return l?{code:l,message:Q(o?.message)??Q(a.message)??(c?void 0:Q(a.error))??``,messageEn:Q(s?.messageEn)??Q(a.messageEn),upgrade:Nt(s?.upgrade,a.upgrade),topUp:Nt(s?.topUp,a.topUp),resetsTonight:Mt(s?.resetsTonight,a.resetsTonight)}:null}function Ft(e){return!!(e&&typeof e==`object`&&e.notSent===!0)}function It(e){let t=e&&typeof e==`object`?e.status:void 0;return typeof t==`number`?t:void 0}function Lt(e){if(It(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 Rt=({className:e,...t})=>(0,i.jsx)(u.StickToBottom,{className:(0,n.cn)(`relative flex flex-1 flex-col overflow-y-hidden`,e),initial:`smooth`,resize:`smooth`,role:`log`,...t}),zt=({className:e,scrollClassName:t,...r})=>(0,i.jsx)(u.StickToBottom.Content,{className:(0,n.cn)(`flex flex-col gap-8 p-4`,e),scrollClassName:(0,n.cn)(`min-h-0 flex-1`,t),...r}),Bt=({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})]})]})}),Vt=({className:e,...a})=>{let{isAtBottom:o,scrollToBottom:s}=(0,u.useStickToBottomContext)(),c=(0,t.useCallback)(()=>{s()},[s]);return!o&&(0,i.jsx)(`div`,{className:`flex shrink-0 justify-center py-2`,"data-conversation-scroll-row":``,children:(0,i.jsx)(n.Button,{className:(0,n.cn)(`rounded-full`,e),onClick:c,size:`icon`,type:`button`,variant:`outline`,...a,children:(0,i.jsx)(r.ArrowDownIcon,{className:`size-4`})})})},Ht=(0,d.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 Ut({className:e,orientation:t,...r}){return(0,i.jsx)(`div`,{role:`group`,"data-slot":`button-group`,"data-orientation":t,className:(0,n.cn)(Ht({orientation:t}),e),...r})}function $({className:e,asChild:t=!1,...r}){return(0,i.jsx)(t?f.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 Wt=/^\/record\/([a-z_][a-z0-9_]*)\/([A-Za-z0-9_-]{1,128})$/;function Gt(e){if(typeof e!=`string`)return null;let t=Wt.exec(e);return t?{objectName:t[1],recordId:t[2]}:null}var Kt=(0,t.createContext)(null);function qt(e,t){if(!t)return e;let n=e??{enabled:!0};return{...n,onLinkCheck:e=>{let r=Gt(e);return r?(t(r),new Promise(()=>{})):n.onLinkCheck?n.onLinkCheck(e):!1}}}var Jt=({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}),Yt=({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}),Xt=({className:e,children:t,...r})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`flex items-center gap-1`,e),...r,children:t}),Zt=({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},Qt=(0,t.createContext)(null),$t=()=>{let e=(0,t.useContext)(Qt);if(!e)throw Error(`MessageBranch components must be used within MessageBranch`);return e},en=({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:()=>{let e=s>0?s-1:l.length-1;d(e)},goToNext:()=>{let e=s<l.length-1?s+1:0;d(e)},branches:l,setBranches:u};return(0,i.jsx)(Qt.Provider,{value:f,children:(0,i.jsx)(`div`,{className:(0,n.cn)(`grid w-full gap-2 [&>div]:pb-0`,a),...o})})},tn=({children:e,...r})=>{let{currentBranch:a,setBranches:o,branches:s}=$t(),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))},nn=({className:e,from:t,...n})=>{let{totalBranches:r}=$t();return r<=1?null:(0,i.jsx)(Ut,{className:`[&>*:not(:first-child)]:rounded-l-md [&>*:not(:last-child)]:rounded-r-md`,orientation:`horizontal`,...n})},rn=({children:e,...t})=>{let{goToPrevious:a,totalBranches:o}=$t();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})})},an=({children:e,className:t,...a})=>{let{goToNext:o,totalBranches:s}=$t();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})})},on=({className:e,...t})=>{let{currentBranch:r,totalBranches:a}=$t();return(0,i.jsxs)($,{className:(0,n.cn)(`border-none bg-transparent text-muted-foreground shadow-none`,e),...t,children:[r+1,` of `,a]})},sn=2,cn=`overflow`,ln={h1:({className:e,node:t,...r})=>(0,i.jsx)(`h1`,{className:(0,n.cn)(`mt-5 mb-2 font-bold text-base leading-snug`,e),"data-streamdown":`heading-1`,...r}),h2:({className:e,node:t,...r})=>(0,i.jsx)(`h2`,{className:(0,n.cn)(`mt-4 mb-2 font-bold text-[15px] leading-snug`,e),"data-streamdown":`heading-2`,...r}),h3:({className:e,node:t,...r})=>(0,i.jsx)(`h3`,{className:(0,n.cn)(`mt-3 mb-1.5 font-semibold text-[15px] leading-snug`,e),"data-streamdown":`heading-3`,...r}),th:({className:e,node:t,...r})=>(0,i.jsx)(`th`,{className:(0,n.cn)(`whitespace-nowrap bg-muted px-3 py-1.5 text-left font-semibold text-[13px]`,`first:sticky first:left-0 first:z-[1] first:border-r first:border-border`,e),"data-streamdown":`table-header-cell`,...r}),td:({className:e,node:t,...r})=>(0,i.jsx)(`td`,{className:(0,n.cn)(`px-3 py-1.5 text-[13px]`,`first:sticky first:left-0 first:z-[1] first:border-r first:border-border first:bg-background`,e),"data-streamdown":`table-cell`,...r})},un=e=>{let t=e.parentElement;for(;t;){let{overflowY:e}=getComputedStyle(t);if(e===`auto`||e===`scroll`)return t;t=t.parentElement}return null},dn=(0,t.memo)(({className:e,components:r,translations:o,isAnimating:s,linkSafety:c,...l})=>{let u=(0,a.useSafeTranslate)(),d=(0,t.useContext)(Kt),f=(0,t.useMemo)(()=>qt(c,d),[c,d]),m=u(`chatbot.answer.showFull`,`Show full answer`),h=u(`chatbot.answer.collapse`,`Collapse`),g=o?.viewFullscreen??u(`chatbot.answer.expandTable`,`Expand`),_=o?.exitFullscreen??u(`chatbot.answer.exitExpandedTable`,`Close`),v=(0,t.useRef)(null),y=(0,t.useRef)(null),[b,x]=(0,t.useState)(!1),[S,C]=(0,t.useState)(!1),w=!!s,T=b&&!S&&!w;(0,t.useEffect)(()=>{let e=v.current,t=y.current;if(!e||!t)return;let n=()=>{for(let t of e.querySelectorAll(`[data-streamdown="table-wrapper"]`)){let e=t.querySelector(`[data-streamdown="table"]`)?.parentElement,n=Array.from(t.querySelectorAll(`button`)).find(e=>e.title===g);e&&n&&n.setAttribute(`data-chat-table-expand`,e.scrollWidth>e.clientWidth?cn:`fit`)}if(w)return;let n=un(e)?.clientHeight||window.innerHeight;x(n>0&&t.scrollHeight>sn*n)};if(n(),typeof ResizeObserver>`u`)return;let r=new ResizeObserver(n);return r.observe(e),()=>r.disconnect()},[l.children,w,g]);let E=()=>{C(e=>!e),S&&v.current?.scrollIntoView?.({block:`nearest`})};return(0,i.jsxs)(`div`,{className:(0,n.cn)(`flex min-w-0 flex-col gap-2`,`[&_[data-chat-table-expand=overflow]]:inline-flex [&_[data-chat-table-expand=overflow]]:items-center [&_[data-chat-table-expand=overflow]]:gap-1 [&_[data-chat-table-expand=overflow]]:rounded-md [&_[data-chat-table-expand=overflow]]:border [&_[data-chat-table-expand=overflow]]:border-border [&_[data-chat-table-expand=overflow]]:bg-background [&_[data-chat-table-expand=overflow]]:px-2 [&_[data-chat-table-expand=overflow]]:py-0.5 [&_[data-chat-table-expand=overflow]]:font-medium [&_[data-chat-table-expand=overflow]]:text-foreground [&_[data-chat-table-expand=overflow]]:text-xs [&_[data-chat-table-expand=overflow]]:after:content-[attr(title)]`),"data-chat-answer":``,"data-folded":T?`true`:void 0,ref:v,children:[(0,i.jsx)(`div`,{className:(0,n.cn)(`min-w-0`,T&&`max-h-[28rem] overflow-hidden [mask-image:linear-gradient(to_bottom,black_75%,transparent)]`),"data-chat-answer-body":``,ref:y,children:(0,i.jsx)(p.Streamdown,{className:(0,n.cn)(`size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0`,e),components:{...ln,...r},isAnimating:s,linkSafety:f,translations:{...o,viewFullscreen:g,exitFullscreen:_},...l})}),b&&!w?(0,i.jsx)(n.Button,{"aria-expanded":!T,className:`self-start`,"data-chat-answer-toggle":``,onClick:E,size:`sm`,type:`button`,variant:`outline`,children:T?m:h}):null]})},(e,t)=>e.children===t.children&&e.isAnimating===t.isAnimating);dn.displayName=`MessageResponse`;function fn({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 pn({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 mn=({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 hn({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 gn=(0,d.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 _n({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)(gn({align:t}),e),onClick:e=>{e.target.closest(`button`)||e.currentTarget.parentElement?.querySelector(`input`)?.focus()},...r})}var vn=(0,d.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 yn({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)(vn({size:a}),e),...o})}function bn({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 xn=(0,t.createContext)(null),Sn=(0,t.createContext)(null),Cn=()=>{let e=(0,t.useContext)(xn);if(!e)throw Error(`Wrap your component inside <PromptInputProvider> to use usePromptInputController().`);return e},wn=()=>(0,t.useContext)(xn),Tn=()=>{let e=(0,t.useContext)(Sn);if(!e)throw Error(`Wrap your component inside <PromptInputProvider> to use useProviderAttachments().`);return e},En=()=>(0,t.useContext)(Sn);function Dn({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,m.nanoid)(),type:`file`,url:URL.createObjectURL(e),mediaType:e.type,filename:e.name,file:e}))))},[]),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)})},[]),p=(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:p,openFileDialog:g,fileInputRef:l}),[s,d,f,p,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)(xn.Provider,{value:y,children:(0,i.jsx)(Sn.Provider,{value:_,children:n})})}var On=(0,t.createContext)(null),kn=()=>{let e=En(),n=(0,t.useContext)(On),r=e??n;if(!r)throw Error(`usePromptInputAttachments must be used within a PromptInput or PromptInputProvider`);return r};function An({data:e,className:t,removeLabel:a=`Remove attachment`,...o}){let s=kn(),c=e.filename||``,l=(e.mediaType?.startsWith(`image/`)&&e.url?`image`:`file`)==`image`,u=c||(l?`Image`:`Attachment`);return(0,i.jsxs)(Zn,{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),...o,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:l?(0,i.jsx)(`img`,{alt:c||`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":a,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(),s.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:u})]},e.id)}),(0,i.jsx)($n,{className:`w-auto p-2`,children:(0,i.jsxs)(`div`,{className:`w-auto space-y-3`,children:[l&&(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:c||`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:c||(l?`Image`:`Attachment`)}),e.mediaType&&(0,i.jsx)(`p`,{className:`truncate font-mono text-muted-foreground text-xs`,children:e.mediaType})]})})]})})]})}function jn({children:e,className:r,...a}){let o=kn();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 Mn=({label:e=`Add photos or files`,...t})=>{let a=kn();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]})},Nn=({className:e,accept:r,multiple:a,fileInputLabel:o=`Upload files`,globalDrop:s,syncHiddenInput:c,maxFiles:l,maxFileSize:u,onError:d,onSubmit:f,children:p,...h})=>{let g=wn(),_=!!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()===``||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);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,m.nanoid)(),type:`file`,url:URL.createObjectURL(e),mediaType:e.type,filename:e.name,file:e});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)(hn,{className:`overflow-hidden`,children:p})})]});return _?I:(0,i.jsx)(On.Provider,{value:F,children:I})},Pn=({className:e,...t})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`contents`,e),...t}),Fn=({onChange:e,className:r,placeholder:a=`What would you like to know?`,...o})=>{let s=wn(),c=kn(),[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)(bn,{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})},In=({className:e,...t})=>(0,i.jsx)(_n,{align:`block-end`,className:(0,n.cn)(`order-first flex-wrap gap-1`,e),...t}),Ln=({className:e,...t})=>(0,i.jsx)(_n,{align:`block-end`,className:(0,n.cn)(`justify-between gap-1`,e),...t}),Rn=({className:e,...t})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`flex items-center gap-1`,e),...t}),zn=({variant:e=`ghost`,className:r,size:a,...o})=>{let s=a??(t.Children.count(o.children)>1?`sm`:`icon-sm`);return(0,i.jsx)(yn,{className:(0,n.cn)(r),size:s,type:`button`,variant:e,...o})},Bn=e=>(0,i.jsx)(n.DropdownMenu,{...e}),Vn=({className:e,children:t,...a})=>(0,i.jsx)(n.DropdownMenuTrigger,{asChild:!0,children:(0,i.jsx)(zn,{className:e,...a,children:t??(0,i.jsx)(r.PlusIcon,{className:`size-4`})})}),Hn=({className:e,...t})=>(0,i.jsx)(n.DropdownMenuContent,{align:`start`,className:(0,n.cn)(e),...t}),Un=({className:e,...t})=>(0,i.jsx)(n.DropdownMenuItem,{className:(0,n.cn)(e),...t}),Wn=({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)(yn,{"aria-label":`Submit`,className:(0,n.cn)(e),size:a,type:`submit`,variant:t,...c,children:s??l})},Gn=({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)(zn,{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`})})},Kn=e=>(0,i.jsx)(n.Select,{...e}),qn=({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}),Jn=({className:e,...t})=>(0,i.jsx)(n.SelectContent,{className:(0,n.cn)(e),...t}),Yn=({className:e,...t})=>(0,i.jsx)(n.SelectItem,{className:(0,n.cn)(e),...t}),Xn=({className:e,...t})=>(0,i.jsx)(n.SelectValue,{className:(0,n.cn)(e),...t}),Zn=({openDelay:e=0,closeDelay:t=0,...r})=>(0,i.jsx)(n.HoverCard,{closeDelay:t,openDelay:e,...r}),Qn=e=>(0,i.jsx)(n.HoverCardTrigger,{...e}),$n=({align:e=`start`,...t})=>(0,i.jsx)(n.HoverCardContent,{align:e,...t}),er=({className:e,...t})=>(0,i.jsx)(`div`,{className:(0,n.cn)(e),...t}),tr=({className:e,...t})=>(0,i.jsx)(`div`,{className:(0,n.cn)(e),...t}),nr=({className:e,...t})=>(0,i.jsx)(`h3`,{className:(0,n.cn)(`mb-2 px-3 font-medium text-muted-foreground text-xs`,e),...t}),rr=({className:e,...t})=>(0,i.jsx)(`div`,{className:(0,n.cn)(`space-y-1`,e),...t}),ir=({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}),ar=({className:e,...t})=>(0,i.jsx)(n.Command,{className:(0,n.cn)(e),...t}),or=({className:e,...t})=>(0,i.jsx)(n.CommandInput,{className:(0,n.cn)(e),...t}),sr=({className:e,...t})=>(0,i.jsx)(n.CommandList,{className:(0,n.cn)(e),...t}),cr=({className:e,...t})=>(0,i.jsx)(n.CommandEmpty,{className:(0,n.cn)(e),...t}),lr=({className:e,...t})=>(0,i.jsx)(n.CommandGroup,{className:(0,n.cn)(e),...t}),ur=({className:e,...t})=>(0,i.jsx)(n.CommandItem,{className:(0,n.cn)(e),...t}),dr=({className:e,...t})=>(0,i.jsx)(n.CommandSeparator,{className:(0,n.cn)(e),...t}),fr=({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`})]}),pr=({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}),mr=(0,t.createContext)({code:``}),hr={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 gr(e,t,n=!1){let r=n?[hr]:[];return await Promise.all([(0,h.codeToHtml)(e,{lang:t,theme:`one-light`,transformers:r}),(0,h.codeToHtml)(e,{lang:t,theme:`one-dark-pro`,transformers:r})])}var _r=({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)(()=>(gr(e,r,a).then(([e,t])=>{p.current||=(u(e),f(t),!0)}),()=>{p.current=!1}),[e,r,a]),(0,i.jsx)(mr.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})]})})})},vr=({onCopy:e,onError:a,timeout:o=2e3,children:s,className:c,...l})=>{let[u,d]=(0,t.useState)(!1),{code:f}=(0,t.useContext)(mr),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})})},yr=({className:e,...t})=>(0,i.jsx)(n.Collapsible,{className:(0,n.cn)(`not-prose mb-4 w-full rounded-md border`,e),...t}),br=(e,t)=>(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],t?.[e]??{"input-streaming":`Pending`,"input-available":`Running`,"approval-requested":`Awaiting Approval`,"approval-responded":`Responded`,"output-available":`Completed`,"output-error":`Error`,"output-denied":`Denied`}[e]]}),xr=({className:e,title:t,type:a,state:o,statusLabels:s,...c})=>(0,i.jsxs)(n.CollapsibleTrigger,{className:(0,n.cn)(`flex w-full items-center justify-between gap-4 p-3`,e),...c,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(`-`)}),br(o,s)]}),(0,i.jsx)(r.ChevronDownIcon,{className:`size-4 text-muted-foreground transition-transform group-data-[state=open]:rotate-180`})]}),Sr=({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}),Cr=({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)(_r,{code:JSON.stringify(t,null,2),language:`json`})})]}),wr=({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)(_r,{code:JSON.stringify(r,null,2),language:`json`}):typeof r==`string`&&(s=(0,i.jsx)(_r,{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]})]})},Tr=(0,t.memo)(({children:e,as:r=`p`,className:a,duration:o=2,spread:s=2})=>{let c=(0,t.useMemo)(()=>_.motion.create(r),[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})}),Er=(0,t.createContext)(null),Dr=()=>{let e=(0,t.useContext)(Er);if(!e)throw Error(`Reasoning components must be used within Reasoning`);return e},Or=1e3,kr=1e3,Ar=(0,t.memo)(({className:e,isStreaming:r=!1,open:a,defaultOpen:o=!0,onOpenChange:s,duration:c,children:l,...u})=>{let[d,f]=(0,g.useControllableState)({prop:a,defaultProp:o,onChange:s}),[p,m]=(0,g.useControllableState)({prop:c,defaultProp:void 0}),[h,_]=(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)/kr)),y(null))},[r,v,m]),(0,t.useEffect)(()=>{if(o&&!r&&d&&!h){let e=setTimeout(()=>{f(!1),_(!0)},Or);return()=>clearTimeout(e)}},[r,d,o,f,h]),(0,i.jsx)(Er.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})})}),jr=(e,t)=>e||t===0?(0,i.jsx)(Tr,{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`]}),Mr=(0,t.memo)(({className:e,children:t,getThinkingMessage:a=jr,...o})=>{let{isStreaming:s,isOpen:c,duration:l}=Dr();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`)})]})})}),Nr=(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)(p.Streamdown,{children:t})}));Ar.displayName=`Reasoning`,Mr.displayName=`ReasoningTrigger`,Nr.displayName=`ReasoningContent`;var Pr=({className:e,...t})=>(0,i.jsx)(n.Collapsible,{className:(0,n.cn)(`not-prose mb-4 text-primary text-xs`,e),...t}),Fr=({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`})]})}),Ir=({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}),Lr=({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 Rr(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}var zr=`outside`;function Br({label:e,models:t,value:r,onPick:a}){let o=t.findIndex(e=>e.id===r);return(0,i.jsxs)(n.Select,{value:o===-1?zr:String(o),onValueChange:e=>{let n=t[Number(e)];n&&a(n.id)},children:[(0,i.jsx)(n.SelectTrigger,{"aria-label":e,className:`h-7 w-auto gap-1 px-2 text-xs text-muted-foreground hover:text-foreground focus:ring-1 focus:ring-offset-0`,children:(0,i.jsx)(n.SelectValue,{})}),(0,i.jsxs)(n.SelectContent,{children:[o===-1&&(0,i.jsx)(n.SelectItem,{value:zr,children:r}),t.map((e,t)=>(0,i.jsxs)(n.SelectItem,{value:String(t),children:[e.label??e.id,e.provider?` · ${e.provider}`:``]},`${t}:${e.id}`))]})]})}function Vr(e){return e===`user`?`user`:`assistant`}function Hr(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 Ur(e){let t=N(e)?.status;return t===`changes_proposed`||t===`blueprint_proposed`||t===`awaiting_confirmation`}function Wr(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`?Ur(e.result)?`awaiting`:`completed`:`running`}function Gr(e){let t=e.replayOutcome?.kind;return t===`failed`?`failed`:t===`published`||t===`drafted`?`settled`:t===`applying`?`in-progress`:e.built||e.confirmed?`settled`:e.approved?`in-progress`:`pending`}var Kr={pending:`approval-requested`,"in-progress":`input-available`,settled:`output-available`,failed:`output-error`},qr={create_object:`Create object`,add_field:`Add field`,modify_field:`Modify field`,delete_field:`Delete field`,create_metadata:`Create`,update_metadata:`Modify`,create_seed:`Generate sample data`,create_package:`Create app package`};function Jr(e,t=qr){return[t[e.verb]??qr[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 Yr(e){return e.posture!==void 0||e.primaryAction!==void 0}function Xr(e){return e===`delete_field`?`remove`:e===`add_field`||e.startsWith(`create_`)?`add`:`modify`}var Zr={add:`+`,modify:`✎`,remove:`-`},Qr={add:`bg-emerald-100 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300`,modify:`bg-amber-100 text-amber-700 dark:bg-amber-950/40 dark:text-amber-300`,remove:`bg-red-100 text-red-700 dark:bg-red-950/40 dark:text-red-300`};function $r(e){let{t:n}=(0,a.useObjectTranslation)();return t.useCallback(t=>{let r=e=>{switch(e){case`object`:return n(`chatbot.changes.kind.object`,{defaultValue:`Object`});case`view`:return n(`chatbot.changes.kind.view`,{defaultValue:`View`});case`dashboard`:return n(`chatbot.changes.kind.dashboard`,{defaultValue:`Dashboard`});case`app`:return n(`chatbot.changes.kind.app`,{defaultValue:`App`});default:return e}};switch(t.verb){case`add_field`:case`modify_field`:case`delete_field`:return n(`chatbot.changes.kind.field`,{defaultValue:`Field`});case`create_object`:return r(`object`);case`create_seed`:return n(`chatbot.changes.kind.seed`,{defaultValue:`Sample data`});case`create_package`:return n(`chatbot.changes.kind.package`,{defaultValue:`App package`});case`create_metadata`:case`update_metadata`:{let e=r(t.type);if(e)return e;break}}return e[t.verb]??qr[t.verb]??t.verb},[n,e])}function ei({changes:e,verbLabels:t}){let{t:o}=(0,a.useObjectTranslation)(),s=$r(t),c=e.changes.length;return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-xs font-semibold text-foreground`,"data-testid":`proposed-changes-title`,children:[(0,i.jsx)(r.ClipboardList,{className:`size-3.5 text-foreground/60`}),o(`chatbot.changes.planTitle`,{count:c,defaultValue:`Change plan · {{count}} changes`})]}),(0,i.jsx)(`div`,{className:`flex flex-col`,"data-testid":`proposed-changes-rows`,children:e.changes.map((e,r)=>{let a=Xr(e.verb),o=e.field?e.object?`${e.object} · ${e.field}`:e.field:e.name??e.object??``,c=[e.type,e.details].filter(Boolean).join(` · `);return(0,i.jsxs)(`div`,{className:`flex items-start gap-2 border-t border-border/60 py-1.5 first-of-type:border-t-0`,"data-testid":`proposed-change-row`,"data-change":a,children:[(0,i.jsx)(`span`,{"aria-hidden":`true`,className:(0,n.cn)(`inline-flex size-[18px] shrink-0 items-center justify-center rounded text-xs font-bold`,Qr[a]),"data-testid":`proposed-change-symbol`,children:Zr[a]}),(0,i.jsx)(`span`,{className:`sr-only`,children:t[e.verb]??qr[e.verb]??e.verb}),(0,i.jsxs)(`div`,{className:`flex min-w-0 flex-col`,children:[(0,i.jsxs)(`span`,{className:`text-xs text-foreground/90`,children:[(0,i.jsx)(`strong`,{className:`font-medium`,"data-testid":`proposed-change-kind`,children:s(e)}),` `,(0,i.jsx)(`span`,{className:`break-all`,"data-testid":`proposed-change-target`,children:o})]}),c?(0,i.jsx)(`span`,{className:`break-words font-mono text-[11px] text-muted-foreground`,"data-testid":`proposed-change-params`,children:c}):null]})]},r)})}),e.summary?e.posture?.mode===`draft`?(0,i.jsxs)(`div`,{className:`flex gap-2 rounded-md bg-amber-50 px-2.5 py-2 text-xs leading-relaxed text-amber-800 dark:bg-amber-950/30 dark:text-amber-300`,"data-testid":`proposed-changes-posture-note`,"data-posture":`draft`,children:[(0,i.jsx)(r.Info,{className:`mt-0.5 size-3.5 shrink-0`,"aria-hidden":`true`}),(0,i.jsx)(`span`,{children:e.summary})]}):(0,i.jsx)(`p`,{className:`text-xs text-muted-foreground`,"data-testid":`proposed-changes-summary`,children:e.summary}):null]})}function ti(e,t,n,r){if(e.length===0)return;let i=e.find(e=>e.type===`app`);if(i){let e=r.onPreviewDraftApp;return e?{run:()=>e(i.name,{materialized:n,appSegment:t}),app:!0}:void 0}let a=r.onPreviewDraft;return a&&t?{run:()=>a([...e],{appSegment:t}),app:!1}:void 0}function ni({card:e,others:t,discard:o,onPreview:s,previewLabel:c,onReview:l,onPublish:u,publishLabel:d,onDiscard:f,onDiscardConfirm:p,onDiscardCancel:m}){let{t:h}=(0,a.useObjectTranslation)(),g=o?.phase===`done`,_=o?.phase===`running`;return(0,i.jsxs)(`div`,{className:`flex flex-col gap-1.5 rounded-md border bg-background px-2.5 py-2`,"data-testid":`applied-card`,children:[(0,i.jsxs)(`span`,{className:(0,n.cn)(`inline-flex items-center gap-2 text-xs font-semibold`,g?`text-muted-foreground line-through`:`text-foreground`),"data-testid":`applied-card-title`,children:[(0,i.jsx)(`span`,{className:`inline-flex size-4 shrink-0 items-center justify-center rounded-full bg-emerald-100 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300`,children:(0,i.jsx)(r.Check,{className:`size-2.5`,strokeWidth:3,"aria-hidden":`true`})}),e.title]}),e.lines.length>0?(0,i.jsx)(`ul`,{className:`flex flex-col gap-0.5 text-xs text-muted-foreground`,"data-testid":`applied-card-lines`,children:e.lines.map((e,t)=>(0,i.jsx)(`li`,{"data-testid":`applied-card-line`,children:e},t))}):null,g?(0,i.jsxs)(`span`,{className:`inline-flex h-7 w-fit items-center gap-1.5 rounded-md border bg-muted/40 px-3 text-xs font-medium text-foreground/70`,"data-testid":`applied-card-discarded`,children:[(0,i.jsx)(r.CheckCircle2,{className:`size-3.5`}),h(`chatbot.changes.undone`,{defaultValue:`Undone`})]}):o?.phase===`confirm`?(0,i.jsxs)(`div`,{className:`flex flex-col gap-1.5 rounded-md bg-amber-50 px-2.5 py-2 text-xs leading-relaxed text-amber-800 dark:bg-amber-950/30 dark:text-amber-300`,role:`alert`,"data-testid":`applied-card-discard-confirm`,children:[(0,i.jsx)(`span`,{"data-testid":`applied-card-discard-confirm-text`,children:o.others!==void 0&&o.total!==void 0?h(`chatbot.changes.undoConfirm`,{count:o.others,total:o.total,defaultValue:`Undo discards all {{total}} unpublished drafts of this package, including {{count}} that are not part of this change.`}):h(`chatbot.changes.undoConfirmUnknown`,{defaultValue:`Undo discards every unpublished draft of this package, not only this change.`})}),(0,i.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[(0,i.jsx)(`button`,{type:`button`,onClick:p,className:`inline-flex h-7 items-center rounded-md bg-red-600 px-3 text-xs font-medium text-white hover:bg-red-700 dark:bg-red-700 dark:hover:bg-red-600`,"data-testid":`applied-card-discard-confirm-run`,children:h(`chatbot.changes.undoConfirmAction`,{defaultValue:`Undo all`})}),(0,i.jsx)(`button`,{type:`button`,onClick:m,className:`inline-flex h-7 items-center rounded-md border bg-background px-3 text-xs font-medium text-foreground hover:bg-accent`,"data-testid":`applied-card-discard-cancel`,children:h(`chatbot.changes.undoCancel`,{defaultValue:`Cancel`})})]})]}):(0,i.jsxs)(i.Fragment,{children:[l||u||s||f?(0,i.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 pt-0.5`,"data-testid":`proposed-changes-actions`,children:[l?(0,i.jsxs)(`button`,{type:`button`,onClick:l,disabled:_,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 disabled:cursor-not-allowed disabled:opacity-50`,"data-testid":`applied-card-review`,children:[(0,i.jsx)(r.GitCompareArrows,{className:`size-3.5`}),h(`chatbot.changes.reviewAndPublish`,{defaultValue:`Review changes and publish`})]}):u?(0,i.jsxs)(`button`,{type:`button`,onClick:u,disabled:_,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 disabled:cursor-not-allowed disabled:opacity-50`,"data-testid":`proposed-changes-publish`,children:[(0,i.jsx)(r.Rocket,{className:`size-3.5`}),d]}):null,s?(0,i.jsxs)(`button`,{type:`button`,onClick:s,disabled:_,className:`inline-flex h-7 items-center gap-1.5 rounded-md border px-3 text-xs font-medium hover:bg-muted disabled:cursor-not-allowed disabled:opacity-50`,"data-testid":`applied-card-preview`,children:[(0,i.jsx)(r.Eye,{className:`size-3.5`}),c]}):null,f?(0,i.jsx)(`button`,{type:`button`,onClick:f,disabled:_,className:`inline-flex h-7 items-center rounded-md px-3 text-xs font-medium text-muted-foreground hover:bg-accent hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50`,"data-testid":`applied-card-discard`,children:_?h(`chatbot.changes.undoing`,{defaultValue:`Undoing…`}):t!==void 0&&t>0?h(`chatbot.changes.undoWithOthers`,{count:t,defaultValue:`Undo (and {{count}} other drafts)`}):h(`chatbot.changes.undo`,{defaultValue:`Undo`})}):null]}):null,o?.phase===`failed`?(0,i.jsxs)(`span`,{className:`flex flex-col text-[11px] text-red-700/80 dark:text-red-300/80`,role:`alert`,"data-testid":`applied-card-discard-failed`,children:[(0,i.jsx)(`span`,{children:h(`chatbot.changes.undoFailed`,{defaultValue:`Undo failed`})}),o.error?(0,i.jsx)(`span`,{children:o.error}):null]}):null]})]})}function ri(e){return e.toolName===`propose_blueprint`}function ii(e){return ri(e)&&Wr(e)===`completed`&&!e.proposedPlan&&!e.proposedChanges&&!e.draftReview?.items.length}var ai=[`待补`,`后续`,`将在`,`稍后`,`暂不`,`暂未`,`尚未`,`确认后一起补`,`一起补`,`另行`,`日后`,`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 oi(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();ai.some(e=>i.includes(e))?n.push(e):t.push(e)}return{designNotes:t,deferred:n}}function si(e){let t=Wr(e);return t===`awaiting`||t===`failed`||!!e.pendingActionId||!!e.draftReview?.items.length||!!e.proposedPlan||!!e.proposedChanges||!!e.builderHandoff||!!e.recordHandoff||ii(e)}function ci(e){switch(e){case`failed`:return 4;case`awaiting`:return 3;case`running`:return 2;case`completed`:return 1}}function li(e){return/^\((?:called [^)]*|tool call|no content)\)$/.test(e.trim())}function ui(){let{t:e}=(0,a.useObjectTranslation)();return t.useCallback(t=>{let n=[];return t?.objects&&n.push(e(`chatbot.plan.countObjects`,{count:t.objects,defaultValue:`{{count}} objects`})),t?.views&&n.push(e(`chatbot.plan.countViews`,{count:t.views,defaultValue:`{{count}} views`})),t?.dashboards&&n.push(e(`chatbot.plan.countDashboards`,{count:t.dashboards,defaultValue:`{{count}} dashboards`})),t?.seedData&&n.push(e(`chatbot.plan.countSeedData`,{defaultValue:`sample data`})),n},[e])}function di(e,n){let{t:r}=(0,a.useObjectTranslation)();return t.useCallback(t=>{let i=n?.(t)||t;return e?`${e} "${i}"`:r(`chatbot.plan.extendTarget`,{app:i,defaultValue:`Adding to existing app: {{app}}`})},[r,e,n])}function fi(e,t){let n=new Map;for(let r of e){let e=Wr(r),i=`${r.toolName}:${e}`,a=n.get(i);if(a){a.count+=1,a.errorText=a.errorText??r.errorText;continue}n.set(i,{key:i,title:Ot(r.toolName,t)||r.toolName,rawName:r.toolName,count:1,state:e,errorText:r.errorText})}return Array.from(n.values()).sort((e,t)=>{let n=ci(t.state)-ci(e.state);return n===0?e.title.localeCompare(t.title):n})}function pi({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 mi=t.forwardRef(({className:e,messages:o=[],placeholder:s=`Type your message...`,onSendMessage:c,onClear:u,onStop:d,onReload:f,onUpgrade:p,disabled:m=!1,readOnly:h=!1,isLoading:g=!1,error:_,showTimestamp:v=!1,showAvatars:y=!1,userAvatarUrl:b,userAvatarFallback:x=`You`,assistantAvatarUrl:S,assistantAvatarFallback:C=`AI`,hideClearBar:w=!1,maxHeight:T=`500px`,enableMarkdown:E=!0,enableFileUpload:D=!1,acceptedFileTypes:O=`image/*,.pdf,.doc,.docx,.txt,.csv,.tsv,.xlsx,.xlsm`,maxFileSize:k=10485760,suggestions:A,labels:j,models:M,selectedModelId:P,onModelChange:F,headerSlot:I,promptOverlaySlot:L,promptHeaderSlot:R,onInputChange:z,onToolApprove:B,toolApproveLabel:ee=`Approve`,toolDenyLabel:V=`Deny`,toolDenyReason:te=`User denied the operation`,toolDecisions:H,onReviewDraft:re,toolReviewLabel:ie=e=>`Review ${e} change${e===1?``:`s`}`,onPublishDrafts:U,onReviewDrafts:ae,onDiscardDrafts:W,onOpenBuiltApp:oe,openBuiltAppLabel:se=`Open app`,onDesignBuiltApp:ce,designBuiltAppLabel:le=`Design in Studio`,getArtifactAction:fe,onPreviewDraftApp:pe,previewDraftLabel:he=`Preview`,onPreviewDraft:ge,onDraftArtifacts:_e,onBuildMaterialized:ve,onPlanApprovalPendingChange:ye,publishDraftsLabel:be=`Publish`,publishedLabel:xe=`Published`,verifiedLabel:Se=`Verified`,nextStepsLabel:Ce=`What's next`,planTitleLabel:we=`Proposed plan`,builderHandoffTitleLabel:Te=`Build this in the Builder`,builderHandoffOpenLabel:Ee=`Open in Builder →`,recordHandoffTitleLabel:De=`Open this record`,recordHandoffOpenLabel:Oe=`Open record →`,builderHandoffSupersededTitle:ke=`A newer request is available`,onOpenBuilder:Ae,onOpenRecord:je,planExtendLabel:Me,resolveAppLabel:Ne,planQuestionsLabel:Pe=`Confirm before building`,planAssumptionsLabel:Fe=`Assumptions`,planDeferredLabel:Ie=`Not yet built`,planApproveHintLabel:Le=`Reply to approve or adjust this plan.`,planApproveLabel:Re=`Build it`,planAdjustLabel:ze=`Adjust`,planBuiltLabel:Be=`Built`,planBuildingLabel:Ve=`Building…`,planReadyLabel:He=`The plan is ready. Build it now, or tell me what to adjust.`,planApproveMessage:Ue=`Looks good — build it as proposed.`,planApproveDefaultsMessage:We=`Build it with your best assumptions; use sensible defaults for the open questions.`,planAnswerMessage:Ge=(e,t)=>`For "${e}", go with: ${t}.`,changesTitleLabel:Ke=`Confirm changes`,changesConfirmedLabel:qe=`Confirmed`,changesConfirmLabel:Je=`Confirm`,changesConfirmHintLabel:Ye=`Reply to confirm or adjust this change.`,changesConfirmMessage:Xe=`Confirm — apply the change you just proposed.`,changeVerbLabels:Ze=qr,changesApplyingLabel:Qe=`Applying…`,changesAppliedLabel:$e=`Applied`,changesDraftedLabel:et=`Saved as draft`,changesFailedLabel:tt=`Not applied`,surfaceContextLabel:nt,surfaceContextTitle:rt,fetchPendingDraftCount:G,autoPublishDrafts:it=!1,processVisibility:K=`summary`,surface:at=`card`,...ot},st)=>{let q=g?`streaming`:`ready`,ct=at===`plain`,[lt,ut]=t.useState(null),dt=t.useRef(``),ft=t.useRef(null),pt=ui(),mt=di(Me,Ne),J=(0,a.useSafeTranslate)(),ht=J(`chatbot.plan.awaitingConfirm`,`Awaiting confirmation`),gt=J(`chatbot.plan.objectsAndFields`,`Objects and fields`),_t=J(`chatbot.plan.views`,`Views`),vt=J(`chatbot.changes.saveDraft`,`Save as draft`),Y=t.useMemo(()=>({emptyTitle:j?.emptyTitle??`Start a conversation`,emptyDescription:j?.emptyDescription??`Ask anything — the assistant has access to your current app context.`,clear:j?.clear??`Clear`,sendHint:j?.sendHint??`to send`,newlineHint:j?.newlineHint,agentActivity:j?.agentActivity??J(`chatbot.toolState.agentActivity`,`Agent activity`),toolCompleted:j?.toolCompleted??J(`chatbot.toolState.completed`,`Completed`),toolRunning:j?.toolRunning??J(`chatbot.toolState.running`,`Running`),toolAwaitingApproval:j?.toolAwaitingApproval??J(`chatbot.toolState.awaitingApproval`,`Awaiting approval`),toolFailed:j?.toolFailed??J(`chatbot.toolState.failed`,`Failed`),toolPending:J(`chatbot.toolState.pending`,`Pending`),toolResponded:J(`chatbot.toolState.responded`,`Responded`),toolDenied:J(`chatbot.toolState.denied`,`Denied`),toolError:J(`chatbot.toolState.error`,`Error`),toolDetailsHidden:j?.toolDetailsHidden??`Detailed tool inputs and outputs are hidden in this view.`,copy:j?.copy??`Copy`,copied:j?.copied??`Copied`,regenerate:j?.regenerate??`Regenerate`,model:j?.model??`Model`,submit:j?.submit??J(`console.ai.submit`,`Submit`),uploadFiles:j?.uploadFiles??`Upload files`,stopResponse:j?.stopResponse??J(`console.ai.stopResponse`,`Stop response`),removeAttachment:J(`detail.removeAttachment`,`Remove attachment`),sendFailedRateLimited:j?.sendFailedRateLimited??`You're sending messages too quickly. Your message is kept below — wait a moment and try again.`,sendFailedGeneric:j?.sendFailedGeneric??`Couldn't send your message. It's kept below — please try again.`,trace:j?.trace??`trace`,viewTrace:j?.viewTrace??`View trace`,connectionWaiting:j?.connectionWaiting??`Waiting for server…`,connectionStalledLabel:j?.connectionStalledLabel??`Still working…`,connectionOfflineLabel:j?.connectionOfflineLabel??`Connection lost — reconnecting…`,designingPlanLabel:j?.designingPlanLabel??`Designing your app…`,designingPlanHints:j?.designingPlanHints??Ci}),[j,J]),yt=t.useMemo(()=>({"input-streaming":Y.toolPending,"input-available":Y.toolRunning,"approval-requested":Y.toolAwaitingApproval,"approval-responded":Y.toolResponded,"output-available":Y.toolCompleted,"output-error":Y.toolError,"output-denied":Y.toolDenied}),[Y]),[bt,xt]=t.useState(()=>new Set),[St,Ct]=t.useState(()=>new Map),[wt,Tt]=t.useState(()=>new Map),Et=t.useRef(new Set),X=t.useCallback(async e=>{if(G)try{let t=await G(e);Tt(n=>{if(n.get(e)===t)return n;let r=new Map(n);return r.set(e,t),r})}catch{}},[G]);t.useEffect(()=>{if(!G||g)return;let e=new Set;for(let t of o)for(let n of t.toolInvocations??[]){let t=n.draftReview?.packageId,r=n.toolCallId;t&&r&&!Et.current.has(r)&&(Et.current.add(r),e.add(t))}for(let t of e)X(t)},[o,g,G,X]);let Dt=t.useCallback(async e=>{if(!U)return;let t=[];for(let n of o)for(let r of n.toolInvocations??[])r.draftReview?.packageId===e&&r.toolCallId&&t.push(r.toolCallId);let n=await U(e),r=n&&typeof n==`object`?n:void 0;if((r?r.ok!==!1:n!==!1)&&t.length>0){xt(e=>{let n=new Set(e);for(let e of t)n.add(e);return n});let e=r?.health;e&&Ct(n=>{let r=new Map(n);for(let n of t)r.set(n,e);return r})}X(e)},[U,o,X]),[At,jt]=t.useState(()=>new Map),Z=t.useCallback((e,t)=>{jt(n=>{let r=new Map(n);return t?r.set(e,t):r.delete(e),r})},[]),Q=t.useCallback(async(e,t)=>{if(W){Z(e,{phase:`running`});try{let n=await W(t),r=n&&typeof n==`object`?n:void 0,i=r?r.ok!==!1:n!==!1;Z(e,i?{phase:`done`}:{phase:`failed`,...r?.error?{error:r.error}:{}})}catch(t){let n=t instanceof Error?t.message:typeof t==`string`?t:``;Z(e,{phase:`failed`,...n?{error:n}:{}})}X(t)}},[W,Z,X]),Mt=t.useCallback(async(e,t,n)=>{if(!W)return;let r=n?.others,i=n?.pending;if(G){Z(e,{phase:`running`});try{let e=await G(t);typeof e==`number`&&Number.isInteger(e)&&e>=0&&(i=e,r=n?Math.max(0,e-(n.pending-n.others)):void 0)}catch{}}if(r===0){await Q(e,t);return}Z(e,{phase:`confirm`,...r===void 0?{}:{others:r},...i===void 0?{}:{total:i}})},[W,G,Q,Z]),Nt=t.useRef(new Set),It=t.useRef(!1);t.useEffect(()=>{let e=[];for(let t of o)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(!It.current){It.current=!0;for(let t of e)Nt.current.add(t.key);return}if(!it||!U||g)return;let t=e.filter(e=>!Nt.current.has(e.key));if(t.length!==0){for(let e of t)Nt.current.add(e.key);for(let e of[...new Set(t.map(e=>e.packageId))])Dt(e)}},[o,g,it,U,Dt]);let Lt=t.useRef(new Set);t.useEffect(()=>{if(!_e)return;let e=new Map,t;for(let n of o){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=Lt.current,r=!1;for(let t of e.keys())n.has(t)||(n.add(t),r=!0);r&&_e([...e.values()],t)},[o,_e]);let Ht=t.useRef(new Set);t.useEffect(()=>{if(ve)for(let e of o)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&&!Ht.current.has(t.toolCallId)&&(Ht.current.add(t.toolCallId),ve(n.name))}},[o,ve]);let Ut=t.useRef(null),$=t.useCallback(()=>{Ut.current?.scrollToBottom({animation:`smooth`})},[]),Wt=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()??``;dt.current=i,ft.current=null,en.current=null,c?.(i,n),$()},[c,$]),Gt=t.useCallback(e=>{en.current=null,dt.current=``,c?.(e),$()},[c,$]),qt=t.useRef(null),[Qt,$t]=t.useState(()=>new Set),en=t.useRef(null),tn=t.useCallback((e,t)=>{dt.current=``,t&&(en.current=t,$t(e=>{let n=new Set(e);return n.add(t),n})),c?.(e?We:Ue),$()},[c,Ue,We,$]),[nn,rn]=t.useState(()=>new Set),an=t.useRef(null),[on,sn]=t.useState(()=>new Map),cn=t.useCallback(e=>{dt.current=``,e&&(an.current=e,rn(t=>{let n=new Set(t);return n.add(e),n})),c?.(Xe),$()},[c,Xe,$]),ln=t.useCallback(()=>{let e=qt.current?.querySelector(`textarea`);e&&(e.focus(),e.scrollIntoView({block:`nearest`}))},[]);t.useEffect(()=>{if(!_||!Ft(_)||ft.current===_)return;if(ft.current=_,en.current){let e=en.current;en.current=null,$t(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})}if(an.current){let e=an.current;an.current=null,rn(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),Pt(_)&&sn(t=>{if(t.has(e))return t;let n=new Map(t);return n.set(e,_),n})}let e=dt.current;if(!e)return;let t=qt.current?.querySelector(`textarea`);t&&t.value.trim()===``&&(t.value=e,t.dispatchEvent(new Event(`input`,{bubbles:!0})),t.focus())},[_]);let un=t.useCallback(e=>{navigator.clipboard?.writeText(e.content),ut(e.id),window.setTimeout(()=>ut(t=>t===e.id?null:t),1500)},[]),fn=t.useMemo(()=>{let e=new Set,t=[],n=-1,r=0;for(let e of o)for(let i of e.toolInvocations??[])(i.proposedPlan||ii(i))&&i.toolCallId&&t.push({id:i.toolCallId,order:r}),i.toolName===`apply_blueprint`&&!Ur(i.result)&&(n=r),r+=1;for(let r of t)r.order<n&&e.add(r.id);return e},[o]),pn=t.useMemo(()=>{let e;for(let t of o)for(let n of t.toolInvocations??[])n.builderHandoff&&n.toolCallId&&(e=n.toolCallId);return e},[o]),mn=t.useMemo(()=>{let e=new Set,t=[],n=new Map,r=0;for(let e of o)for(let i of e.toolInvocations??[])i.proposedChanges&&i.toolCallId?t.push({id:i.toolCallId,toolName:i.toolName??``,order:r}):i.toolName&&!Ur(i.result)&&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},[o]),hn=t.useMemo(()=>{let e=new Map,t=new Map,n=[],r=0;for(let i of o)for(let a of i.toolInvocations??[]){if(a.proposedChanges&&a.toolCallId)n.push({id:a.toolCallId,toolName:a.toolName??``,order:r}),t.delete(a.toolCallId);else if(a.toolCallId?.startsWith(`replay_`)){let i;for(let e of n)e.order<r&&e.toolName===(a.toolName??``)&&(i=e);i&&(a.replayOutcome?(e.set(i.id,a.replayOutcome),a.replayOutcome.dispatchError?t.set(i.id,r):t.delete(i.id)):a.result===void 0&&!a.errorText&&e.set(i.id,{kind:`applying`}))}else if(a.result!==void 0&&t.size>0){let n=ue(a.result);if(n)for(let[i,a]of t)r>a&&e.set(i,n)}r+=1}return e},[o]),gn=g,_n;for(let e of o)for(let t of e.toolInvocations??[])(t.proposedPlan||ii(t))&&t.toolCallId&&(_n=t.toolCallId);let vn=_n!==void 0&&Gr({replayOutcome:hn.get(_n),built:fn.has(_n),confirmed:mn.has(_n),approved:Qt.has(_n)})===`pending`,yn=t.useRef(ye);t.useEffect(()=>{yn.current=ye},[ye]),t.useEffect(()=>{yn.current?.(vn)},[vn]);let bn=e=>{let t=e.state??(e.errorText?`output-error`:e.result===void 0?`input-available`:`output-available`),n=`tool-${e.toolName}`,a=H?.[e.toolCallId],o=t===`approval-requested`&&!!B&&!a,s=t===`approval-requested`&&!!e.pendingActionId,l=Ot(e.toolName,J),u=kt(e.result),d=K===`debug`&&l&&l.toLowerCase()!==e.toolName.toLowerCase(),f=K===`debug`||o,m=e.draftReview?.packageId,h=m===void 0?void 0:wt.get(m),g=h===void 0?bt.has(e.toolCallId):h===0,_=t===`input-streaming`||t===`input-available`,v=Gr({replayOutcome:hn.get(e.toolCallId),built:fn.has(e.toolCallId),confirmed:mn.has(e.toolCallId),approved:Qt.has(e.toolCallId)}),y=t===`output-available`&&Ur(e.result)?Kr[v]:t,b=(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,_?ri(e)?(0,i.jsx)(Ei,{label:Y.designingPlanLabel,hints:Y.designingPlanHints,offlineLabel:Y.connectionOfflineLabel}):(0,i.jsx)(Di,{offlineLabel:Y.connectionOfflineLabel}):null]});return(0,i.jsxs)(yr,{defaultOpen:t===`output-error`||t===`approval-requested`||!!(e.draftReview&&e.draftReview.items.length>0)||!!e.proposedPlan||!!e.proposedChanges||!!e.builderHandoff||!!e.recordHandoff||ii(e),children:[(0,i.jsx)(xr,{type:n,state:y,title:b,statusLabels:yt}),(0,i.jsxs)(Sr,{children:[f&&e.args!==void 0?(0,i.jsx)(Cr,{input:e.args}):null,s?null:f||t===`output-error`?(0,i.jsx)(qi,{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:()=>B?.(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:()=>B?.(e.toolCallId,!1,te),className:`inline-flex h-7 items-center rounded-md border bg-background px-3 text-xs font-medium hover:bg-accent`,children:V})]}):null,e.draftReview&&e.draftReview.items.length>0&&(re||(U||ge)&&e.draftReview.packageId)?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 p-3 border-t bg-muted/30`,children:[U&&e.draftReview.packageId?g?(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`}),xe,e.draftReview.failedCount?` · ${e.draftReview.failedCount} need${e.draftReview.failedCount===1?`s`:``} attention`:``]}):(0,i.jsxs)(`button`,{type:`button`,onClick:()=>void Dt(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`}),be,typeof h==`number`&&h>0?` (${h})`:``]}):null,re?(0,i.jsxs)(`button`,{type:`button`,onClick:()=>re(e.draftReview.items),className:U&&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,g?null:(()=>{let t=e.draftReview,n=ti(t.items,t.packageId,t.materialized===!0,{onPreviewDraftApp:pe,onPreviewDraft:ge});return n?(0,i.jsxs)(`button`,{type:`button`,onClick:n.run,className:`inline-flex h-7 items-center gap-1.5 rounded-md border px-3 text-xs font-medium hover:bg-muted`,"data-testid":n.app?`draft-preview-app`:`draft-preview`,children:[(0,i.jsx)(r.Eye,{className:`size-3.5`}),he]}):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`}),Se]}):null,e.draftReview.summary?(0,i.jsx)(`span`,{className:`min-w-0 flex-1 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,bt.has(e.toolCallId)?(0,i.jsx)(pi,{health:St.get(e.toolCallId)}):null,e.draftReview.nextSteps&&e.draftReview.nextSteps.length>0&&!me(e.draftReview)?(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:Ce}),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.builderHandoff?(0,i.jsxs)(`div`,{className:`flex flex-col gap-2 border-t bg-muted/20 px-3 py-2.5`,"data-testid":`builder-handoff`,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.Sparkles,{className:`size-3.5`}),Te]}),(0,i.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.builderHandoff.prompt}),(()=>{let t=!!pn&&e.toolCallId!==pn;return(0,i.jsx)(`button`,{type:`button`,onClick:()=>Ae?.(e.builderHandoff),disabled:!Ae||t,"data-testid":t?`builder-handoff-superseded`:`builder-handoff-open`,title:t?ke:void 0,className:`inline-flex w-fit items-center gap-1 rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-50`,children:Ee})})()]}):null,e.recordHandoff?(0,i.jsxs)(`div`,{className:`flex flex-col gap-2 border-t bg-muted/20 px-3 py-2.5`,"data-testid":`record-handoff`,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.Sparkles,{className:`size-3.5`}),De]}),(0,i.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[e.recordHandoff.label??e.recordHandoff.objectName,e.recordHandoff.reason?` — ${e.recordHandoff.reason}`:``]}),(0,i.jsx)(`button`,{type:`button`,onClick:()=>je?.(e.recordHandoff),disabled:!je,"data-testid":`record-handoff-open`,className:`inline-flex w-fit items-center gap-1 rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-50`,children:Oe})]}):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)(`div`,{className:`flex items-center gap-2`,children:[(0,i.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-1.5 text-xs font-medium text-foreground/80`,"data-testid":`proposed-plan-title`,children:[(0,i.jsx)(r.ClipboardList,{className:`size-3.5 shrink-0`}),(0,i.jsx)(`span`,{className:`truncate`,children:e.proposedPlan.appLabel?`${we} · ${e.proposedPlan.appLabel}`:we})]}),c&&!fn.has(e.toolCallId)&&!Qt.has(e.toolCallId)?(0,i.jsx)(`span`,{className:`ml-auto inline-flex h-5 shrink-0 items-center rounded-md bg-amber-50 px-1.5 text-[10px] font-medium text-amber-700 dark:bg-amber-950/30 dark:text-amber-300`,"data-testid":`proposed-plan-awaiting`,children:ht}):null]}),(()=>{let t=e.proposedPlan,n=t.planCard?.sampleData?.line,r=pt(n?{...t.counts,seedData:0}:t.counts);return n&&r.push(n),r.length?(0,i.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,"data-testid":`proposed-plan-counts`,children:r.join(` · `)}):null})(),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`,title:e.proposedPlan.targetApp,children:[`+ `,mt(e.proposedPlan.targetApp)]}):null,e.proposedPlan.summary?(0,i.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.proposedPlan.summary}):null,e.proposedPlan.planCard?(0,i.jsx)(ji,{objects:e.proposedPlan.planCard.objects,heading:gt}):e.proposedPlan.objects.some(e=>e.fields)?(0,i.jsxs)(`div`,{className:`flex flex-col`,"data-testid":`proposed-plan-objects`,children:[(0,i.jsx)(`span`,{className:`text-[11px] font-medium text-foreground/70`,children:gt}),e.proposedPlan.objects.map(e=>(0,i.jsxs)(`div`,{className:`flex items-start gap-2 border-t border-border/60 py-1.5 first-of-type:border-t-0`,"data-testid":`proposed-plan-object-${e.name}`,children:[(0,i.jsx)(`span`,{className:`w-20 shrink-0 truncate pt-0.5 text-xs font-medium text-foreground`,title:e.name,children:e.label||e.name}),(0,i.jsx)(`div`,{className:`flex min-w-0 flex-wrap gap-1`,children:e.fields?e.fields.map(e=>(0,i.jsx)(`span`,{className:`inline-flex h-5 items-center rounded-md bg-muted px-1.5 text-[11px] text-foreground/80`,title:e.name,"data-testid":`proposed-plan-field`,children:e.label||e.name},e.name)):e.fieldCount>0?(0,i.jsxs)(`span`,{className:`pt-0.5 text-[11px] text-foreground/40`,children:[`· `,e.fieldCount]}):null})]},e.name))]}):e.proposedPlan.objects.length>0?(0,i.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,"data-testid":`proposed-plan-object-chips`,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,n=t.planCard?t.planCard.views:t.viewIntents;return n&&n.length>0?(0,i.jsxs)(`div`,{className:`flex flex-col`,"data-testid":`proposed-plan-views`,children:[(0,i.jsx)(`span`,{className:`text-[11px] font-medium text-foreground/70`,children:_t}),n.map(e=>(0,i.jsxs)(`div`,{className:`flex items-start gap-2 border-t border-border/60 py-1.5 first-of-type:border-t-0`,title:e.view,"data-testid":`proposed-plan-view`,children:[(0,i.jsx)(`span`,{className:`inline-flex h-5 w-24 shrink-0 items-center justify-center truncate rounded-md bg-muted px-1.5 text-[11px] text-foreground/80`,children:e.label??e.view}),(0,i.jsx)(`span`,{className:`min-w-0 pt-0.5 text-[11px] text-foreground/80`,"data-testid":`proposed-plan-view-line`,children:e.line})]},`${e.object}.${e.view}`))]}):t.views&&t.views.length>0?(0,i.jsxs)(`div`,{className:`flex flex-col gap-0.5`,"data-testid":`proposed-plan-views`,children:[(0,i.jsx)(`span`,{className:`text-[11px] font-medium text-foreground/70`,children:_t}),t.views.map(e=>(0,i.jsxs)(`div`,{className:`flex items-start gap-1.5 text-[11px] text-foreground/80`,title:e.name,"data-testid":`proposed-plan-view`,children:[(0,i.jsx)(`span`,{className:`mt-px shrink-0 text-foreground/40`,children:`·`}),(0,i.jsx)(`span`,{children:e.label||e.name})]},e.name))]}):null})(),(()=>{let{designNotes:t,deferred:n}=oi(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:Fe}),(0,i.jsx)(`ul`,{className:`flex list-disc flex-col gap-0.5 pl-4 text-[11px] text-muted-foreground marker:text-foreground/40`,children:t.map((e,t)=>(0,i.jsx)(`li`,{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`}),Ie]}),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`}),Pe]}),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})]}),c&&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:()=>c(Ge(t,e)),disabled:gn,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 disabled:cursor-not-allowed disabled:opacity-50 dark:border-amber-800 dark:text-amber-200 dark:hover:bg-amber-900/40`,children:e},n))}):null]},n)})]}):null,c?fn.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]})}):Qt.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 bg-muted/40 px-3 text-xs font-medium text-muted-foreground`,"data-testid":`proposed-plan-building`,children:[(0,i.jsx)(r.Loader2,{className:`size-3.5 animate-spin`}),Ve]})}):(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:()=>tn(e.proposedPlan.questions.length>0,e.toolCallId),disabled:gn,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 disabled:cursor-not-allowed disabled:opacity-50`,"data-testid":`proposed-plan-approve`,children:[(0,i.jsx)(r.Rocket,{className:`size-3.5`}),Re]}),(0,i.jsx)(`button`,{type:`button`,onClick:ln,disabled:gn,className:`inline-flex h-7 items-center rounded-md border bg-background px-3 text-xs font-medium hover:bg-accent disabled:cursor-not-allowed disabled:opacity-50`,"data-testid":`proposed-plan-adjust`,children:ze}),(0,i.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,"data-testid":`proposed-plan-reply-hint`,children:Le})]}):(0,i.jsx)(`span`,{className:`text-[11px] italic text-muted-foreground/80`,children:Le})]}):null,ii(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`}),we]}),(0,i.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:He}),c?fn.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]})}):Qt.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 bg-muted/40 px-3 text-xs font-medium text-muted-foreground`,"data-testid":`proposed-plan-building`,children:[(0,i.jsx)(r.Loader2,{className:`size-3.5 animate-spin`}),Ve]})}):(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:()=>tn(!1,e.toolCallId),disabled:gn,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 disabled:cursor-not-allowed disabled:opacity-50`,"data-testid":`proposed-plan-approve`,children:[(0,i.jsx)(r.Rocket,{className:`size-3.5`}),Re]}),(0,i.jsx)(`button`,{type:`button`,onClick:ln,disabled:gn,className:`inline-flex h-7 items-center rounded-md border bg-background px-3 text-xs font-medium hover:bg-accent disabled:cursor-not-allowed disabled:opacity-50`,"data-testid":`proposed-plan-adjust`,children:ze})]}):(0,i.jsx)(`span`,{className:`text-[11px] italic text-muted-foreground/80`,children:Le})]}):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:[Yr(e.proposedChanges)?(0,i.jsx)(ei,{changes:e.proposedChanges,verbLabels:Ze}):(0,i.jsxs)(i.Fragment,{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`}),Ke]}),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:Jr(e,Ze)})]},t))})]}),(()=>{let t=hn.get(e.toolCallId);if(t?.kind===`published`)return(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-applied`,children:[(0,i.jsx)(r.CheckCircle2,{className:`size-3.5`}),$e]})});if(t?.kind===`failed`)return(0,i.jsxs)(`div`,{className:`flex flex-col gap-1 pt-0.5`,"data-testid":`proposed-changes-actions`,children:[(0,i.jsxs)(`span`,{className:`inline-flex h-7 w-fit items-center gap-1.5 rounded-md border border-red-200 bg-red-50 px-3 text-xs font-medium text-red-700 dark:border-red-900/50 dark:bg-red-950/30 dark:text-red-300`,"data-testid":`proposed-changes-failed`,children:[(0,i.jsx)(r.XCircle,{className:`size-3.5`}),tt]}),t.error?(0,i.jsx)(`span`,{className:`text-[11px] text-red-700/80 dark:text-red-300/80`,"data-testid":`proposed-changes-failed-reason`,children:t.error}):null]});if(t?.kind===`drafted`&&t.appliedCard){let n=t.packageId,r=At.get(e.toolCallId),a=ti(t.items??[],n,!1,{onPreviewDraftApp:pe,onPreviewDraft:ge});return(0,i.jsx)(ni,{card:t.appliedCard,others:t.draftState?.others,discard:r,onPreview:a?.run,previewLabel:he,onReview:ae&&n?()=>ae(n):void 0,onPublish:!ae&&U&&n?()=>void Dt(n):void 0,publishLabel:be,onDiscard:W&&n?()=>void Mt(e.toolCallId,n,t.draftState):void 0,onDiscardConfirm:W&&n?()=>void Q(e.toolCallId,n):void 0,onDiscardCancel:()=>Z(e.toolCallId,void 0)})}if(t?.kind===`drafted`){let e=ti(t.items??[],t.packageId,!1,{onPreviewDraftApp:pe,onPreviewDraft:ge});return(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)(`span`,{className:`inline-flex h-7 items-center gap-1.5 rounded-md border border-amber-200 bg-amber-50 px-3 text-xs font-medium text-amber-800 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-300`,"data-testid":`proposed-changes-drafted`,children:[(0,i.jsx)(r.Clock3,{className:`size-3.5`}),et]}),U&&t.packageId?(0,i.jsxs)(`button`,{type:`button`,onClick:()=>void Dt(t.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":`proposed-changes-publish`,children:[(0,i.jsx)(r.Rocket,{className:`size-3.5`}),be]}):null,e?(0,i.jsxs)(`button`,{type:`button`,onClick:e.run,className:`inline-flex h-7 items-center gap-1.5 rounded-md border px-3 text-xs font-medium hover:bg-muted`,"data-testid":`proposed-changes-preview`,children:[(0,i.jsx)(r.Eye,{className:`size-3.5`}),he]}):null]})}return on.has(e.toolCallId)?(0,i.jsxs)(`div`,{className:`flex flex-col items-start gap-1 pt-0.5`,"data-testid":`proposed-changes-actions`,children:[(0,i.jsxs)(`span`,{className:`inline-flex h-7 w-fit items-center gap-1.5 rounded-md border border-amber-200 bg-amber-50 px-3 text-xs font-medium text-amber-800 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-300`,"data-testid":`proposed-changes-quota-blocked`,children:[(0,i.jsx)(r.XCircle,{className:`size-3.5`}),tt]}),(0,i.jsx)(Gi,{error:on.get(e.toolCallId),onUpgrade:p})]}):t?.kind===`applying`||nn.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 bg-muted/40 px-3 text-xs font-medium text-foreground/70`,"data-testid":`proposed-changes-applying`,children:[(0,i.jsx)(r.Loader2,{className:`size-3.5 animate-spin`}),Qe]})}):c?mn.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`}),qe]})}):(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:()=>cn(e.toolCallId),disabled:gn,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 disabled:cursor-not-allowed disabled:opacity-50`,"data-testid":`proposed-changes-confirm`,children:[(0,i.jsx)(r.CheckCircle2,{className:`size-3.5`}),e.proposedChanges?.primaryAction===`save_draft`?vt:Je]}),(0,i.jsx)(`button`,{type:`button`,onClick:ln,disabled:gn,className:`inline-flex h-7 items-center rounded-md border bg-background px-3 text-xs font-medium hover:bg-accent disabled:cursor-not-allowed disabled:opacity-50`,"data-testid":`proposed-changes-adjust`,children:ze})]}):(0,i.jsx)(`span`,{className:`text-[11px] italic text-muted-foreground/80`,children:Ye})})()]}):null]})]},e.toolCallId)};return(0,i.jsxs)(`div`,{ref:st,className:(0,n.cn)(ct?`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:T},...ot,children:[u&&!w&&o.length>0&&(0,i.jsx)(`div`,{className:(0,n.cn)(`flex items-center justify-end px-4 py-2`,ct?`bg-background`:`border-b bg-muted/30`),children:(0,i.jsx)(`button`,{type:`button`,onClick:u,className:`text-xs text-muted-foreground hover:text-foreground transition-colors`,children:Y.clear})}),I?(0,i.jsx)(`div`,{className:(0,n.cn)(`shrink-0`,!ct&&`border-b bg-background/50`),children:I}):null,(0,i.jsxs)(Rt,{className:`flex-1 min-h-0`,contextRef:Ut,children:[(0,i.jsxs)(zt,{className:(0,n.cn)(`space-y-4`,ct?`mx-auto w-full max-w-2xl px-4 py-8 sm:px-0`:`px-4 py-3`),children:[o.length===0?(0,i.jsxs)(Bt,{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:S?(0,i.jsx)(`img`,{src:S,alt:``,className:`size-full rounded-md object-cover`}):(0,i.jsx)(r.Bot,{className:`size-4`})}),(0,i.jsxs)(`div`,{className:`w-full max-w-full space-y-1`,children:[(0,i.jsx)(`h3`,{className:`text-sm font-medium text-foreground/90 break-words`,children:Y.emptyTitle}),(0,i.jsx)(`p`,{className:`text-sm text-muted-foreground break-words`,children:Y.emptyDescription})]}),A&&A.length>0?(0,i.jsx)(`div`,{className:`flex w-full max-w-full flex-wrap justify-center gap-2`,children:A.map(e=>(0,i.jsx)(pr,{className:`h-auto min-h-8 min-w-0 max-w-full whitespace-normal break-words rounded-full border-border/60 bg-background/80 px-3 py-1 text-left text-xs font-medium text-foreground/90 shadow-none hover:bg-muted/60`,suggestion:e,onClick:Gt},e))}):null]}):o.map(e=>{let t=e.role===`user`,a=e.toolInvocations??[],o=e.reasoning?.trim(),s=e.sources??[],c=t?void 0:e.buildProgress,u=!t&&!a.some(e=>!!e.proposedPlan)?e.blueprintProgress:void 0,d=!t&&K===`summary`?a.filter(e=>!si(e)&&!(u&&e.toolName===`propose_blueprint`)):[],p=!t&&K===`debug`?a:!t&&K!==`debug`?a.filter(si):[],m=!t&&e.content.trim().length>0&&!li(e.content),h=K===`debug`&&!!o,g=!t&&!!e.streaming&&!m&&d.length===0&&p.length===0&&!h&&!c&&!u,_=a.find(e=>e.draftReview?.packageId&&e.draftReview.kind!==`edit`&&e.draftReview.items?.some(e=>e.type===`app`)),w=a.find(e=>N(e.result)?.status===`published`&&!!de(e.result)),T=_?.draftReview?.packageId??(w?de(w.result):void 0),E;if(c?.phase===`done`)for(let e=a.length-1;e>=0&&!E;e--)E=ne(a[e].result);let D=w!==void 0||_!==void 0&&(T!==void 0&&wt.has(T)?wt.get(T)===0:bt.has(_.toolCallId)),O=d.length>0||p.length>0||!!c||!!u;return(0,i.jsx)(Jt,{from:Vr(e.role),children:(0,i.jsxs)(`div`,{className:(0,n.cn)(`flex w-full gap-2.5`,y?t?`flex-row-reverse items-start`:`flex-row items-start`:`flex-col`),children:[y?(0,i.jsx)(hi,{isUser:t,url:t?b:S,fallback:t?x:C}):null,(0,i.jsxs)(`div`,{className:(0,n.cn)(`flex min-w-0 flex-col gap-2`,y&&!t&&`flex-1`),children:[(0,i.jsxs)(Yt,{children:[!t&&K===`summary`&&d.length>0?(0,i.jsx)(zi,{phaseKey:e.id,streaming:!!e.streaming,phaseTools:a,summaryTools:d,translateToolTitle:J,labels:Y}):null,u?(0,i.jsx)(Ai,{progress:u,designingLabel:Y.designingPlanLabel,extendChip:mt,waitingLabel:Y.connectionWaiting,stalledLabel:Y.connectionStalledLabel,offlineLabel:Y.connectionOfflineLabel}):null,c?(0,i.jsx)(Ni,{progress:c,appSegment:T,live:D,nextSteps:_?.draftReview?.nextSteps,checklist:E,onOpenBuiltApp:oe,openBuiltAppLabel:se,onDesignBuiltApp:ce,designBuiltAppLabel:le,getArtifactAction:fe,onPreviewDraftApp:pe,previewDraftLabel:he,waitingLabel:Y.connectionWaiting,stalledLabel:Y.connectionStalledLabel,offlineLabel:Y.connectionOfflineLabel}):null,!t&&K===`debug`&&o?(0,i.jsxs)(Ar,{isStreaming:!!e.streaming&&!e.content,className:`mb-2`,children:[(0,i.jsx)(Mr,{}),(0,i.jsx)(Nr,{children:o})]}):null,!t&&p.length>0?p.map(bn):null,t?e.content?(0,i.jsx)(`div`,{className:`whitespace-pre-wrap break-words`,children:e.content}):null:g?(0,i.jsx)(_i,{}):m?(0,i.jsx)(Kt.Provider,{value:je??null,children:(0,i.jsx)(dn,{isAnimating:!!e.streaming,children:e.content})}):!e.streaming&&!O&&li(e.content)?(0,i.jsx)(`span`,{className:`text-xs italic text-muted-foreground/70`,title:e.content,children:Y.agentActivity}):null,e.streaming&&m?(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)(l.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)(Pr,{children:[(0,i.jsx)(Fr,{count:s.length}),(0,i.jsx)(Ir,{children:s.map((e,t)=>(0,i.jsx)(Lr,{href:e.url,title:e.title??e.url},e.id??e.url??t))})]}):null,v&&e.timestamp?(0,i.jsx)(`div`,{className:`text-[10px] opacity-70 mt-1`,children:e.timestamp}):null]}),!t&&!g&&m?(0,i.jsxs)(Xt,{className:`opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100`,children:[(0,i.jsx)(Zt,{label:lt===e.id?Y.copied:Y.copy,tooltip:lt===e.id?Y.copied:Y.copy,onClick:()=>un(e),children:lt===e.id?(0,i.jsx)(r.Check,{className:`size-3.5`}):(0,i.jsx)(r.Copy,{className:`size-3.5`})}),f?(0,i.jsx)(Zt,{label:Y.regenerate,tooltip:Y.regenerate,onClick:f,children:(0,i.jsx)(r.RefreshCw,{className:`size-3.5`})}):null,K===`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)}),g&&!o.some(e=>e.streaming)?(0,i.jsx)(gi,{showAvatar:y,assistantAvatarUrl:S,assistantAvatarFallback:C,waitingLabel:Y.connectionWaiting,stalledLabel:Y.connectionStalledLabel,offlineLabel:Y.connectionOfflineLabel}):null]}),(0,i.jsx)(Vt,{})]}),_?Ft(_)&&!Pt(_)?(0,i.jsx)(Ui,{error:_,rateLimitedLabel:Y.sendFailedRateLimited,genericLabel:Y.sendFailedGeneric}):(0,i.jsx)(Ki,{error:_,onReload:f,onUpgrade:p}):null,h?null:(0,i.jsxs)(`div`,{ref:qt,className:(0,n.cn)(`relative`,ct&&`mx-auto w-full max-w-2xl px-4 pb-4 sm:px-0`),children:[R?(0,i.jsx)(`div`,{className:`mb-2 flex empty:hidden`,"data-testid":`prompt-header-slot`,children:R}):null,nt?(0,i.jsx)(`div`,{className:`mb-1 flex`,"data-testid":`surface-context-chip`,children:(0,i.jsx)(`span`,{className:`inline-flex items-center gap-1 rounded-full border bg-muted/40 px-2 py-0.5 text-[11px] text-muted-foreground`,title:rt,children:nt})}):null,L?(0,i.jsx)(`div`,{className:`absolute bottom-full left-0 right-0 z-10 px-3 pb-1`,children:L}):null,(0,i.jsxs)(Nn,{accept:O,fileInputLabel:Y.uploadFiles,maxFileSize:k,onSubmit:Wt,onError:e=>{console.warn(`[plugin-chatbot] prompt-input error`,e)},children:[D?(0,i.jsx)(Pn,{children:(0,i.jsx)(jn,{children:e=>(0,i.jsx)(An,{data:e,removeLabel:Y.removeAttachment})})}):null,(0,i.jsx)(Fn,{placeholder:s,disabled:m||q===`streaming`,onChange:z?e=>z(e.currentTarget.value):void 0}),(0,i.jsxs)(Ln,{children:[(0,i.jsxs)(Rn,{children:[D?(0,i.jsxs)(Bn,{children:[(0,i.jsx)(Vn,{}),(0,i.jsx)(Hn,{children:(0,i.jsx)(Mn,{})})]}):null,M&&M.length>1?(0,i.jsx)(Br,{label:Y.model,models:M,value:P??M[0].id,onPick:e=>F?.(e)}):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)(r.CornerDownLeft,{className:`h-3 w-3`}),(0,i.jsx)(`span`,{className:`opacity-70`,children:Y.sendHint}),Y.newlineHint?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(`span`,{className:`opacity-40`,children:`·`}),(0,i.jsx)(`span`,{className:`opacity-70`,children:`Shift+`}),(0,i.jsx)(r.CornerDownLeft,{className:`h-3 w-3`}),(0,i.jsx)(`span`,{className:`opacity-70`,"data-testid":`composer-newline-hint`,children:Y.newlineHint})]}):null]})]}),(0,i.jsx)(Wn,{"aria-label":q===`streaming`?Y.stopResponse:Y.submit,status:q,disabled:m,onClick:q===`streaming`?d:void 0,type:q===`streaming`?`button`:`submit`})]})]})]})]})});mi.displayName=`ChatbotEnhanced`;function hi({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 gi({showAvatar:e,assistantAvatarUrl:t,assistantAvatarFallback:r,waitingLabel:a,stalledLabel:o,offlineLabel:s}){return(0,i.jsx)(Jt,{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)(hi,{isUser:!1,url:t,fallback:r}):null,(0,i.jsx)(Yt,{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)(_i,{}),(0,i.jsx)(Si,{active:!0,pending:!0,activityKey:0,waitingLabel:a,stalledLabel:o,offlineLabel:s})]})})]})})}function _i(){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 vi(e){let t=Math.floor(e/60),n=e%60;return`${t}:${String(n).padStart(2,`0`)}`}var yi=6;function bi(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<yi}}function xi(){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 Si({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}=bi(e,t),f=xi()?`offline`:d?a?`waiting`:`receiving`:`stalled`,p=vi(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 Ci=[`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…`],wi=3500;function Ti(e,t,n=wi){if(t<=0)return-1;if(t===1)return 0;let r=Math.floor((Number.isFinite(e)&&e>0?e:0)/(n>0?n:wi));return Math.min(r,t-1)}function Ei({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),wi);return()=>clearInterval(t)},[a.length]);let l=Ti(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)(Di,{offlineLabel:o})]})}function Di({offlineLabel:e}){let[a,o]=t.useState(0),s=xi();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:vi(a)}),s?(0,i.jsxs)(`span`,{children:[`· `,e]}):null]})}var Oi=[`object`,`view`,`dashboard`,`app`,`seed`];function ki(){let{t:e}=(0,a.useObjectTranslation)();return t.useCallback(t=>{switch(t){case`object`:return e(`chatbot.build.group.object`,{defaultValue:`Objects`});case`view`:return e(`chatbot.build.group.view`,{defaultValue:`Views`});case`dashboard`:return e(`chatbot.build.group.dashboard`,{defaultValue:`Dashboards`});case`app`:return e(`chatbot.build.group.app`,{defaultValue:`App`});case`seed`:return e(`chatbot.build.group.seed`,{defaultValue:`Sample data`});default:return t}},[e])}function Ai({progress:e,designingLabel:t=`Designing your app…`,extendChip:n,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=ui(),g=c===`done`,_=m??`${c}:${f.length}`,v=g&&(l||u)||t,y=h(p??{});return(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:[g?(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:v}),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`,title:d,children:[`+ `,n(d)]}):null,g?null:(0,i.jsx)(`span`,{className:`ml-auto shrink-0`,children:(0,i.jsx)(Si,{active:!0,activityKey:_,waitingLabel:a,stalledLabel:o,offlineLabel:s})})]}),!g&&(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,y.length>0?(0,i.jsx)(`span`,{className:`mt-2 block text-[11px] text-muted-foreground`,children:y.join(` · `)}):null]})}function ji({objects:e,heading:t}){let{t:r}=(0,a.useObjectTranslation)(),o=r(`chatbot.plan.suggestedField`,{defaultValue:`suggested`});return(0,i.jsxs)(`div`,{className:`flex flex-col`,"data-testid":`proposed-plan-objects`,children:[(0,i.jsx)(`span`,{className:`text-[11px] font-medium text-foreground/70`,children:t}),e.map(e=>(0,i.jsxs)(`div`,{className:`flex items-start gap-2 border-t border-border/60 py-1.5 first-of-type:border-t-0`,"data-testid":`proposed-plan-object-${e.name}`,children:[(0,i.jsx)(`span`,{className:`inline-flex h-5 w-20 shrink-0 items-center justify-center truncate rounded-md bg-primary/10 px-1.5 text-[11px] font-medium text-primary`,title:e.name,children:e.label}),(0,i.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-1`,children:[(0,i.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:e.fields.map(e=>(0,i.jsxs)(`span`,{className:(0,n.cn)(`inline-flex h-5 items-center gap-1 rounded-md px-1.5 text-[11px]`,e.suggested?`border border-dashed border-border text-muted-foreground`:`bg-muted text-foreground/80`),title:e.name,"data-testid":`proposed-plan-field`,...e.suggested?{"data-suggested":`true`}:{},children:[e.label,e.format?(0,i.jsx)(`span`,{className:`font-mono text-[10.5px] text-muted-foreground`,"data-testid":`proposed-plan-field-format`,children:e.format.label}):null,e.lifecycle?(0,i.jsx)(`span`,{className:`text-[10.5px] text-muted-foreground`,"data-testid":`proposed-plan-field-lifecycle`,children:e.lifecycle.label}):null,e.suggested?(0,i.jsxs)(`span`,{children:[`· `,o]}):null]},e.name))}),e.nameField?(0,i.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,"data-testid":`proposed-plan-name-field`,...e.nameField.generated?{"data-generated":`true`}:{},children:e.nameField.generated?e.nameField.generated.line:r(`chatbot.plan.nameField`,{field:e.nameField.label,defaultValue:`Name: {{field}}`})}):null]})]},e.name))]})}function Mi({checklist:e}){let t=e.lines.filter(e=>e.kind===`object`),n=e.lines.filter(e=>e.kind!==`object`),a=(e,t)=>e.length>0?(0,i.jsx)(`ul`,{className:`flex flex-col`,"data-testid":t,children:e.map((e,t)=>(0,i.jsxs)(`li`,{className:`flex items-start gap-2 py-1 text-xs text-foreground/90`,"data-testid":`build-checklist-line`,"data-status":e.status,children:[e.status===`passed`?(0,i.jsx)(r.CheckCircle2,{className:`mt-0.5 size-3.5 shrink-0 text-emerald-600`}):(0,i.jsx)(r.TriangleAlert,{className:`mt-0.5 size-3.5 shrink-0 text-amber-600`}),(0,i.jsx)(`span`,{className:`min-w-0`,children:e.line})]},t))}):null;return(0,i.jsx)(`div`,{className:`@container`,"data-testid":`build-checklist`,children:(0,i.jsxs)(`div`,{className:`grid grid-cols-1 gap-x-6 @md:grid-cols-2`,children:[a(t,`build-checklist-objects`),a(n,`build-checklist-checks`)]})})}function Ni({progress:e,appSegment:o,onOpenBuiltApp:s,openBuiltAppLabel:c=`Open app`,onDesignBuiltApp:l,designBuiltAppLabel:u=`Design in Studio`,getArtifactAction:d,onPreviewDraftApp:f,previewDraftLabel:p=`Preview`,live:m=!1,nextSteps:h,checklist:g,waitingLabel:_=`Waiting for server…`,stalledLabel:v=`Still working…`,offlineLabel:y=`Connection lost — reconnecting…`}){let{phase:b,appLabel:x,items:S,done:C,total:w,seq:T,verify:E}=e,{t:D}=(0,a.useObjectTranslation)(),O=ki(),k=b===`done`,A=D(`chatbot.build.unknownPhase`,{defaultValue:`Unknown build phase`}),j=!k&&b!==`structure`&&b!==`data`,M=g?.app?.label??x??D(`chatbot.build.appFallback`,{defaultValue:`your app`}),N=T??`${b}:${C}:${S.length}`,P=S.find(e=>e.type===`app`),F=g?.app??P,I=g?.packageId??o,L=k&&g!==void 0,R=w>0?Math.min(100,Math.round(C/w*100)):k?100:6,z=new Map;for(let e of S){let t=z.get(e.type)??[];t.push({name:e.name,display:e.name.replace(/_sample$/,``)}),z.set(e.type,t)}let B=[...Oi.filter(e=>z.has(e)),...[...z.keys()].filter(e=>!Oi.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:[k?(0,i.jsx)(r.CheckCircle2,{className:`size-4 shrink-0 text-emerald-600`}):j?(0,i.jsx)(r.TriangleAlert,{className:`size-4 shrink-0 text-amber-600`}):(0,i.jsx)(r.Loader2,{className:`size-4 shrink-0 animate-spin text-primary`}),(0,i.jsx)(`span`,{"data-testid":`build-progress-title`,children:k?m?D(`chatbot.build.builtAndLive`,{app:M,defaultValue:`Built and live · {{app}}`}):D(`chatbot.build.built`,{app:M,defaultValue:`Built {{app}}`}):j?A:D(`chatbot.build.building`,{app:M,defaultValue:`Building {{app}}…`})}),!k&&b===`data`?(0,i.jsx)(`span`,{className:`text-xs font-normal text-muted-foreground`,children:D(`chatbot.build.addingSampleData`,{defaultValue:`adding sample data`})}):null,k?null:(0,i.jsx)(`span`,{className:`ml-auto`,children:(0,i.jsx)(Si,{active:!0,activityKey:N,waitingLabel:_,stalledLabel:v,offlineLabel:y})}),L?(0,i.jsx)(`span`,{className:(0,n.cn)(`ml-auto inline-flex h-5 shrink-0 items-center rounded-md px-1.5 text-[11px] font-medium`,g.status===`passed`?`bg-emerald-50 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-300`:`bg-amber-50 text-amber-700 dark:bg-amber-950/30 dark:text-amber-300`),"data-testid":`build-checklist-chip`,"data-status":g.status,children:D(`chatbot.build.checksPassed`,{passed:g.passed,total:g.total,defaultValue:`Checks passed {{passed}}/{{total}}`})}):null]}),k?null:(0,i.jsx)(`div`,{className:`mb-2 h-1.5 w-full overflow-hidden rounded-full bg-muted`,children:(0,i.jsx)(`div`,{className:`h-full rounded-full bg-primary transition-all duration-500`,style:{width:`${R}%`}})}),L?(0,i.jsx)(Mi,{checklist:g}):(0,i.jsx)(`ul`,{className:`space-y-1`,children:B.map(e=>{let n=z.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:O(e)}),` `,n.slice(0,6).map((n,r)=>{let a=k?d?.({type:e,name:n.name},o):null;return(0,i.jsxs)(t.Fragment,{children:[r>0?`, `:null,a?(0,i.jsx)(`button`,{type:`button`,onClick:a,className:`rounded-sm text-primary underline decoration-primary/40 underline-offset-2 hover:decoration-primary`,"data-testid":`build-artifact-link-${e}-${n.name}`,children:n.display}):n.display]},n.name)}),n.length>6?` ${D(`chatbot.build.moreArtifacts`,{n:n.length-6,defaultValue:`+{{n}} more`})}`:``]})]},e)})}),E?(0,i.jsxs)(`div`,{className:`mt-2 flex items-center gap-2 text-xs text-muted-foreground`,"data-testid":`build-verify`,title:E.tool,children:[E.phase===`done`?(0,i.jsx)(r.CheckCircle2,{className:`size-3.5 shrink-0 text-emerald-600`}):E.phase===`verify`?(0,i.jsx)(r.Loader2,{className:`size-3.5 shrink-0 animate-spin`}):(0,i.jsx)(r.TriangleAlert,{className:`size-3.5 shrink-0 text-amber-600`}),E.phase===`done`?D(`chatbot.build.verified`,{defaultValue:`Checked the change`}):E.phase===`verify`?D(`chatbot.build.verifying`,{defaultValue:`Checking the change…`}):A,E.phase===`verify`&&E.hop!==void 0?` ${D(`chatbot.build.verifyStep`,{n:E.hop,defaultValue:`step {{n}}`})}`:null]}):null,k&&F&&(l||s||f)?(0,i.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-2`,children:[s?(0,i.jsxs)(`button`,{type:`button`,onClick:()=>s(F.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:[c,(0,i.jsx)(r.ArrowRight,{className:`size-3.5`})]}):null,l?(0,i.jsx)(`button`,{type:`button`,onClick:()=>l(F.name,I),className:(0,n.cn)(`inline-flex h-7 items-center gap-1.5 rounded-md px-3 text-xs font-medium`,s?`border hover:bg-muted`:`bg-primary text-primary-foreground hover:bg-primary/90`),"data-testid":`build-progress-design-app`,children:u}):null,f&&P?(0,i.jsxs)(`button`,{type:`button`,onClick:()=>f(P.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`}),p]}):null]}):null,k&&F?(0,i.jsxs)(`p`,{className:`mt-3 border-t pt-2.5 text-xs text-muted-foreground`,"data-testid":`build-result-footer`,children:[h&&h.length>0?(0,i.jsxs)(`span`,{"data-testid":`build-result-next-steps`,children:[D(`chatbot.build.nextStepsLead`,{steps:h.map(e=>D(`chatbot.build.nextStepQuote`,{step:e,defaultValue:`“{{step}}”`})).join(` `),defaultValue:`Next, you can say: {{steps}}`}),` `]}):null,(0,i.jsx)(`span`,{"data-testid":`build-result-posture`,children:D(`chatbot.build.draftPosture`,{defaultValue:`Later changes are saved as drafts, and you publish them in Studio.`})})]}):null]})}var Pi=new Set([`load_tools`]);function Fi(e){return Pi.has(e.toolName)}function Ii(e,t){let n=new Map;for(let r of e){if(Fi(r))continue;let e=n.get(r.toolName);e?e.count+=1:n.set(r.toolName,{title:Ot(r.toolName,t)||r.toolName,count:1})}return[...n.values()]}var Li=new Map;function Ri(e,n){let[r,i]=t.useState(void 0);t.useEffect(()=>{if(!n){let t=Li.get(e);t&&t.end===void 0&&(t.end=Date.now()),i(Date.now());return}let t=Li.get(e);t?t.end=void 0:Li.set(e,{start:Date.now()}),i(Date.now());let r=setInterval(()=>i(Date.now()),1e3);return()=>clearInterval(r)},[e,n]);let a=Li.get(e);if(a&&r!==void 0)return Math.max(0,Math.floor(((a.end??r)-a.start)/1e3))}function zi({phaseKey:e,streaming:o,phaseTools:s,summaryTools:c,translateToolTitle:l,labels:u}){let{t:d}=(0,a.useObjectTranslation)(),f=fi(c.filter(e=>!Fi(e)),l),p=Ii(s,l),m=e=>f.some(t=>t.state===e),h=m(`failed`)?`failed`:m(`awaiting`)?`awaiting`:m(`running`)?`running`:`completed`,[g,_]=t.useState(null),v=g??h!==`completed`,y=Ri(e,o||h===`running`),b=s.map(e=>e.toolName),x=b.includes(`apply_blueprint`)?d(`chatbot.phase.build`,{defaultValue:`Build`}):b.includes(`propose_blueprint`)?d(`chatbot.phase.design`,{defaultValue:`Design the plan`}):void 0,S=[...x?[x]:[],d(`chatbot.phase.stepCount`,{count:p.length,defaultValue:`{{count}} steps`}),...y===void 0?[]:[vi(y)]].join(` · `),C=p.map(e=>e.count>1?`${e.title} ×${e.count}`:e.title).join(` · `);return f.length===0?null:(0,i.jsxs)(`div`,{className:`not-prose mb-2`,"data-testid":`tool-phase`,children:[(0,i.jsxs)(`div`,{className:`flex min-h-6 min-w-0 items-center gap-2 text-xs text-muted-foreground`,"data-testid":`tool-phase-line`,children:[(0,i.jsx)(Vi,{state:h}),v?null:(0,i.jsx)(`span`,{className:`sr-only`,children:Hi(h,u)}),(0,i.jsx)(`span`,{className:`shrink-0 font-medium text-foreground`,"data-testid":`tool-phase-headline`,children:S}),(0,i.jsx)(`span`,{className:`min-w-0 truncate`,title:C,"data-testid":`tool-phase-steps`,children:C}),f.length>0?(0,i.jsx)(`button`,{type:`button`,onClick:()=>_(!v),"aria-expanded":v,"aria-label":v?d(`chatbot.phase.collapse`,{defaultValue:`Hide steps`}):d(`chatbot.phase.expand`,{defaultValue:`Show steps`}),className:`ml-auto inline-flex size-5 shrink-0 items-center justify-center rounded-md hover:bg-muted hover:text-foreground`,"data-testid":`tool-phase-toggle`,children:(0,i.jsx)(r.ChevronDown,{className:(0,n.cn)(`size-3.5 transition-transform`,v&&`rotate-180`)})}):null]}),v&&f.length>0?(0,i.jsx)(`div`,{className:`mt-1`,"data-testid":`tool-phase-steps-expanded`,children:(0,i.jsx)(Bi,{groups:f,labels:u})}):null]})}function Bi({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)(Vi,{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)(Ei,{label:t.designingPlanLabel,hints:t.designingPlanHints,offlineLabel:t.connectionOfflineLabel}):(0,i.jsx)(Di,{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:Hi(e.state,t)})]},e.key))})})}function Vi({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 Hi(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 Ui({error:e,rateLimitedLabel:n,genericLabel:a}){let o=t.useMemo(()=>Lt(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 Wi(e){let{language:n}=(0,a.useObjectTranslation)(),r=(0,a.useSafeTranslate)(),i=t.useMemo(()=>Pt(e),[e]);return i?{text:(n.toLowerCase().startsWith(`zh`)?i.message:i.messageEn??i.message)||r(`chatbotQuota.fallbackMessage`,`You have reached your AI quota.`),cta:i.topUp?r(`chatbotQuota.buyCredits`,`Buy a credit pack`):r(`chatbotQuota.upgradePlan`,`Upgrade plan`)}:null}function Gi({error:e,onUpgrade:t}){let n=Wi(e);return n?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(`span`,{className:`text-[11px] leading-snug text-muted-foreground`,"data-testid":`proposed-changes-quota-reason`,children:n.text}),t?(0,i.jsx)(`button`,{type:`button`,onClick:t,className:`inline-flex h-7 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`,"data-testid":`proposed-changes-quota-upgrade`,children:n.cta}):null]}):null}function Ki({error:e,onReload:n,onUpgrade:o}){let s=(0,a.useSafeTranslate)(),c=Wi(e),{summary:l,details:u}=t.useMemo(()=>At(e),[e]),[d,f]=t.useState(!1);if(c){let{text:e,cta:t}=c,n=s(`chatbotQuota.title`,`Upgrade needed`);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:n}),(0,i.jsx)(`div`,{className:`mt-0.5 break-words leading-snug text-muted-foreground`,children:e})]}),o?(0,i.jsx)(`button`,{type:`button`,onClick:o,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:t}):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:s(`chatbotError.title`,`Response failed`)}),(0,i.jsx)(`div`,{className:`mt-0.5 break-words leading-snug text-muted-foreground`,children:l||s(`chatbotError.fallbackDetail`,`Something went wrong. Please try again.`)})]}),(0,i.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[u?(0,i.jsx)(`button`,{type:`button`,onClick:()=>f(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":d,children:d?s(`chatbotError.hide`,`Hide`):s(`chatbotError.details`,`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`}),s(`chatbotError.retry`,`Retry`)]}):null]})]}),d&&u?(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:u}):null]})})}function qi({output:e,errorText:t}){return t?(0,i.jsx)(wr,{output:void 0,errorText:t}):e==null||e===``?null:typeof e==`string`&&!Hr(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)(dn,{children:e})})]}):(0,i.jsx)(wr,{output:e,errorText:void 0})}function Ji({floatingConfig:e,headerExtra:r,headerActions:a,...o}){let{position:s=`bottom-right`,defaultOpen:l=!1,panelWidth:u=400,panelHeight:d=520,title:f=`Chat`,triggerSize:p=56}=e??{},[m,h]=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)),h(e),()=>{e&&e.parentNode&&!e.hasChildNodes()&&e.parentNode.removeChild(e)}},[]);let g=(0,i.jsxs)(ht,{defaultOpen:l,children:[(0,i.jsx)(bt,{position:s,size:p}),(0,i.jsx)(Et,{title:f,position:s,width:u,height:d,headerExtra:r,headerActions:a,children:(0,i.jsx)(mi,{...o,maxHeight:`100%`,className:(0,n.cn)(`h-full border-0 rounded-none`,o.className)})})]});return m?c.createPortal(g,m):g}v.ComponentRegistry.register(`chatbot`,({schema:e,className:n,disabled:r,...a})=>{let{messages:o,isLoading:s,sendMessage:c}=Je({api:e.api,initialMessages:e.messages,conversationId:e.conversationId,systemPrompt:e.systemPrompt,model:e.model,streamingEnabled:e.streamingEnabled,headers:e.headers,body:e.requestBody,onError:e.onError,showTimestamp:e.showTimestamp,autoResponse:e.autoResponse,autoResponseText:e.autoResponseText,autoResponseDelay:e.autoResponseDelay,onSend:e.onSend}),l=e=>{c(e)},u=(0,t.useMemo)(()=>Pe(o),[o]);return(0,i.jsx)(ba,{...(0,v.toDomProps)(a),messages:u,placeholder:e.placeholder,onSendMessage:l,disabled:r||s,showTimestamp:e.showTimestamp,userAvatarUrl:e.userAvatarUrl,userAvatarFallback:e.userAvatarFallback,assistantAvatarUrl:e.assistantAvatarUrl,assistantAvatarFallback:e.assistantAvatarFallback,maxHeight:e.maxHeight,className:n})},{namespace:`plugin-chatbot`,label:`Chatbot`,inputs:[{name:`messages`,type:`array`,description:`Array of message objects with id, role, content, and optional timestamp`},{name:`placeholder`,type:`string`},{name:`showTimestamp`,type:`boolean`},{name:`disabled`,type:`boolean`},{name:`userAvatarUrl`,type:`string`,description:`URL of the user avatar image`},{name:`userAvatarFallback`,type:`string`,description:`Fallback text shown when user avatar image is not available`},{name:`assistantAvatarUrl`,type:`string`,description:`URL of the assistant avatar image`},{name:`assistantAvatarFallback`,type:`string`,description:`Fallback text shown when assistant avatar image is not available`},{name:`maxHeight`,type:`string`},{name:`api`,type:`string`,description:`Backend SSE endpoint (e.g., /api/v1/ai/chat). When set, enables streaming AI mode.`},{name:`conversationId`,type:`string`,description:`Multi-turn conversation identifier`},{name:`systemPrompt`,type:`string`,description:`System prompt to configure assistant behavior`},{name:`model`,type:`string`,description:`AI model identifier (e.g., gpt-4o)`},{name:`streamingEnabled`,type:`boolean`},{name:`autoResponse`,type:`boolean`,description:`Automatically send a response after user message (for demo purposes, ignored when API is set)`},{name:`autoResponseText`,type:`string`},{name:`autoResponseDelay`,type:`number`},{name:`className`,type:`string`}],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`}}),v.ComponentRegistry.register(`chatbot-enhanced`,({schema:e,className:n,disabled:r,...a})=>{let{messages:o,isLoading:s,error:c,sendMessage:l,stop:u,reload:d,clear:f,isApiMode:p}=Je({api:e.api,initialMessages:e.messages,conversationId:e.conversationId,systemPrompt:e.systemPrompt,model:e.model,streamingEnabled:e.streamingEnabled,headers:e.headers,body:e.requestBody,onError:e.onError,showTimestamp:e.showTimestamp,autoResponse:e.autoResponse,autoResponseText:e.autoResponseText,autoResponseDelay:e.autoResponseDelay,onSend:e.onSend}),m=(e,t)=>{l(e,t)},h=()=>{f(),e.onClear?.()},g=(0,t.useMemo)(()=>Pe(o),[o]);return(0,i.jsx)(mi,{...(0,v.toDomProps)(a),messages:g,placeholder:e.placeholder,onSendMessage:m,onClear:h,onStop:p&&s?u:void 0,onReload:p?d:void 0,disabled:r,isLoading:s,error:c,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,surface:e.surface,className:n})},{namespace:`plugin-chatbot`,label:`Chatbot (Enhanced)`,inputs:[{name:`messages`,type:`array`},{name:`placeholder`,type:`string`},{name:`showTimestamp`,type:`boolean`},{name:`disabled`,type:`boolean`},{name:`enableMarkdown`,type:`boolean`},{name:`enableFileUpload`,type:`boolean`},{name:`processVisibility`,type:`enum`},{name:`surface`,type:`enum`,description:`'card' bordered panel, or 'plain' frameless full-page workspace`},{name:`userAvatarUrl`,type:`string`},{name:`userAvatarFallback`,type:`string`},{name:`assistantAvatarUrl`,type:`string`},{name:`assistantAvatarFallback`,type:`string`},{name:`maxHeight`,type:`string`},{name:`api`,type:`string`,description:`Backend SSE endpoint for streaming AI mode`},{name:`conversationId`,type:`string`},{name:`systemPrompt`,type:`string`},{name:`model`,type:`string`},{name:`streamingEnabled`,type:`boolean`},{name:`autoResponse`,type:`boolean`},{name:`autoResponseText`,type:`string`},{name:`autoResponseDelay`,type:`number`},{name:`className`,type:`string`}],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`}}),v.ComponentRegistry.register(`chatbot-floating`,({schema:e,className:n,disabled:r,...a})=>{let{messages:o,isLoading:s,error:c,sendMessage:l,stop:u,reload:d,clear:f,isApiMode:p}=Je({api:e.api,initialMessages:e.messages,conversationId:e.conversationId,systemPrompt:e.systemPrompt,model:e.model,streamingEnabled:e.streamingEnabled,headers:e.headers,body:e.requestBody,onError:e.onError,showTimestamp:e.showTimestamp,autoResponse:e.autoResponse,autoResponseText:e.autoResponseText,autoResponseDelay:e.autoResponseDelay,onSend:e.onSend}),m=(e,t)=>{l(e,t)},h=()=>{f(),e.onClear?.()},g=(0,t.useMemo)(()=>Pe(o),[o]);return(0,i.jsx)(Ji,{...(0,v.toDomProps)(a),floatingConfig:e.floatingConfig,messages:g,placeholder:e.placeholder,onSendMessage:m,onClear:h,onStop:p&&s?u:void 0,onReload:p?d:void 0,disabled:r,isLoading:s,error:c,showTimestamp:e.showTimestamp,userAvatarUrl:e.userAvatarUrl,userAvatarFallback:e.userAvatarFallback,assistantAvatarUrl:e.assistantAvatarUrl,assistantAvatarFallback:e.assistantAvatarFallback,enableMarkdown:e.enableMarkdown??!0,enableFileUpload:e.enableFileUpload??!1,className:n})},{namespace:`plugin-chatbot`,label:`Chatbot (Floating)`,inputs:[{name:`floatingConfig.position`,type:`string`,description:`bottom-right or bottom-left`},{name:`floatingConfig.defaultOpen`,type:`boolean`},{name:`floatingConfig.panelWidth`,type:`number`},{name:`floatingConfig.panelHeight`,type:`number`},{name:`floatingConfig.title`,type:`string`},{name:`floatingConfig.triggerSize`,type:`number`},{name:`messages`,type:`array`},{name:`placeholder`,type:`string`},{name:`enableMarkdown`,type:`boolean`},{name:`enableFileUpload`,type:`boolean`},{name:`api`,type:`string`,description:`Backend SSE endpoint for streaming AI mode`},{name:`conversationId`,type:`string`},{name:`systemPrompt`,type:`string`},{name:`model`,type:`string`},{name:`streamingEnabled`,type:`boolean`},{name:`autoResponse`,type:`boolean`},{name:`autoResponseText`,type:`string`},{name:`autoResponseDelay`,type:`number`},{name:`className`,type:`string`}],defaultProps:{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 Yi=({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`})})})]}),Xi=({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)(Yi,{size:t})}),Zi=T({CodeBlock:()=>_r,CodeBlockCopyButton:()=>vr,Conversation:()=>Rt,ConversationContent:()=>zt,ConversationEmptyState:()=>Bt,ConversationScrollButton:()=>Vt,Loader:()=>Xi,Message:()=>Jt,MessageAction:()=>Zt,MessageActions:()=>Xt,MessageAttachment:()=>fn,MessageAttachments:()=>pn,MessageBranch:()=>en,MessageBranchContent:()=>tn,MessageBranchNext:()=>an,MessageBranchPage:()=>on,MessageBranchPrevious:()=>rn,MessageBranchSelector:()=>nn,MessageContent:()=>Yt,MessageResponse:()=>dn,MessageToolbar:()=>mn,PromptInput:()=>Nn,PromptInputActionAddAttachments:()=>Mn,PromptInputActionMenu:()=>Bn,PromptInputActionMenuContent:()=>Hn,PromptInputActionMenuItem:()=>Un,PromptInputActionMenuTrigger:()=>Vn,PromptInputAttachment:()=>An,PromptInputAttachments:()=>jn,PromptInputBody:()=>Pn,PromptInputButton:()=>zn,PromptInputCommand:()=>ar,PromptInputCommandEmpty:()=>cr,PromptInputCommandGroup:()=>lr,PromptInputCommandInput:()=>or,PromptInputCommandItem:()=>ur,PromptInputCommandList:()=>sr,PromptInputCommandSeparator:()=>dr,PromptInputFooter:()=>Ln,PromptInputHeader:()=>In,PromptInputHoverCard:()=>Zn,PromptInputHoverCardContent:()=>$n,PromptInputHoverCardTrigger:()=>Qn,PromptInputProvider:()=>Dn,PromptInputSelect:()=>Kn,PromptInputSelectContent:()=>Jn,PromptInputSelectItem:()=>Yn,PromptInputSelectTrigger:()=>qn,PromptInputSelectValue:()=>Xn,PromptInputSpeechButton:()=>Gn,PromptInputSubmit:()=>Wn,PromptInputTab:()=>tr,PromptInputTabBody:()=>rr,PromptInputTabItem:()=>ir,PromptInputTabLabel:()=>nr,PromptInputTabsList:()=>er,PromptInputTextarea:()=>Fn,PromptInputTools:()=>Rn,Reasoning:()=>Ar,ReasoningContent:()=>Nr,ReasoningTrigger:()=>Mr,Shimmer:()=>Tr,Source:()=>Lr,Sources:()=>Pr,SourcesContent:()=>Ir,SourcesTrigger:()=>Fr,Suggestion:()=>pr,Suggestions:()=>fr,Tool:()=>yr,ToolContent:()=>Sr,ToolHeader:()=>xr,ToolInput:()=>Cr,ToolOutput:()=>wr,highlightCode:()=>gr,usePromptInputAttachments:()=>kn,usePromptInputController:()=>Cn,useProviderAttachments:()=>Tn,useReasoning:()=>Dr}),Qi=`/api/v1/ai`;function $i(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 ea(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}var ta=12e4;function na(e){let t=e.status;return typeof t!=`number`||t===408||t===429||t>=500&&t!==501?`transient`:`refused`}function ra(e,t,n,r){if(t!==e.generation||e.interval<=0||(clearTimeout(e.timer),e.timer=void 0,n===`refused`))return;e.failures=n===`ok`?0:e.failures+1;let i=Math.max(e.interval,ta),a=Math.min(e.interval*2**e.failures,i);e.timer=setTimeout(()=>{e.timer=void 0,r()},a)}function ia(e={}){let{apiBase:n=Qi,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.useRef({generation:0,interval:0,failures:0,timer:void 0}),y=t.useCallback(async function e(){let t=v.current,n=t.generation,{apiBase:r,status:i,conversationId:a,limit:o,headers:s}=_.current;m(!0),g(void 0);let c=`ok`;try{let e=await ea($i(r,`/pending-actions`,{status:i&&i!==`all`?i:void 0,conversationId:a,limit:o}),{method:`GET`},s);u(Array.isArray(e.items)?e.items:[]),f(typeof e.total==`number`?e.total:e.items?.length??0)}catch(e){let t=e instanceof Error?e:Error(String(e));g(t),c=na(t)}finally{m(!1)}ra(t,n,c,e)},[]),b=t.useRef(y);b.current=y;let x=t.useCallback(async e=>{let{apiBase:t,headers:n}=_.current,r=$i(t,`/pending-actions/${encodeURIComponent(e)}/approve`);try{return await ea(r,{method:`POST`,body:`{}`},n)}finally{y()}},[y]),S=t.useCallback(async(e,t)=>{let{apiBase:n,headers:r}=_.current,i=$i(n,`/pending-actions/${encodeURIComponent(e)}/reject`);try{return await ea(i,{method:`POST`,body:JSON.stringify(t?{reason:t}:{})},r)}finally{y()}},[y]);return t.useEffect(()=>{if(!c)return;let e=v.current;return e.generation+=1,e.interval=s>0?s:0,e.failures=0,b.current(),()=>{e.generation+=1,e.interval=0,clearTimeout(e.timer),e.timer=void 0}},[c,s,n,r,i,a]),{items:l,total:d,isLoading:p,error:h,refresh:y,approve:x,reject:S}}var aa=(0,a.createSafeTranslation)({"aiApprovals.title":`AI Approvals`,"aiApprovals.description":`Actions an AI agent proposed that need a human review before execution.`,"aiApprovals.tabPending":`Pending`,"aiApprovals.tabDecided":`Decided`,"aiApprovals.tabAll":`All`,"aiApprovals.statusPending":`Pending`,"aiApprovals.statusApproved":`Approved`,"aiApprovals.statusExecuted":`Executed`,"aiApprovals.statusFailed":`Failed`,"aiApprovals.statusRejected":`Rejected`,"aiApprovals.colTool":`Tool`,"aiApprovals.colAction":`Action`,"aiApprovals.colObject":`Object`,"aiApprovals.colStatus":`Status`,"aiApprovals.colProposed":`Proposed`,"aiApprovals.colDecision":`Decision`,"aiApprovals.emptyTitle":`No actions waiting`,"aiApprovals.emptyDescription":`When the AI proposes a sensitive action it will appear here for review.`,"aiApprovals.view":`View`,"aiApprovals.approve":`Approve`,"aiApprovals.reject":`Reject`,"aiApprovals.working":`Working…`,"aiApprovals.approveAndExecute":`Approve & Execute`,"aiApprovals.outcomeApprove":`Approve for {{id}}: {{message}}`,"aiApprovals.outcomeReject":`Reject for {{id}}: {{message}}`,"aiApprovals.outcomeExecuteFailed":`Action failed during execution`,"aiApprovals.drawerFallbackTitle":`Pending action`,"aiApprovals.drawerSubtitle":`Tool {{tool}} on {{object}}`,"aiApprovals.fieldProposedBy":`Proposed by`,"aiApprovals.fieldDecidedBy":`Decided by`,"aiApprovals.fieldConversation":`Conversation`,"aiApprovals.fieldToolInput":`Tool input`,"aiApprovals.fieldResult":`Result`,"aiApprovals.fieldError":`Error`,"aiApprovals.fieldRejectionReason":`Rejection reason`,"aiApprovals.rejectTitle":`Reject this action?`,"aiApprovals.rejectBody":`The reason is shown back to the AI so it can adjust its next response.`,"aiApprovals.rejectPlaceholder":`Optional reason (e.g. 'Wrong record id — please confirm with the user first.')`,"detail.justNow":`just now`,"detail.minutesAgo":`{{count}}m ago`,"detail.hoursAgo":`{{count}}h ago`,"detail.daysAgo":`{{count}}d ago`,"common.refresh":`Refresh`,"common.cancel":`Cancel`,"common.loading":`Loading…`,"common.ok":`OK`},`aiApprovals.title`),oa={pending:`secondary`,approved:`default`,executed:`default`,failed:`destructive`,rejected:`outline`};function sa(e,t){switch(e){case`pending`:return t(`aiApprovals.statusPending`);case`approved`:return t(`aiApprovals.statusApproved`);case`executed`:return t(`aiApprovals.statusExecuted`);case`failed`:return t(`aiApprovals.statusFailed`);case`rejected`:return t(`aiApprovals.statusRejected`);default:return null}}function ca({status:e,t}){let r=sa(e,t);return r===null?(0,i.jsx)(n.Badge,{variant:`outline`,children:e}):(0,i.jsx)(n.Badge,{variant:oa[e]??`outline`,children:r})}function la(e,t,n){if(!e)return`—`;let r=Date.parse(e);if(Number.isNaN(r))return e;let i=Date.now()-r,a=Math.round(i/1e3);if(a<45)return t(`detail.justNow`);let o=Math.round(a/60);if(o<60)return t(`detail.minutesAgo`,{count:o});let s=Math.round(o/60);if(s<24)return t(`detail.hoursAgo`,{count:s});let c=Math.round(s/24);if(c<30)return t(`detail.daysAgo`,{count:c});try{return new Date(e).toLocaleDateString(n)}catch{return e}}function ua(e){if(!e)return null;try{return JSON.parse(e)}catch{return e}}function da({value:e,max:t=320}){let r=typeof e==`string`?e:JSON.stringify(e,null,2);return r==null||r===``?(0,i.jsx)(n.EmptyValue,{className:`text-xs`}):(0,i.jsx)(`pre`,{className:`bg-muted/40 rounded text-xs p-2 overflow-auto whitespace-pre-wrap break-all`,style:{maxHeight:t},children:r})}function fa(e){switch(e){case`pending`:return`pending`;case`all`:return`all`;case`decided`:return`all`}}function pa({apiBase:e,headers:o,pollInterval:s=5e3,conversationId:c,variant:l=`card`,title:u,description:d,className:f}){let{t:p}=aa(),m=(0,a.useDisplayLocale)(),h=u??p(`aiApprovals.title`),g=d??p(`aiApprovals.description`),[_,v]=t.useState(`pending`),[y,b]=t.useState(null),[x,S]=t.useState(null),[C,w]=t.useState(``),[T,E]=t.useState(null),[D,O]=t.useState(null),[k,A]=t.useState(null),{items:j,isLoading:M,error:N,refresh:P,approve:F,reject:I}=ia({apiBase:e,headers:o,pollInterval:s,conversationId:c,status:fa(_)}),L=t.useMemo(()=>_===`decided`?j.filter(e=>e.status!==`pending`):j,[j,_]),R=t.useMemo(()=>y?j.find(e=>e.id===y)??null:null,[y,j]),z=t.useCallback(async e=>{E(e),O(null);try{let t=await F(e),n=t.status===`executed`;A({id:e,kind:`approve`,ok:n,message:n?p(`aiApprovals.statusExecuted`):t.error??p(`aiApprovals.outcomeExecuteFailed`)})}catch(t){let n=t instanceof Error?t.message:String(t);O(n),A({id:e,kind:`approve`,ok:!1,message:n})}finally{E(null)}},[F,p]),B=t.useCallback(async(e,t)=>{E(e),O(null);try{await I(e,t.trim()||void 0),A({id:e,kind:`reject`,ok:!0,message:p(`aiApprovals.statusRejected`)}),S(null),w(``)}catch(t){let n=t instanceof Error?t.message:String(t);O(n),A({id:e,kind:`reject`,ok:!1,message:n})}finally{E(null)}},[I,p]),ee=(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:_,onValueChange:e=>v(e),children:(0,i.jsxs)(n.TabsList,{children:[(0,i.jsx)(n.TabsTrigger,{value:`pending`,children:p(`aiApprovals.tabPending`)}),(0,i.jsx)(n.TabsTrigger,{value:`decided`,children:p(`aiApprovals.tabDecided`)}),(0,i.jsx)(n.TabsTrigger,{value:`all`,children:p(`aiApprovals.tabAll`)})]})}),(0,i.jsxs)(n.Button,{variant:`outline`,size:`sm`,onClick:()=>void P(),disabled:M,"data-testid":`ai-inbox-refresh`,children:[(0,i.jsx)(r.RefreshCw,{className:`h-3.5 w-3.5 mr-1.5 ${M?`animate-spin`:``}`}),p(`common.refresh`)]})]}),N?(0,i.jsxs)(n.Alert,{variant:`destructive`,children:[(0,i.jsx)(r.AlertCircle,{className:`h-4 w-4`}),(0,i.jsx)(n.AlertDescription,{children:N.message})]}):null,D?(0,i.jsxs)(n.Alert,{variant:`destructive`,children:[(0,i.jsx)(r.AlertCircle,{className:`h-4 w-4`}),(0,i.jsx)(n.AlertDescription,{children:D})]}):null,k&&!D?(0,i.jsxs)(n.Alert,{variant:k.ok?`default`:`destructive`,children:[k.ok?(0,i.jsx)(r.CheckCircle2,{className:`h-4 w-4`}):(0,i.jsx)(r.XCircle,{className:`h-4 w-4`}),(0,i.jsx)(n.AlertDescription,{children:p(k.kind===`approve`?`aiApprovals.outcomeApprove`:`aiApprovals.outcomeReject`,{id:`${k.id.slice(0,8)}…`,message:k.message??(k.ok?p(`common.ok`):p(`aiApprovals.statusFailed`))})})]}):null,M&&L.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`})]}):L.length===0&&N?null:L.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:p(`aiApprovals.emptyTitle`)}),(0,i.jsx)(n.EmptyDescription,{children:p(`aiApprovals.emptyDescription`)})]})}):(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:p(`aiApprovals.colTool`)}),(0,i.jsx)(n.TableHead,{className:`w-[140px]`,children:p(`aiApprovals.colAction`)}),(0,i.jsx)(n.TableHead,{className:`w-[120px]`,children:p(`aiApprovals.colObject`)}),(0,i.jsx)(n.TableHead,{className:`w-[110px]`,children:p(`aiApprovals.colStatus`)}),(0,i.jsx)(n.TableHead,{className:`w-[110px]`,children:p(`aiApprovals.colProposed`)}),(0,i.jsx)(n.TableHead,{className:`w-[260px] text-right`,children:p(`aiApprovals.colDecision`)})]})}),(0,i.jsx)(n.TableBody,{children:L.map(e=>{let t=e.status===`pending`,a=T===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)(ca,{status:e.status,t:p})}),(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`}),` `,la(e.proposed_at,p,m)]})}),(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:()=>b(e.id),"data-testid":`ai-inbox-view-${e.id}`,children:[(0,i.jsx)(r.Eye,{className:`h-3.5 w-3.5 mr-1`}),` `,p(`aiApprovals.view`)]}),t?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)(n.Button,{size:`sm`,variant:`default`,disabled:a,onClick:()=>void z(e.id),"data-testid":`ai-inbox-approve-${e.id}`,children:[(0,i.jsx)(r.CheckCircle2,{className:`h-3.5 w-3.5 mr-1`}),p(a?`aiApprovals.working`:`aiApprovals.approve`)]}),(0,i.jsxs)(n.Button,{size:`sm`,variant:`destructive`,disabled:a,onClick:()=>{S(e.id),w(``)},"data-testid":`ai-inbox-reject-${e.id}`,children:[(0,i.jsx)(r.XCircle,{className:`h-3.5 w-3.5 mr-1`}),p(`aiApprovals.reject`)]})]}):null]})})]},e.id)})})]})})]});return(0,i.jsxs)(i.Fragment,{children:[l===`card`?(0,i.jsxs)(n.Card,{className:f,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`}),` `,h]}),g?(0,i.jsx)(n.CardDescription,{children:g}):null]}),(0,i.jsx)(n.CardContent,{children:ee})]}):(0,i.jsx)(`div`,{className:f,children:ee}),(0,i.jsx)(n.Sheet,{open:!!y,onOpenChange:e=>{e||b(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`}),R?R.action_name:p(`aiApprovals.drawerFallbackTitle`)]}),(0,i.jsx)(n.SheetDescription,{children:R?p(`aiApprovals.drawerSubtitle`,{tool:R.tool_name,object:R.object_name}):p(`common.loading`)})]}),R?(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:p(`aiApprovals.colStatus`)}),(0,i.jsx)(`div`,{className:`mt-1`,children:(0,i.jsx)(ca,{status:R.status,t:p})})]}),(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs text-muted-foreground`,children:p(`aiApprovals.colProposed`)}),(0,i.jsx)(`div`,{className:`mt-1 text-xs`,children:la(R.proposed_at,p,m)})]}),(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs text-muted-foreground`,children:p(`aiApprovals.fieldProposedBy`)}),(0,i.jsx)(`div`,{className:`mt-1 text-xs font-mono break-all`,children:R.proposed_by??(0,i.jsx)(n.EmptyValue,{})})]}),(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs text-muted-foreground`,children:p(`aiApprovals.fieldDecidedBy`)}),(0,i.jsx)(`div`,{className:`mt-1 text-xs font-mono break-all`,children:R.decided_by??(0,i.jsx)(n.EmptyValue,{})})]}),R.conversation_id?(0,i.jsxs)(`div`,{className:`col-span-2`,children:[(0,i.jsx)(n.Label,{className:`text-xs text-muted-foreground`,children:p(`aiApprovals.fieldConversation`)}),(0,i.jsx)(`div`,{className:`mt-1 text-xs font-mono break-all`,children:R.conversation_id})]}):null]}),(0,i.jsx)(n.Separator,{}),(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs`,children:p(`aiApprovals.fieldToolInput`)}),(0,i.jsx)(`div`,{className:`mt-1.5`,children:(0,i.jsx)(da,{value:ua(R.tool_input)})})]}),R.result?(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs`,children:p(`aiApprovals.fieldResult`)}),(0,i.jsx)(`div`,{className:`mt-1.5`,children:(0,i.jsx)(da,{value:ua(R.result)})})]}):null,R.error?(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs text-destructive`,children:p(`aiApprovals.fieldError`)}),(0,i.jsx)(`div`,{className:`mt-1.5`,children:(0,i.jsx)(da,{value:R.error})})]}):null,R.rejection_reason?(0,i.jsxs)(`div`,{children:[(0,i.jsx)(n.Label,{className:`text-xs`,children:p(`aiApprovals.fieldRejectionReason`)}),(0,i.jsx)(`div`,{className:`mt-1.5 text-sm`,children:R.rejection_reason})]}):null,R.status===`pending`?(0,i.jsxs)(`div`,{className:`pt-2 flex gap-2`,children:[(0,i.jsxs)(n.Button,{size:`sm`,onClick:()=>void z(R.id),disabled:T===R.id,children:[(0,i.jsx)(r.CheckCircle2,{className:`h-3.5 w-3.5 mr-1`}),p(`aiApprovals.approveAndExecute`)]}),(0,i.jsxs)(n.Button,{size:`sm`,variant:`destructive`,onClick:()=>{S(R.id),w(``)},disabled:T===R.id,children:[(0,i.jsx)(r.XCircle,{className:`h-3.5 w-3.5 mr-1`}),p(`aiApprovals.reject`)]})]}):null]}):null]})}),(0,i.jsx)(n.Sheet,{open:!!x,onOpenChange:e=>{e||(S(null),w(``))},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:p(`aiApprovals.rejectTitle`)}),(0,i.jsx)(n.SheetDescription,{children:p(`aiApprovals.rejectBody`)})]}),(0,i.jsxs)(`div`,{className:`px-4 mt-3 space-y-3`,children:[(0,i.jsx)(n.Textarea,{value:C,onChange:e=>w(e.target.value),placeholder:p(`aiApprovals.rejectPlaceholder`),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:()=>{S(null),w(``)},children:p(`common.cancel`)}),(0,i.jsxs)(n.Button,{variant:`destructive`,size:`sm`,onClick:()=>x&&void B(x,C),disabled:!x||T===x,"data-testid":`ai-inbox-reject-confirm`,children:[(0,i.jsx)(r.XCircle,{className:`h-3.5 w-3.5 mr-1`}),p(`aiApprovals.reject`)]})]})]})]})})]})}function ma(e){return!e||e.length===0?`/api/v1/ai`:e.endsWith(`/`)?e.slice(0,-1):e}function ha(e,t){let n={...e??{}};return t&&(n[`Content-Type`]=`application/json`),n}async function ga(e){let t=await e.text();if(!t)return null;try{return JSON.parse(t)}catch{return{raw:t}}}function _a(e){let{messages:n,apiBase:r,headers:i,onDecided:a,continueConversation:o}=e,s=ma(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:ha(i,!0),body:c}),f=await ga(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;else if(p===`rejected`)m(e,{state:`success`,message:n?`Rejected: ${n}`:`Rejected.`}),h=!0;else if(p===`failed`){let t=f.error??`Action approved but execution failed.`;m(e,{state:`error`,message:t})}else m(e,{state:`success`,message:`Status: ${p}`}),h=!0;if(a?.(e,f),h&&o){let r=va({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){let n=t instanceof Error?t.message:String(t);m(e,{state:`error`,message:n})}finally{--d.current,d.current<=0&&(d.current=0,p(!1))}},[s,i,c,a,o,m]),isDeciding:f}}function va(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:ya(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:ya(JSON.stringify(e??{}),400)}. Apologize concisely and offer alternatives.`}}function ya(e,t){return e.length<=t?e:`${e.slice(0,t-1)}…`}var ba=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)(xa,{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`})})]})})]})});ba.displayName=`Chatbot`;var xa=({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})]})]})},Sa=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`})]})})]}));Sa.displayName=`TypingIndicator`,e.AGENT_ALIAS_GROUPS=Ye,Object.defineProperty(e,"AIElements",{enumerable:!0,get:function(){return Zi}}),e.AI_USAGE_REFRESH_EVENT=Fe,e.AiPendingActionsInbox=pa,e.Chatbot=ba,e.ChatbotEnhanced=mi,e.FloatingChatbot=Ji,e.FloatingChatbotPanel=Et,e.FloatingChatbotProvider=ht,e.FloatingChatbotTrigger=bt,e.PLATFORM_DEFAULT_AGENT=G,e.TypingIndicator=Sa,e.agentAliasGroup=Xe,e.agentHasCapability=rt,e.agentRouteName=Ze,e.authoredToRuntimeMessage=Ne,e.buildProgressFromDraftReview=me,e.detectAuthoringVerdict=ue,e.detectBuilderHandoff=re,e.detectBuiltAppPackage=de,e.detectDraftResult=fe,e.detectPendingApproval=P,e.detectProposedChanges=U,e.detectProposedPlan=L,e.detectRecordHandoff=ie,e.detectReplayOutcome=le,e.emitAiUsageRefresh=Ie,e.humanizeToolName=Ot,e.isAskAgent=tt,e.isBuildAgent=et,e.isBuiltinAgentName=$e,e.publishHealthFromResponse=Rr,e.resolveAgentParam=Qe,e.resolveDefaultAgentName=it,e.summarizeChatError=At,e.toRuntimeMessages=Pe,e.toRuntimeRole=Ae,e.toRuntimeTimestamp=ke,e.toRuntimeToolInvocation=Me,e.toRuntimeToolState=je,e.uiMessageToChatMessage=De,e.uiMessagesToChatMessages=Oe,e.unwrapToolResult=kt,e.useAgents=dt,e.useAiModels=mt,e.useFloatingChatbot=gt,e.useHitlInChat=_a,e.useObjectChat=Je,e.usePendingActions=ia});
|