@townco/gui-template 0.1.10 → 0.1.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/index-B4gi_GLt.js +8 -0
- package/dist/index.html +1 -1
- package/package.json +3 -3
- package/src/App.tsx +18 -2
- package/src/ChatView.tsx +19 -6
- package/dist/assets/index-BvPp7Gvn.js +0 -8
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{r as o,j as s,M as vt,e as Nt,a as St}from"./react-oZw8z-KQ.js";import{L as Ct,M as I,N as z,O as U,P as x,Q as F,R as V,S as K,T as $,U as k,W as B,X as jt,Y as It,Z as Et,$ as A,a0 as Rt}from"./vendor-CEpcc87q.js";import{P as kt,a as Tt}from"./acp-sdk-C7r2g8Gx.js";import{S as q,L as ae,T as ie,C as le,R as Mt,O as ce,P as At,a as de,b as Dt,c as ue,D as fe,d as me,e as pe,f as Lt,g as he,I as ge,h as xe,i as be,j as ye,k as we,l as ve,m as Ne,n as Se,o as Pt,p as Ce,q as je,r as Ht,s as Ie,V as Ft,t as Ee,u as Re,v as zt,w as Ut,x as ke}from"./radix-5M08E2bk.js";import{S as $t,P as Ot,M as Vt,A as _t,X as Bt,C as qt,a as Te,b as Me,c as ee,L as Ae,d as Wt,e as Qt,f as Yt,g as Kt,h as Gt,F as Jt,i as te,j as Xt,k as Zt}from"./icons-DyKSdrA7.js";import{r as es}from"./markdown-BYclSlXM.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const u of i.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&n(u)}).observe(document,{childList:!0,subtree:!0});function t(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(a){if(a.ep)return;a.ep=!0;const i=t(a);fetch(a.href,i)}})();const j=Ct(r=>({connectionStatus:"disconnected",sessionId:null,error:null,messages:[],isStreaming:!1,streamingStartTime:null,input:{value:"",isSubmitting:!1,attachedFiles:[]},setConnectionStatus:e=>r({connectionStatus:e}),setSessionId:e=>r({sessionId:e}),setError:e=>r({error:e}),addMessage:e=>r(t=>({messages:[...t.messages,e]})),updateMessage:(e,t)=>r(n=>({messages:n.messages.map(a=>a.id===e?{...a,...t}:a)})),clearMessages:()=>r({messages:[]}),setIsStreaming:e=>r({isStreaming:e}),setStreamingStartTime:e=>r({streamingStartTime:e}),setInputValue:e=>r(t=>({input:{...t.input,value:e}})),setInputSubmitting:e=>r(t=>({input:{...t.input,isSubmitting:e}})),addFileAttachment:e=>r(t=>({input:{...t.input,attachedFiles:[...t.input.attachedFiles,e]}})),removeFileAttachment:e=>r(t=>({input:{...t.input,attachedFiles:t.input.attachedFiles.filter((n,a)=>a!==e)}})),clearInput:()=>r(e=>({input:{value:"",isSubmitting:!1,attachedFiles:[]}}))}));function De(r){const e=j(l=>l.messages),t=j(l=>l.isStreaming),n=j(l=>l.sessionId),a=j(l=>l.setIsStreaming),i=j(l=>l.setStreamingStartTime),u=j(l=>l.addMessage),p=j(l=>l.updateMessage),f=j(l=>l.setError),c=o.useCallback(async l=>{if(!r){console.error("❌ No client available"),f("No client available");return}if(!n){console.error("❌ No active session"),f("No active session");return}try{const d=Date.now();a(!0),i(d);const h={id:`msg_${Date.now()}_user`,role:"user",content:l,timestamp:new Date().toISOString(),isStreaming:!1};u(h);const g=`msg_${Date.now()}_assistant`,b={id:g,role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!0,streamingStartTime:d};u(b);const S=e.filter(v=>v.role!=="system").map(v=>`${v.role==="user"?"Human":"Assistant"}: ${v.content}`).join(`
|
|
2
|
+
|
|
3
|
+
`),N=S?`${S}
|
|
4
|
+
|
|
5
|
+
Human: ${l}`:l,y=r.receiveMessages();r.sendMessage(N,n).catch(v=>{const E=v instanceof Error?v.message:String(v);f(E),a(!1),i(null)});let w="";for await(const v of y)if(v.isComplete){p(g,{content:w,isStreaming:!1,streamingStartTime:void 0}),a(!1),i(null);break}else v.contentDelta.type==="text"&&(w+=v.contentDelta.text,p(g,{content:w}),await new Promise(E=>setTimeout(E,16)))}catch(d){const h=d instanceof Error?d.message:String(d);f(h),a(!1),i(null)}},[r,n,e,u,p,a,i,f]);return{messages:e,isStreaming:t,sendMessage:c}}function ts(r){const e=j(d=>d.input),t=j(d=>d.setInputValue),n=j(d=>d.setInputSubmitting),a=j(d=>d.addFileAttachment),i=j(d=>d.removeFileAttachment),{sendMessage:u}=De(r),p=o.useCallback(d=>{t(d)},[t]),f=o.useCallback(async()=>{if(!e.value.trim()||e.isSubmitting)return;const d=e.value;t(""),n(!0);try{await u(d)}catch(h){console.error("Failed to send message:",h)}finally{n(!1)}},[e,t,n,u]),c=o.useCallback(d=>{a(d)},[a]),l=o.useCallback(d=>{i(d)},[i]);return{value:e.value,isSubmitting:e.isSubmitting,attachedFiles:e.attachedFiles,onChange:p,onSubmit:f,onAttachFile:c,onRemoveFile:l}}function ss(r){const e=j(l=>l.connectionStatus),t=j(l=>l.sessionId),n=j(l=>l.setConnectionStatus),a=j(l=>l.setSessionId),i=j(l=>l.setError),u=j(l=>l.clearMessages),p=o.useCallback(async()=>{if(!r){i("No client available");return}try{n("connecting"),i(null),await r.connect(),n("connected")}catch(l){console.log(l);const d=l instanceof Error?l.message:String(l);i(d),n("error")}},[r,n,i]),f=o.useCallback(async()=>{if(!r){i("No client available");return}try{const l=await r.startSession();a(l),u()}catch(l){const d=l instanceof Error?l.message:String(l);i(d)}},[r,a,i,u]),c=o.useCallback(async()=>{if(r)try{await r.disconnect(),n("disconnected"),a(null)}catch(l){const d=l instanceof Error?l.message:String(l);i(d)}},[r,n,a,i]);return o.useEffect(()=>{r&&e==="disconnected"&&p()},[r,e,p]),o.useEffect(()=>{e==="connected"&&!t&&f()},[e,t,f]),{connectionStatus:e,sessionId:t,connect:p,startSession:f,disconnect:c}}const se={trace:0,debug:1,info:2,warn:3,error:4,fatal:5},rs={trace:"color: #6B7280",debug:"color: #3B82F6; font-weight: bold",info:"color: #10B981; font-weight: bold",warn:"color: #F59E0B; font-weight: bold",error:"color: #EF4444; font-weight: bold",fatal:"color: #DC2626; font-weight: bold; background: #FEE2E2"};class ns{service;minLevel;constructor(e,t="debug"){this.service=e,this.minLevel=t,typeof process<"u"&&(this.minLevel="info")}shouldLog(e){return se[e]>=se[this.minLevel]}log(e,t,n){if(!this.shouldLog(e))return;const a={timestamp:new Date().toISOString(),level:e,service:this.service,message:t,...n&&{metadata:n}},i=rs[e],u=e.toUpperCase().padEnd(5);if(typeof console<"u"){const p=`%c[${a.timestamp}] [${this.service}] [${u}]`,f=n?`${t} %o`:t;switch(e){case"trace":case"debug":case"info":console.log(p,i,f,...n?[n]:[]);break;case"warn":console.warn(p,i,f,...n?[n]:[]);break;case"error":case"fatal":console.error(p,i,f,...n?[n]:[]);break}}(e==="fatal"||e==="error")&&console.debug("Structured log:",JSON.stringify(a))}trace(e,t){this.log("trace",e,t)}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}fatal(e,t){this.log("fatal",e,t)}}function Le(r,e="debug"){return new ns(r,e)}const os=I({id:x(),role:$(["user","assistant","system"]),content:x(),timestamp:K(),isStreaming:V().default(!1),streamingStartTime:F().optional(),metadata:z(x(),U()).optional()}),as=I({value:x(),isSubmitting:V(),attachedFiles:k(I({name:x(),path:x(),size:F(),mimeType:x()}))});I({sessionId:x().nullable(),isConnected:V(),isStreaming:V(),messages:k(os),input:as,error:x().nullable()});$(["disconnected","connecting","connected","error"]);class is{connected=!1;sessionUpdateCallbacks=new Set;errorCallbacks=new Set;messageQueue=[];currentSessionId=null;chunkResolvers=[];streamComplete=!1;sseAbortController=null;reconnectAttempts=0;maxReconnectAttempts=5;reconnectDelay=1e3;reconnecting=!1;abortController=null;options;constructor(e){this.options={...e,baseUrl:e.baseUrl.replace(/\/$/,"")}}async connect(){if(!this.connected)try{this.abortController=new AbortController;const e={protocolVersion:kt,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},t=await this.sendRpcRequest("initialize",e);console.log("ACP connection initialized:",t);const n={cwd:"/",mcpServers:[]},a=await this.sendRpcRequest("session/new",n);this.currentSessionId=a.sessionId,console.log("Session created:",this.currentSessionId),await this.connectSSE(),this.connected=!0,this.reconnectAttempts=0}catch(e){this.connected=!1;const t=e instanceof Error?e:new Error(String(e));throw this.notifyError(t),t}}async disconnect(){if(this.connected)try{this.abortController&&(this.abortController.abort(),this.abortController=null),this.sseAbortController&&(this.sseAbortController.abort(),this.sseAbortController=null),this.connected=!1,this.currentSessionId=null,this.messageQueue=[],this.chunkResolvers=[],this.streamComplete=!1,this.reconnecting=!1,this.reconnectAttempts=0}catch(e){const t=e instanceof Error?e:new Error(String(e));throw this.notifyError(t),t}}async send(e){if(!this.connected||!this.currentSessionId)throw new Error("Transport not connected");try{this.streamComplete=!1,this.messageQueue=[];const t=e.content.filter(u=>u.type==="text").map(u=>u.text).join(`
|
|
6
|
+
`),n={sessionId:this.currentSessionId,prompt:[{type:"text",text:t}]},a=await this.sendRpcRequest("session/prompt",n);console.log("Prompt sent:",a),this.streamComplete=!0;const i=this.chunkResolvers.shift();i?i({id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0}):this.messageQueue.push({id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0})}catch(t){this.streamComplete=!0;const n=t instanceof Error?t:new Error(String(t));throw this.notifyError(n),n}}async*receive(){for(;!this.streamComplete;)if(this.messageQueue.length>0){const e=this.messageQueue.shift();if(e&&(yield e,e.isComplete))return}else{const e=await new Promise(t=>{this.chunkResolvers.push(t)});if(e.isComplete){yield e;return}else yield e}for(;this.messageQueue.length>0;){const e=this.messageQueue.shift();e&&(yield e)}yield{id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0}}isConnected(){return this.connected}onSessionUpdate(e){return this.sessionUpdateCallbacks.add(e),()=>{this.sessionUpdateCallbacks.delete(e)}}onError(e){return this.errorCallbacks.add(e),()=>{this.errorCallbacks.delete(e)}}async sendRpcRequest(e,t){const a={jsonrpc:"2.0",id:this.generateRequestId(),method:e,params:t},i={"Content-Type":"application/json",...this.options.headers},u=this.options.timeout||3e4,p=new AbortController,f=setTimeout(()=>p.abort(),u);try{const c=await fetch(`${this.options.baseUrl}/rpc`,{method:"POST",headers:i,body:JSON.stringify(a),signal:p.signal});if(clearTimeout(f),!c.ok){const d=await c.text();throw new Error(`HTTP ${c.status}: ${d}`)}const l=await c.json();if(l.error)throw new Error(`ACP error: ${l.error.message||JSON.stringify(l.error)}`);return l.result||l}catch(c){throw clearTimeout(f),c instanceof Error&&c.name==="AbortError"?new Error(`Request timeout after ${u}ms`):c}}async connectSSE(){if(!this.currentSessionId)throw new Error("Cannot connect SSE without a session ID");const e=`${this.options.baseUrl}/events`,t={"X-Session-ID":this.currentSessionId,...this.options.headers};this.sseAbortController=new AbortController;try{const n=await fetch(e,{method:"GET",headers:t,signal:this.sseAbortController.signal});if(!n.ok)throw new Error(`SSE connection failed: HTTP ${n.status}`);if(!n.body)throw new Error("Response body is null");console.log("SSE connection opened"),this.reconnectAttempts=0,this.reconnectDelay=1e3;const a=n.body.getReader(),i=new TextDecoder;let u="";(async()=>{try{for(;;){const{done:p,value:f}=await a.read();if(p){console.log("SSE stream closed by server"),this.connected&&await this.handleSSEDisconnect();break}u+=i.decode(f,{stream:!0});const c=u.split(`
|
|
7
|
+
`);u=c.pop()||"";let l={event:"message",data:""};for(const d of c)d.startsWith("event:")?l.event=d.substring(6).trim():d.startsWith("data:")?l.data=d.substring(5).trim():d===""&&(l.event==="message"&&l.data&&this.handleSSEMessage(l.data),l={event:"message",data:""})}}catch(p){if(p instanceof Error&&p.name==="AbortError"){console.log("SSE stream aborted");return}console.error("Error reading SSE stream:",p),this.connected&&!this.reconnecting&&await this.handleSSEDisconnect()}})()}catch(n){throw console.error("SSE connection error:",n),n}}async handleSSEDisconnect(){if(this.reconnecting||!this.connected)return;if(this.reconnecting=!0,this.sseAbortController&&(this.sseAbortController.abort(),this.sseAbortController=null),this.reconnectAttempts>=this.maxReconnectAttempts){const t=new Error(`SSE reconnection failed after ${this.maxReconnectAttempts} attempts`);this.notifyError(t),this.connected=!1,this.reconnecting=!1;return}this.reconnectAttempts++;const e=Math.min(this.reconnectDelay*2**(this.reconnectAttempts-1),32e3);console.log(`SSE reconnecting in ${e}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`),await new Promise(t=>setTimeout(t,e));try{await this.connectSSE(),console.log("SSE reconnected successfully"),this.reconnecting=!1}catch(t){console.error("SSE reconnection failed:",t),this.reconnecting=!1}}handleSSEMessage(e){try{const t=JSON.parse(e),n=Tt.safeParse(t);if(!n.success){console.error("Invalid ACP message from SSE:",n.error.issues);return}const a=n.data;"method"in a&&a.method==="session/update"&&"params"in a&&a.params&&this.handleSessionNotification(a.params)}catch(t){console.error("Error parsing SSE message:",t),this.notifyError(t instanceof Error?t:new Error(String(t)))}}handleSessionNotification(e){const n=e.update,a={sessionId:this.currentSessionId||e.sessionId,status:"active"};if(n?.content){const i=n.content;let u=null;if(i.type==="text"&&i.text?u={id:e.sessionId,role:"assistant",contentDelta:{type:"text",text:i.text},isComplete:!1}:i.type==="tool_call"&&(u={id:e.sessionId,role:"assistant",contentDelta:i,isComplete:!1}),u){const p=this.chunkResolvers.shift();p?p(u):this.messageQueue.push(u)}}this.notifySessionUpdate(a)}generateRequestId(){return`req-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}notifySessionUpdate(e){for(const t of this.sessionUpdateCallbacks)try{t(e)}catch(n){console.error("Error in session update callback:",n)}}notifyError(e){for(const t of this.errorCallbacks)try{t(e)}catch(n){console.error("Error in error callback:",n)}}}class ls{constructor(){throw new Error("StdioTransport is not available in the browser. Use HttpTransport or WebSocketTransport instead.")}async connect(){throw new Error("StdioTransport not available in browser")}async disconnect(){}async send(){throw new Error("StdioTransport not available in browser")}async*receive(){throw new Error("StdioTransport not available in browser")}isConnected(){return!1}onSessionUpdate(){return()=>{}}onError(){return()=>{}}}class cs{ws=null;connected=!1;sessionUpdateCallbacks=new Set;errorCallbacks=new Set;constructor(e){}async connect(){throw new Error("WebSocketTransport not yet implemented. Waiting for HTTP ACP server.")}async disconnect(){this.ws&&(this.ws.close(),this.ws=null),this.connected=!1}async send(e){throw!this.connected||!this.ws?new Error("Transport not connected"):new Error("WebSocketTransport not yet implemented. Waiting for HTTP ACP server.")}async*receive(){throw new Error("WebSocketTransport not yet implemented. Waiting for HTTP ACP server.")}isConnected(){return this.connected}onSessionUpdate(e){return this.sessionUpdateCallbacks.add(e),()=>{this.sessionUpdateCallbacks.delete(e)}}onError(e){return this.errorCallbacks.add(e),()=>{this.errorCallbacks.delete(e)}}}class ds{config;transport;sessions=new Map;currentSessionId=null;sessionUpdateHandlers=new Set;errorHandlers=new Set;constructor(e){this.config=e,this.transport=this.createTransport(),this.setupTransportListeners(),e.autoConnect&&this.connect().catch(t=>{console.error("Failed to auto-connect:",t)})}async connect(){await this.transport.connect()}async disconnect(){await this.transport.disconnect(),this.currentSessionId=null}isConnected(){return this.transport.isConnected()}async startSession(e){const t=this.generateSessionId(),n=new Date().toISOString(),a={id:t,status:"connecting",config:e?{...e,agentPath:e.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:n}};return this.sessions.set(t,a),this.currentSessionId=t,this.updateSessionStatus(t,"connected"),t}async sendMessage(e,t){const n=t||this.currentSessionId;if(!n)throw new Error("No active session. Start a session first.");if(!this.transport.isConnected())throw new Error("Transport not connected");const a=this.sessions.get(n);if(!a)throw new Error(`Session ${n} not found`);const i={id:this.generateMessageId(),role:"user",content:[{type:"text",text:e}],timestamp:new Date().toISOString()};a.messages.push(i),this.updateSessionStatus(n,"active"),await this.transport.send(i)}async*receiveMessages(){if(!this.transport.isConnected())throw new Error("Transport not connected");yield*this.transport.receive()}getSession(e){return this.sessions.get(e)}getCurrentSession(){return this.currentSessionId?this.sessions.get(this.currentSessionId):void 0}getAllSessions(){return Array.from(this.sessions.values())}onSessionUpdate(e){return this.sessionUpdateHandlers.add(e),()=>{this.sessionUpdateHandlers.delete(e)}}onError(e){return this.errorHandlers.add(e),()=>{this.errorHandlers.delete(e)}}createTransport(){switch(this.config.type){case"stdio":return new ls(this.config.options);case"http":return new is(this.config.options);case"websocket":return new cs(this.config.options);default:throw new Error(`Unknown transport type: ${this.config.type}`)}}setupTransportListeners(){this.transport.onSessionUpdate(e=>{this.handleSessionUpdate(e)}),this.transport.onError(e=>{this.handleError(e)})}handleSessionUpdate(e){if(e.sessionId){const t=this.sessions.get(e.sessionId);t&&(e.status&&(t.status=e.status),e.message&&t.messages.push(e.message),e.error&&(t.error=e.error))}for(const t of this.sessionUpdateHandlers)try{t(e)}catch(n){console.error("Error in session update handler:",n)}}handleError(e){for(const t of this.errorHandlers)try{t(e)}catch(n){console.error("Error in error handler:",n)}}updateSessionStatus(e,t){const n=this.sessions.get(e);n&&(n.status=t,this.handleSessionUpdate({sessionId:e,status:t}))}generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}generateMessageId(){return`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}const us=I({name:x(),description:x().optional(),parameters:z(x(),U()).optional()}),fs=I({name:x(),description:x(),parameters:z(x(),U()),required:k(x()).optional()}),ms=I({name:x(),version:x().optional(),description:x().optional(),author:x().optional(),capabilities:k(us).optional(),tools:k(fs).optional(),supportedFormats:k(x()).optional()}),ps=$(["initializing","ready","busy","error","terminated"]);I({status:ps,info:ms.optional(),pid:F().optional(),error:x().optional(),uptime:F().optional()});const Pe=$(["user","assistant","system","tool"]),hs=$(["text","image","file","tool_call","tool_result"]),W=I({type:hs}),gs=W.extend({type:B("text"),text:x()}),xs=W.extend({type:B("image"),url:x().url().optional(),data:x().optional(),mimeType:x().optional()}),bs=W.extend({type:B("file"),name:x(),path:x().optional(),url:x().url().optional(),mimeType:x(),size:F().optional()}),ys=W.extend({type:B("tool_call"),id:x(),name:x(),arguments:z(x(),U())}),ws=W.extend({type:B("tool_result"),callId:x(),result:U(),error:x().optional()}),He=jt("type",[gs,xs,bs,ys,ws]),Fe=I({id:x(),role:Pe,content:k(He),timestamp:K(),metadata:z(x(),U()).optional()});I({id:x(),role:Pe,contentDelta:He,isComplete:V()});const ze=$(["idle","connecting","connected","active","streaming","error","disconnected"]),vs=I({agentPath:x(),agentArgs:k(x()).optional(),environment:z(x(),x()).optional(),workingDirectory:x().optional(),timeout:F().optional()}),Ns=I({agentName:x().optional(),agentVersion:x().optional(),capabilities:k(x()).optional(),startedAt:K(),lastActivityAt:K().optional()});I({id:x(),status:ze,config:vs,metadata:Ns.optional(),messages:k(Fe),error:x().optional()});I({sessionId:x(),status:ze.optional(),message:Fe.optional(),error:x().optional()});function m(...r){return It(Et(r))}const Ss=A("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),Q=o.forwardRef(({className:r,variant:e,size:t,asChild:n=!1,...a},i)=>{const u=n?q:"button";return s.jsx(u,{className:m(Ss({variant:e,size:t,className:r})),ref:i,...a})});Q.displayName="Button";const Cs=o.forwardRef(({className:r,...e},t)=>s.jsx("div",{ref:t,className:m("rounded-lg border bg-card text-card-foreground shadow-sm",r),...e}));Cs.displayName="Card";const js=o.forwardRef(({className:r,...e},t)=>s.jsx("div",{ref:t,className:m("flex flex-col space-y-1.5 p-6",r),...e}));js.displayName="CardHeader";const Is=o.forwardRef(({className:r,...e},t)=>s.jsx("div",{ref:t,className:m("text-2xl font-semibold leading-none tracking-tight",r),...e}));Is.displayName="CardTitle";const Es=o.forwardRef(({className:r,...e},t)=>s.jsx("div",{ref:t,className:m("text-sm text-muted-foreground",r),...e}));Es.displayName="CardDescription";const Rs=o.forwardRef(({className:r,...e},t)=>s.jsx("div",{ref:t,className:m("p-6 pt-0",r),...e}));Rs.displayName="CardContent";const ks=o.forwardRef(({className:r,...e},t)=>s.jsx("div",{ref:t,className:m("flex items-center p-6 pt-0",r),...e}));ks.displayName="CardFooter";const Ue=o.createContext(void 0),$e=()=>{const r=o.useContext(Ue);if(!r)throw new Error("ChatHeader components must be used within ChatHeader.Root");return r},Ts=o.forwardRef(({defaultExpanded:r=!1,expanded:e,onExpandedChange:t,className:n,children:a,...i},u)=>{const[p,f]=o.useState(r),c=e??p,l=o.useCallback(b=>{f(b),t?.(b)},[t]),d=o.Children.toArray(a),h=d.find(b=>o.isValidElement(b)&&typeof b.type=="function"&&b.type.displayName==="ChatHeader.ExpandablePanel"),g=d.filter(b=>b!==h);return s.jsxs(Ue.Provider,{value:{isExpanded:c,setIsExpanded:l},children:[s.jsx("div",{ref:u,className:m("flex items-center justify-between px-6 py-4",n),...i,children:g}),h]})});Ts.displayName="ChatHeader.Root";const Ms=o.forwardRef(({className:r,children:e,...t},n)=>s.jsx("h1",{ref:n,className:m("m-0 text-xl font-semibold",r),...t,children:e}));Ms.displayName="ChatHeader.Title";const As=o.forwardRef(({className:r,children:e,...t},n)=>s.jsx("div",{ref:n,className:m("flex items-center gap-3",r),...t,children:e}));As.displayName="ChatHeader.Actions";const Ds=r=>{switch(r){case"connected":return"bg-green-500";case"connecting":return"bg-yellow-500";case"error":return"bg-red-500";default:return"bg-gray-500"}},Ls=r=>{switch(r){case"connected":return"Connected";case"connecting":return"Connecting...";case"error":return"Connection Error";default:return"No Server"}},Ps=o.forwardRef(({status:r,statusText:e,className:t,...n},a)=>{const i=e??Ls(r),u=Ds(r);return s.jsxs("div",{ref:a,className:m("flex items-center gap-2",t),...n,children:[s.jsx("div",{className:m("h-2 w-2 rounded-full",u)}),s.jsx("span",{className:"text-sm text-muted-foreground",children:i})]})});Ps.displayName="ChatHeader.StatusIndicator";const Hs=o.forwardRef(({icon:r,className:e,children:t,onClick:n,...a},i)=>{const{isExpanded:u,setIsExpanded:p}=$e(),f=c=>{p(!u),n?.(c)};return s.jsxs("button",{ref:i,type:"button",onClick:f,className:m("rounded p-1 transition-colors hover:bg-background lg:hidden",e),"aria-label":u?"Collapse header":"Expand header",...a,children:[r&&s.jsx("div",{className:m("transition-transform duration-200",u&&"rotate-180"),children:r}),t]})});Hs.displayName="ChatHeader.Toggle";const Fs=o.forwardRef(({className:r,children:e,...t},n)=>{const{isExpanded:a}=$e();return a?s.jsx("div",{ref:n,className:m("absolute top-full left-0 right-0 z-50 border-b border-border bg-card px-6 py-4 shadow-lg lg:hidden",r),...t,children:e}):null});Fs.displayName="ChatHeader.ExpandablePanel";const Oe=o.forwardRef(({commands:r=[],showCommandMenu:e,commandMenuQuery:t,selectedMenuIndex:n,setSelectedMenuIndex:a,setMenuItemCount:i,triggerCounter:u,onChange:p,className:f,...c},l)=>{const d=o.useCallback((g,b)=>{const S=g.toLowerCase(),N=b.toLowerCase();if(!b)return 1;if(S.includes(N))return 1-N.length/S.length;let y=0;for(let w=0;w<S.length&&y<N.length;w++)S[w]===N[y]&&y++;return y===N.length?.5-y/S.length:0},[]),h=o.useMemo(()=>r.map(g=>({...g,score:Math.max(d(g.label,t),g.description?d(g.description,t):0)})).filter(g=>g.score>0).sort((g,b)=>b.score-g.score),[r,t,d]);return o.useEffect(()=>{i(h.length)},[h.length,i]),o.useEffect(()=>{a(0)},[a]),o.useEffect(()=>{u>0&&h[n]&&(h[n].onSelect(),p(""))},[u,h,n,p]),!e||h.length===0?null:s.jsxs("div",{ref:l,className:m("absolute bottom-full left-0 z-50 mb-2 w-full max-w-md","rounded-md border border-border bg-card p-2 shadow-lg",f),...c,children:[s.jsx("div",{className:"text-xs font-semibold text-muted-foreground px-2 py-1",children:"Commands"}),s.jsx("div",{className:"max-h-64 overflow-y-auto",children:h.map((g,b)=>s.jsxs("button",{type:"button",onClick:()=>g.onSelect(),className:m("w-full rounded-sm px-2 py-2 text-left text-sm transition-colors","flex items-start gap-2","hover:bg-muted",b===n&&"bg-muted"),children:[g.icon&&s.jsx("span",{className:"shrink-0 mt-0.5",children:g.icon}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"font-medium",children:g.label}),g.description&&s.jsx("div",{className:"text-xs text-muted-foreground truncate",children:g.description})]})]},g.id))})]})});Oe.displayName="ChatInputCommandMenu";const Ve=o.createContext(void 0),J=()=>{const r=o.useContext(Ve);if(!r)throw new Error("ChatInput components must be used within ChatInput.Root");return r},_e=o.forwardRef(({client:r,value:e,onChange:t,onSubmit:n,disabled:a=!1,isSubmitting:i,submitOnEnter:u=!0,className:p,children:f,...c},l)=>{const d=o.useRef(null),h=ts(r??null),g=j(M=>M.isStreaming),b=h?h.value:e||"",S=h?h.onChange:t||(()=>{}),N=h?h.onSubmit:n||(async()=>{}),y=h?h.isSubmitting||g:i||!1,[w,v]=o.useState(!1),[E,D]=o.useState(""),[L,C]=o.useState(0),[R,T]=o.useState(0),[X,Z]=o.useState(0),yt=o.useCallback(()=>{Z(M=>M+1)},[]),wt=async M=>{M.preventDefault(),b.trim()&&!y&&!a&&(await N(),setTimeout(()=>{d.current?.focus()},0))};return o.useEffect(()=>{const M=document.querySelector('textarea[name="chat-input"]');M&&d.current!==M&&(d.current=M)},[]),o.useEffect(()=>{!b&&d.current&&(d.current.style.height="auto",d.current.style.overflowY="hidden")},[b]),s.jsx(Ve.Provider,{value:{value:b,onChange:S,onSubmit:N,disabled:a,isSubmitting:y,submitOnEnter:u,showCommandMenu:w,setShowCommandMenu:v,commandMenuQuery:E,setCommandMenuQuery:D,selectedMenuIndex:L,setSelectedMenuIndex:C,menuItemCount:R,setMenuItemCount:T,triggerMenuSelect:yt,triggerCounter:X},children:s.jsx("form",{ref:l,onSubmit:wt,className:m("relative w-full divide-y rounded-xl border bg-background shadow-md",p),...c,children:f})})});_e.displayName="ChatInput.Root";const Be=o.forwardRef(({asChild:r=!1,className:e,onKeyDown:t,children:n,...a},i)=>{const{value:u,onChange:p,onSubmit:f,disabled:c,isSubmitting:l,submitOnEnter:d,showCommandMenu:h,setShowCommandMenu:g,setCommandMenuQuery:b,setSelectedMenuIndex:S,menuItemCount:N,triggerMenuSelect:y}=J(),w=o.useRef(null),L={ref:o.useCallback(C=>{w.current=C,typeof i=="function"?i(C):i&&(i.current=C)},[i]),name:"chat-input",value:u,onChange:C=>{const R=C.target.value;if(p(R),R.startsWith("/")&&!R.includes(`
|
|
8
|
+
`)){g(!0);const Z=R.slice(1);b(Z)}else g(!1),b("");const T=w.current;if(!T)return;T.style.height="auto";const X=Math.min(T.scrollHeight,164);T.style.height=`${X}px`,T.scrollHeight>164?T.style.overflowY="auto":T.style.overflowY="hidden"},onKeyDown:C=>{if(h&&N>0){if(C.key==="ArrowDown"){C.preventDefault(),S(R=>(R+1)%N);return}else if(C.key==="ArrowUp"){C.preventDefault(),S(R=>(R-1+N)%N);return}else if(C.key==="Enter"&&!C.shiftKey){C.preventDefault(),y();return}else if(C.key==="Escape"){C.preventDefault(),g(!1),b("");return}}d&&C.key==="Enter"&&!C.shiftKey&&(u.trim()&&!l&&!c?(C.preventDefault(),f()):(l||c)&&C.preventDefault()),t?.(C)},disabled:c,...a};return r&&o.isValidElement(n)?o.cloneElement(n,L):s.jsx("textarea",{...L,className:m("w-full resize-none rounded-none border-none p-4 shadow-none","outline-none ring-0 field-sizing-content max-h-[6lh]","bg-transparent dark:bg-transparent focus-visible:ring-0","text-sm placeholder:text-muted-foreground","disabled:cursor-not-allowed disabled:opacity-50",e)})});Be.displayName="ChatInput.Field";const qe=o.forwardRef(({asChild:r=!1,className:e,disabled:t,children:n,...a},i)=>{const{value:u,disabled:p,isSubmitting:f}=J(),c=t||p||f||!u.trim(),l=r?q:Q;return s.jsx(l,{ref:i,type:"submit",disabled:c,variant:r?void 0:"default",size:"icon",className:m(!r&&"gap-1.5 rounded-full",e),...a,children:n})});qe.displayName="ChatInput.Submit";const We=o.forwardRef(({className:r,children:e,...t},n)=>s.jsx("div",{ref:n,className:m("flex items-center justify-between p-2",r),...t,children:e}));We.displayName="ChatInput.Toolbar";const Qe=o.forwardRef(({asChild:r=!1,className:e,children:t,onClick:n,...a},i)=>{const{value:u,onChange:p,setShowCommandMenu:f,setCommandMenuQuery:c}=J(),l=h=>{u.startsWith("/")||(p("/"),f(!0),c("")),n?.(h)},d=r?q:Q;return s.jsx(d,{ref:i,type:"button",variant:"ghost",size:"icon",className:m("rounded-full",e),onClick:l,...a,children:t||s.jsx($t,{className:"size-4"})})});Qe.displayName="ChatInput.Actions";const Ye=o.forwardRef(({asChild:r=!1,className:e,children:t,...n},a)=>{const i=r?q:Q;return s.jsx(i,{ref:a,type:"button",variant:"ghost",size:"icon",className:m("rounded-full",e),...n,children:t||s.jsx(Ot,{className:"size-4"})})});Ye.displayName="ChatInput.Attachment";const Ke=o.forwardRef(({asChild:r=!1,className:e,children:t,...n},a)=>{const i=r?q:Q;return s.jsx(i,{ref:a,type:"button",variant:"ghost",size:"icon",className:m("rounded-full",e),...n,children:t||s.jsx(Vt,{className:"size-4"})})});Ke.displayName="ChatInput.VoiceInput";const Ge=o.forwardRef(({commands:r=[],className:e,onChange:t,...n},a)=>{const{showCommandMenu:i,commandMenuQuery:u,selectedMenuIndex:p,setSelectedMenuIndex:f,setMenuItemCount:c,triggerCounter:l,onChange:d}=J();return s.jsx(Oe,{ref:a,commands:r,showCommandMenu:i,commandMenuQuery:u,selectedMenuIndex:p,setSelectedMenuIndex:f,setMenuItemCount:c,triggerCounter:l,onChange:d,className:e,...n})});Ge.displayName="ChatInput.CommandMenu";const zs=({...r})=>s.jsx(Rt,{position:"top-center",className:"toaster group",style:{"--top-offset":"16px","--width:":"calc(100% - 2 * var(--top-offset))",position:"absolute",zIndex:5,top:"var(--top-offset)",left:"50%",transform:"translateX(-50%)",width:"calc(100% - 2 * var(--top-offset))",maxWidth:"480px"},offset:0,toastOptions:{classNames:{toast:"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground"}},...r}),Je=o.createContext(void 0),Xe=()=>{const r=o.useContext(Je);if(!r)throw new Error("ChatLayout components must be used within ChatLayout.Root");return r},Ze=o.forwardRef(({defaultSidebarOpen:r=!1,defaultPanelSize:e="hidden",defaultActiveTab:t="todo",className:n,children:a,...i},u)=>{const[p,f]=o.useState(r),[c,l]=o.useState(e),[d,h]=o.useState(t);return s.jsx(Je.Provider,{value:{sidebarOpen:p,setSidebarOpen:f,panelSize:c,setPanelSize:l,activeTab:d,setActiveTab:h},children:s.jsx("div",{ref:u,className:m("flex h-screen flex-row bg-background text-foreground",n),...i,children:a})})});Ze.displayName="ChatLayout.Root";const Us=o.forwardRef(({className:r,children:e,...t},n)=>s.jsx("div",{ref:n,className:m("relative z-10 border-b border-border bg-card shrink-0",r),...t,children:e}));Us.displayName="ChatLayout.Header";const et=o.forwardRef(({className:r,children:e,...t},n)=>s.jsx("div",{ref:n,className:m("flex flex-1 flex-col overflow-hidden",r),...t,children:e}));et.displayName="ChatLayout.Main";const tt=o.forwardRef(({showToaster:r=!0,className:e,children:t,...n},a)=>s.jsxs("div",{ref:a,className:m("relative flex flex-1 flex-col overflow-hidden",e),...n,children:[t,r&&s.jsx(zs,{})]}));tt.displayName="ChatLayout.Body";const st=o.forwardRef(({className:r,children:e,onScrollChange:t,showScrollToBottom:n=!0,...a},i)=>{const[u,p]=o.useState(!1),f=o.useRef(null);o.useImperativeHandle(i,()=>f.current);const c=o.useCallback(()=>{const h=f.current;if(!h)return;const{scrollTop:g,scrollHeight:b,clientHeight:S}=h,y=b-g-S<100;p(!y&&n),t?.(y)},[t,n]),l=o.useCallback(()=>{c()},[c]),d=o.useCallback(()=>{const h=f.current;h&&h.scrollTo({top:h.scrollHeight,behavior:"smooth"})},[]);return o.useEffect(()=>{c()},[c]),s.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[s.jsx("div",{ref:f,className:m("h-full overflow-y-auto",r),onScroll:l,...a,children:e}),u&&s.jsx("button",{type:"button",onClick:d,className:m("absolute bottom-4 left-1/2 -translate-x-1/2 z-10","flex items-center justify-center p-2 rounded-full","bg-card border border-border shadow-lg","text-foreground","hover:bg-accent hover:text-accent-foreground","transition-all duration-200 ease-in-out","animate-in fade-in slide-in-from-bottom-2"),"aria-label":"Scroll to bottom",children:s.jsx(_t,{className:"h-4 w-4"})})]})});st.displayName="ChatLayout.Messages";const rt=o.forwardRef(({className:r,children:e,...t},n)=>s.jsx("div",{ref:n,className:m("bg-linear-to-t from-background to-transparent px-4 pb-4",r),...t,children:e}));rt.displayName="ChatLayout.Footer";const $s=o.forwardRef(({className:r,children:e,...t},n)=>{const{sidebarOpen:a}=Xe();return a?s.jsx("div",{ref:n,className:m("border-r border-border bg-card w-64 overflow-y-auto",r),...t,children:e}):null});$s.displayName="ChatLayout.Sidebar";const nt=o.forwardRef(({breakpoint:r="lg",className:e,children:t,...n},a)=>{const{panelSize:i}=Xe();return i==="hidden"?null:s.jsx("div",{ref:a,className:m("hidden border-l border-border bg-card overflow-y-auto transition-all duration-300",r==="md"&&"md:block",r==="lg"&&"lg:block",r==="xl"&&"xl:block",r==="2xl"&&"2xl:block",i==="small"&&"w-80",i==="large"&&"w-lg",e),...n,children:t})});nt.displayName="ChatLayout.Aside";const ot=o.forwardRef(({todos:r,className:e,...t},n)=>s.jsx("div",{ref:n,className:m("space-y-2",e),...t,children:r.length===0?s.jsx("div",{className:"flex items-center justify-center h-full min-h-[200px]",children:s.jsx("p",{className:"text-sm text-muted-foreground",children:"No todos yet"})}):r.map(a=>s.jsx("div",{className:"text-sm",children:a.text},a.id))}));ot.displayName="TodoTabContent";const at=o.forwardRef(({files:r=[],className:e,...t},n)=>s.jsx("div",{ref:n,className:m("space-y-2",e),...t,children:r.length===0?s.jsx("div",{className:"flex items-center justify-center h-full min-h-[200px]",children:s.jsx("p",{className:"text-sm text-muted-foreground",children:"No files attached"})}):r.map(a=>s.jsx("div",{className:"text-sm",children:a},a))}));at.displayName="FilesTabContent";const Os=o.forwardRef(({data:r,className:e,...t},n)=>s.jsxs("div",{ref:n,className:m("space-y-4",e),...t,children:[s.jsx("h3",{className:"font-semibold text-lg",children:"Database"}),s.jsxs("div",{className:"text-sm text-muted-foreground",children:[s.jsx("p",{children:"Database viewer - panel automatically expanded to large size"}),s.jsxs("div",{className:"mt-4 p-4 border border-border rounded",children:[s.jsx("p",{children:"Your large data table would go here"}),r&&typeof r=="object"?s.jsx("pre",{className:"mt-2 text-xs overflow-auto",children:JSON.stringify(r,null,2)}):null]})]})]}));Os.displayName="DatabaseTabContent";const it=Mt,G=o.forwardRef(({className:r,...e},t)=>s.jsx(ae,{ref:t,className:m("inline-flex h-10 items-center rounded-md bg-muted p-1 text-muted-foreground gap-1",r),...e}));G.displayName=ae.displayName;const _=o.forwardRef(({className:r,...e},t)=>s.jsx(ie,{ref:t,className:m("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",r),...e}));_.displayName=ie.displayName;const H=o.forwardRef(({className:r,...e},t)=>s.jsx(le,{ref:t,className:m("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",r),...e}));H.displayName=le.displayName;const lt=o.forwardRef(({todo:r,className:e,...t},n)=>s.jsx("div",{ref:n,className:m("flex items-center gap-3 px-3 py-2 rounded-lg",e),...t,children:s.jsx("span",{className:m("flex-1 text-[var(--font-size)] font-[var(--font-family)]",r.status==="completed"&&"line-through opacity-60",r.status==="in_progress"&&"shimmer-animation"),children:r.text})}));lt.displayName="TodoListItem";const ct=o.forwardRef(({client:r,todos:e,className:t,...n},a)=>{const i=e||[];return s.jsx("div",{ref:a,className:m("space-y-2 max-h-64 overflow-y-auto",t),...n,children:i.length===0?s.jsx("p",{className:"text-sm text-foreground opacity-60 italic",children:"No tasks yet."}):i.map(u=>s.jsx(lt,{todo:u},u.id))})});ct.displayName="TodoList";const Vs=o.forwardRef(({client:r,todos:e,className:t,...n},a)=>{const i=e||[],[u,p]=o.useState("todo"),f=o.useRef(null),c=o.useRef(null);o.useEffect(()=>{const h=setTimeout(()=>{const g=f.current;if(u&&g){const b=c.current;if(b){const S=g.getBoundingClientRect(),N=b.getBoundingClientRect(),y=N.left-S.left,w=N.width,v=y/S.width*100,E=100-(y+w)/S.width*100;g.style.clipPath=`inset(0 ${E.toFixed(2)}% 0 ${v.toFixed(2)}% round 999px)`}}},0);return()=>clearTimeout(h)},[u]);const l=[{id:"todo",label:"To-Do List"},{id:"files",label:"Files"},{id:"database",label:"Database"}];return s.jsx("div",{ref:a,className:m("select-none",t),...n,children:s.jsxs(it,{value:u,onValueChange:p,className:"w-full",children:[s.jsxs("div",{className:"relative mb-4 border-border",children:[s.jsx(G,{className:"bg-transparent p-0 h-auto rounded-none w-full border-none",children:l.map(d=>s.jsx(_,{value:d.id,className:"px-3 py-1 text-sm font-[var(--font-family)] font-medium rounded-none text-foreground opacity-60 data-[state=active]:opacity-100 data-[state=active]:bg-transparent data-[state=active]:shadow-none",children:d.label},d.id))}),s.jsx("div",{ref:f,className:"absolute top-0 left-0 w-full overflow-hidden z-10 pointer-events-none",style:{clipPath:"inset(0 100% 0 0% round 999px)",transition:"clip-path 0.25s ease-out"},children:s.jsx(G,{className:"bg-secondary p-0 h-auto rounded-none w-full border-none",children:l.map(d=>s.jsx(_,{value:d.id,ref:u===d.id?c:null,className:"px-3 py-1 text-sm font-[var(--font-family)] font-medium rounded-none text-primary bg-transparent data-[state=active]:shadow-none shadow-none",tabIndex:-1,children:d.label},d.id))})})]}),s.jsx(H,{value:"todo",children:s.jsx(ct,{todos:i})}),s.jsx(H,{value:"files",children:s.jsx("div",{className:"text-sm text-foreground opacity-60 italic",children:"Files tab coming soon..."})}),s.jsx(H,{value:"database",children:s.jsx("div",{className:"text-sm text-foreground opacity-60 italic",children:"Database tab coming soon..."})})]})})});Vs.displayName="ChatSecondaryPanel";const _s=o.forwardRef(({className:r,children:e,...t},n)=>s.jsx("div",{ref:n,className:m("flex h-full flex-col",r),...t,children:e}));_s.displayName="ChatSidebar.Root";const Bs=o.forwardRef(({className:r,children:e,...t},n)=>s.jsx("div",{ref:n,className:m("border-b border-border px-4 py-3",r),...t,children:e}));Bs.displayName="ChatSidebar.Header";const qs=o.forwardRef(({className:r,children:e,...t},n)=>s.jsx("div",{ref:n,className:m("flex-1 overflow-y-auto p-4",r),...t,children:e}));qs.displayName="ChatSidebar.Content";const Ws=o.forwardRef(({className:r,children:e,...t},n)=>s.jsx("div",{ref:n,className:m("border-t border-border px-4 py-3",r),...t,children:e}));Ws.displayName="ChatSidebar.Footer";const Qs=o.forwardRef(({children:r,className:e,...t},n)=>{const[a,i]=o.useState(r),[u,p]=o.useState(!1),f=o.useRef(r),c=o.useRef(!0);return o.useEffect(()=>{if(c.current){c.current=!1,f.current=r;return}if(f.current===r)return;p(!0);const l=setTimeout(()=>{i(r),f.current=r,requestAnimationFrame(()=>{p(!1)})},150);return()=>{clearTimeout(l)}},[r]),s.jsx("span",{ref:n,className:m("text-sm text-foreground opacity-60 transition-opacity duration-300",u?"opacity-0":"opacity-60",e),...t,children:a})});Qs.displayName="ChatStatus";const Ys=o.forwardRef(({autoScroll:r=!0,isStreaming:e=!1,scrollBehavior:t="smooth",scrollThreshold:n=100,showScrollButton:a=!0,scrollButton:i,className:u,children:p,...f},c)=>{const l=o.useRef(null),[d,h]=o.useState(!0),[g,b]=o.useState(!1),S=o.useRef(0);o.useImperativeHandle(c,()=>{if(!l.current)throw new Error("Container ref not initialized");return l.current});const N=o.useCallback(()=>{const w=l.current;if(!w)return;const{scrollTop:v,scrollHeight:E,clientHeight:D}=w,C=E-v-D<n;h(C),b(!C&&a),S.current=v},[n,a]),y=o.useCallback((w=t)=>{const v=l.current;v&&v.scrollTo({top:v.scrollHeight,behavior:w})},[t]);return o.useEffect(()=>{!r||!l.current||(e&&d?y("auto"):!e&&d&&y())},[r,e,d,y]),o.useEffect(()=>{const w=l.current;if(!w)return;const v=()=>{N()};return w.addEventListener("scroll",v,{passive:!0}),N(),()=>{w.removeEventListener("scroll",v)}},[N]),o.useEffect(()=>{const w=l.current;if(!w)return;const v=new ResizeObserver(()=>{d&&r&&y("auto")});return v.observe(w),()=>{v.disconnect()}},[d,r,y]),s.jsxs("div",{className:"relative flex-1",children:[s.jsx("div",{ref:l,className:m("h-full overflow-y-auto overflow-x-hidden","scrollbar-thin scrollbar-thumb-[border] scrollbar-track-transparent",u),...f,children:s.jsx("div",{className:"flex flex-col gap-4 px-4 py-4",children:p})}),g&&s.jsx("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 z-10",children:i||s.jsxs("button",{type:"button",onClick:()=>y(),className:"px-4 py-2 rounded-full bg-card border border-border shadow-lg hover:shadow-xl hover:bg-card/90 transition-all text-sm font-medium text-foreground flex items-center gap-2","aria-label":"Scroll to bottom",children:[s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":"Down arrow",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 14l-7 7m0 0l-7-7m7 7V3"})}),"Scroll to bottom"]})})]})});Ys.displayName="Conversation";const Ks=At,dt=o.forwardRef(({className:r,...e},t)=>s.jsx(ce,{ref:t,className:m("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",r),...e}));dt.displayName=ce.displayName;const Gs=o.forwardRef(({className:r,children:e,...t},n)=>s.jsxs(Ks,{children:[s.jsx(dt,{}),s.jsxs(de,{ref:n,className:m("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",r),...t,children:[e,s.jsxs(Dt,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[s.jsx(Bt,{className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Gs.displayName=de.displayName;const Js=o.forwardRef(({className:r,...e},t)=>s.jsx(ue,{ref:t,className:m("text-lg font-semibold leading-none tracking-tight",r),...e}));Js.displayName=ue.displayName;const Xs=o.forwardRef(({className:r,...e},t)=>s.jsx(fe,{ref:t,className:m("text-sm text-muted-foreground",r),...e}));Xs.displayName=fe.displayName;const Zs=o.forwardRef(({className:r,inset:e,children:t,...n},a)=>s.jsxs(me,{ref:a,className:m("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none","focus:bg-muted data-[state=open]:bg-muted",e&&"pl-8",r),...n,children:[t,s.jsx(qt,{className:"ml-auto h-4 w-4"})]}));Zs.displayName=me.displayName;const er=o.forwardRef(({className:r,...e},t)=>s.jsx(pe,{ref:t,className:m("z-50 min-w-[8rem] overflow-hidden rounded-md border border-border bg-card p-1 shadow-lg","data-[state=open]:animate-in data-[state=closed]:animate-out","data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0","data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95","data-[side=bottom]:slide-in-from-top-2","data-[side=left]:slide-in-from-right-2","data-[side=right]:slide-in-from-left-2","data-[side=top]:slide-in-from-bottom-2",r),...e}));er.displayName=pe.displayName;const tr=o.forwardRef(({className:r,sideOffset:e=4,...t},n)=>s.jsx(Lt,{children:s.jsx(he,{ref:n,sideOffset:e,className:m("z-50 min-w-[8rem] overflow-hidden rounded-md border border-border bg-card p-1 shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out","data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0","data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95","data-[side=bottom]:slide-in-from-top-2","data-[side=left]:slide-in-from-right-2","data-[side=right]:slide-in-from-left-2","data-[side=top]:slide-in-from-bottom-2",r),...t})}));tr.displayName=he.displayName;const sr=o.forwardRef(({className:r,inset:e,...t},n)=>s.jsx(ge,{ref:n,className:m("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e&&"pl-8",r),...t}));sr.displayName=ge.displayName;const rr=o.forwardRef(({className:r,children:e,...t},n)=>s.jsxs(xe,{ref:n,className:m("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",r),...t,children:[s.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:s.jsx(be,{children:s.jsx(Te,{className:"h-4 w-4"})})}),e]}));rr.displayName=xe.displayName;const nr=o.forwardRef(({className:r,children:e,...t},n)=>s.jsxs(ye,{ref:n,className:m("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",r),...t,children:[s.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:s.jsx(be,{children:s.jsx(Me,{className:"h-2 w-2 fill-current"})})}),e]}));nr.displayName=ye.displayName;const or=o.forwardRef(({className:r,inset:e,...t},n)=>s.jsx(we,{ref:n,className:m("px-2 py-1.5 text-sm font-semibold",e&&"pl-8",r),...t}));or.displayName=we.displayName;const ar=o.forwardRef(({className:r,...e},t)=>s.jsx(ve,{ref:t,className:m("-mx-1 my-1 h-px bg-border",r),...e}));ar.displayName=ve.displayName;const ir=A("flex h-10 w-full rounded-md border bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",{variants:{variant:{default:"border-input focus-visible:ring-ring",error:"border-destructive focus-visible:ring-destructive",success:"border-green-500 focus-visible:ring-green-500"}},defaultVariants:{variant:"default"}}),lr=o.forwardRef(({className:r,type:e,variant:t,...n},a)=>s.jsx("input",{type:e,className:m(ir({variant:t,className:r})),ref:a,...n}));lr.displayName="Input";const cr=o.forwardRef(({className:r,...e},t)=>s.jsx(Ne,{ref:t,className:m("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",r),...e}));cr.displayName=Ne.displayName;const dr=A("flex animate-fadeIn",{variants:{role:{user:"max-w-[80%] self-end ml-auto mr-2",assistant:"self-start mr-auto",system:"self-start mr-auto max-w-full"},layout:{default:"",full:"max-w-full",compact:"max-w-[90%]"}},defaultVariants:{role:"assistant",layout:"default"}}),ut=o.forwardRef(({message:r,role:e,layout:t,className:n,children:a,messageId:i,autoScroll:u,isLastMessage:p=!1,...f},c)=>{const l=r?r.role:e||"assistant",d=r?r.id:i,h=o.useRef(null),[g,b]=o.useState(void 0);return o.useImperativeHandle(c,()=>h.current),o.useEffect(()=>{if(!p||l!=="assistant"){b(void 0);return}const S=()=>{const y=h.current;if(!y)return;let w=y.parentElement;for(;w&&!w.classList.contains("overflow-y-auto");)w=w.parentElement;if(!w)return;const v=y.previousElementSibling;if(!v||v.getAttribute("aria-label")!=="user message"){b(void 0);return}const E=w.clientHeight,D=v.offsetHeight,C=Math.max(0,E-D-32);b(C)};S();const N=new ResizeObserver(S);if(h.current){N.observe(h.current);let y=h.current.parentElement;for(;y&&!y.classList.contains("overflow-y-auto");)y=y.parentElement;y&&N.observe(y)}return()=>N.disconnect()},[p,l]),o.useEffect(()=>{if((u!==void 0?u:l==="user")&&h.current){const N=setTimeout(()=>{h.current?.scrollIntoView({behavior:"smooth",block:"start",inline:"nearest"})},50);return()=>clearTimeout(N)}},[l,u]),s.jsx("article",{ref:h,"aria-label":`${l} message`,"data-message-id":d,className:m(dr({role:l,layout:t}),n),style:{minHeight:g!==void 0?`${g}px`:void 0},...f,children:a})});ut.displayName="Message";const re=A("mb-3 rounded-lg bg-card border border-border transition-all",{variants:{variant:{default:"opacity-70",subtle:"opacity-50",prominent:"opacity-90 shadow-sm"}},defaultVariants:{variant:"default"}}),ur=A("w-4 h-4 text-foreground opacity-60 transition-transform duration-200",{variants:{expanded:{true:"rotate-180",false:""}},defaultVariants:{expanded:!1}}),ft=o.forwardRef(({content:r,isStreaming:e=!1,mode:t="collapsible",defaultExpanded:n=!1,autoExpand:a=!1,autoCollapse:i=!0,autoCollapseDelay:u=2e3,label:p="Thinking",variant:f,className:c},l)=>{const[d,h]=o.useState(t==="inline"?!0:n),[g,b]=o.useState(!1);return o.useEffect(()=>{if(i&&!e&&r&&t==="collapsible"){const S=setTimeout(()=>{b(!0),h(!1)},u);return()=>clearTimeout(S)}},[e,r,i,u,t]),o.useEffect(()=>{a&&e&&t==="collapsible"&&!g&&h(!0)},[a,e,t,g]),!r&&!e?null:t==="inline"?s.jsxs("div",{ref:l,className:m(re({variant:f}),"p-3",c),children:[s.jsxs("div",{className:"flex items-start gap-2 mb-2",children:[s.jsx("span",{className:"text-xs font-medium text-foreground opacity-60 uppercase tracking-wide",children:p}),e&&s.jsx("span",{className:"inline-block w-2 h-2 bg-primary rounded-full animate-pulse"})]}),s.jsxs("div",{className:"text-sm italic text-foreground opacity-80 leading-relaxed whitespace-pre-wrap",children:[r,e&&r&&s.jsx("span",{className:"inline-block animate-typing text-primary",children:"..."})]})]}):s.jsxs("div",{ref:l,className:m("mb-3",c),children:[s.jsxs("button",{type:"button",onClick:()=>{h(!d),b(!1)},className:"w-full flex items-center justify-between p-2.5 rounded-lg bg-card border border-border hover:bg-card/80 hover:shadow-sm transition-all text-left","aria-expanded":d,"aria-label":`${d?"Collapse":"Expand"} reasoning`,children:[s.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[s.jsx("span",{className:"text-xs font-medium text-foreground opacity-60 uppercase tracking-wide shrink-0",children:p}),e&&s.jsx("span",{className:"inline-block w-2 h-2 bg-primary rounded-full animate-pulse shrink-0"}),!d&&r&&s.jsxs("span",{className:"text-xs text-foreground opacity-50 truncate",children:[r.substring(0,60),r.length>60&&"..."]})]}),s.jsx(ee,{className:ur({expanded:d}),"aria-hidden":"true"})]}),d&&s.jsx("div",{className:m(re({variant:f}),"mt-2 p-3 animate-fadeIn"),children:s.jsxs("div",{className:"text-sm italic text-foreground opacity-80 leading-relaxed whitespace-pre-wrap",children:[r,e&&r&&s.jsx("span",{className:"inline-block animate-typing text-primary",children:"..."})]})})]})});ft.displayName="Reasoning";const mt=o.forwardRef(({content:r,isStreaming:e=!1,showEmpty:t=!0,emptyMessage:n="",className:a,...i},u)=>{if(!r&&e&&t)return s.jsx("div",{ref:u,className:m("opacity-70 italic text-sm",a),...i,children:n});if(!r)return null;const p={table:({node:f,...c})=>s.jsx("div",{className:"overflow-x-auto my-4",children:s.jsx("table",{className:"min-w-full border-collapse border border-border rounded-md",...c})}),thead:({node:f,...c})=>s.jsx("thead",{className:"bg-card border-b border-border",...c}),tbody:({node:f,...c})=>s.jsx("tbody",{...c}),tr:({node:f,...c})=>s.jsx("tr",{className:"border-b border-border hover:bg-card transition-colors",...c}),th:({node:f,...c})=>s.jsx("th",{className:"px-4 py-2 text-left font-semibold text-foreground border-r border-border last:border-r-0",...c}),td:({node:f,...c})=>s.jsx("td",{className:"px-4 py-2 text-foreground border-r border-border last:border-r-0",...c}),input:({node:f,checked:c,...l})=>l.type==="checkbox"?s.jsx("input",{type:"checkbox",checked:c||!1,disabled:!0,readOnly:!0,className:"mr-2 w-4 h-4 accent-[primary] cursor-not-allowed",...l}):s.jsx("input",{...l}),code:({node:f,...c})=>c.className?.includes("language-")?s.jsx("code",{className:"block p-4 bg-card border border-border rounded-md overflow-x-auto text-sm font-mono text-foreground shadow-sm",...c}):s.jsx("code",{className:"px-1.5 py-0.5 bg-card border border-border rounded text-sm font-mono text-foreground",...c}),pre:({node:f,...c})=>s.jsx("pre",{className:"my-4 rounded-lg",...c}),h1:({node:f,...c})=>s.jsx("h1",{className:"text-2xl font-bold mt-6 mb-4 text-foreground border-b border-border pb-2",...c}),h2:({node:f,...c})=>s.jsx("h2",{className:"text-xl font-semibold mt-5 mb-3 text-foreground border-b border-border/50 pb-1.5",...c}),h3:({node:f,...c})=>s.jsx("h3",{className:"text-lg font-semibold mt-4 mb-2 text-foreground",...c}),h4:({node:f,...c})=>s.jsx("h4",{className:"text-base font-semibold mt-3 mb-2 text-foreground",...c}),ul:({node:f,...c})=>{const l=f?.children?.some(d=>typeof d=="object"&&d!==null&&"type"in d&&d.type==="element"&&"tagName"in d&&d.tagName==="li"&&"children"in d&&Array.isArray(d.children)&&d.children.some(h=>typeof h=="object"&&h!==null&&"type"in h&&h.type==="element"&&"tagName"in h&&h.tagName==="input"&&"properties"in h&&typeof h.properties=="object"&&h.properties!==null&&"type"in h.properties&&h.properties.type==="checkbox"));return s.jsx("ul",{className:m("my-2 space-y-1 text-foreground",l?"list-none space-y-2":"list-disc list-inside"),...c})},ol:({node:f,...c})=>s.jsx("ol",{className:"list-decimal list-inside my-2 space-y-1 text-foreground",...c}),li:({node:f,...c})=>{const l=f?.children?.some(d=>typeof d=="object"&&d!==null&&"type"in d&&d.type==="element"&&"tagName"in d&&d.tagName==="input"&&"properties"in d&&typeof d.properties=="object"&&d.properties!==null&&"type"in d.properties&&d.properties.type==="checkbox");return s.jsx("li",{className:m("flex items-start",l?"gap-2":"ml-2"),...c})},a:({node:f,...c})=>s.jsx("a",{className:"text-primary hover:underline decoration-2 underline-offset-2 transition-all",target:"_blank",rel:"noopener noreferrer",...c}),p:({node:f,...c})=>s.jsx("p",{className:"my-2 text-foreground leading-relaxed",...c}),blockquote:({node:f,...c})=>s.jsx("blockquote",{className:"border-l-4 border-[primary] pl-4 italic my-4 text-foreground bg-card py-2 rounded-r-md shadow-sm",...c}),hr:({node:f,...c})=>s.jsx("hr",{className:"my-6 border-t border-border opacity-50",...c})};return s.jsxs("div",{ref:u,className:m("markdown-content prose prose-sm max-w-none dark:prose-invert",a),...i,children:[s.jsx(vt,{remarkPlugins:[es],components:p,children:r}),e&&r&&s.jsx("span",{className:"inline-block ml-1 animate-typing text-primary",children:"..."})]})});mt.displayName="Response";const Y=["Thinking","Pensando","Pensant","Denkend","Pensando","考えている","생각 중","思考中","Размышляя","Düşünüyor","Myślący","Tänkande","Pensando","Ajatellen","Σκεπτόμενος","חושב","सोच रहा है","Berpikir"],ne=["...","·..",".·.","..·",".·.","·.."];function fr({startTime:r}){const[e,t]=o.useState(0),[n,a]=o.useState(()=>Y[Math.floor(Math.random()*Y.length)]),[i,u]=o.useState(0);o.useEffect(()=>{const c=setInterval(()=>{const d=Date.now()-r;t(d)},100);return()=>clearInterval(c)},[r]),o.useEffect(()=>{const c=setInterval(()=>{const l=Math.floor(Math.random()*Y.length);a(Y[l])},1500);return()=>clearInterval(c)},[]),o.useEffect(()=>{const c=setInterval(()=>{u(l=>(l+1)%ne.length)},100);return()=>clearInterval(c)},[]);const p=(e/1e3).toFixed(1),f=ne[i];return s.jsxs("span",{className:"text-muted-foreground text-sm",children:[n,f," ",p,"s"]})}const mr=A("w-full px-4 py-3 rounded-xl text-[var(--font-size)] font-[var(--font-family)] leading-relaxed break-words transition-colors",{variants:{role:{user:"bg-primary text-primary-foreground shadow-sm",assistant:"text-foreground",system:"bg-card border border-border text-foreground opacity-80 text-sm"},variant:{default:"",outline:"border border-border",ghost:"bg-transparent"}},defaultVariants:{role:"assistant",variant:"default"}}),pt=o.forwardRef(({role:r,variant:e,isStreaming:t,message:n,thinkingDisplayStyle:a="collapsible",className:i,children:u,...p},f)=>{const c=j(b=>b.streamingStartTime),l=n&&!u,d=l?n.role:r||"assistant",h=l?n.isStreaming:t;let g=u;if(l){const b=n.metadata?.thinking,S=!!b,N=n.isStreaming&&!n.content&&n.role==="assistant";g=s.jsxs(s.Fragment,{children:[n.role==="assistant"&&S&&s.jsx(ft,{content:b,isStreaming:n.isStreaming,mode:a,autoCollapse:!0}),N&&c&&s.jsxs("div",{className:"flex items-center gap-2 opacity-50",children:[s.jsx(Ae,{className:"size-4 animate-spin text-muted-foreground"}),s.jsx(fr,{startTime:c})]}),n.role==="user"?s.jsx("div",{className:"whitespace-pre-wrap",children:n.content}):s.jsx(mt,{content:n.content,isStreaming:n.isStreaming,showEmpty:!1})]})}return s.jsx("div",{ref:f,className:m(mr({role:d,variant:e}),h&&"animate-pulse-subtle",i),...p,children:g})});pt.displayName="MessageContent";const pr=o.forwardRef(({className:r,children:e,...t},n)=>s.jsxs(Se,{ref:n,className:m("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",r),...t,children:[e,s.jsx(Pt,{asChild:!0,children:s.jsx(Wt,{className:"h-4 w-4 opacity-50"})})]}));pr.displayName=Se.displayName;const ht=o.forwardRef(({className:r,...e},t)=>s.jsx(Ce,{ref:t,className:m("flex cursor-default items-center justify-center py-1",r),...e,children:s.jsx(Qt,{className:"h-4 w-4"})}));ht.displayName=Ce.displayName;const gt=o.forwardRef(({className:r,...e},t)=>s.jsx(je,{ref:t,className:m("flex cursor-default items-center justify-center py-1",r),...e,children:s.jsx(ee,{className:"h-4 w-4"})}));gt.displayName=je.displayName;const hr=o.forwardRef(({className:r,children:e,position:t="popper",...n},a)=>s.jsx(Ht,{children:s.jsxs(Ie,{ref:a,className:m("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",r),position:t,...n,children:[s.jsx(ht,{}),s.jsx(Ft,{className:m("p-1",t==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:e}),s.jsx(gt,{})]})}));hr.displayName=Ie.displayName;const gr=o.forwardRef(({className:r,...e},t)=>s.jsx(Ee,{ref:t,className:m("py-1.5 pl-8 pr-2 text-sm font-semibold",r),...e}));gr.displayName=Ee.displayName;const xr=o.forwardRef(({className:r,children:e,...t},n)=>s.jsxs(Re,{ref:n,className:m("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",r),...t,children:[s.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:s.jsx(zt,{children:s.jsx(Te,{className:"h-4 w-4"})})}),s.jsx(Ut,{children:e})]}));xr.displayName=Re.displayName;const br=o.forwardRef(({className:r,...e},t)=>s.jsx(ke,{ref:t,className:m("-mx-1 my-1 h-px bg-muted",r),...e}));br.displayName=ke.displayName;const xt=o.forwardRef(({task:r,collapsible:e=!0,defaultExpanded:t=!1,onTaskClick:n,className:a,...i},u)=>{const[p,f]=o.useState(t),c=!!(r.details||r.files&&r.files.length>0),l={pending:Me,in_progress:Ae,completed:Yt}[r.status],d=()=>{switch(r.status){case"completed":return"text-green-500";case"in_progress":return"text-primary";default:return"text-foreground opacity-40"}},h=()=>{c&&e&&f(!p),n?.(r)};return s.jsxs("div",{ref:u,className:m("rounded-lg border border-border bg-card transition-all","hover:shadow-sm hover:border-border/80",a),...i,children:[s.jsxs("button",{type:"button",onClick:h,className:m("w-full flex items-center gap-3 px-3 py-2.5 text-left",c&&e&&"cursor-pointer"),disabled:!c&&!e,children:[s.jsx(l,{className:m("w-4 h-4 shrink-0",d(),r.status==="in_progress"&&"animate-spin")}),s.jsx("span",{className:m("flex-1 text-sm font-[var(--font-family)]",r.status==="completed"&&"line-through opacity-60",r.status==="in_progress"&&"font-medium"),children:r.text}),c&&e&&s.jsx(ee,{className:m("w-4 h-4 text-foreground opacity-50 transition-transform duration-200 shrink-0",p&&"rotate-180"),"aria-hidden":"true"})]}),c&&p&&s.jsxs("div",{className:"px-3 pb-3 pt-1 border-t border-border/50 animate-fadeIn",children:[r.details&&s.jsx("p",{className:"text-sm text-foreground opacity-80 leading-relaxed mb-2",children:r.details}),r.files&&r.files.length>0&&s.jsxs("div",{className:"space-y-1",children:[s.jsx("span",{className:"text-xs font-medium text-foreground opacity-60 uppercase tracking-wide",children:"Files:"}),s.jsx("div",{className:"space-y-1",children:r.files.map(g=>s.jsx("div",{className:"text-xs font-mono text-foreground opacity-70 bg-background px-2 py-1 rounded border border-border/50",children:g},g))})]})]})]})});xt.displayName="Task";const yr=o.forwardRef(({tasks:r,collapsible:e=!0,onTaskClick:t,emptyMessage:n="No tasks yet.",className:a,...i},u)=>s.jsx("div",{ref:u,className:m("space-y-2 max-h-96 overflow-y-auto",a),...i,children:r.length===0?s.jsx("p",{className:"text-sm text-foreground opacity-60 italic py-4 text-center",children:n}):r.map(p=>s.jsx(xt,{task:p,collapsible:e,...t?{onTaskClick:t}:{}},p.id))}));yr.displayName="TaskList";const wr=A("flex min-h-[80px] w-full rounded-md border bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 resize-none",{variants:{variant:{default:"border-input focus-visible:ring-ring",error:"border-destructive focus-visible:ring-destructive",success:"border-green-500 focus-visible:ring-green-500"}},defaultVariants:{variant:"default"}}),vr=o.forwardRef(({className:r,autoResize:e=!1,maxHeight:t=200,variant:n,...a},i)=>{const u=o.useRef(null),p=o.useCallback(c=>{u.current=c,typeof i=="function"?i(c):i&&(i.current=c)},[i]),f=o.useCallback(()=>{const c=u.current;if(!c||!e)return;c.style.height="auto";const l=Math.min(c.scrollHeight,t);c.style.height=`${l}px`,c.scrollHeight>t?c.style.overflowY="auto":c.style.overflowY="hidden"},[e,t]);return o.useEffect(()=>{f()},[f]),s.jsx("textarea",{className:m(wr({variant:n}),e&&"overflow-y-hidden",r),ref:p,...a})});vr.displayName="Textarea";const P=Le("gui");function Nr({client:r}){const{connectionStatus:e,connect:t}=ss(r),{messages:n}=De(r),a=j(p=>p.error);o.useEffect(()=>{P.debug("Connection status changed",{status:e}),e==="error"&&a&&P.error("Connection error occurred",{error:a})},[e,a]);const i=[],u=[{id:"model-sonnet",label:"Use Sonnet 4.5",description:"Switch to Claude Sonnet 4.5 model",icon:s.jsx(te,{className:"h-4 w-4"}),category:"model",onSelect:()=>{P.info("User selected Sonnet 4.5 model")}},{id:"model-opus",label:"Use Opus",description:"Switch to Claude Opus model",icon:s.jsx(te,{className:"h-4 w-4"}),category:"model",onSelect:()=>{P.info("User selected Opus model")}},{id:"settings",label:"Open Settings",description:"Configure chat preferences",icon:s.jsx(Xt,{className:"h-4 w-4"}),category:"action",onSelect:()=>{P.info("User opened settings")}},{id:"code-mode",label:"Code Mode",description:"Enable code-focused responses",icon:s.jsx(Zt,{className:"h-4 w-4"}),category:"mode",onSelect:()=>{P.info("User enabled code mode")}}];return s.jsxs(Ze,{defaultPanelSize:"small",defaultActiveTab:"todo",children:[s.jsxs(et,{children:[e==="error"&&a&&s.jsx("div",{className:"border-b border-red-500/20 bg-red-500/10 px-6 py-4",children:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{className:"flex-1",children:[s.jsx("h3",{className:"mb-1 text-sm font-semibold text-red-500",children:"Connection Error"}),s.jsx("p",{className:"whitespace-pre-line text-sm text-foreground",children:a})]}),s.jsx("button",{type:"button",onClick:t,className:"rounded-lg bg-red-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-600",children:"Retry"})]})}),s.jsxs(tt,{children:[s.jsx(st,{className:"pt-4",children:n.length===0?s.jsx("div",{className:"flex h-full items-center justify-center",children:s.jsx("div",{className:"text-center text-muted-foreground",children:s.jsx("p",{className:"mb-2 text-lg",children:"No messages yet"})})}):s.jsx("div",{className:"flex flex-col gap-4 px-4",children:n.map((p,f)=>s.jsx(ut,{message:p,isLastMessage:f===n.length-1,children:s.jsx(pt,{message:p,thinkingDisplayStyle:"collapsible"})},p.id))})}),s.jsx(rt,{children:s.jsxs(_e,{client:r,children:[s.jsx(Ge,{commands:u}),s.jsx(Be,{placeholder:"Type a message or / for commands...",autoFocus:!0}),s.jsxs(We,{children:[s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx(Qe,{}),s.jsx(Ye,{})]}),s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx(Ke,{}),s.jsx(qe,{children:s.jsx(Kt,{className:"size-4"})})]})]})]})})]})]}),s.jsx(nt,{breakpoint:"lg",children:s.jsxs(it,{defaultValue:"todo",className:"flex flex-col h-full",children:[s.jsxs(G,{className:"w-full justify-start rounded-none border-b border-border bg-card px-4",children:[s.jsxs(_,{value:"todo",children:[s.jsx(Gt,{className:"h-4 w-4 mr-2"}),"To-Do"]}),s.jsxs(_,{value:"files",children:[s.jsx(Jt,{className:"h-4 w-4 mr-2"}),"Files"]})]}),s.jsx(H,{value:"todo",className:"flex-1 p-4 mt-0",children:s.jsx(ot,{todos:i})}),s.jsx(H,{value:"files",className:"flex-1 p-4 mt-0",children:s.jsx(at,{})})]})})]})}function Sr(){return"http://localhost:3100"}const oe={agentServerUrl:Sr()},O=Le("gui");function Cr(){const[r,e]=o.useState(null),[t,n]=o.useState(null);return o.useEffect(()=>{try{O.info("Initializing ACP client",{serverUrl:oe.agentServerUrl});const a=new ds({type:"http",options:{baseUrl:oe.agentServerUrl}});return e(a),O.info("ACP client initialized successfully"),()=>{O.debug("Disconnecting ACP client"),a.disconnect().catch(i=>{O.error("Failed to disconnect ACP client",{error:i instanceof Error?i.message:String(i)})})}}catch(a){const i=a instanceof Error?a.message:"Failed to initialize ACP client";n(i),O.error("Failed to initialize ACP client",{error:a instanceof Error?a.message:String(a),stack:a instanceof Error?a.stack:void 0});return}},[]),t?s.jsx("div",{className:"flex items-center justify-center h-screen bg-[var(--color-bg)]",children:s.jsxs("div",{className:"text-center p-8 max-w-md",children:[s.jsx("h1",{className:"text-2xl font-bold text-red-500 mb-4",children:"Initialization Error"}),s.jsx("p",{className:"text-[var(--color-text)] mb-4",children:t}),s.jsx("p",{className:"text-sm text-[var(--color-text-secondary)]",children:"Failed to initialize the ACP client. Check the console for details."})]})}):s.jsx(Nr,{client:r})}const bt=document.getElementById("root");if(!bt)throw new Error("Root element not found");Nt.createRoot(bt).render(s.jsx(St.StrictMode,{children:s.jsx(Cr,{})}));
|
package/dist/index.html
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
<meta charset="UTF-8" />
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
6
|
<title>Agent Chat</title>
|
|
7
|
-
<script type="module" crossorigin src="/assets/index-
|
|
7
|
+
<script type="module" crossorigin src="/assets/index-B4gi_GLt.js"></script>
|
|
8
8
|
<link rel="modulepreload" crossorigin href="/assets/vendor-CEpcc87q.js">
|
|
9
9
|
<link rel="modulepreload" crossorigin href="/assets/react-oZw8z-KQ.js">
|
|
10
10
|
<link rel="modulepreload" crossorigin href="/assets/acp-sdk-C7r2g8Gx.js">
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@townco/gui-template",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.12",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist",
|
|
@@ -22,14 +22,14 @@
|
|
|
22
22
|
"check": "tsc --noEmit"
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
|
-
"@townco/ui": "0.1.
|
|
25
|
+
"@townco/ui": "0.1.15",
|
|
26
26
|
"lucide-react": "^0.552.0",
|
|
27
27
|
"react": "^19.2.0",
|
|
28
28
|
"react-dom": "^19.2.0"
|
|
29
29
|
},
|
|
30
30
|
"devDependencies": {
|
|
31
31
|
"@tailwindcss/postcss": "^4.1.17",
|
|
32
|
-
"@townco/tsconfig": "0.1.
|
|
32
|
+
"@townco/tsconfig": "0.1.12",
|
|
33
33
|
"@types/react": "^19.2.2",
|
|
34
34
|
"@types/react-dom": "^19.2.2",
|
|
35
35
|
"@vitejs/plugin-react": "^5.1.0",
|
package/src/App.tsx
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import { AcpClient } from "@townco/ui";
|
|
2
|
+
import { createLogger } from "@townco/ui/core";
|
|
2
3
|
import { useEffect, useState } from "react";
|
|
3
4
|
import { ChatView } from "./ChatView.js";
|
|
4
5
|
import { config } from "./config.js";
|
|
5
6
|
|
|
7
|
+
const logger = createLogger("gui");
|
|
8
|
+
|
|
6
9
|
function App() {
|
|
7
10
|
const [client, setClient] = useState<AcpClient | null>(null);
|
|
8
11
|
const [error, setError] = useState<string | null>(null);
|
|
@@ -10,6 +13,10 @@ function App() {
|
|
|
10
13
|
useEffect(() => {
|
|
11
14
|
// Create AcpClient with HTTP transport
|
|
12
15
|
try {
|
|
16
|
+
logger.info("Initializing ACP client", {
|
|
17
|
+
serverUrl: config.agentServerUrl,
|
|
18
|
+
});
|
|
19
|
+
|
|
13
20
|
const acpClient = new AcpClient({
|
|
14
21
|
type: "http",
|
|
15
22
|
options: {
|
|
@@ -18,16 +25,25 @@ function App() {
|
|
|
18
25
|
});
|
|
19
26
|
|
|
20
27
|
setClient(acpClient);
|
|
28
|
+
logger.info("ACP client initialized successfully");
|
|
21
29
|
|
|
22
30
|
// Clean up on unmount
|
|
23
31
|
return () => {
|
|
24
|
-
|
|
32
|
+
logger.debug("Disconnecting ACP client");
|
|
33
|
+
acpClient.disconnect().catch((err) => {
|
|
34
|
+
logger.error("Failed to disconnect ACP client", {
|
|
35
|
+
error: err instanceof Error ? err.message : String(err),
|
|
36
|
+
});
|
|
37
|
+
});
|
|
25
38
|
};
|
|
26
39
|
} catch (err) {
|
|
27
40
|
const errorMessage =
|
|
28
41
|
err instanceof Error ? err.message : "Failed to initialize ACP client";
|
|
29
42
|
setError(errorMessage);
|
|
30
|
-
|
|
43
|
+
logger.error("Failed to initialize ACP client", {
|
|
44
|
+
error: err instanceof Error ? err.message : String(err),
|
|
45
|
+
stack: err instanceof Error ? err.stack : undefined,
|
|
46
|
+
});
|
|
31
47
|
return undefined;
|
|
32
48
|
}
|
|
33
49
|
}, []);
|
package/src/ChatView.tsx
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
+
import type { AcpClient } from "@townco/ui";
|
|
1
2
|
import {
|
|
2
|
-
|
|
3
|
+
createLogger,
|
|
3
4
|
useChatMessages,
|
|
4
5
|
useChatSession,
|
|
5
6
|
useChatStore,
|
|
6
|
-
} from "@townco/ui";
|
|
7
|
+
} from "@townco/ui/core";
|
|
7
8
|
import {
|
|
8
9
|
ChatInputActions,
|
|
9
10
|
ChatInputAttachment,
|
|
@@ -33,6 +34,9 @@ import {
|
|
|
33
34
|
Settings,
|
|
34
35
|
Sparkles,
|
|
35
36
|
} from "lucide-react";
|
|
37
|
+
import { useEffect } from "react";
|
|
38
|
+
|
|
39
|
+
const logger = createLogger("gui");
|
|
36
40
|
|
|
37
41
|
export interface ChatViewProps {
|
|
38
42
|
client: AcpClient | null;
|
|
@@ -44,6 +48,15 @@ export function ChatView({ client }: ChatViewProps) {
|
|
|
44
48
|
const { messages } = useChatMessages(client);
|
|
45
49
|
const error = useChatStore((state) => state.error);
|
|
46
50
|
|
|
51
|
+
// Log connection status changes
|
|
52
|
+
useEffect(() => {
|
|
53
|
+
logger.debug("Connection status changed", { status: connectionStatus });
|
|
54
|
+
|
|
55
|
+
if (connectionStatus === "error" && error) {
|
|
56
|
+
logger.error("Connection error occurred", { error });
|
|
57
|
+
}
|
|
58
|
+
}, [connectionStatus, error]);
|
|
59
|
+
|
|
47
60
|
// TODO: Replace with useChatStore((state) => state.todos) when todos are added to the store
|
|
48
61
|
const todos: TodoItem[] = [];
|
|
49
62
|
|
|
@@ -56,7 +69,7 @@ export function ChatView({ client }: ChatViewProps) {
|
|
|
56
69
|
icon: <Sparkles className="h-4 w-4" />,
|
|
57
70
|
category: "model",
|
|
58
71
|
onSelect: () => {
|
|
59
|
-
|
|
72
|
+
logger.info("User selected Sonnet 4.5 model");
|
|
60
73
|
},
|
|
61
74
|
},
|
|
62
75
|
{
|
|
@@ -66,7 +79,7 @@ export function ChatView({ client }: ChatViewProps) {
|
|
|
66
79
|
icon: <Sparkles className="h-4 w-4" />,
|
|
67
80
|
category: "model",
|
|
68
81
|
onSelect: () => {
|
|
69
|
-
|
|
82
|
+
logger.info("User selected Opus model");
|
|
70
83
|
},
|
|
71
84
|
},
|
|
72
85
|
{
|
|
@@ -76,7 +89,7 @@ export function ChatView({ client }: ChatViewProps) {
|
|
|
76
89
|
icon: <Settings className="h-4 w-4" />,
|
|
77
90
|
category: "action",
|
|
78
91
|
onSelect: () => {
|
|
79
|
-
|
|
92
|
+
logger.info("User opened settings");
|
|
80
93
|
},
|
|
81
94
|
},
|
|
82
95
|
{
|
|
@@ -86,7 +99,7 @@ export function ChatView({ client }: ChatViewProps) {
|
|
|
86
99
|
icon: <Code className="h-4 w-4" />,
|
|
87
100
|
category: "mode",
|
|
88
101
|
onSelect: () => {
|
|
89
|
-
|
|
102
|
+
logger.info("User enabled code mode");
|
|
90
103
|
},
|
|
91
104
|
},
|
|
92
105
|
];
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{r as o,j as t,M as gt,e as xt,a as bt}from"./react-oZw8z-KQ.js";import{L as yt,M as I,N as z,O as F,P as x,Q as L,R as $,S as Q,T as O,U as T,W as V,X as wt,Y as vt,Z as Nt,$ as A,a0 as St}from"./vendor-CEpcc87q.js";import{P as Ct,a as jt}from"./acp-sdk-C7r2g8Gx.js";import{S as _,L as se,T as ne,C as re,R as It,O as oe,P as Rt,a as ae,b as Et,c as ie,D as le,d as ce,e as de,f as Tt,g as ue,I as me,h as fe,i as pe,j as he,k as ge,l as xe,m as be,n as ye,o as kt,p as we,q as ve,r as Mt,s as Ne,V as At,t as Se,u as Ce,v as Dt,w as Ht,x as je}from"./radix-5M08E2bk.js";import{S as Pt,P as Lt,M as zt,A as Ft,X as Ot,C as $t,a as Ie,b as Re,c as G,L as Ee,d as Ut,e as Vt,f as _t,g as Bt,h as qt,F as Wt,i as Z,j as Qt,k as Kt}from"./icons-DyKSdrA7.js";import{r as Yt}from"./markdown-BYclSlXM.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const c of a)if(c.type==="childList")for(const u of c.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(a){const c={};return a.integrity&&(c.integrity=a.integrity),a.referrerPolicy&&(c.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?c.credentials="include":a.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function r(a){if(a.ep)return;a.ep=!0;const c=n(a);fetch(a.href,c)}})();const j=yt(s=>({connectionStatus:"disconnected",sessionId:null,error:null,messages:[],isStreaming:!1,streamingStartTime:null,input:{value:"",isSubmitting:!1,attachedFiles:[]},setConnectionStatus:e=>s({connectionStatus:e}),setSessionId:e=>s({sessionId:e}),setError:e=>s({error:e}),addMessage:e=>s(n=>({messages:[...n.messages,e]})),updateMessage:(e,n)=>s(r=>({messages:r.messages.map(a=>a.id===e?{...a,...n}:a)})),clearMessages:()=>s({messages:[]}),setIsStreaming:e=>s({isStreaming:e}),setStreamingStartTime:e=>s({streamingStartTime:e}),setInputValue:e=>s(n=>({input:{...n.input,value:e}})),setInputSubmitting:e=>s(n=>({input:{...n.input,isSubmitting:e}})),addFileAttachment:e=>s(n=>({input:{...n.input,attachedFiles:[...n.input.attachedFiles,e]}})),removeFileAttachment:e=>s(n=>({input:{...n.input,attachedFiles:n.input.attachedFiles.filter((r,a)=>a!==e)}})),clearInput:()=>s(e=>({input:{value:"",isSubmitting:!1,attachedFiles:[]}}))}));function Te(s){const e=j(i=>i.messages),n=j(i=>i.isStreaming),r=j(i=>i.sessionId),a=j(i=>i.setIsStreaming),c=j(i=>i.setStreamingStartTime),u=j(i=>i.addMessage),p=j(i=>i.updateMessage),f=j(i=>i.setError),l=o.useCallback(async i=>{if(!s){console.error("❌ No client available"),f("No client available");return}if(!r){console.error("❌ No active session"),f("No active session");return}try{const d=Date.now();a(!0),c(d);const h={id:`msg_${Date.now()}_user`,role:"user",content:i,timestamp:new Date().toISOString(),isStreaming:!1};u(h);const g=`msg_${Date.now()}_assistant`,b={id:g,role:"assistant",content:"",timestamp:new Date().toISOString(),isStreaming:!0,streamingStartTime:d};u(b);const S=e.filter(v=>v.role!=="system").map(v=>`${v.role==="user"?"Human":"Assistant"}: ${v.content}`).join(`
|
|
2
|
-
|
|
3
|
-
`),N=S?`${S}
|
|
4
|
-
|
|
5
|
-
Human: ${i}`:i,y=s.receiveMessages();s.sendMessage(N,r).catch(v=>{const R=v instanceof Error?v.message:String(v);f(R),a(!1),c(null)});let w="";for await(const v of y)if(v.isComplete){p(g,{content:w,isStreaming:!1,streamingStartTime:void 0}),a(!1),c(null);break}else v.contentDelta.type==="text"&&(w+=v.contentDelta.text,p(g,{content:w}),await new Promise(R=>setTimeout(R,16)))}catch(d){const h=d instanceof Error?d.message:String(d);f(h),a(!1),c(null)}},[s,r,e,u,p,a,c,f]);return{messages:e,isStreaming:n,sendMessage:l}}function Jt(s){const e=j(d=>d.input),n=j(d=>d.setInputValue),r=j(d=>d.setInputSubmitting),a=j(d=>d.addFileAttachment),c=j(d=>d.removeFileAttachment),{sendMessage:u}=Te(s),p=o.useCallback(d=>{n(d)},[n]),f=o.useCallback(async()=>{if(!e.value.trim()||e.isSubmitting)return;const d=e.value;n(""),r(!0);try{await u(d)}catch(h){console.error("Failed to send message:",h)}finally{r(!1)}},[e,n,r,u]),l=o.useCallback(d=>{a(d)},[a]),i=o.useCallback(d=>{c(d)},[c]);return{value:e.value,isSubmitting:e.isSubmitting,attachedFiles:e.attachedFiles,onChange:p,onSubmit:f,onAttachFile:l,onRemoveFile:i}}function Xt(s){const e=j(i=>i.connectionStatus),n=j(i=>i.sessionId),r=j(i=>i.setConnectionStatus),a=j(i=>i.setSessionId),c=j(i=>i.setError),u=j(i=>i.clearMessages),p=o.useCallback(async()=>{if(!s){c("No client available");return}try{r("connecting"),c(null),await s.connect(),r("connected")}catch(i){console.log(i);const d=i instanceof Error?i.message:String(i);c(d),r("error")}},[s,r,c]),f=o.useCallback(async()=>{if(!s){c("No client available");return}try{const i=await s.startSession();a(i),u()}catch(i){const d=i instanceof Error?i.message:String(i);c(d)}},[s,a,c,u]),l=o.useCallback(async()=>{if(s)try{await s.disconnect(),r("disconnected"),a(null)}catch(i){const d=i instanceof Error?i.message:String(i);c(d)}},[s,r,a,c]);return o.useEffect(()=>{s&&e==="disconnected"&&p()},[s,e,p]),o.useEffect(()=>{e==="connected"&&!n&&f()},[e,n,f]),{connectionStatus:e,sessionId:n,connect:p,startSession:f,disconnect:l}}const Gt=I({id:x(),role:O(["user","assistant","system"]),content:x(),timestamp:Q(),isStreaming:$().default(!1),streamingStartTime:L().optional(),metadata:z(x(),F()).optional()}),Zt=I({value:x(),isSubmitting:$(),attachedFiles:T(I({name:x(),path:x(),size:L(),mimeType:x()}))});I({sessionId:x().nullable(),isConnected:$(),isStreaming:$(),messages:T(Gt),input:Zt,error:x().nullable()});O(["disconnected","connecting","connected","error"]);class es{connected=!1;sessionUpdateCallbacks=new Set;errorCallbacks=new Set;messageQueue=[];currentSessionId=null;chunkResolvers=[];streamComplete=!1;sseAbortController=null;reconnectAttempts=0;maxReconnectAttempts=5;reconnectDelay=1e3;reconnecting=!1;abortController=null;options;constructor(e){this.options={...e,baseUrl:e.baseUrl.replace(/\/$/,"")}}async connect(){if(!this.connected)try{this.abortController=new AbortController;const e={protocolVersion:Ct,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},n=await this.sendRpcRequest("initialize",e);console.log("ACP connection initialized:",n);const r={cwd:"/",mcpServers:[]},a=await this.sendRpcRequest("session/new",r);this.currentSessionId=a.sessionId,console.log("Session created:",this.currentSessionId),await this.connectSSE(),this.connected=!0,this.reconnectAttempts=0}catch(e){this.connected=!1;const n=e instanceof Error?e:new Error(String(e));throw this.notifyError(n),n}}async disconnect(){if(this.connected)try{this.abortController&&(this.abortController.abort(),this.abortController=null),this.sseAbortController&&(this.sseAbortController.abort(),this.sseAbortController=null),this.connected=!1,this.currentSessionId=null,this.messageQueue=[],this.chunkResolvers=[],this.streamComplete=!1,this.reconnecting=!1,this.reconnectAttempts=0}catch(e){const n=e instanceof Error?e:new Error(String(e));throw this.notifyError(n),n}}async send(e){if(!this.connected||!this.currentSessionId)throw new Error("Transport not connected");try{this.streamComplete=!1,this.messageQueue=[];const n=e.content.filter(u=>u.type==="text").map(u=>u.text).join(`
|
|
6
|
-
`),r={sessionId:this.currentSessionId,prompt:[{type:"text",text:n}]},a=await this.sendRpcRequest("session/prompt",r);console.log("Prompt sent:",a),this.streamComplete=!0;const c=this.chunkResolvers.shift();c?c({id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0}):this.messageQueue.push({id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0})}catch(n){this.streamComplete=!0;const r=n instanceof Error?n:new Error(String(n));throw this.notifyError(r),r}}async*receive(){for(;!this.streamComplete;)if(this.messageQueue.length>0){const e=this.messageQueue.shift();if(e&&(yield e,e.isComplete))return}else{const e=await new Promise(n=>{this.chunkResolvers.push(n)});if(e.isComplete){yield e;return}else yield e}for(;this.messageQueue.length>0;){const e=this.messageQueue.shift();e&&(yield e)}yield{id:this.currentSessionId||"unknown",role:"assistant",contentDelta:{type:"text",text:""},isComplete:!0}}isConnected(){return this.connected}onSessionUpdate(e){return this.sessionUpdateCallbacks.add(e),()=>{this.sessionUpdateCallbacks.delete(e)}}onError(e){return this.errorCallbacks.add(e),()=>{this.errorCallbacks.delete(e)}}async sendRpcRequest(e,n){const a={jsonrpc:"2.0",id:this.generateRequestId(),method:e,params:n},c={"Content-Type":"application/json",...this.options.headers},u=this.options.timeout||3e4,p=new AbortController,f=setTimeout(()=>p.abort(),u);try{const l=await fetch(`${this.options.baseUrl}/rpc`,{method:"POST",headers:c,body:JSON.stringify(a),signal:p.signal});if(clearTimeout(f),!l.ok){const d=await l.text();throw new Error(`HTTP ${l.status}: ${d}`)}const i=await l.json();if(i.error)throw new Error(`ACP error: ${i.error.message||JSON.stringify(i.error)}`);return i.result||i}catch(l){throw clearTimeout(f),l instanceof Error&&l.name==="AbortError"?new Error(`Request timeout after ${u}ms`):l}}async connectSSE(){if(!this.currentSessionId)throw new Error("Cannot connect SSE without a session ID");const e=`${this.options.baseUrl}/events`,n={"X-Session-ID":this.currentSessionId,...this.options.headers};this.sseAbortController=new AbortController;try{const r=await fetch(e,{method:"GET",headers:n,signal:this.sseAbortController.signal});if(!r.ok)throw new Error(`SSE connection failed: HTTP ${r.status}`);if(!r.body)throw new Error("Response body is null");console.log("SSE connection opened"),this.reconnectAttempts=0,this.reconnectDelay=1e3;const a=r.body.getReader(),c=new TextDecoder;let u="";(async()=>{try{for(;;){const{done:p,value:f}=await a.read();if(p){console.log("SSE stream closed by server"),this.connected&&await this.handleSSEDisconnect();break}u+=c.decode(f,{stream:!0});const l=u.split(`
|
|
7
|
-
`);u=l.pop()||"";let i={event:"message",data:""};for(const d of l)d.startsWith("event:")?i.event=d.substring(6).trim():d.startsWith("data:")?i.data=d.substring(5).trim():d===""&&(i.event==="message"&&i.data&&this.handleSSEMessage(i.data),i={event:"message",data:""})}}catch(p){if(p instanceof Error&&p.name==="AbortError"){console.log("SSE stream aborted");return}console.error("Error reading SSE stream:",p),this.connected&&!this.reconnecting&&await this.handleSSEDisconnect()}})()}catch(r){throw console.error("SSE connection error:",r),r}}async handleSSEDisconnect(){if(this.reconnecting||!this.connected)return;if(this.reconnecting=!0,this.sseAbortController&&(this.sseAbortController.abort(),this.sseAbortController=null),this.reconnectAttempts>=this.maxReconnectAttempts){const n=new Error(`SSE reconnection failed after ${this.maxReconnectAttempts} attempts`);this.notifyError(n),this.connected=!1,this.reconnecting=!1;return}this.reconnectAttempts++;const e=Math.min(this.reconnectDelay*2**(this.reconnectAttempts-1),32e3);console.log(`SSE reconnecting in ${e}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`),await new Promise(n=>setTimeout(n,e));try{await this.connectSSE(),console.log("SSE reconnected successfully"),this.reconnecting=!1}catch(n){console.error("SSE reconnection failed:",n),this.reconnecting=!1}}handleSSEMessage(e){try{const n=JSON.parse(e),r=jt.safeParse(n);if(!r.success){console.error("Invalid ACP message from SSE:",r.error.issues);return}const a=r.data;"method"in a&&a.method==="session/update"&&"params"in a&&a.params&&this.handleSessionNotification(a.params)}catch(n){console.error("Error parsing SSE message:",n),this.notifyError(n instanceof Error?n:new Error(String(n)))}}handleSessionNotification(e){const r=e.update,a={sessionId:this.currentSessionId||e.sessionId,status:"active"};if(r?.content){const c=r.content;let u=null;if(c.type==="text"&&c.text?u={id:e.sessionId,role:"assistant",contentDelta:{type:"text",text:c.text},isComplete:!1}:c.type==="tool_call"&&(u={id:e.sessionId,role:"assistant",contentDelta:c,isComplete:!1}),u){const p=this.chunkResolvers.shift();p?p(u):this.messageQueue.push(u)}}this.notifySessionUpdate(a)}generateRequestId(){return`req-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}notifySessionUpdate(e){for(const n of this.sessionUpdateCallbacks)try{n(e)}catch(r){console.error("Error in session update callback:",r)}}notifyError(e){for(const n of this.errorCallbacks)try{n(e)}catch(r){console.error("Error in error callback:",r)}}}class ts{constructor(){throw new Error("StdioTransport is not available in the browser. Use HttpTransport or WebSocketTransport instead.")}async connect(){throw new Error("StdioTransport not available in browser")}async disconnect(){}async send(){throw new Error("StdioTransport not available in browser")}async*receive(){throw new Error("StdioTransport not available in browser")}isConnected(){return!1}onSessionUpdate(){return()=>{}}onError(){return()=>{}}}class ss{ws=null;connected=!1;sessionUpdateCallbacks=new Set;errorCallbacks=new Set;constructor(e){}async connect(){throw new Error("WebSocketTransport not yet implemented. Waiting for HTTP ACP server.")}async disconnect(){this.ws&&(this.ws.close(),this.ws=null),this.connected=!1}async send(e){throw!this.connected||!this.ws?new Error("Transport not connected"):new Error("WebSocketTransport not yet implemented. Waiting for HTTP ACP server.")}async*receive(){throw new Error("WebSocketTransport not yet implemented. Waiting for HTTP ACP server.")}isConnected(){return this.connected}onSessionUpdate(e){return this.sessionUpdateCallbacks.add(e),()=>{this.sessionUpdateCallbacks.delete(e)}}onError(e){return this.errorCallbacks.add(e),()=>{this.errorCallbacks.delete(e)}}}class ns{config;transport;sessions=new Map;currentSessionId=null;sessionUpdateHandlers=new Set;errorHandlers=new Set;constructor(e){this.config=e,this.transport=this.createTransport(),this.setupTransportListeners(),e.autoConnect&&this.connect().catch(n=>{console.error("Failed to auto-connect:",n)})}async connect(){await this.transport.connect()}async disconnect(){await this.transport.disconnect(),this.currentSessionId=null}isConnected(){return this.transport.isConnected()}async startSession(e){const n=this.generateSessionId(),r=new Date().toISOString(),a={id:n,status:"connecting",config:e?{...e,agentPath:e.agentPath||""}:{agentPath:""},messages:[],metadata:{startedAt:r}};return this.sessions.set(n,a),this.currentSessionId=n,this.updateSessionStatus(n,"connected"),n}async sendMessage(e,n){const r=n||this.currentSessionId;if(!r)throw new Error("No active session. Start a session first.");if(!this.transport.isConnected())throw new Error("Transport not connected");const a=this.sessions.get(r);if(!a)throw new Error(`Session ${r} not found`);const c={id:this.generateMessageId(),role:"user",content:[{type:"text",text:e}],timestamp:new Date().toISOString()};a.messages.push(c),this.updateSessionStatus(r,"active"),await this.transport.send(c)}async*receiveMessages(){if(!this.transport.isConnected())throw new Error("Transport not connected");yield*this.transport.receive()}getSession(e){return this.sessions.get(e)}getCurrentSession(){return this.currentSessionId?this.sessions.get(this.currentSessionId):void 0}getAllSessions(){return Array.from(this.sessions.values())}onSessionUpdate(e){return this.sessionUpdateHandlers.add(e),()=>{this.sessionUpdateHandlers.delete(e)}}onError(e){return this.errorHandlers.add(e),()=>{this.errorHandlers.delete(e)}}createTransport(){switch(this.config.type){case"stdio":return new ts(this.config.options);case"http":return new es(this.config.options);case"websocket":return new ss(this.config.options);default:throw new Error(`Unknown transport type: ${this.config.type}`)}}setupTransportListeners(){this.transport.onSessionUpdate(e=>{this.handleSessionUpdate(e)}),this.transport.onError(e=>{this.handleError(e)})}handleSessionUpdate(e){if(e.sessionId){const n=this.sessions.get(e.sessionId);n&&(e.status&&(n.status=e.status),e.message&&n.messages.push(e.message),e.error&&(n.error=e.error))}for(const n of this.sessionUpdateHandlers)try{n(e)}catch(r){console.error("Error in session update handler:",r)}}handleError(e){for(const n of this.errorHandlers)try{n(e)}catch(r){console.error("Error in error handler:",r)}}updateSessionStatus(e,n){const r=this.sessions.get(e);r&&(r.status=n,this.handleSessionUpdate({sessionId:e,status:n}))}generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}generateMessageId(){return`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}const rs=I({name:x(),description:x().optional(),parameters:z(x(),F()).optional()}),os=I({name:x(),description:x(),parameters:z(x(),F()),required:T(x()).optional()}),as=I({name:x(),version:x().optional(),description:x().optional(),author:x().optional(),capabilities:T(rs).optional(),tools:T(os).optional(),supportedFormats:T(x()).optional()}),is=O(["initializing","ready","busy","error","terminated"]);I({status:is,info:as.optional(),pid:L().optional(),error:x().optional(),uptime:L().optional()});const ke=O(["user","assistant","system","tool"]),ls=O(["text","image","file","tool_call","tool_result"]),B=I({type:ls}),cs=B.extend({type:V("text"),text:x()}),ds=B.extend({type:V("image"),url:x().url().optional(),data:x().optional(),mimeType:x().optional()}),us=B.extend({type:V("file"),name:x(),path:x().optional(),url:x().url().optional(),mimeType:x(),size:L().optional()}),ms=B.extend({type:V("tool_call"),id:x(),name:x(),arguments:z(x(),F())}),fs=B.extend({type:V("tool_result"),callId:x(),result:F(),error:x().optional()}),Me=wt("type",[cs,ds,us,ms,fs]),Ae=I({id:x(),role:ke,content:T(Me),timestamp:Q(),metadata:z(x(),F()).optional()});I({id:x(),role:ke,contentDelta:Me,isComplete:$()});const De=O(["idle","connecting","connected","active","streaming","error","disconnected"]),ps=I({agentPath:x(),agentArgs:T(x()).optional(),environment:z(x(),x()).optional(),workingDirectory:x().optional(),timeout:L().optional()}),hs=I({agentName:x().optional(),agentVersion:x().optional(),capabilities:T(x()).optional(),startedAt:Q(),lastActivityAt:Q().optional()});I({id:x(),status:De,config:ps,metadata:hs.optional(),messages:T(Ae),error:x().optional()});I({sessionId:x(),status:De.optional(),message:Ae.optional(),error:x().optional()});function m(...s){return vt(Nt(s))}const gs=A("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),q=o.forwardRef(({className:s,variant:e,size:n,asChild:r=!1,...a},c)=>{const u=r?_:"button";return t.jsx(u,{className:m(gs({variant:e,size:n,className:s})),ref:c,...a})});q.displayName="Button";const xs=o.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:m("rounded-lg border bg-card text-card-foreground shadow-sm",s),...e}));xs.displayName="Card";const bs=o.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:m("flex flex-col space-y-1.5 p-6",s),...e}));bs.displayName="CardHeader";const ys=o.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:m("text-2xl font-semibold leading-none tracking-tight",s),...e}));ys.displayName="CardTitle";const ws=o.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:m("text-sm text-muted-foreground",s),...e}));ws.displayName="CardDescription";const vs=o.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:m("p-6 pt-0",s),...e}));vs.displayName="CardContent";const Ns=o.forwardRef(({className:s,...e},n)=>t.jsx("div",{ref:n,className:m("flex items-center p-6 pt-0",s),...e}));Ns.displayName="CardFooter";const He=o.createContext(void 0),Pe=()=>{const s=o.useContext(He);if(!s)throw new Error("ChatHeader components must be used within ChatHeader.Root");return s},Ss=o.forwardRef(({defaultExpanded:s=!1,expanded:e,onExpandedChange:n,className:r,children:a,...c},u)=>{const[p,f]=o.useState(s),l=e??p,i=o.useCallback(b=>{f(b),n?.(b)},[n]),d=o.Children.toArray(a),h=d.find(b=>o.isValidElement(b)&&typeof b.type=="function"&&b.type.displayName==="ChatHeader.ExpandablePanel"),g=d.filter(b=>b!==h);return t.jsxs(He.Provider,{value:{isExpanded:l,setIsExpanded:i},children:[t.jsx("div",{ref:u,className:m("flex items-center justify-between px-6 py-4",r),...c,children:g}),h]})});Ss.displayName="ChatHeader.Root";const Cs=o.forwardRef(({className:s,children:e,...n},r)=>t.jsx("h1",{ref:r,className:m("m-0 text-xl font-semibold",s),...n,children:e}));Cs.displayName="ChatHeader.Title";const js=o.forwardRef(({className:s,children:e,...n},r)=>t.jsx("div",{ref:r,className:m("flex items-center gap-3",s),...n,children:e}));js.displayName="ChatHeader.Actions";const Is=s=>{switch(s){case"connected":return"bg-green-500";case"connecting":return"bg-yellow-500";case"error":return"bg-red-500";default:return"bg-gray-500"}},Rs=s=>{switch(s){case"connected":return"Connected";case"connecting":return"Connecting...";case"error":return"Connection Error";default:return"No Server"}},Es=o.forwardRef(({status:s,statusText:e,className:n,...r},a)=>{const c=e??Rs(s),u=Is(s);return t.jsxs("div",{ref:a,className:m("flex items-center gap-2",n),...r,children:[t.jsx("div",{className:m("h-2 w-2 rounded-full",u)}),t.jsx("span",{className:"text-sm text-muted-foreground",children:c})]})});Es.displayName="ChatHeader.StatusIndicator";const Ts=o.forwardRef(({icon:s,className:e,children:n,onClick:r,...a},c)=>{const{isExpanded:u,setIsExpanded:p}=Pe(),f=l=>{p(!u),r?.(l)};return t.jsxs("button",{ref:c,type:"button",onClick:f,className:m("rounded p-1 transition-colors hover:bg-background lg:hidden",e),"aria-label":u?"Collapse header":"Expand header",...a,children:[s&&t.jsx("div",{className:m("transition-transform duration-200",u&&"rotate-180"),children:s}),n]})});Ts.displayName="ChatHeader.Toggle";const ks=o.forwardRef(({className:s,children:e,...n},r)=>{const{isExpanded:a}=Pe();return a?t.jsx("div",{ref:r,className:m("absolute top-full left-0 right-0 z-50 border-b border-border bg-card px-6 py-4 shadow-lg lg:hidden",s),...n,children:e}):null});ks.displayName="ChatHeader.ExpandablePanel";const Le=o.forwardRef(({commands:s=[],showCommandMenu:e,commandMenuQuery:n,selectedMenuIndex:r,setSelectedMenuIndex:a,setMenuItemCount:c,triggerCounter:u,onChange:p,className:f,...l},i)=>{const d=o.useCallback((g,b)=>{const S=g.toLowerCase(),N=b.toLowerCase();if(!b)return 1;if(S.includes(N))return 1-N.length/S.length;let y=0;for(let w=0;w<S.length&&y<N.length;w++)S[w]===N[y]&&y++;return y===N.length?.5-y/S.length:0},[]),h=o.useMemo(()=>s.map(g=>({...g,score:Math.max(d(g.label,n),g.description?d(g.description,n):0)})).filter(g=>g.score>0).sort((g,b)=>b.score-g.score),[s,n,d]);return o.useEffect(()=>{c(h.length)},[h.length,c]),o.useEffect(()=>{a(0)},[a]),o.useEffect(()=>{u>0&&h[r]&&(h[r].onSelect(),p(""))},[u,h,r,p]),!e||h.length===0?null:t.jsxs("div",{ref:i,className:m("absolute bottom-full left-0 z-50 mb-2 w-full max-w-md","rounded-md border border-border bg-card p-2 shadow-lg",f),...l,children:[t.jsx("div",{className:"text-xs font-semibold text-muted-foreground px-2 py-1",children:"Commands"}),t.jsx("div",{className:"max-h-64 overflow-y-auto",children:h.map((g,b)=>t.jsxs("button",{type:"button",onClick:()=>g.onSelect(),className:m("w-full rounded-sm px-2 py-2 text-left text-sm transition-colors","flex items-start gap-2","hover:bg-muted",b===r&&"bg-muted"),children:[g.icon&&t.jsx("span",{className:"shrink-0 mt-0.5",children:g.icon}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("div",{className:"font-medium",children:g.label}),g.description&&t.jsx("div",{className:"text-xs text-muted-foreground truncate",children:g.description})]})]},g.id))})]})});Le.displayName="ChatInputCommandMenu";const ze=o.createContext(void 0),Y=()=>{const s=o.useContext(ze);if(!s)throw new Error("ChatInput components must be used within ChatInput.Root");return s},Fe=o.forwardRef(({client:s,value:e,onChange:n,onSubmit:r,disabled:a=!1,isSubmitting:c,submitOnEnter:u=!0,className:p,children:f,...l},i)=>{const d=o.useRef(null),h=Jt(s??null),g=j(M=>M.isStreaming),b=h?h.value:e||"",S=h?h.onChange:n||(()=>{}),N=h?h.onSubmit:r||(async()=>{}),y=h?h.isSubmitting||g:c||!1,[w,v]=o.useState(!1),[R,D]=o.useState(""),[H,C]=o.useState(0),[E,k]=o.useState(0),[J,X]=o.useState(0),pt=o.useCallback(()=>{X(M=>M+1)},[]),ht=async M=>{M.preventDefault(),b.trim()&&!y&&!a&&(await N(),setTimeout(()=>{d.current?.focus()},0))};return o.useEffect(()=>{const M=document.querySelector('textarea[name="chat-input"]');M&&d.current!==M&&(d.current=M)},[]),o.useEffect(()=>{!b&&d.current&&(d.current.style.height="auto",d.current.style.overflowY="hidden")},[b]),t.jsx(ze.Provider,{value:{value:b,onChange:S,onSubmit:N,disabled:a,isSubmitting:y,submitOnEnter:u,showCommandMenu:w,setShowCommandMenu:v,commandMenuQuery:R,setCommandMenuQuery:D,selectedMenuIndex:H,setSelectedMenuIndex:C,menuItemCount:E,setMenuItemCount:k,triggerMenuSelect:pt,triggerCounter:J},children:t.jsx("form",{ref:i,onSubmit:ht,className:m("relative w-full divide-y rounded-xl border bg-background shadow-md",p),...l,children:f})})});Fe.displayName="ChatInput.Root";const Oe=o.forwardRef(({asChild:s=!1,className:e,onKeyDown:n,children:r,...a},c)=>{const{value:u,onChange:p,onSubmit:f,disabled:l,isSubmitting:i,submitOnEnter:d,showCommandMenu:h,setShowCommandMenu:g,setCommandMenuQuery:b,setSelectedMenuIndex:S,menuItemCount:N,triggerMenuSelect:y}=Y(),w=o.useRef(null),H={ref:o.useCallback(C=>{w.current=C,typeof c=="function"?c(C):c&&(c.current=C)},[c]),name:"chat-input",value:u,onChange:C=>{const E=C.target.value;if(p(E),E.startsWith("/")&&!E.includes(`
|
|
8
|
-
`)){g(!0);const X=E.slice(1);b(X)}else g(!1),b("");const k=w.current;if(!k)return;k.style.height="auto";const J=Math.min(k.scrollHeight,164);k.style.height=`${J}px`,k.scrollHeight>164?k.style.overflowY="auto":k.style.overflowY="hidden"},onKeyDown:C=>{if(h&&N>0){if(C.key==="ArrowDown"){C.preventDefault(),S(E=>(E+1)%N);return}else if(C.key==="ArrowUp"){C.preventDefault(),S(E=>(E-1+N)%N);return}else if(C.key==="Enter"&&!C.shiftKey){C.preventDefault(),y();return}else if(C.key==="Escape"){C.preventDefault(),g(!1),b("");return}}d&&C.key==="Enter"&&!C.shiftKey&&(u.trim()&&!i&&!l?(C.preventDefault(),f()):(i||l)&&C.preventDefault()),n?.(C)},disabled:l,...a};return s&&o.isValidElement(r)?o.cloneElement(r,H):t.jsx("textarea",{...H,className:m("w-full resize-none rounded-none border-none p-4 shadow-none","outline-none ring-0 field-sizing-content max-h-[6lh]","bg-transparent dark:bg-transparent focus-visible:ring-0","text-sm placeholder:text-muted-foreground","disabled:cursor-not-allowed disabled:opacity-50",e)})});Oe.displayName="ChatInput.Field";const $e=o.forwardRef(({asChild:s=!1,className:e,disabled:n,children:r,...a},c)=>{const{value:u,disabled:p,isSubmitting:f}=Y(),l=n||p||f||!u.trim(),i=s?_:q;return t.jsx(i,{ref:c,type:"submit",disabled:l,variant:s?void 0:"default",size:"icon",className:m(!s&&"gap-1.5 rounded-full",e),...a,children:r})});$e.displayName="ChatInput.Submit";const Ue=o.forwardRef(({className:s,children:e,...n},r)=>t.jsx("div",{ref:r,className:m("flex items-center justify-between p-2",s),...n,children:e}));Ue.displayName="ChatInput.Toolbar";const Ve=o.forwardRef(({asChild:s=!1,className:e,children:n,onClick:r,...a},c)=>{const{value:u,onChange:p,setShowCommandMenu:f,setCommandMenuQuery:l}=Y(),i=h=>{u.startsWith("/")||(p("/"),f(!0),l("")),r?.(h)},d=s?_:q;return t.jsx(d,{ref:c,type:"button",variant:"ghost",size:"icon",className:m("rounded-full",e),onClick:i,...a,children:n||t.jsx(Pt,{className:"size-4"})})});Ve.displayName="ChatInput.Actions";const _e=o.forwardRef(({asChild:s=!1,className:e,children:n,...r},a)=>{const c=s?_:q;return t.jsx(c,{ref:a,type:"button",variant:"ghost",size:"icon",className:m("rounded-full",e),...r,children:n||t.jsx(Lt,{className:"size-4"})})});_e.displayName="ChatInput.Attachment";const Be=o.forwardRef(({asChild:s=!1,className:e,children:n,...r},a)=>{const c=s?_:q;return t.jsx(c,{ref:a,type:"button",variant:"ghost",size:"icon",className:m("rounded-full",e),...r,children:n||t.jsx(zt,{className:"size-4"})})});Be.displayName="ChatInput.VoiceInput";const qe=o.forwardRef(({commands:s=[],className:e,onChange:n,...r},a)=>{const{showCommandMenu:c,commandMenuQuery:u,selectedMenuIndex:p,setSelectedMenuIndex:f,setMenuItemCount:l,triggerCounter:i,onChange:d}=Y();return t.jsx(Le,{ref:a,commands:s,showCommandMenu:c,commandMenuQuery:u,selectedMenuIndex:p,setSelectedMenuIndex:f,setMenuItemCount:l,triggerCounter:i,onChange:d,className:e,...r})});qe.displayName="ChatInput.CommandMenu";const Ms=({...s})=>t.jsx(St,{position:"top-center",className:"toaster group",style:{"--top-offset":"16px","--width:":"calc(100% - 2 * var(--top-offset))",position:"absolute",zIndex:5,top:"var(--top-offset)",left:"50%",transform:"translateX(-50%)",width:"calc(100% - 2 * var(--top-offset))",maxWidth:"480px"},offset:0,toastOptions:{classNames:{toast:"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground"}},...s}),We=o.createContext(void 0),Qe=()=>{const s=o.useContext(We);if(!s)throw new Error("ChatLayout components must be used within ChatLayout.Root");return s},Ke=o.forwardRef(({defaultSidebarOpen:s=!1,defaultPanelSize:e="hidden",defaultActiveTab:n="todo",className:r,children:a,...c},u)=>{const[p,f]=o.useState(s),[l,i]=o.useState(e),[d,h]=o.useState(n);return t.jsx(We.Provider,{value:{sidebarOpen:p,setSidebarOpen:f,panelSize:l,setPanelSize:i,activeTab:d,setActiveTab:h},children:t.jsx("div",{ref:u,className:m("flex h-screen flex-row bg-background text-foreground",r),...c,children:a})})});Ke.displayName="ChatLayout.Root";const As=o.forwardRef(({className:s,children:e,...n},r)=>t.jsx("div",{ref:r,className:m("relative z-10 border-b border-border bg-card shrink-0",s),...n,children:e}));As.displayName="ChatLayout.Header";const Ye=o.forwardRef(({className:s,children:e,...n},r)=>t.jsx("div",{ref:r,className:m("flex flex-1 flex-col overflow-hidden",s),...n,children:e}));Ye.displayName="ChatLayout.Main";const Je=o.forwardRef(({showToaster:s=!0,className:e,children:n,...r},a)=>t.jsxs("div",{ref:a,className:m("relative flex flex-1 flex-col overflow-hidden",e),...r,children:[n,s&&t.jsx(Ms,{})]}));Je.displayName="ChatLayout.Body";const Xe=o.forwardRef(({className:s,children:e,onScrollChange:n,showScrollToBottom:r=!0,...a},c)=>{const[u,p]=o.useState(!1),f=o.useRef(null);o.useImperativeHandle(c,()=>f.current);const l=o.useCallback(()=>{const h=f.current;if(!h)return;const{scrollTop:g,scrollHeight:b,clientHeight:S}=h,y=b-g-S<100;p(!y&&r),n?.(y)},[n,r]),i=o.useCallback(()=>{l()},[l]),d=o.useCallback(()=>{const h=f.current;h&&h.scrollTo({top:h.scrollHeight,behavior:"smooth"})},[]);return o.useEffect(()=>{l()},[l]),t.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[t.jsx("div",{ref:f,className:m("h-full overflow-y-auto",s),onScroll:i,...a,children:e}),u&&t.jsx("button",{type:"button",onClick:d,className:m("absolute bottom-4 left-1/2 -translate-x-1/2 z-10","flex items-center justify-center p-2 rounded-full","bg-card border border-border shadow-lg","text-foreground","hover:bg-accent hover:text-accent-foreground","transition-all duration-200 ease-in-out","animate-in fade-in slide-in-from-bottom-2"),"aria-label":"Scroll to bottom",children:t.jsx(Ft,{className:"h-4 w-4"})})]})});Xe.displayName="ChatLayout.Messages";const Ge=o.forwardRef(({className:s,children:e,...n},r)=>t.jsx("div",{ref:r,className:m("bg-linear-to-t from-background to-transparent px-4 pb-4",s),...n,children:e}));Ge.displayName="ChatLayout.Footer";const Ds=o.forwardRef(({className:s,children:e,...n},r)=>{const{sidebarOpen:a}=Qe();return a?t.jsx("div",{ref:r,className:m("border-r border-border bg-card w-64 overflow-y-auto",s),...n,children:e}):null});Ds.displayName="ChatLayout.Sidebar";const Ze=o.forwardRef(({breakpoint:s="lg",className:e,children:n,...r},a)=>{const{panelSize:c}=Qe();return c==="hidden"?null:t.jsx("div",{ref:a,className:m("hidden border-l border-border bg-card overflow-y-auto transition-all duration-300",s==="md"&&"md:block",s==="lg"&&"lg:block",s==="xl"&&"xl:block",s==="2xl"&&"2xl:block",c==="small"&&"w-80",c==="large"&&"w-lg",e),...r,children:n})});Ze.displayName="ChatLayout.Aside";const et=o.forwardRef(({todos:s,className:e,...n},r)=>t.jsx("div",{ref:r,className:m("space-y-2",e),...n,children:s.length===0?t.jsx("div",{className:"flex items-center justify-center h-full min-h-[200px]",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"No todos yet"})}):s.map(a=>t.jsx("div",{className:"text-sm",children:a.text},a.id))}));et.displayName="TodoTabContent";const tt=o.forwardRef(({files:s=[],className:e,...n},r)=>t.jsx("div",{ref:r,className:m("space-y-2",e),...n,children:s.length===0?t.jsx("div",{className:"flex items-center justify-center h-full min-h-[200px]",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"No files attached"})}):s.map(a=>t.jsx("div",{className:"text-sm",children:a},a))}));tt.displayName="FilesTabContent";const Hs=o.forwardRef(({data:s,className:e,...n},r)=>t.jsxs("div",{ref:r,className:m("space-y-4",e),...n,children:[t.jsx("h3",{className:"font-semibold text-lg",children:"Database"}),t.jsxs("div",{className:"text-sm text-muted-foreground",children:[t.jsx("p",{children:"Database viewer - panel automatically expanded to large size"}),t.jsxs("div",{className:"mt-4 p-4 border border-border rounded",children:[t.jsx("p",{children:"Your large data table would go here"}),s&&typeof s=="object"?t.jsx("pre",{className:"mt-2 text-xs overflow-auto",children:JSON.stringify(s,null,2)}):null]})]})]}));Hs.displayName="DatabaseTabContent";const st=It,K=o.forwardRef(({className:s,...e},n)=>t.jsx(se,{ref:n,className:m("inline-flex h-10 items-center rounded-md bg-muted p-1 text-muted-foreground gap-1",s),...e}));K.displayName=se.displayName;const U=o.forwardRef(({className:s,...e},n)=>t.jsx(ne,{ref:n,className:m("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",s),...e}));U.displayName=ne.displayName;const P=o.forwardRef(({className:s,...e},n)=>t.jsx(re,{ref:n,className:m("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",s),...e}));P.displayName=re.displayName;const nt=o.forwardRef(({todo:s,className:e,...n},r)=>t.jsx("div",{ref:r,className:m("flex items-center gap-3 px-3 py-2 rounded-lg",e),...n,children:t.jsx("span",{className:m("flex-1 text-[var(--font-size)] font-[var(--font-family)]",s.status==="completed"&&"line-through opacity-60",s.status==="in_progress"&&"shimmer-animation"),children:s.text})}));nt.displayName="TodoListItem";const rt=o.forwardRef(({client:s,todos:e,className:n,...r},a)=>{const c=e||[];return t.jsx("div",{ref:a,className:m("space-y-2 max-h-64 overflow-y-auto",n),...r,children:c.length===0?t.jsx("p",{className:"text-sm text-foreground opacity-60 italic",children:"No tasks yet."}):c.map(u=>t.jsx(nt,{todo:u},u.id))})});rt.displayName="TodoList";const Ps=o.forwardRef(({client:s,todos:e,className:n,...r},a)=>{const c=e||[],[u,p]=o.useState("todo"),f=o.useRef(null),l=o.useRef(null);o.useEffect(()=>{const h=setTimeout(()=>{const g=f.current;if(u&&g){const b=l.current;if(b){const S=g.getBoundingClientRect(),N=b.getBoundingClientRect(),y=N.left-S.left,w=N.width,v=y/S.width*100,R=100-(y+w)/S.width*100;g.style.clipPath=`inset(0 ${R.toFixed(2)}% 0 ${v.toFixed(2)}% round 999px)`}}},0);return()=>clearTimeout(h)},[u]);const i=[{id:"todo",label:"To-Do List"},{id:"files",label:"Files"},{id:"database",label:"Database"}];return t.jsx("div",{ref:a,className:m("select-none",n),...r,children:t.jsxs(st,{value:u,onValueChange:p,className:"w-full",children:[t.jsxs("div",{className:"relative mb-4 border-border",children:[t.jsx(K,{className:"bg-transparent p-0 h-auto rounded-none w-full border-none",children:i.map(d=>t.jsx(U,{value:d.id,className:"px-3 py-1 text-sm font-[var(--font-family)] font-medium rounded-none text-foreground opacity-60 data-[state=active]:opacity-100 data-[state=active]:bg-transparent data-[state=active]:shadow-none",children:d.label},d.id))}),t.jsx("div",{ref:f,className:"absolute top-0 left-0 w-full overflow-hidden z-10 pointer-events-none",style:{clipPath:"inset(0 100% 0 0% round 999px)",transition:"clip-path 0.25s ease-out"},children:t.jsx(K,{className:"bg-secondary p-0 h-auto rounded-none w-full border-none",children:i.map(d=>t.jsx(U,{value:d.id,ref:u===d.id?l:null,className:"px-3 py-1 text-sm font-[var(--font-family)] font-medium rounded-none text-primary bg-transparent data-[state=active]:shadow-none shadow-none",tabIndex:-1,children:d.label},d.id))})})]}),t.jsx(P,{value:"todo",children:t.jsx(rt,{todos:c})}),t.jsx(P,{value:"files",children:t.jsx("div",{className:"text-sm text-foreground opacity-60 italic",children:"Files tab coming soon..."})}),t.jsx(P,{value:"database",children:t.jsx("div",{className:"text-sm text-foreground opacity-60 italic",children:"Database tab coming soon..."})})]})})});Ps.displayName="ChatSecondaryPanel";const Ls=o.forwardRef(({className:s,children:e,...n},r)=>t.jsx("div",{ref:r,className:m("flex h-full flex-col",s),...n,children:e}));Ls.displayName="ChatSidebar.Root";const zs=o.forwardRef(({className:s,children:e,...n},r)=>t.jsx("div",{ref:r,className:m("border-b border-border px-4 py-3",s),...n,children:e}));zs.displayName="ChatSidebar.Header";const Fs=o.forwardRef(({className:s,children:e,...n},r)=>t.jsx("div",{ref:r,className:m("flex-1 overflow-y-auto p-4",s),...n,children:e}));Fs.displayName="ChatSidebar.Content";const Os=o.forwardRef(({className:s,children:e,...n},r)=>t.jsx("div",{ref:r,className:m("border-t border-border px-4 py-3",s),...n,children:e}));Os.displayName="ChatSidebar.Footer";const $s=o.forwardRef(({children:s,className:e,...n},r)=>{const[a,c]=o.useState(s),[u,p]=o.useState(!1),f=o.useRef(s),l=o.useRef(!0);return o.useEffect(()=>{if(l.current){l.current=!1,f.current=s;return}if(f.current===s)return;p(!0);const i=setTimeout(()=>{c(s),f.current=s,requestAnimationFrame(()=>{p(!1)})},150);return()=>{clearTimeout(i)}},[s]),t.jsx("span",{ref:r,className:m("text-sm text-foreground opacity-60 transition-opacity duration-300",u?"opacity-0":"opacity-60",e),...n,children:a})});$s.displayName="ChatStatus";const Us=o.forwardRef(({autoScroll:s=!0,isStreaming:e=!1,scrollBehavior:n="smooth",scrollThreshold:r=100,showScrollButton:a=!0,scrollButton:c,className:u,children:p,...f},l)=>{const i=o.useRef(null),[d,h]=o.useState(!0),[g,b]=o.useState(!1),S=o.useRef(0);o.useImperativeHandle(l,()=>{if(!i.current)throw new Error("Container ref not initialized");return i.current});const N=o.useCallback(()=>{const w=i.current;if(!w)return;const{scrollTop:v,scrollHeight:R,clientHeight:D}=w,C=R-v-D<r;h(C),b(!C&&a),S.current=v},[r,a]),y=o.useCallback((w=n)=>{const v=i.current;v&&v.scrollTo({top:v.scrollHeight,behavior:w})},[n]);return o.useEffect(()=>{!s||!i.current||(e&&d?y("auto"):!e&&d&&y())},[s,e,d,y]),o.useEffect(()=>{const w=i.current;if(!w)return;const v=()=>{N()};return w.addEventListener("scroll",v,{passive:!0}),N(),()=>{w.removeEventListener("scroll",v)}},[N]),o.useEffect(()=>{const w=i.current;if(!w)return;const v=new ResizeObserver(()=>{d&&s&&y("auto")});return v.observe(w),()=>{v.disconnect()}},[d,s,y]),t.jsxs("div",{className:"relative flex-1",children:[t.jsx("div",{ref:i,className:m("h-full overflow-y-auto overflow-x-hidden","scrollbar-thin scrollbar-thumb-[border] scrollbar-track-transparent",u),...f,children:t.jsx("div",{className:"flex flex-col gap-4 px-4 py-4",children:p})}),g&&t.jsx("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 z-10",children:c||t.jsxs("button",{type:"button",onClick:()=>y(),className:"px-4 py-2 rounded-full bg-card border border-border shadow-lg hover:shadow-xl hover:bg-card/90 transition-all text-sm font-medium text-foreground flex items-center gap-2","aria-label":"Scroll to bottom",children:[t.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":"Down arrow",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 14l-7 7m0 0l-7-7m7 7V3"})}),"Scroll to bottom"]})})]})});Us.displayName="Conversation";const Vs=Rt,ot=o.forwardRef(({className:s,...e},n)=>t.jsx(oe,{ref:n,className:m("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",s),...e}));ot.displayName=oe.displayName;const _s=o.forwardRef(({className:s,children:e,...n},r)=>t.jsxs(Vs,{children:[t.jsx(ot,{}),t.jsxs(ae,{ref:r,className:m("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",s),...n,children:[e,t.jsxs(Et,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[t.jsx(Ot,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));_s.displayName=ae.displayName;const Bs=o.forwardRef(({className:s,...e},n)=>t.jsx(ie,{ref:n,className:m("text-lg font-semibold leading-none tracking-tight",s),...e}));Bs.displayName=ie.displayName;const qs=o.forwardRef(({className:s,...e},n)=>t.jsx(le,{ref:n,className:m("text-sm text-muted-foreground",s),...e}));qs.displayName=le.displayName;const Ws=o.forwardRef(({className:s,inset:e,children:n,...r},a)=>t.jsxs(ce,{ref:a,className:m("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none","focus:bg-muted data-[state=open]:bg-muted",e&&"pl-8",s),...r,children:[n,t.jsx($t,{className:"ml-auto h-4 w-4"})]}));Ws.displayName=ce.displayName;const Qs=o.forwardRef(({className:s,...e},n)=>t.jsx(de,{ref:n,className:m("z-50 min-w-[8rem] overflow-hidden rounded-md border border-border bg-card p-1 shadow-lg","data-[state=open]:animate-in data-[state=closed]:animate-out","data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0","data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95","data-[side=bottom]:slide-in-from-top-2","data-[side=left]:slide-in-from-right-2","data-[side=right]:slide-in-from-left-2","data-[side=top]:slide-in-from-bottom-2",s),...e}));Qs.displayName=de.displayName;const Ks=o.forwardRef(({className:s,sideOffset:e=4,...n},r)=>t.jsx(Tt,{children:t.jsx(ue,{ref:r,sideOffset:e,className:m("z-50 min-w-[8rem] overflow-hidden rounded-md border border-border bg-card p-1 shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out","data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0","data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95","data-[side=bottom]:slide-in-from-top-2","data-[side=left]:slide-in-from-right-2","data-[side=right]:slide-in-from-left-2","data-[side=top]:slide-in-from-bottom-2",s),...n})}));Ks.displayName=ue.displayName;const Ys=o.forwardRef(({className:s,inset:e,...n},r)=>t.jsx(me,{ref:r,className:m("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e&&"pl-8",s),...n}));Ys.displayName=me.displayName;const Js=o.forwardRef(({className:s,children:e,...n},r)=>t.jsxs(fe,{ref:r,className:m("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s),...n,children:[t.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:t.jsx(pe,{children:t.jsx(Ie,{className:"h-4 w-4"})})}),e]}));Js.displayName=fe.displayName;const Xs=o.forwardRef(({className:s,children:e,...n},r)=>t.jsxs(he,{ref:r,className:m("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors","focus:bg-muted focus:text-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s),...n,children:[t.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:t.jsx(pe,{children:t.jsx(Re,{className:"h-2 w-2 fill-current"})})}),e]}));Xs.displayName=he.displayName;const Gs=o.forwardRef(({className:s,inset:e,...n},r)=>t.jsx(ge,{ref:r,className:m("px-2 py-1.5 text-sm font-semibold",e&&"pl-8",s),...n}));Gs.displayName=ge.displayName;const Zs=o.forwardRef(({className:s,...e},n)=>t.jsx(xe,{ref:n,className:m("-mx-1 my-1 h-px bg-border",s),...e}));Zs.displayName=xe.displayName;const en=A("flex h-10 w-full rounded-md border bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",{variants:{variant:{default:"border-input focus-visible:ring-ring",error:"border-destructive focus-visible:ring-destructive",success:"border-green-500 focus-visible:ring-green-500"}},defaultVariants:{variant:"default"}}),tn=o.forwardRef(({className:s,type:e,variant:n,...r},a)=>t.jsx("input",{type:e,className:m(en({variant:n,className:s})),ref:a,...r}));tn.displayName="Input";const sn=o.forwardRef(({className:s,...e},n)=>t.jsx(be,{ref:n,className:m("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",s),...e}));sn.displayName=be.displayName;const nn=A("flex animate-fadeIn",{variants:{role:{user:"max-w-[80%] self-end ml-auto mr-2",assistant:"self-start mr-auto",system:"self-start mr-auto max-w-full"},layout:{default:"",full:"max-w-full",compact:"max-w-[90%]"}},defaultVariants:{role:"assistant",layout:"default"}}),at=o.forwardRef(({message:s,role:e,layout:n,className:r,children:a,messageId:c,autoScroll:u,isLastMessage:p=!1,...f},l)=>{const i=s?s.role:e||"assistant",d=s?s.id:c,h=o.useRef(null),[g,b]=o.useState(void 0);return o.useImperativeHandle(l,()=>h.current),o.useEffect(()=>{if(!p||i!=="assistant"){b(void 0);return}const S=()=>{const y=h.current;if(!y)return;let w=y.parentElement;for(;w&&!w.classList.contains("overflow-y-auto");)w=w.parentElement;if(!w)return;const v=y.previousElementSibling;if(!v||v.getAttribute("aria-label")!=="user message"){b(void 0);return}const R=w.clientHeight,D=v.offsetHeight,C=Math.max(0,R-D-32);b(C)};S();const N=new ResizeObserver(S);if(h.current){N.observe(h.current);let y=h.current.parentElement;for(;y&&!y.classList.contains("overflow-y-auto");)y=y.parentElement;y&&N.observe(y)}return()=>N.disconnect()},[p,i]),o.useEffect(()=>{if((u!==void 0?u:i==="user")&&h.current){const N=setTimeout(()=>{h.current?.scrollIntoView({behavior:"smooth",block:"start",inline:"nearest"})},50);return()=>clearTimeout(N)}},[i,u]),t.jsx("article",{ref:h,"aria-label":`${i} message`,"data-message-id":d,className:m(nn({role:i,layout:n}),r),style:{minHeight:g!==void 0?`${g}px`:void 0},...f,children:a})});at.displayName="Message";const ee=A("mb-3 rounded-lg bg-card border border-border transition-all",{variants:{variant:{default:"opacity-70",subtle:"opacity-50",prominent:"opacity-90 shadow-sm"}},defaultVariants:{variant:"default"}}),rn=A("w-4 h-4 text-foreground opacity-60 transition-transform duration-200",{variants:{expanded:{true:"rotate-180",false:""}},defaultVariants:{expanded:!1}}),it=o.forwardRef(({content:s,isStreaming:e=!1,mode:n="collapsible",defaultExpanded:r=!1,autoExpand:a=!1,autoCollapse:c=!0,autoCollapseDelay:u=2e3,label:p="Thinking",variant:f,className:l},i)=>{const[d,h]=o.useState(n==="inline"?!0:r),[g,b]=o.useState(!1);return o.useEffect(()=>{if(c&&!e&&s&&n==="collapsible"){const S=setTimeout(()=>{b(!0),h(!1)},u);return()=>clearTimeout(S)}},[e,s,c,u,n]),o.useEffect(()=>{a&&e&&n==="collapsible"&&!g&&h(!0)},[a,e,n,g]),!s&&!e?null:n==="inline"?t.jsxs("div",{ref:i,className:m(ee({variant:f}),"p-3",l),children:[t.jsxs("div",{className:"flex items-start gap-2 mb-2",children:[t.jsx("span",{className:"text-xs font-medium text-foreground opacity-60 uppercase tracking-wide",children:p}),e&&t.jsx("span",{className:"inline-block w-2 h-2 bg-primary rounded-full animate-pulse"})]}),t.jsxs("div",{className:"text-sm italic text-foreground opacity-80 leading-relaxed whitespace-pre-wrap",children:[s,e&&s&&t.jsx("span",{className:"inline-block animate-typing text-primary",children:"..."})]})]}):t.jsxs("div",{ref:i,className:m("mb-3",l),children:[t.jsxs("button",{type:"button",onClick:()=>{h(!d),b(!1)},className:"w-full flex items-center justify-between p-2.5 rounded-lg bg-card border border-border hover:bg-card/80 hover:shadow-sm transition-all text-left","aria-expanded":d,"aria-label":`${d?"Collapse":"Expand"} reasoning`,children:[t.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[t.jsx("span",{className:"text-xs font-medium text-foreground opacity-60 uppercase tracking-wide shrink-0",children:p}),e&&t.jsx("span",{className:"inline-block w-2 h-2 bg-primary rounded-full animate-pulse shrink-0"}),!d&&s&&t.jsxs("span",{className:"text-xs text-foreground opacity-50 truncate",children:[s.substring(0,60),s.length>60&&"..."]})]}),t.jsx(G,{className:rn({expanded:d}),"aria-hidden":"true"})]}),d&&t.jsx("div",{className:m(ee({variant:f}),"mt-2 p-3 animate-fadeIn"),children:t.jsxs("div",{className:"text-sm italic text-foreground opacity-80 leading-relaxed whitespace-pre-wrap",children:[s,e&&s&&t.jsx("span",{className:"inline-block animate-typing text-primary",children:"..."})]})})]})});it.displayName="Reasoning";const lt=o.forwardRef(({content:s,isStreaming:e=!1,showEmpty:n=!0,emptyMessage:r="",className:a,...c},u)=>{if(!s&&e&&n)return t.jsx("div",{ref:u,className:m("opacity-70 italic text-sm",a),...c,children:r});if(!s)return null;const p={table:({node:f,...l})=>t.jsx("div",{className:"overflow-x-auto my-4",children:t.jsx("table",{className:"min-w-full border-collapse border border-border rounded-md",...l})}),thead:({node:f,...l})=>t.jsx("thead",{className:"bg-card border-b border-border",...l}),tbody:({node:f,...l})=>t.jsx("tbody",{...l}),tr:({node:f,...l})=>t.jsx("tr",{className:"border-b border-border hover:bg-card transition-colors",...l}),th:({node:f,...l})=>t.jsx("th",{className:"px-4 py-2 text-left font-semibold text-foreground border-r border-border last:border-r-0",...l}),td:({node:f,...l})=>t.jsx("td",{className:"px-4 py-2 text-foreground border-r border-border last:border-r-0",...l}),input:({node:f,checked:l,...i})=>i.type==="checkbox"?t.jsx("input",{type:"checkbox",checked:l||!1,disabled:!0,readOnly:!0,className:"mr-2 w-4 h-4 accent-[primary] cursor-not-allowed",...i}):t.jsx("input",{...i}),code:({node:f,...l})=>l.className?.includes("language-")?t.jsx("code",{className:"block p-4 bg-card border border-border rounded-md overflow-x-auto text-sm font-mono text-foreground shadow-sm",...l}):t.jsx("code",{className:"px-1.5 py-0.5 bg-card border border-border rounded text-sm font-mono text-foreground",...l}),pre:({node:f,...l})=>t.jsx("pre",{className:"my-4 rounded-lg",...l}),h1:({node:f,...l})=>t.jsx("h1",{className:"text-2xl font-bold mt-6 mb-4 text-foreground border-b border-border pb-2",...l}),h2:({node:f,...l})=>t.jsx("h2",{className:"text-xl font-semibold mt-5 mb-3 text-foreground border-b border-border/50 pb-1.5",...l}),h3:({node:f,...l})=>t.jsx("h3",{className:"text-lg font-semibold mt-4 mb-2 text-foreground",...l}),h4:({node:f,...l})=>t.jsx("h4",{className:"text-base font-semibold mt-3 mb-2 text-foreground",...l}),ul:({node:f,...l})=>{const i=f?.children?.some(d=>typeof d=="object"&&d!==null&&"type"in d&&d.type==="element"&&"tagName"in d&&d.tagName==="li"&&"children"in d&&Array.isArray(d.children)&&d.children.some(h=>typeof h=="object"&&h!==null&&"type"in h&&h.type==="element"&&"tagName"in h&&h.tagName==="input"&&"properties"in h&&typeof h.properties=="object"&&h.properties!==null&&"type"in h.properties&&h.properties.type==="checkbox"));return t.jsx("ul",{className:m("my-2 space-y-1 text-foreground",i?"list-none space-y-2":"list-disc list-inside"),...l})},ol:({node:f,...l})=>t.jsx("ol",{className:"list-decimal list-inside my-2 space-y-1 text-foreground",...l}),li:({node:f,...l})=>{const i=f?.children?.some(d=>typeof d=="object"&&d!==null&&"type"in d&&d.type==="element"&&"tagName"in d&&d.tagName==="input"&&"properties"in d&&typeof d.properties=="object"&&d.properties!==null&&"type"in d.properties&&d.properties.type==="checkbox");return t.jsx("li",{className:m("flex items-start",i?"gap-2":"ml-2"),...l})},a:({node:f,...l})=>t.jsx("a",{className:"text-primary hover:underline decoration-2 underline-offset-2 transition-all",target:"_blank",rel:"noopener noreferrer",...l}),p:({node:f,...l})=>t.jsx("p",{className:"my-2 text-foreground leading-relaxed",...l}),blockquote:({node:f,...l})=>t.jsx("blockquote",{className:"border-l-4 border-[primary] pl-4 italic my-4 text-foreground bg-card py-2 rounded-r-md shadow-sm",...l}),hr:({node:f,...l})=>t.jsx("hr",{className:"my-6 border-t border-border opacity-50",...l})};return t.jsxs("div",{ref:u,className:m("markdown-content prose prose-sm max-w-none dark:prose-invert",a),...c,children:[t.jsx(gt,{remarkPlugins:[Yt],components:p,children:s}),e&&s&&t.jsx("span",{className:"inline-block ml-1 animate-typing text-primary",children:"..."})]})});lt.displayName="Response";const W=["Thinking","Pensando","Pensant","Denkend","Pensando","考えている","생각 중","思考中","Размышляя","Düşünüyor","Myślący","Tänkande","Pensando","Ajatellen","Σκεπτόμενος","חושב","सोच रहा है","Berpikir"],te=["...","·..",".·.","..·",".·.","·.."];function on({startTime:s}){const[e,n]=o.useState(0),[r,a]=o.useState(()=>W[Math.floor(Math.random()*W.length)]),[c,u]=o.useState(0);o.useEffect(()=>{const l=setInterval(()=>{const d=Date.now()-s;n(d)},100);return()=>clearInterval(l)},[s]),o.useEffect(()=>{const l=setInterval(()=>{const i=Math.floor(Math.random()*W.length);a(W[i])},1500);return()=>clearInterval(l)},[]),o.useEffect(()=>{const l=setInterval(()=>{u(i=>(i+1)%te.length)},100);return()=>clearInterval(l)},[]);const p=(e/1e3).toFixed(1),f=te[c];return t.jsxs("span",{className:"text-muted-foreground text-sm",children:[r,f," ",p,"s"]})}const an=A("w-full px-4 py-3 rounded-xl text-[var(--font-size)] font-[var(--font-family)] leading-relaxed break-words transition-colors",{variants:{role:{user:"bg-primary text-primary-foreground shadow-sm",assistant:"text-foreground",system:"bg-card border border-border text-foreground opacity-80 text-sm"},variant:{default:"",outline:"border border-border",ghost:"bg-transparent"}},defaultVariants:{role:"assistant",variant:"default"}}),ct=o.forwardRef(({role:s,variant:e,isStreaming:n,message:r,thinkingDisplayStyle:a="collapsible",className:c,children:u,...p},f)=>{const l=j(b=>b.streamingStartTime),i=r&&!u,d=i?r.role:s||"assistant",h=i?r.isStreaming:n;let g=u;if(i){const b=r.metadata?.thinking,S=!!b,N=r.isStreaming&&!r.content&&r.role==="assistant";g=t.jsxs(t.Fragment,{children:[r.role==="assistant"&&S&&t.jsx(it,{content:b,isStreaming:r.isStreaming,mode:a,autoCollapse:!0}),N&&l&&t.jsxs("div",{className:"flex items-center gap-2 opacity-50",children:[t.jsx(Ee,{className:"size-4 animate-spin text-muted-foreground"}),t.jsx(on,{startTime:l})]}),r.role==="user"?t.jsx("div",{className:"whitespace-pre-wrap",children:r.content}):t.jsx(lt,{content:r.content,isStreaming:r.isStreaming,showEmpty:!1})]})}return t.jsx("div",{ref:f,className:m(an({role:d,variant:e}),h&&"animate-pulse-subtle",c),...p,children:g})});ct.displayName="MessageContent";const ln=o.forwardRef(({className:s,children:e,...n},r)=>t.jsxs(ye,{ref:r,className:m("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",s),...n,children:[e,t.jsx(kt,{asChild:!0,children:t.jsx(Ut,{className:"h-4 w-4 opacity-50"})})]}));ln.displayName=ye.displayName;const dt=o.forwardRef(({className:s,...e},n)=>t.jsx(we,{ref:n,className:m("flex cursor-default items-center justify-center py-1",s),...e,children:t.jsx(Vt,{className:"h-4 w-4"})}));dt.displayName=we.displayName;const ut=o.forwardRef(({className:s,...e},n)=>t.jsx(ve,{ref:n,className:m("flex cursor-default items-center justify-center py-1",s),...e,children:t.jsx(G,{className:"h-4 w-4"})}));ut.displayName=ve.displayName;const cn=o.forwardRef(({className:s,children:e,position:n="popper",...r},a)=>t.jsx(Mt,{children:t.jsxs(Ne,{ref:a,className:m("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",s),position:n,...r,children:[t.jsx(dt,{}),t.jsx(At,{className:m("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:e}),t.jsx(ut,{})]})}));cn.displayName=Ne.displayName;const dn=o.forwardRef(({className:s,...e},n)=>t.jsx(Se,{ref:n,className:m("py-1.5 pl-8 pr-2 text-sm font-semibold",s),...e}));dn.displayName=Se.displayName;const un=o.forwardRef(({className:s,children:e,...n},r)=>t.jsxs(Ce,{ref:r,className:m("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s),...n,children:[t.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:t.jsx(Dt,{children:t.jsx(Ie,{className:"h-4 w-4"})})}),t.jsx(Ht,{children:e})]}));un.displayName=Ce.displayName;const mn=o.forwardRef(({className:s,...e},n)=>t.jsx(je,{ref:n,className:m("-mx-1 my-1 h-px bg-muted",s),...e}));mn.displayName=je.displayName;const mt=o.forwardRef(({task:s,collapsible:e=!0,defaultExpanded:n=!1,onTaskClick:r,className:a,...c},u)=>{const[p,f]=o.useState(n),l=!!(s.details||s.files&&s.files.length>0),i={pending:Re,in_progress:Ee,completed:_t}[s.status],d=()=>{switch(s.status){case"completed":return"text-green-500";case"in_progress":return"text-primary";default:return"text-foreground opacity-40"}},h=()=>{l&&e&&f(!p),r?.(s)};return t.jsxs("div",{ref:u,className:m("rounded-lg border border-border bg-card transition-all","hover:shadow-sm hover:border-border/80",a),...c,children:[t.jsxs("button",{type:"button",onClick:h,className:m("w-full flex items-center gap-3 px-3 py-2.5 text-left",l&&e&&"cursor-pointer"),disabled:!l&&!e,children:[t.jsx(i,{className:m("w-4 h-4 shrink-0",d(),s.status==="in_progress"&&"animate-spin")}),t.jsx("span",{className:m("flex-1 text-sm font-[var(--font-family)]",s.status==="completed"&&"line-through opacity-60",s.status==="in_progress"&&"font-medium"),children:s.text}),l&&e&&t.jsx(G,{className:m("w-4 h-4 text-foreground opacity-50 transition-transform duration-200 shrink-0",p&&"rotate-180"),"aria-hidden":"true"})]}),l&&p&&t.jsxs("div",{className:"px-3 pb-3 pt-1 border-t border-border/50 animate-fadeIn",children:[s.details&&t.jsx("p",{className:"text-sm text-foreground opacity-80 leading-relaxed mb-2",children:s.details}),s.files&&s.files.length>0&&t.jsxs("div",{className:"space-y-1",children:[t.jsx("span",{className:"text-xs font-medium text-foreground opacity-60 uppercase tracking-wide",children:"Files:"}),t.jsx("div",{className:"space-y-1",children:s.files.map(g=>t.jsx("div",{className:"text-xs font-mono text-foreground opacity-70 bg-background px-2 py-1 rounded border border-border/50",children:g},g))})]})]})]})});mt.displayName="Task";const fn=o.forwardRef(({tasks:s,collapsible:e=!0,onTaskClick:n,emptyMessage:r="No tasks yet.",className:a,...c},u)=>t.jsx("div",{ref:u,className:m("space-y-2 max-h-96 overflow-y-auto",a),...c,children:s.length===0?t.jsx("p",{className:"text-sm text-foreground opacity-60 italic py-4 text-center",children:r}):s.map(p=>t.jsx(mt,{task:p,collapsible:e,...n?{onTaskClick:n}:{}},p.id))}));fn.displayName="TaskList";const pn=A("flex min-h-[80px] w-full rounded-md border bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 resize-none",{variants:{variant:{default:"border-input focus-visible:ring-ring",error:"border-destructive focus-visible:ring-destructive",success:"border-green-500 focus-visible:ring-green-500"}},defaultVariants:{variant:"default"}}),hn=o.forwardRef(({className:s,autoResize:e=!1,maxHeight:n=200,variant:r,...a},c)=>{const u=o.useRef(null),p=o.useCallback(l=>{u.current=l,typeof c=="function"?c(l):c&&(c.current=l)},[c]),f=o.useCallback(()=>{const l=u.current;if(!l||!e)return;l.style.height="auto";const i=Math.min(l.scrollHeight,n);l.style.height=`${i}px`,l.scrollHeight>n?l.style.overflowY="auto":l.style.overflowY="hidden"},[e,n]);return o.useEffect(()=>{f()},[f]),t.jsx("textarea",{className:m(pn({variant:r}),e&&"overflow-y-hidden",s),ref:p,...a})});hn.displayName="Textarea";function gn({client:s}){const{connectionStatus:e,connect:n}=Xt(s),{messages:r}=Te(s),a=j(p=>p.error),c=[],u=[{id:"model-sonnet",label:"Use Sonnet 4.5",description:"Switch to Claude Sonnet 4.5 model",icon:t.jsx(Z,{className:"h-4 w-4"}),category:"model",onSelect:()=>{console.log("Selected Sonnet 4.5")}},{id:"model-opus",label:"Use Opus",description:"Switch to Claude Opus model",icon:t.jsx(Z,{className:"h-4 w-4"}),category:"model",onSelect:()=>{console.log("Selected Opus")}},{id:"settings",label:"Open Settings",description:"Configure chat preferences",icon:t.jsx(Qt,{className:"h-4 w-4"}),category:"action",onSelect:()=>{console.log("Opening settings")}},{id:"code-mode",label:"Code Mode",description:"Enable code-focused responses",icon:t.jsx(Kt,{className:"h-4 w-4"}),category:"mode",onSelect:()=>{console.log("Enabled code mode")}}];return t.jsxs(Ke,{defaultPanelSize:"small",defaultActiveTab:"todo",children:[t.jsxs(Ye,{children:[e==="error"&&a&&t.jsx("div",{className:"border-b border-red-500/20 bg-red-500/10 px-6 py-4",children:t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{className:"flex-1",children:[t.jsx("h3",{className:"mb-1 text-sm font-semibold text-red-500",children:"Connection Error"}),t.jsx("p",{className:"whitespace-pre-line text-sm text-foreground",children:a})]}),t.jsx("button",{type:"button",onClick:n,className:"rounded-lg bg-red-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-600",children:"Retry"})]})}),t.jsxs(Je,{children:[t.jsx(Xe,{className:"pt-4",children:r.length===0?t.jsx("div",{className:"flex h-full items-center justify-center",children:t.jsx("div",{className:"text-center text-muted-foreground",children:t.jsx("p",{className:"mb-2 text-lg",children:"No messages yet"})})}):t.jsx("div",{className:"flex flex-col gap-4 px-4",children:r.map((p,f)=>t.jsx(at,{message:p,isLastMessage:f===r.length-1,children:t.jsx(ct,{message:p,thinkingDisplayStyle:"collapsible"})},p.id))})}),t.jsx(Ge,{children:t.jsxs(Fe,{client:s,children:[t.jsx(qe,{commands:u}),t.jsx(Oe,{placeholder:"Type a message or / for commands...",autoFocus:!0}),t.jsxs(Ue,{children:[t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(Ve,{}),t.jsx(_e,{})]}),t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(Be,{}),t.jsx($e,{children:t.jsx(Bt,{className:"size-4"})})]})]})]})})]})]}),t.jsx(Ze,{breakpoint:"lg",children:t.jsxs(st,{defaultValue:"todo",className:"flex flex-col h-full",children:[t.jsxs(K,{className:"w-full justify-start rounded-none border-b border-border bg-card px-4",children:[t.jsxs(U,{value:"todo",children:[t.jsx(qt,{className:"h-4 w-4 mr-2"}),"To-Do"]}),t.jsxs(U,{value:"files",children:[t.jsx(Wt,{className:"h-4 w-4 mr-2"}),"Files"]})]}),t.jsx(P,{value:"todo",className:"flex-1 p-4 mt-0",children:t.jsx(et,{todos:c})}),t.jsx(P,{value:"files",className:"flex-1 p-4 mt-0",children:t.jsx(tt,{})})]})})]})}function xn(){return"http://localhost:3100"}const bn={agentServerUrl:xn()};function yn(){const[s,e]=o.useState(null),[n,r]=o.useState(null);return o.useEffect(()=>{try{const a=new ns({type:"http",options:{baseUrl:bn.agentServerUrl}});return e(a),()=>{a.disconnect().catch(console.error)}}catch(a){const c=a instanceof Error?a.message:"Failed to initialize ACP client";r(c),console.error("Failed to initialize ACP client:",a);return}},[]),n?t.jsx("div",{className:"flex items-center justify-center h-screen bg-[var(--color-bg)]",children:t.jsxs("div",{className:"text-center p-8 max-w-md",children:[t.jsx("h1",{className:"text-2xl font-bold text-red-500 mb-4",children:"Initialization Error"}),t.jsx("p",{className:"text-[var(--color-text)] mb-4",children:n}),t.jsx("p",{className:"text-sm text-[var(--color-text-secondary)]",children:"Failed to initialize the ACP client. Check the console for details."})]})}):t.jsx(gn,{client:s})}const ft=document.getElementById("root");if(!ft)throw new Error("Root element not found");xt.createRoot(ft).render(t.jsx(bt.StrictMode,{children:t.jsx(yn,{})}));
|