@wrongstack/webui 0.68.0 → 0.77.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,94 @@
1
+ var ds=Object.defineProperty;var us=(s,t,n)=>t in s?ds(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n;var ne=(s,t,n)=>us(s,typeof t!="symbol"?t+"":t,n);import{c as ge,p as _e,t as ms,a as ps,j as e,r as d,X as be,C as he,b as nt,T as ot,I as xs,H as hs,W as Me,B as Dt,S as Rt,d as fs,e as gs,f as Ee,R as Ae,D as rt,g as Ye,h as at,i as it,k as Se,l as lt,M as ct,m as dt,n as bs,V as ys,o as vs,A as Lt,q as je,F as ws,s as js,u as Ns,v as ks,P as At,w as Ss,x as Cs,y as It,L as fe,z as ut,G as $s,E as Ce,J as mt,K as We,N as Ts,O as Ms,Q as Es,U as Ds,Y as Ne,Z as pt,_ as Oe,$ as Rs,a0 as Ls,a1 as As,a2 as Is,a3 as Pt,a4 as Ot,a5 as Ft,a6 as Ue,a7 as Ps,a8 as _t,a9 as Os,aa as Wt,ab as Ut,ac as Fs,ad as _s,ae as Kt,af as Ws,ag as Us,ah as Ks,ai as zs,aj as qs,ak as wt,al as Hs,am as jt,an as qe,ao as zt,ap as Bs,aq as Vs,ar as qt,as as Js,at as Ht,au as Qs,av as Bt,aw as Vt,ax as Gs,ay as Ys,az as Xs,aA as De,aB as xt,aC as Jt,aD as Qt,aE as Gt,aF as Zs,aG as He,aH as Nt,aI as en,aJ as tn,aK as sn,aL as nn,aM as on,aN as Xe,aO as kt,aP as rn,aQ as an,aR as ln,aS as cn}from"./vendor-DBuK7aZd.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function n(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(a){if(a.ep)return;a.ep=!0;const o=n(a);fetch(a.href,o)}})();const dn="#4f46e5";function un(s){return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
2
+ <rect x="2" y="2" width="60" height="60" rx="14" fill="${dn}" />
3
+ <text x="32" y="44" text-anchor="middle" font-family="-apple-system,Segoe UI,Roboto,sans-serif" font-size="38" font-weight="700" fill="#fff">W</text>
4
+ ${s==="ready"?'<circle cx="50" cy="14" r="14" fill="#22c55e" stroke="#fff" stroke-width="3" />':s==="error"?'<circle cx="50" cy="14" r="14" fill="#ef4444" stroke="#fff" stroke-width="3" />':s==="running"?'<circle cx="50" cy="14" r="14" fill="#f59e0b" stroke="#fff" stroke-width="3" />':s==="attention"?'<circle cx="50" cy="14" r="14" fill="#eab308" stroke="#fff" stroke-width="3"><animate attributeName="opacity" values="1;0.3;1" dur="1s" repeatCount="indefinite"/></circle>':""}
5
+ </svg>`}function mn(s){return`data:image/svg+xml;charset=utf-8,${encodeURIComponent(s)}`}function pn(){if(typeof document>"u")return null;let s=document.querySelector('link[rel="icon"]');return s||(s=document.createElement("link"),s.rel="icon",s.type="image/svg+xml",document.head.appendChild(s)),s}let Pe="idle";function Re(s){Pe=s;const t=pn();t&&(t.href=mn(un(s)))}let St=!1;function xn(){St||typeof document>"u"||(St=!0,document.addEventListener("visibilitychange",()=>{!document.hidden&&(Pe==="ready"||Pe==="error"||Pe==="attention")&&Re("idle")}))}const ht="ws_token";function hn(){try{return sessionStorage.getItem(ht)}catch{return null}}function fn(s){try{sessionStorage.setItem(ht,s)}catch{}}function gn(){try{sessionStorage.removeItem(ht)}catch{}}class bn{constructor(t){ne(this,"ws",null);ne(this,"url");ne(this,"handlers",new Map);ne(this,"reconnectAttempts",0);ne(this,"maxReconnectAttempts",10);ne(this,"reconnectDelay",1e3);ne(this,"shouldReconnect",!0);ne(this,"reconnectTimer",null);ne(this,"messageQueue",[]);ne(this,"pendingConfirms",new Map);ne(this,"sessionId",null);ne(this,"lastErrorText");ne(this,"statusListeners",new Set);ne(this,"currentStatus",{state:"connecting"});this.url=t??vn()}onStatus(t){return this.statusListeners.add(t),t(this.currentStatus),()=>this.statusListeners.delete(t)}get status(){return this.currentStatus}setStatus(t){this.currentStatus=t;for(const n of this.statusListeners)try{n(t)}catch{}}async connect(){return new Promise((t,n)=>{var r;if(((r=this.ws)==null?void 0:r.readyState)===WebSocket.OPEN){t();return}this.setStatus({state:"connecting"});try{const a=hn(),o=a?`${this.url}${this.url.includes("?")?"&":"?"}token=${a}`:this.url;this.ws=new WebSocket(o),this.ws.binaryType="arraybuffer";const l=setTimeout(()=>{n(new Error("Connection timeout"))},1e4);let c=!1;this.ws.onopen=()=>{clearTimeout(l),c=!0,console.log("[WS Client] Connected"),this.reconnectAttempts=0,this.lastErrorText=void 0,this.setStatus({state:"open"}),this.flushMessageQueue(),t()},this.ws.onmessage=i=>{try{const u=JSON.parse(i.data);this.handleMessage(u)}catch(u){console.error("[WS Client] Failed to parse message",u)}},this.ws.onerror=i=>{console.error("[WS Client] Error",i),this.lastErrorText="Connection error (see browser devtools)",c||(clearTimeout(l),n(new Error(this.lastErrorText)))},this.ws.onclose=i=>{if(console.log("[WS Client] Disconnected",i.code,i.reason),!c){clearTimeout(l);const u=i.reason||`Closed with code ${i.code}`;this.lastErrorText=u,n(new Error(u));return}i.reason&&!this.lastErrorText?this.lastErrorText=`${i.reason} (code ${i.code})`:!this.lastErrorText&&i.code!==1e3&&(this.lastErrorText=`Closed with code ${i.code}`),this.attemptReconnect()}}catch(a){this.lastErrorText=a instanceof Error?a.message:String(a),this.setStatus({state:"closed",error:this.lastErrorText}),n(a)}})}attemptReconnect(){if(!this.shouldReconnect||this.reconnectAttempts>=this.maxReconnectAttempts){console.log("[WS Client] Not reconnecting"),this.reconnectTimer=null,this.setStatus({state:"closed",error:this.lastErrorText??"Disconnected"});return}this.reconnectAttempts++;const t=Math.min(this.reconnectDelay*2**(this.reconnectAttempts-1),3e4),n=Date.now()+t;console.log(`[WS Client] Reconnecting in ${t}ms (attempt ${this.reconnectAttempts})`),this.setStatus({state:"reconnecting",attempt:this.reconnectAttempts,nextRetryAt:n,lastError:this.lastErrorText}),this.reconnectTimer=setTimeout(async()=>{if(this.shouldReconnect)try{await this.connect()}catch(r){console.error("[WS Client] Reconnect failed",r)}},t)}retryNow(){this.currentStatus.state!=="open"&&(this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempts=0,this.connect().catch(()=>{}))}flushMessageQueue(){for(;this.messageQueue.length>0;){const t=this.messageQueue.shift();t&&this.send(t)}}handleMessage(t){if(t.type==="tool.confirm_needed"){const n=t.payload;this.pendingConfirms.set(n.id,{resolve:n.resolve});const r={...t,payload:{...n,resolve:()=>{}}};this.emit(r);return}if(t.type==="session.start"){const n=t.payload;this.sessionId=n.sessionId,n.wsToken&&fn(n.wsToken)}this.emit(t)}emit(t){const n=this.handlers.get(t.type);if(n)for(const r of n)try{r(t)}catch(a){console.error(`[WS Client] Handler error for ${t.type}`,a)}}send(t){var n;((n=this.ws)==null?void 0:n.readyState)===WebSocket.OPEN?this.ws.send(JSON.stringify(t)):this.messageQueue.push(t)}on(t,n){let r=this.handlers.get(t);return r||(r=new Set,this.handlers.set(t,r)),r.add(n),()=>r==null?void 0:r.delete(n)}off(t,n){var r;(r=this.handlers.get(t))==null||r.delete(n)}sendMessage(t){const n=`msg_${Date.now()}_${crypto.randomUUID().slice(0,8)}`;return this.send({type:"user_message",payload:{id:n,content:t,timestamp:Date.now()}}),n}sendAbort(){this.send({type:"abort",payload:{}})}sendConfirm(t,n){const r=this.pendingConfirms.get(t);r&&(r.resolve(n),this.pendingConfirms.delete(t)),this.send({type:"tool.confirm_result",payload:{id:t,decision:n}})}switchModel(t,n){this.send({type:"model.switch",payload:{provider:t,model:n}})}listProviders(){this.send({type:"providers.list"})}listProviderModels(t){this.send({type:"provider.models",payload:{providerId:t}})}listSavedProviders(){this.send({type:"providers.saved"})}addKey(t,n,r){this.send({type:"key.add",payload:{providerId:t,label:n,apiKey:r}})}updateKey(t,n,r){this.send({type:"key.update",payload:{providerId:t,label:n,apiKey:r}})}deleteKey(t,n){this.send({type:"key.delete",payload:{providerId:t,label:n}})}setActiveKey(t,n){this.send({type:"key.set_active",payload:{providerId:t,label:n}})}addProvider(t,n,r,a){this.send({type:"provider.add",payload:{id:t,family:n,baseUrl:r,apiKey:a}})}removeProvider(t){this.send({type:"provider.remove",payload:{providerId:t}})}newSession(){this.send({type:"session.new"})}clearContext(){this.send({type:"context.clear"})}compactContext(t=!1){this.send({type:"context.compact",payload:{aggressive:t}})}repairContext(){this.send({type:"context.repair"})}debugContext(){this.send({type:"context.debug"})}listContextModes(){this.send({type:"context.modes.list"})}switchContextMode(t){this.send({type:"context.mode.switch",payload:{id:t}})}listTools(){this.send({type:"tools.list"})}listMemory(){this.send({type:"memory.list"})}remember(t,n){this.send({type:"memory.remember",payload:{text:t,scope:n}})}forget(t,n){this.send({type:"memory.forget",payload:{text:t,scope:n}})}listSkills(){this.send({type:"skills.list"})}getDiag(){this.send({type:"diag.get"})}getStats(){this.send({type:"stats.get"})}saveSession(){this.send({type:"session.save"})}resumeSessionById(t){this.send({type:"session.resume",payload:{id:t}})}listModes(){this.send({type:"modes.list"})}switchMode(t){this.send({type:"mode.switch",payload:{id:t}})}listFiles(t,n){this.send({type:"files.list",payload:{query:t,limit:n}})}getTodos(){this.send({type:"todos.get"})}clearTodos(){this.send({type:"todos.clear"})}removeTodo(t){const n=typeof t=="number"?{index:t}:{id:t};this.send({type:"todos.remove",payload:n})}listSessions(t=50){this.send({type:"sessions.list",payload:{limit:t}})}deleteSession(t){this.send({type:"session.delete",payload:{id:t}})}resumeSession(t){this.send({type:"session.resume",payload:{id:t}})}ping(){this.send({type:"ping"})}disconnect(){var t;this.shouldReconnect=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),(t=this.ws)==null||t.close(),this.ws=null,gn()}get isConnected(){var t;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN}get currentSessionId(){return this.sessionId}}let Be=null;const Ct=3457;function yn(){var n;if(typeof document>"u")return Ct;const s=(n=document.querySelector('meta[name="wrongstack-ws-port"]'))==null?void 0:n.getAttribute("content"),t=s?Number.parseInt(s,10):Number.NaN;return Number.isFinite(t)&&t>0&&t<65536?t:Ct}function vn(){var n;const s=yn();if(typeof window>"u"||!((n=window.location)!=null&&n.hostname))return`ws://127.0.0.1:${s}`;const t=window.location.hostname.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t==="::1"?`ws://127.0.0.1:${s}`:`ws://${window.location.hostname}:${s}`}function ae(s){return Be||(Be=new bn(s)),Be}function wn(s){if(!s)return s;const t=s.split(/\n{2,}/),n=[];for(const a of t)n.length>0&&n[n.length-1].trim()===a.trim()||n.push(a);return n.map(a=>{const o=a.split(`
6
+ `),l=[];for(const c of o)l.length>0&&c.trim().length>0&&l[l.length-1].trim()===c.trim()||l.push(c);return l.join(`
7
+ `)}).join(`
8
+
9
+ `)}const M=ge()(_e((s,t)=>({messages:[],currentAssistantMessageId:null,currentToolId:null,isLoading:!1,abortController:null,executions:new Map,queue:[],runStart:null,thinkingBuffer:"",thinkingStartedAt:null,addMessage:n=>{const r=`msg_${Date.now()}_${crypto.randomUUID().slice(0,8)}`,a={...n,id:r,timestamp:Date.now()};return s(o=>({messages:[...o.messages,a],currentAssistantMessageId:n.role==="assistant"?r:o.currentAssistantMessageId})),r},updateMessage:(n,r)=>{s(a=>({messages:a.messages.map(o=>o.id===n?{...o,...r}:o)}))},appendToMessage:(n,r)=>{s(a=>({messages:a.messages.map(o=>o.id===n?{...o,content:o.content+r}:o)}))},finalizeMessage:n=>{s(r=>({messages:r.messages.map(a=>a.id===n?{...a,content:wn(a.content),streaming:!1}:a)}))},setToolResult:(n,r,a)=>{s(o=>({messages:o.messages.map(l=>l.id===n?{...l,toolResult:r,isError:!a,progressLines:void 0}:l)}))},appendToolProgress:(n,r)=>{s(a=>({messages:a.messages.map(o=>{if(o.id!==n)return o;const c=[...o.progressLines??[],r],i=c.length>30?c.slice(c.length-30):c;return{...o,progressLines:i}})}))},setLoading:n=>s({isLoading:n}),setAbortController:n=>s({abortController:n}),clearMessages:()=>s({messages:[],currentAssistantMessageId:null,currentToolId:null,executions:new Map}),setCurrentAssistantMessage:n=>s({currentAssistantMessageId:n}),setCurrentToolId:n=>s({currentToolId:n}),truncateAfter:n=>s(r=>{const a=r.messages.findIndex(o=>o.id===n);return a===-1?r:{messages:r.messages.slice(0,a),currentAssistantMessageId:null,currentToolId:null}}),addExecution:n=>{s(r=>{const a=new Map(r.executions);return a.set(n.id,n),{executions:a}})},updateExecution:(n,r)=>{s(a=>{const o=new Map(a.executions),l=o.get(n);return l&&o.set(n,{...l,...r}),{executions:o}})},enqueue:n=>s(r=>({queue:[...r.queue,n]})),dequeue:()=>{const{queue:n}=t();if(n.length===0)return null;const[r,...a]=n;return s({queue:a}),r},removeQueued:n=>s(r=>({queue:r.queue.filter((a,o)=>o!==n)})),clearQueue:()=>s({queue:[]}),setRunStart:n=>s({runStart:n}),appendThinking:n=>s(r=>({thinkingBuffer:r.thinkingBuffer+n,thinkingStartedAt:r.thinkingStartedAt??Date.now()})),clearThinking:()=>s({thinkingBuffer:"",thinkingStartedAt:null})}),{name:"wrongstack-chat",partialize:()=>({})})),B=ge()(_e(s=>({provider:"anthropic",model:"claude-sonnet-4-20250514",wsUrl:(()=>{var n;if(typeof window>"u"||!((n=window.location)!=null&&n.hostname))return"ws://127.0.0.1:3457";const t=window.location.hostname.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t==="::1"?"ws://127.0.0.1:3457":`ws://${window.location.hostname}:3457`})(),wsConnected:!1,wsStatus:{state:"connecting"},theme:"system",autoConnect:!0,soundOnComplete:!1,setProvider:t=>s({provider:t}),setModel:t=>s({model:t}),setConfig:t=>s(t),setTheme:t=>s({theme:t}),setWsConnected:t=>s({wsConnected:t}),setWsStatus:t=>s({wsStatus:t,wsConnected:t.state==="open"}),setSoundOnComplete:t=>s({soundOnComplete:t})}),{name:"wrongstack-config"})),z=ge()(_e(s=>({session:null,totalTokens:{input:0,output:0,cacheRead:0,cacheWrite:0},lastInputTokens:0,cost:0,startTime:null,maxContext:0,inputCost:0,outputCost:0,cacheReadCost:0,projectName:"",mode:"default",modes:[],contextMode:"balanced",contextModes:[],iteration:null,todos:[],setSession:t=>s({session:t}),updateUsage:t=>s(n=>{const r=t.input+(t.cacheRead??0)+(t.cacheWrite??0),a=t.cacheRead??0,o=t.cacheWrite??0;return{totalTokens:{input:n.totalTokens.input+t.input,output:n.totalTokens.output+t.output,cacheRead:(n.totalTokens.cacheRead??0)+a,cacheWrite:(n.totalTokens.cacheWrite??0)+o},lastInputTokens:r||n.lastInputTokens}}),addCost:t=>s(n=>({cost:n.cost+t})),startSession:t=>s({session:t,startTime:Date.now(),iteration:null,lastInputTokens:0,totalTokens:{input:0,output:0,cacheRead:0,cacheWrite:0},cost:0}),endSession:()=>s({session:null,startTime:null,iteration:null}),setEnv:t=>s(n=>({maxContext:t.maxContext??n.maxContext,projectName:t.projectName??n.projectName,mode:t.mode??n.mode,contextMode:t.contextMode??n.contextMode,inputCost:t.inputCost??n.inputCost,outputCost:t.outputCost??n.outputCost,cacheReadCost:t.cacheReadCost??n.cacheReadCost})),setIteration:t=>s({iteration:t}),setModes:t=>s({modes:t}),setContextModes:t=>s({contextModes:t}),setTodos:t=>s({todos:t})}),{name:"wrongstack-session",partialize:()=>({})})),P=ge()(_e(s=>({sidebarOpen:!0,settingsOpen:!1,currentView:"chat",showConfirmDialog:!1,confirmInfo:null,paletteOpen:!1,shortcutsOpen:!1,searchOpen:!1,searchQuery:"",promptHistory:[],sidebarWidth:288,pinnedIds:[],compactMode:!1,modelSwitcherOpen:!1,favoriteSessionIds:[],sessionNicknames:{},toggleSidebar:()=>s(t=>({sidebarOpen:!t.sidebarOpen})),setSidebarOpen:t=>s({sidebarOpen:t}),setSettingsOpen:t=>s({settingsOpen:t}),setCurrentView:t=>s({currentView:t}),showConfirm:t=>s({showConfirmDialog:!0,confirmInfo:t}),hideConfirm:()=>s({showConfirmDialog:!1,confirmInfo:null}),setPaletteOpen:t=>s({paletteOpen:t}),setShortcutsOpen:t=>s({shortcutsOpen:t}),setSearchOpen:t=>s({searchOpen:t,searchQuery:""}),setSearchQuery:t=>s({searchQuery:t}),pushPrompt:t=>s(n=>{const r=t.trim();if(!r)return n;const a=n.promptHistory.filter(o=>o!==r);return{promptHistory:[r,...a].slice(0,50)}}),setSidebarWidth:t=>s({sidebarWidth:Math.max(200,Math.min(480,Math.round(t)))}),togglePin:t=>s(n=>({pinnedIds:n.pinnedIds.includes(t)?n.pinnedIds.filter(a=>a!==t):[...n.pinnedIds,t]})),unpinAll:()=>s({pinnedIds:[]}),toggleCompactMode:()=>s(t=>({compactMode:!t.compactMode})),setModelSwitcherOpen:t=>s({modelSwitcherOpen:t}),toggleFavoriteSession:t=>s(n=>({favoriteSessionIds:n.favoriteSessionIds.includes(t)?n.favoriteSessionIds.filter(a=>a!==t):[...n.favoriteSessionIds,t]})),setSessionNickname:(t,n)=>s(r=>{const a=n.trim(),o={...r.sessionNicknames};return a?o[t]=a:delete o[t],{sessionNicknames:o}})}),{name:"wrongstack-ui",partialize:s=>({sidebarOpen:s.sidebarOpen,sidebarWidth:s.sidebarWidth,promptHistory:s.promptHistory,pinnedIds:s.pinnedIds,compactMode:s.compactMode,favoriteSessionIds:s.favoriteSessionIds,sessionNicknames:s.sessionNicknames})})),ke=ge()(s=>({entries:[],loading:!1,error:null,setEntries:(t,n=null)=>s({entries:t,error:n,loading:!1}),setLoading:t=>s({loading:t}),removeEntry:t=>s(n=>({entries:n.entries.filter(r=>r.id!==t)})),clearHistory:()=>s({entries:[]})})),Yt=ge()(s=>({worktrees:[],baseBranch:"",activity:[],setSnapshot:(t,n)=>s({worktrees:t,baseBranch:n}),pushEvent:t=>s(n=>({activity:[...n.activity,t].slice(-40)}))}));function jn(s,t){return{id:s,name:(t==null?void 0:t.trim())||s,status:"running",iteration:0,toolCalls:0,costUsd:0,ctxPct:0,ctxTokens:0,maxContext:0,extensions:0,startedAt:Date.now()}}const ft=ge()(s=>({agents:new Map,clear:()=>s({agents:new Map}),applyEvent:t=>s(n=>{var l;const r=new Map(n.agents),o={...r.get(t.subagentId)??jn(t.subagentId,t.name)};switch(t.kind){case"spawned":o.name=((l=t.name)==null?void 0:l.trim())||o.name,o.provider=t.provider??o.provider,o.model=t.model??o.model,o.description=t.description??o.description,o.taskId=t.taskId??o.taskId,o.status="running";break;case"task_started":o.description=t.description??o.description,o.taskId=t.taskId??o.taskId,o.status="running";break;case"tool_executed":o.lastTool=t.toolName??o.lastTool,o.toolCalls=o.toolCalls+1;break;case"iteration_summary":o.iteration=t.iteration??o.iteration,typeof t.toolCalls=="number"&&(o.toolCalls=t.toolCalls),typeof t.costUsd=="number"&&(o.costUsd=t.costUsd),o.currentTool=t.currentTool??o.currentTool;break;case"budget_extended":o.extensions=t.totalExtensions??o.extensions+1;break;case"ctx_pct":o.ctxPct=Math.round(Math.min(1,Math.max(0,t.load??0))*100),o.ctxTokens=t.tokens??o.ctxTokens,o.maxContext=t.maxContext??o.maxContext;break;case"task_completed":o.status=t.status==="success"?"completed":t.status??"completed",typeof t.iterations=="number"&&(o.iteration=t.iterations),typeof t.toolCalls=="number"&&(o.toolCalls=t.toolCalls),o.error=t.error,o.currentTool=void 0,o.completedAt=Date.now();break}return r.set(t.subagentId,o),{agents:r}})}));function k(...s){return ms(ps(s))}const ye=ge(s=>({toasts:[],push:t=>{const n=`toast_${Date.now()}_${Math.random().toString(36).slice(2,7)}`;return s(r=>({toasts:[...r.toasts,{...t,id:n}]})),n},dismiss:t=>s(n=>({toasts:n.toasts.filter(r=>r.id!==t)}))})),Le={success:(s,t=3500)=>ye.getState().push({message:s,variant:"success",ttl:t}),error:(s,t=6e3)=>ye.getState().push({message:s,variant:"error",ttl:t}),warn:(s,t=4500)=>ye.getState().push({message:s,variant:"warn",ttl:t}),info:(s,t=3500)=>ye.getState().push({message:s,variant:"info",ttl:t}),dismiss:s=>ye.getState().dismiss(s)};function Nn({variant:s}){return s==="success"?e.jsx(he,{className:"h-4 w-4 text-green-500"}):s==="error"?e.jsx(nt,{className:"h-4 w-4 text-destructive"}):s==="warn"?e.jsx(ot,{className:"h-4 w-4 text-amber-500"}):e.jsx(xs,{className:"h-4 w-4 text-blue-500"})}function kn({entry:s}){const t=ye(n=>n.dismiss);return d.useEffect(()=>{const n=setTimeout(()=>t(s.id),s.ttl);return()=>clearTimeout(n)},[s.id,s.ttl,t]),e.jsxs("div",{className:k("flex items-start gap-2 rounded-lg border bg-popover shadow-lg px-3 py-2 text-sm max-w-sm","animate-message",s.variant==="error"&&"border-destructive/40",s.variant==="warn"&&"border-amber-500/40",s.variant==="success"&&"border-green-500/40"),children:[e.jsx(Nn,{variant:s.variant}),e.jsx("div",{className:"flex-1 min-w-0 whitespace-pre-wrap break-words leading-snug",children:s.message}),e.jsx("button",{type:"button",onClick:()=>t(s.id),className:"text-muted-foreground hover:text-foreground",title:"Dismiss",children:e.jsx(be,{className:"h-3.5 w-3.5"})})]})}function Sn(){const s=ye(t=>t.toasts);return s.length===0?null:e.jsx("div",{className:"fixed bottom-4 right-4 z-[60] flex flex-col gap-2 pointer-events-auto",children:s.map(t=>e.jsx(kn,{entry:t},t.id))})}let Ie=null;function Cn(){if(typeof window>"u")return null;if(Ie)return Ie;const s=window.AudioContext||window.webkitAudioContext;if(!s)return null;try{Ie=new s}catch{return null}return Ie}function Te(s,t,n){const r=Cn();if(!r)return;const a=r.currentTime+t,o=r.createOscillator(),l=r.createGain();o.type="sine",o.frequency.value=s,l.gain.setValueAtTime(0,a),l.gain.linearRampToValueAtTime(.18,a+.01),l.gain.exponentialRampToValueAtTime(1e-4,a+n),o.connect(l).connect(r.destination),o.start(a),o.stop(a+n+.02)}function gt(){Te(659.25,0,.18),Te(880,.12,.24)}function $n(){Te(523.25,0,.15),Te(659.25,.1,.15),Te(783.99,.2,.25)}let xe="default";typeof window<"u"&&"Notification"in window?xe=Notification.permission:xe="unsupported";async function Xt(){if(xe==="unsupported"||xe==="granted"||xe==="denied")return xe;try{const s=await Notification.requestPermission();return xe=s,s}catch{return"denied"}}function Ze(s,t,n){if(!(typeof document>"u"||!document.hidden)&&xe==="granted")try{const r=new Notification(s,{body:t,icon:"/favicon.ico",tag:n??"wrongstack-run",requireInteraction:n==="wrongstack-confirm"});r.onclick=()=>{window.focus(),r.close()}}catch{}}function Tn(s){var o;const t=s.payload,n=(o=z.getState().session)==null?void 0:o.id,r=!n||n!==t.sessionId;z.getState().startSession({id:t.sessionId,startedAt:Date.now(),model:t.model,provider:t.provider}),z.getState().setEnv({maxContext:t.maxContext,projectName:t.projectName,mode:t.mode,contextMode:t.contextMode,inputCost:t.inputCost,outputCost:t.outputCost,cacheReadCost:t.cacheReadCost}),B.getState().setConfig({provider:t.provider,model:t.model}),(r||t.reset)&&(M.getState().clearMessages(),ft.getState().clear());const a=t.replayMessages;if(a&&a.length>0){const l=M.getState();for(const c of a)if(c.role==="user"||c.role==="assistant"||c.role==="system"){let i="";if(typeof c.content=="string")i=c.content;else if(Array.isArray(c.content)){for(const u of c.content)if(u.type==="text"&&typeof u.text=="string")i+=(i?`
10
+ `:"")+u.text;else if(u.type==="tool_use")i&&(l.addMessage({role:c.role,content:i}),i=""),l.addMessage({role:"tool",content:"",toolName:String(u.name??"tool"),toolInput:u.input,toolUseId:String(u.id??"")});else if(u.type==="tool_result"){const m=M.getState().messages;let x;for(let p=m.length-1;p>=0;p--)if(m[p].toolUseId===String(u.tool_use_id??"")){x=m[p];break}x&&l.setToolResult(x.id,typeof u.content=="string"?u.content:JSON.stringify(u.content),!u.is_error)}}i&&l.addMessage({role:c.role,content:i})}}}function Mn(s){const t=s.payload,n=o=>o.toLocaleString(),r=[...t.tools.breakdown].sort((o,l)=>l.tokens-o.tokens).slice(0,8),a=[...t.messages.breakdown].sort((o,l)=>l.tokens-o.tokens).slice(0,8);M.getState().addMessage({role:"assistant",content:["📊 **Context breakdown** (heuristic — 4 chars/token)","",`**Total estimate:** ${n(t.total)} tokens`,`• System prompt: ${n(t.systemPrompt)}`,`• Tool schemas: ${n(t.tools.total)} (${t.tools.count} tools)`,`• Messages: ${n(t.messages.total)} (${t.messages.count} messages)`,"","**Top tool schemas:**",...r.map(o=>` · ${o.name}: ${n(o.tokens)}`),"","**Top messages:**",...a.map(o=>` · #${o.index} ${o.role}: ${n(o.tokens)} — ${o.preview||"(empty)"}`)].join(`
11
+ `)})}function En(s){const t=s.payload;t.success?Le.success(t.message):Le.error(t.message),ae(B.getState().wsUrl).listSavedProviders()}function Dn(s){const t=s.payload;let n=t.reductions.length?t.reductions.map(r=>`${r.phase}: ${r.saved}`).join(", "):"no-op";t.repaired&&(n+=`; repaired ${t.repaired.removedToolUses.length} tool_use, ${t.repaired.removedToolResults.length} tool_result, ${t.repaired.removedMessages} empty messages`),M.getState().addMessage({role:"assistant",content:`🗜️ Context compacted: ${t.before} → ${t.after} tokens (saved ~${t.saved}). ${n}`}),z.setState({lastInputTokens:t.after})}function Rn(s){const t=s.payload,n=t.usage,r=(n.input??0)+(n.cacheWrite??0)-(n.cacheRead??0);r>0&&z.setState({lastInputTokens:r}),z.getState().updateUsage(t.usage);const{inputCost:a,outputCost:o,cacheReadCost:l}=z.getState(),c=(t.usage.input*a+t.usage.output*o+(t.usage.cacheRead??0)*l)/1e6;c>0&&z.getState().addCost(c),t.stopReason!=="tool_use"&&t.stopReason!=="tool_call"&&M.getState().setLoading(!1);const i=M.getState().currentAssistantMessageId;i&&(M.getState().finalizeMessage(i),t.usage.output>0&&M.getState().updateMessage(i,{usage:t.usage})),M.getState().setCurrentAssistantMessage(null),M.getState().clearThinking()}function Ln(s){const t=s.payload,n=t.removedToolUses.length+t.removedToolResults.length+t.removedMessages,r=t.beforeMessages!==void 0&&t.afterMessages!==void 0?` Messages: ${t.beforeMessages} -> ${t.afterMessages}.`:"";M.getState().addMessage({role:"assistant",content:`Context repaired: removed ${n} orphan protocol item(s).${r} tool_use ${t.removedToolUses.length}, tool_result ${t.removedToolResults.length}.`})}function An(){B.getState().setWsConnected(!1)}function In(s){const t=s.payload;z.getState().setIteration({index:t.index,max:t.maxIterations??0}),M.getState().setLoading(!0),typeof document<"u"&&document.hidden&&Re("running"),M.getState().runStart===null&&M.getState().setRunStart({at:Date.now(),cost:z.getState().cost}),M.getState().setCurrentAssistantMessage(null)}function Pn(s){const t=s.payload;M.getState().clearThinking();let n=M.getState().currentAssistantMessageId;n||(n=M.getState().addMessage({role:"assistant",content:"",streaming:!0}),M.getState().setCurrentAssistantMessage(n)),M.getState().appendToMessage(n,t.text)}function On(s){const t=s.payload;t.text&&M.getState().appendThinking(t.text)}function Fn(s){const t=s.payload,n=M.getState().messages.find(a=>a.toolUseId===t.id);if(n){M.getState().setCurrentToolId(n.id);return}M.getState().clearThinking(),M.getState().setCurrentAssistantMessage(null);const r=M.getState().addMessage({role:"tool",content:"",toolName:t.name,toolInput:t.input,toolUseId:t.id});M.getState().setCurrentToolId(r),M.getState().addExecution({id:t.id,name:t.name,input:t.input,ok:!0,startedAt:Date.now()})}function _n(s){var l,c;const t=s.payload,n=(((l=t.event)==null?void 0:l.text)??"").trim();if(!n)return;const a=M.getState().messages.find(i=>i.toolUseId===t.id);if(!a)return;const o=((c=t.event)==null?void 0:c.type)==="warning"?"⚠ ":"";M.getState().appendToolProgress(a.id,o+n)}function Wn(s){const t=s.payload,{messages:n,currentToolId:r}=M.getState(),a=t.id?n.find(o=>o.toolUseId===t.id):r?n.find(o=>o.id===r):void 0;(a==null?void 0:a.toolResult)===void 0&&(a&&(M.getState().setToolResult(a.id,t.output??"",t.ok),M.getState().updateMessage(a.id,{toolDurationMs:t.durationMs})),t.id&&M.getState().updateExecution(t.id,{completedAt:Date.now(),durationMs:t.durationMs,output:t.output,ok:t.ok}),r&&a&&a.id===r&&M.getState().setCurrentToolId(null))}function Un(s){const t=s.payload;P.getState().showConfirm({id:t.id,toolName:t.toolName,input:t.input,suggestedPattern:t.suggestedPattern});try{$n()}catch{}Xt(),Ze("WrongStack needs approval",`Tool "${t.toolName}" is waiting for your decision.`,"wrongstack-confirm"),typeof document<"u"&&document.hidden&&Re("attention")}function Kn(s){const t=s.payload;z.getState().setIteration(null),M.getState().setLoading(!1),M.getState().setCurrentAssistantMessage(null),M.getState().clearThinking();const n=M.getState().runStart;if(n&&t.status==="done"){const a=M.getState().messages;let o=-1,l=0;for(let c=a.length-1;c>=0;c--){const i=a[c];if(i.role==="assistant"&&o===-1&&i.content&&(o=c),i.role==="tool"&&i.timestamp>=n.at&&(l+=1),i.role==="user"&&i.timestamp<=n.at)break}if(o!==-1){const c=z.getState().cost;M.getState().updateMessage(a[o].id,{runSummary:{iterations:t.iterations,tools:l,durationMs:Date.now()-n.at,costDelta:Math.max(0,c-n.cost)}})}}if(M.getState().setRunStart(null),t.status!=="done"&&t.error)M.getState().addMessage({role:"assistant",content:`Error: ${t.error.message}`,isError:!0}),Le.error(`Run ended: ${t.error.message}`),Ze("WrongStack run failed",t.error.message),typeof document<"u"&&document.hidden&&Re("error");else if(t.status==="done"&&(typeof document<"u"&&document.hidden&&(Le.success(`Run completed in ${t.iterations} iteration${t.iterations===1?"":"s"}`),Ze("WrongStack run finished",`Completed in ${t.iterations} iteration${t.iterations===1?"":"s"}.`),Re("ready")),Xt(),B.getState().soundOnComplete))try{gt()}catch{}const r=M.getState().dequeue();if(r){const a=ae(B.getState().wsUrl);M.getState().addMessage({role:"user",content:r}),M.getState().setLoading(!0),a.sendMessage(r)}}function zn(s){const t=s.payload;M.getState().addMessage({role:"assistant",content:[`🛠️ **Registered tools** (${t.tools.length})`,"",...t.tools.map(n=>`• \`${n.name}\`${n.params.length?` (${n.params.join(", ")})`:""} — ${n.description||"_no description_"}`)].join(`
12
+ `)})}function qn(s){var r;const t=s.payload,n=(r=t.text)==null?void 0:r.trim();M.getState().addMessage({role:"assistant",content:t.error?`Memory read failed: ${t.error}`:n?`🧠 **Memory**
13
+
14
+ ${n}`:`🧠 **Memory**
15
+
16
+ _empty — nothing remembered yet_`})}function Hn(s){const t=s.payload;if(!t.enabled){M.getState().addMessage({role:"assistant",content:`🎯 **Skills**
17
+
18
+ _disabled (config.features.skills = false)_`});return}const n=[`🎯 **Skills** (${t.skills.length})`,"",...t.skills.length===0?["_none registered_"]:t.skills.map(r=>`• \`${r.name}\`${r.version?` v${r.version}`:""} _(${r.source})_ — ${r.description||r.trigger||"_no description_"}`)];t.error&&n.push("",`⚠ ${t.error}`),M.getState().addMessage({role:"assistant",content:n.join(`
19
+ `)})}function Bn(s){const t=s.payload;M.getState().addMessage({role:"assistant",content:["🩺 **Runtime diagnostics**","",`**Provider:** \`${t.provider}\` / \`${t.model}\``,`**Mode:** \`${t.mode}\``,`**Session:** \`${t.sessionId}\``,`**CWD:** \`${t.cwd}\``,"",`**Tools:** ${t.tools.count}`,`**Messages:** ${t.messages} · **Todos:** ${t.todos}`,`**Usage:** ${t.usage.input.toLocaleString()} in · ${t.usage.output.toLocaleString()} out${t.usage.cacheRead?` · ${t.usage.cacheRead.toLocaleString()} cache`:""}`,"",`**Features:** memory=${t.features.memory?"✓":"✗"} · skills=${t.features.skills?"✓":"✗"} · modelsRegistry=${t.features.modelsRegistry?"✓":"✗"}`].join(`
20
+ `)})}function Vn(s){const t=s.payload,n=Math.floor(t.elapsedMs/1e3),r=n<60?`${n}s`:n<3600?`${Math.floor(n/60)}m ${n%60}s`:`${Math.floor(n/3600)}h ${Math.floor(n%3600/60)}m`;M.getState().addMessage({role:"assistant",content:["📈 **Session stats**","",`**Session:** \`${t.sessionId}\``,`**Provider/Model:** \`${t.provider}\` / \`${t.model}\``,`**Elapsed:** ${r}`,"",`**Usage:** ${t.usage.input.toLocaleString()} in · ${t.usage.output.toLocaleString()} out`,...t.cache&&t.cache.readTokens>0?[`**Cache:** ${t.cache.readTokens.toLocaleString()} read · ${t.cache.writeTokens.toLocaleString()} write · hit ratio ${(t.cache.hitRatio*100).toFixed(1)}%`]:[],`**Cost:** $${t.cost.toFixed(4)}`,"",`**Messages:** ${t.messages} · **Files read:** ${t.readFiles} · **Tools available:** ${t.tools}`].join(`
21
+ `)})}function Jn(s){const t=s.payload;z.getState().setTodos(t.todos??[])}function Qn(s){const t=s.payload;z.getState().setModes(t.modes.map(n=>({id:n.id,name:n.name,description:n.description}))),z.getState().setEnv({mode:t.activeId})}function Gn(s){const t=s.payload;z.getState().setContextModes(t.modes.map(n=>({id:n.id,name:n.name,description:n.description,thresholds:n.thresholds,preserveK:n.preserveK,eliseThreshold:n.eliseThreshold}))),z.getState().setEnv({contextMode:t.activeId})}function Yn(s){const t=s.payload;z.getState().setEnv({contextMode:t.id})}function Xn(s){const t=s.payload;ke.getState().setEntries(t.sessions??[],t.error??null)}function Zn(s){const t=s.payload;M.getState().addMessage({role:"assistant",content:`[${t.phase}] ${t.message}`,isError:!0}),M.getState().setLoading(!1)}function eo(s){const t=s.payload;Yt.getState().setSnapshot(t.worktrees??[],t.baseBranch??"")}function to(s){const t=s.payload;Yt.getState().pushEvent(t)}function so(s){ft.getState().applyEvent(s.payload)}const no={"session.start":Tn,"context.debug":Mn,"key.operation_result":En,"context.compacted":Dn,"provider.response":Rn,"context.repaired":Ln,"session.end":An,"iteration.started":In,"provider.text_delta":Pn,"provider.thinking_delta":On,"tool.started":Fn,"tool.progress":_n,"tool.executed":Wn,"tool.confirm_needed":Un,"run.result":Kn,"tools.list":zn,"memory.list":qn,"skills.list":Hn,"diag.get":Bn,"stats.get":Vn,"todos.updated":Jn,"modes.list":Qn,"context.modes.list":Gn,"context.mode.changed":Yn,"sessions.list":Xn,error:Zn,"worktree.state":eo,"worktree.event":to,"subagent.event":so};function oo(s){const t=[];for(const[n,r]of Object.entries(no))t.push(s.on(n,r));return()=>{for(const n of t)n()}}function ro(){const{autoConnect:s,wsUrl:t}=B(),n=B(a=>a.setWsStatus),r=d.useRef(!1);d.useEffect(()=>{if(!s)return;xn();const a=ae(t),o=a.onStatus(c=>n(c));if(a.connect().catch(c=>{console.error("[WS] Connection failed:",c)}),r.current)return()=>{o()};r.current=!0;const l=oo(a);return()=>{l(),o()}},[s,t,n])}function de(){const{wsUrl:s}=B(),t=ae(s),n=d.useCallback(L=>t.isConnected?t.sendMessage(L):null,[t]),r=d.useCallback(()=>t.sendAbort(),[t]),{hideConfirm:a}=P(),o=d.useCallback((L,T)=>{t.sendConfirm(L,T),a()},[t,a]),l=d.useCallback((L,T)=>t.switchModel(L,T),[t]),c=d.useCallback(()=>t.listProviders(),[t]),i=d.useCallback(L=>t.listProviderModels(L),[t]),u=d.useCallback(()=>t.listSavedProviders(),[t]),m=d.useCallback((L,T,f)=>t.addKey(L,T,f),[t]),x=d.useCallback((L,T,f)=>t.updateKey(L,T,f),[t]),p=d.useCallback((L,T)=>t.deleteKey(L,T),[t]),b=d.useCallback((L,T)=>t.setActiveKey(L,T),[t]),y=d.useCallback((L,T,f,S)=>t.addProvider(L,T,f,S),[t]),w=d.useCallback(L=>t.removeProvider(L),[t]),N=d.useCallback(L=>{ke.getState().setLoading(!0),t.listSessions(L)},[t]),v=d.useCallback(L=>{ke.getState().removeEntry(L),t.deleteSession(L)},[t]),h=d.useCallback(L=>t.resumeSessionById(L),[t]),j=d.useCallback(()=>t.saveSession(),[t]),C=d.useCallback(()=>t.listTools(),[t]),D=d.useCallback(()=>t.listMemory(),[t]),R=d.useCallback(()=>t.listSkills(),[t]),I=d.useCallback(()=>t.getDiag(),[t]),F=d.useCallback(()=>t.getStats(),[t]),K=d.useCallback(()=>t.listModes(),[t]),X=d.useCallback(L=>t.switchMode(L),[t]),G=d.useCallback(()=>t.listContextModes(),[t]),V=d.useCallback(L=>t.switchContextMode(L),[t]),q=d.useCallback(()=>t.repairContext(),[t]),ee=d.useCallback(L=>{t.send({type:"autophase.toggleAutonomous",payload:{autonomous:L}})},[t]),Y=d.useCallback((L,T,f=!0)=>{t.send({type:"autophase.start",payload:{title:L,phases:T,autonomous:f}})},[t]),$=d.useCallback(()=>{t.send({type:"autophase.pause",payload:{}})},[t]),W=d.useCallback(()=>{t.send({type:"autophase.resume",payload:{}})},[t]),A=d.useCallback(()=>{t.send({type:"autophase.stop",payload:{}})},[t]),O=d.useCallback(L=>{t.send({type:"autophase.selectPhase",payload:{phaseId:L}})},[t]);return{client:t,sendMessage:n,sendAbort:r,sendConfirm:o,switchModel:l,listProviders:c,listProviderModels:i,listSavedProviders:u,addKey:m,updateKey:x,deleteKey:p,setActiveKey:b,addProvider:y,removeProvider:w,listSessions:N,deleteSession:v,resumeSession:h,saveSession:j,listTools:C,listMemory:D,listSkills:R,getDiag:I,getStats:F,listModes:K,switchMode:X,listContextModes:G,switchContextMode:V,repairContext:q,toggleAutoPhaseAutonomous:ee,startAutoPhase:Y,pauseAutoPhase:$,resumeAutoPhase:W,stopAutoPhase:A,selectAutoPhase:O}}function bt(){const s=M.getState().messages,t=[],n=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-");t.push("# WrongStack chat export"),t.push(`*Exported: ${new Date().toISOString()}*`),t.push("");for(const l of s)if(l.role==="user")t.push("## 👤 User"),t.push(""),t.push(l.content),t.push("");else if(l.role==="assistant")t.push("## 🤖 Assistant"),t.push(""),t.push(l.content),t.push("");else if(l.role==="tool"){const c=l.isError?"❌":l.toolResult!==void 0?"✅":"⏳";t.push(`### 🔧 Tool: \`${l.toolName??"unknown"}\` ${c}`),l.toolInput!==void 0&&(t.push("```json"),t.push(JSON.stringify(l.toolInput,null,2)),t.push("```")),l.toolResult&&(t.push("<details><summary>Output</summary>"),t.push(""),t.push("```"),t.push(l.toolResult),t.push("```"),t.push("</details>")),t.push("")}const r=new Blob([t.join(`
22
+ `)],{type:"text/markdown"}),a=URL.createObjectURL(r),o=document.createElement("a");o.href=a,o.download=`wrongstack-chat-${n}.md`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(a)}function ao(){var u,m,x;const s=M.getState().messages,t=z.getState(),n=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),r=p=>p.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),a=s.map(p=>{if(p.role==="tool"){const N=p.isError?"❌":p.toolResult!==void 0?"✅":"⏳";return`
23
+ <section class="bubble tool ${p.isError?"error":""}">
24
+ <header><span class="icon">🔧</span><code>${r(p.toolName??"tool")}</code> ${N}</header>
25
+ ${p.toolInput!==void 0?`<details><summary>Input</summary><pre>${r(JSON.stringify(p.toolInput,null,2))}</pre></details>`:""}
26
+ ${p.toolResult?`<details><summary>Output</summary><pre>${r(p.toolResult)}</pre></details>`:""}
27
+ </section>`}const b=p.role==="user"?"user":"assistant",y=p.role==="user"?"👤":"🤖",w=p.role==="user"?"User":"Assistant";return`
28
+ <section class="bubble ${b}">
29
+ <header><span class="icon">${y}</span><strong>${w}</strong></header>
30
+ <pre class="content">${r(p.content)}</pre>
31
+ </section>`}),o=`<!doctype html>
32
+ <html lang="en"><head>
33
+ <meta charset="utf-8">
34
+ <title>WrongStack chat — ${escape(((u=t.session)==null?void 0:u.title)||t.projectName||"export")}</title>
35
+ <style>
36
+ :root { color-scheme: light dark; }
37
+ body { font: 14px/1.55 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; max-width: 920px; margin: 24px auto; padding: 0 16px; }
38
+ h1 { font-size: 20px; margin-bottom: 4px; }
39
+ .meta { color: #666; font-size: 12px; margin-bottom: 24px; }
40
+ .bubble { margin: 12px 0; padding: 10px 14px; border-radius: 10px; border: 1px solid #ddd; }
41
+ .bubble header { font-size: 11px; text-transform: uppercase; letter-spacing: .05em; color: #666; margin-bottom: 6px; }
42
+ .bubble header .icon { margin-right: 4px; }
43
+ .bubble.user { background: #eef4ff; border-color: #c8d8f5; }
44
+ .bubble.assistant { background: #fff; }
45
+ .bubble.tool { background: #fafafa; }
46
+ .bubble.tool.error { background: #fff5f5; border-color: #f5c8c8; }
47
+ pre.content, .bubble pre { white-space: pre-wrap; word-break: break-word; font: 12px/1.5 ui-monospace, Menlo, Consolas, monospace; margin: 0; }
48
+ details summary { cursor: pointer; color: #555; font-size: 12px; }
49
+ details pre { margin-top: 6px; background: #f4f4f4; padding: 8px; border-radius: 6px; max-height: 360px; overflow: auto; }
50
+ @media (prefers-color-scheme: dark) {
51
+ body { background: #0d0d0f; color: #e6e6e6; }
52
+ .bubble { border-color: #2a2a2e; }
53
+ .bubble.user { background: #16213a; border-color: #2a3d6b; }
54
+ .bubble.assistant { background: #161618; }
55
+ .bubble.tool { background: #131315; }
56
+ .bubble.tool.error { background: #2a1717; border-color: #5c2a2a; }
57
+ details pre { background: #1a1a1c; }
58
+ .meta, .bubble header, details summary { color: #999; }
59
+ }
60
+ </style>
61
+ </head><body>
62
+ <h1>WrongStack chat — ${escape(((m=t.session)==null?void 0:m.title)||t.projectName||"export")}</h1>
63
+ <div class="meta">
64
+ Exported ${new Date().toISOString()}${(x=t.session)!=null&&x.provider?` · ${escape(t.session.provider)}/${escape(t.session.model)}`:""} · ${s.length} message${s.length===1?"":"s"}
65
+ </div>
66
+ ${a.join("")}
67
+ </body></html>`,l=new Blob([o],{type:"text/html;charset=utf-8"}),c=URL.createObjectURL(l),i=document.createElement("a");i.href=c,i.download=`wrongstack-chat-${n}.html`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(c)}function io(){const s=P(N=>N.paletteOpen),t=P(N=>N.setPaletteOpen),n=P(N=>N.setCurrentView),r=B(N=>N.setTheme),{entries:a}=ke(),{addMessage:o,clearMessages:l}=M(),c=de(),[i,u]=d.useState(""),[m,x]=d.useState(0),p=d.useRef(null);d.useEffect(()=>{s&&(u(""),x(0),requestAnimationFrame(()=>{var N;return(N=p.current)==null?void 0:N.focus()}))},[s]),d.useEffect(()=>{const N=v=>{if((v.ctrlKey||v.metaKey)&&v.key.toLowerCase()==="k"){v.preventDefault(),t(!P.getState().paletteOpen);return}v.key==="Escape"&&P.getState().paletteOpen&&(v.preventDefault(),t(!1))};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[t]);const b=d.useMemo(()=>{const N=[{id:"help",category:"Command",label:"Show slash commands",icon:hs,keywords:["help","commands","?"],run:()=>{o({role:"assistant",content:"Type `/` in the message box to see every slash command."})}},{id:"tools",category:"Command",label:"List tools",icon:Me,keywords:["tools","list"],run:()=>c.listTools()},{id:"memory",category:"Command",label:"Show memory",icon:Dt,keywords:["memory","remember","notes"],run:()=>c.listMemory()},{id:"skills",category:"Command",label:"List skills",icon:Rt,keywords:["skills"],run:()=>c.listSkills()},{id:"diag",category:"Command",label:"Runtime diagnostics",icon:fs,keywords:["diag","diagnostics","debug"],run:()=>c.getDiag()},{id:"stats",category:"Command",label:"Session stats (tokens, cache, cost)",icon:gs,keywords:["stats","tokens","cost","cache"],run:()=>c.getStats()},{id:"clear",category:"Session",label:"Clear context",hint:"Wipe in-memory context, keep session id",icon:Ee,keywords:["clear","reset","wipe"],run:()=>{var v,h;l(),(h=(v=c.client)==null?void 0:v.clearContext)==null||h.call(v)}},{id:"new",category:"Session",label:"New session",hint:"Brand-new on disk + memory",icon:Ae,keywords:["new","fresh","session"],run:()=>{var v,h;return(h=(v=c.client)==null?void 0:v.newSession)==null?void 0:h.call(v)}},{id:"compact",category:"Session",label:"Compact context",icon:rt,keywords:["compact","shrink","context"],run:()=>{var v,h;return(h=(v=c.client)==null?void 0:v.compactContext)==null?void 0:h.call(v)}},{id:"repair-context",category:"Session",label:"Repair context",hint:"Remove orphan tool protocol blocks",icon:Me,keywords:["repair","context","tool_use","tool_result"],run:()=>{var v,h;return(h=(v=c.client)==null?void 0:v.repairContext)==null?void 0:h.call(v)}},{id:"export",category:"Session",label:"Export chat as markdown",icon:Ye,keywords:["export","save","markdown","download"],run:()=>bt()},{id:"export-html",category:"Session",label:"Export chat as HTML",hint:"Self-contained, opens in any browser",icon:Ye,keywords:["export","html","download","archive"],run:()=>ao()},{id:"history",category:"Command",label:"Open history",icon:at,keywords:["history","sessions"],run:()=>n("history")},{id:"settings",category:"Command",label:"Open settings",icon:it,keywords:["settings","config"],run:()=>n("settings")},{id:"model",category:"Command",label:"Change provider/model",icon:Se,keywords:["model","provider","change"],run:()=>n("settings")},{id:"theme-light",category:"Theme",label:"Theme: Light",icon:lt,keywords:["theme","light","mode"],run:()=>r("light")},{id:"theme-dark",category:"Theme",label:"Theme: Dark",icon:ct,keywords:["theme","dark","mode"],run:()=>r("dark")},{id:"theme-system",category:"Theme",label:"Theme: Follow system",icon:dt,keywords:["theme","system","auto"],run:()=>r("system")},{id:"compact-toggle",category:"Command",label:"Toggle compact density",icon:bs,hint:"Ctrl+Shift+D",keywords:["compact","dense","density","size"],run:()=>P.getState().toggleCompactMode()},{id:"sound-toggle",category:"Command",label:B.getState().soundOnComplete?"Sound on completion: ON — turn off":"Sound on completion: OFF — turn on",icon:B.getState().soundOnComplete?ys:vs,hint:"Chime when a run finishes",keywords:["sound","audio","chime","notify","beep"],run:()=>{const v=!B.getState().soundOnComplete;B.getState().setSoundOnComplete(v),v&&gt()}}];for(const v of a.slice(0,10))v.isCurrent||N.push({id:`resume-${v.id}`,category:"Session",label:`Resume: ${v.title||"(empty)"}`,hint:`${v.provider}/${v.model}`,icon:Lt,keywords:["resume",v.title,v.id,v.provider,v.model],run:()=>c.resumeSession(v.id)});return N},[a,c,n,r,o,l]),y=d.useMemo(()=>{const N=i.toLowerCase().trim();return N?b.filter(v=>[v.label,v.hint??"",v.category,...v.keywords??[]].join(" ").toLowerCase().includes(N)):b},[b,i]);if(d.useEffect(()=>{m>=y.length&&x(0)},[y.length,m]),!s)return null;const w=N=>{N&&(t(!1),N.run())};return e.jsx("div",{className:"fixed inset-0 z-50 bg-background/60 backdrop-blur-sm flex items-start justify-center pt-[14vh] px-4",onClick:()=>t(!1),onKeyDown:N=>{N.key==="Escape"&&t(!1)},children:e.jsxs("div",{onClick:N=>N.stopPropagation(),onKeyDown:N=>N.stopPropagation(),className:"w-full max-w-2xl rounded-xl border bg-popover shadow-2xl overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 border-b",children:[e.jsx(je,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("input",{ref:p,value:i,onChange:N=>u(N.target.value),placeholder:"Search commands, sessions, settings…",className:"flex-1 bg-transparent outline-none text-sm placeholder:text-muted-foreground",onKeyDown:N=>{N.key==="ArrowDown"?(N.preventDefault(),x(v=>(v+1)%Math.max(1,y.length))):N.key==="ArrowUp"?(N.preventDefault(),x(v=>(v-1+Math.max(1,y.length))%Math.max(1,y.length))):N.key==="Enter"&&(N.preventDefault(),w(y[m]))}}),e.jsx("kbd",{className:"text-[10px] text-muted-foreground border rounded px-1.5 py-0.5",children:"Esc"})]}),e.jsx("div",{className:"max-h-[60vh] overflow-y-auto",children:y.length===0?e.jsxs("div",{className:"px-4 py-8 text-center text-sm text-muted-foreground",children:['No matches for "',i,'"']}):lo(y,m,w,x)}),e.jsxs("div",{className:"border-t px-4 py-2 text-[10px] uppercase tracking-wider text-muted-foreground flex items-center gap-3",children:[e.jsx("span",{children:"↑↓ navigate"}),e.jsx("span",{children:"↵ select"}),e.jsx("span",{children:"Esc dismiss"})]})]})})}function lo(s,t,n,r){const a={};return s.forEach((o,l)=>{a[o.category]||(a[o.category]=[]),a[o.category].push({item:o,globalIdx:l})}),e.jsx("div",{className:"p-1",children:Object.entries(a).map(([o,l])=>e.jsxs("div",{children:[e.jsx("div",{className:"px-3 pt-2 pb-1 text-[10px] uppercase tracking-wider text-muted-foreground",children:o}),l.map(({item:c,globalIdx:i})=>{const u=c.icon,m=i===t;return e.jsxs("button",{type:"button",onMouseEnter:()=>r(i),onClick:()=>n(c),className:k("w-full flex items-center gap-3 px-3 py-2 rounded text-left text-sm transition-colors",m?"bg-accent text-accent-foreground":"hover:bg-accent/40"),children:[e.jsx(u,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"truncate",children:c.label}),c.hint&&e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:c.hint})]}),m&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"↵"})]},c.id)})]},o))})}function co({query:s,onPick:t,onClose:n}){const r=de(),a=B(x=>x.wsUrl),[o,l]=d.useState([]),[c,i]=d.useState(0),u=d.useRef(null),m=d.useRef(null);return d.useEffect(()=>{const p=ae(a).on("files.list",b=>{var w;const y=b.payload;l(y.files??[]),i(0),(w=m.current)==null||w.resolve(y.files??[]),m.current=null});return()=>p()},[a]),d.useEffect(()=>(u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{r.client.listFiles(s,50)},80),()=>{u.current&&clearTimeout(u.current)}),[s,r.client]),d.useEffect(()=>{const x=p=>{if(p.key==="ArrowDown")p.preventDefault(),i(b=>(b+1)%Math.max(1,o.length));else if(p.key==="ArrowUp")p.preventDefault(),i(b=>(b-1+Math.max(1,o.length))%Math.max(1,o.length));else if(p.key==="Enter"||p.key==="Tab"){if(o.length===0)return;p.preventDefault(),t(o[c])}else p.key==="Escape"&&(p.preventDefault(),n())};return window.addEventListener("keydown",x,!0),()=>window.removeEventListener("keydown",x,!0)},[o,c,t,n]),e.jsxs("div",{className:"absolute bottom-full left-0 right-0 mb-2 rounded-lg border bg-popover shadow-md p-1 text-sm max-h-72 overflow-auto",children:[e.jsxs("div",{className:"px-3 py-1 text-[10px] uppercase tracking-wider text-muted-foreground border-b mb-1 flex items-center justify-between",children:[e.jsxs("span",{children:["@ Files ",s&&`· "${s}"`]}),e.jsx("span",{children:"↑/↓ select · ↵ insert · Esc dismiss"})]}),o.length===0?e.jsx("div",{className:"px-3 py-2 text-xs text-muted-foreground italic",children:s?`No files match "${s}"`:"Searching project…"}):o.map((x,p)=>e.jsxs("button",{type:"button",onClick:()=>t(x),onMouseEnter:()=>i(p),className:k("w-full text-left px-3 py-1.5 rounded transition-colors flex items-center gap-2 font-mono text-xs",p===c?"bg-accent text-accent-foreground":"hover:bg-accent/40"),children:[x.includes("/")?e.jsx(ws,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}):e.jsx(js,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),e.jsx("span",{className:"truncate",children:x})]},x))]})}const uo=ks("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",{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"}}),J=d.forwardRef(({className:s,variant:t,size:n,asChild:r=!1,...a},o)=>{const l=r?Ns:"button";return e.jsx(l,{className:k(uo({variant:t,size:n,className:s})),ref:o,...a})});J.displayName="Button";const et=[{name:"/help",category:"App",description:"Show every slash command and what it does"},{name:"/export",category:"Session",description:"Download the current chat as markdown"},{name:"/todos",category:"Inspect",description:"List current todos (try `/todos clear` to reset)"},{name:"/clear",category:"Session",description:"Wipe current context (keeps session id, disk record stays)"},{name:"/new",category:"Session",description:"Start a brand-new session (fresh on disk and in memory)"},{name:"/compact",category:"Session",description:"Shrink context — elide ancient tool output"},{name:"/repair",category:"Session",description:"Repair orphan tool_use/tool_result blocks in context"},{name:"/debug",category:"Inspect",aliases:["/context"],description:"Per-section context size breakdown"},{name:"/tools",category:"Inspect",description:"List every registered tool the model can call"},{name:"/memory",category:"Inspect",description:"Show all remembered notes (project + user scope)"},{name:"/skill",category:"Inspect",aliases:["/skills"],description:"List active skills"},{name:"/diag",category:"Inspect",description:"Runtime diagnostics (provider, tools, features, mode, usage)"},{name:"/stats",category:"Inspect",description:"Session stats: tokens, cache hit ratio, cost, elapsed"},{name:"/save",category:"Session",description:"Force-flush the session (auto-saved already)"},{name:"/abort",category:"Run",aliases:["/stop"],description:"Abort the current run"},{name:"/settings",category:"App",aliases:["/model"],description:"Open settings (provider/model/keys)"}],mo=["Run","Session","Inspect","App"];function po(s){const t=s.toLowerCase();return t==="/"||t===""?et:et.filter(n=>{var r;return n.name.startsWith(t)||(((r=n.aliases)==null?void 0:r.some(a=>a.startsWith(t)))??!1)})}function $t(s,t){let n=t-1;for(;n>=0;){const r=s[n];if(r==="@"){const a=n>0?s[n-1]:"";return n===0||/\s/.test(a??"")?{start:n,query:s.slice(n+1,t)}:null}if(/\s/.test(r))return null;n--}return null}function xo(){const{isLoading:s,setLoading:t,addMessage:n,clearMessages:r}=M(),a=M(f=>f.queue),o=M(f=>f.enqueue),l=M(f=>f.removeQueued),c=M(f=>f.clearQueue),{setCurrentView:i}=P(),u=P(f=>f.pushPrompt),m=P(f=>f.promptHistory),x=de(),{sendMessage:p,sendAbort:b,client:y}=x,w=z(f=>f.lastInputTokens),N=z(f=>f.maxContext),[v,h]=d.useState(""),[j,C]=d.useState(0),[D,R]=d.useState(-1),[I,F]=d.useState(null),[K,X]=d.useState(null),[G,V]=d.useState(!1),q=d.useRef(null),ee=d.useCallback(f=>{var ie,ce,te,U,H,Z;const S=f.trim(),g=S.indexOf(" "),E=(g===-1?S:S.slice(0,g)).toLowerCase(),Q=g===-1?"":S.slice(g+1).trim(),_=E;switch(_){case"/help":{const se=["📖 **Slash commands**","",...et.map(le=>{var oe;return`• \`${le.name}\`${(oe=le.aliases)!=null&&oe.length?` (${le.aliases.map(re=>`\`${re}\``).join(", ")})`:""} — ${le.description}`})];return n({role:"assistant",content:se.join(`
68
+ `)}),!0}case"/clear":return r(),(ie=y==null?void 0:y.clearContext)==null||ie.call(y),!0;case"/new":return(ce=y==null?void 0:y.newSession)==null||ce.call(y),!0;case"/compact":case"/compact!":return(te=y==null?void 0:y.compactContext)==null||te.call(y,_==="/compact!"),!0;case"/repair":return(U=y==null?void 0:y.repairContext)==null||U.call(y),!0;case"/debug":case"/context":return(H=y==null?void 0:y.debugContext)==null||H.call(y),!0;case"/tools":return x.listTools(),!0;case"/memory":return x.listMemory(),!0;case"/skill":case"/skills":return x.listSkills(),!0;case"/diag":return x.getDiag(),!0;case"/stats":return x.getStats(),!0;case"/save":return x.saveSession(),!0;case"/todos":{if(Q.toLowerCase()==="clear")return(Z=y==null?void 0:y.clearTodos)==null||Z.call(y),!0;const le=z.getState().todos;if(le.length===0)return n({role:"assistant",content:"✅ **Todos** — _empty. Ask the agent to plan something and they'll show up here._"}),!0;const oe=[`✅ **Todos** (${le.filter(re=>re.status==="completed").length}/${le.length} done)`,""];for(const re of le){const ue=re.status==="completed"?"[x]":re.status==="in_progress"?"[~]":"[ ]",ze=re.status==="in_progress"&&re.activeForm?re.activeForm:re.content;oe.push(`- ${ue} ${ze}`)}return oe.push("","_Use `/todos clear` to wipe the list._"),n({role:"assistant",content:oe.join(`
69
+ `)}),!0}case"/export":return bt(),n({role:"assistant",content:"📥 Chat exported to your downloads folder."}),!0;case"/abort":case"/stop":return b(),t(!1),!0;case"/settings":case"/model":return i("settings"),!0;default:return!1}},[n,r,y,b,t,i,x]),Y=v.startsWith("/")&&!v.includes(" ")?po(v):[];d.useEffect(()=>{j>=Y.length&&C(0)},[Y.length,j]);const $=d.useCallback(()=>{const f=q.current;f&&(f.value="",f.style.height="auto",f.style.height=`${Math.min(f.scrollHeight,200)}px`,s||f.focus())},[s]),W=d.useCallback(async f=>{if(f.preventDefault(),!v.trim())return;const S=v.trim();if(S.startsWith("/")&&ee(S)){u(S),h(""),R(-1),$();return}if(h(""),R(-1),$(),u(S),$(),s){o(S);return}try{y!=null&&y.isConnected?(n({role:"user",content:S}),t(!0),p(S)):console.error("WebSocket not connected")}catch(g){console.error("Failed to send:",g),t(!1)}},[v,s,o,y,p,t,n,ee,u,$]),A=d.useCallback(()=>{b(),t(!1)},[b,t]),O=d.useCallback(()=>{b(),t(!1);const f=M.getState().messages;for(let S=f.length-1;S>=0;S--){const g=f[S];if(g.role==="user"&&g.content){h(g.content),requestAnimationFrame(()=>{const E=q.current;E&&(E.style.height="auto",E.style.height=`${Math.min(E.scrollHeight,200)}px`,E.focus(),E.setSelectionRange(g.content.length,g.content.length))});return}}},[b,t]),L=d.useCallback(f=>{if(Y.length===0&&!I&&m.length>0){if(f.key==="ArrowUp"){const S=f.currentTarget,g=S.value.slice(0,S.selectionStart);if(D>=0||g.indexOf(`
70
+ `)===-1){f.preventDefault();const E=Math.min(m.length-1,D+1);R(E);const Q=m[E]??"";h(Q),requestAnimationFrame(()=>{const _=q.current;_&&(_.style.height="auto",_.style.height=`${Math.min(_.scrollHeight,200)}px`,_.setSelectionRange(Q.length,Q.length))});return}}if(f.key==="ArrowDown"&&D>=0){f.preventDefault();const S=D-1;if(S<0)R(-1),h("");else{R(S);const g=m[S]??"";h(g),requestAnimationFrame(()=>{const E=q.current;E&&(E.style.height="auto",E.style.height=`${Math.min(E.scrollHeight,200)}px`,E.setSelectionRange(g.length,g.length))})}return}}if(Y.length>0){if(f.key==="ArrowDown"){f.preventDefault(),C(S=>(S+1)%Y.length);return}if(f.key==="ArrowUp"){f.preventDefault(),C(S=>(S-1+Y.length)%Y.length);return}if(f.key==="Tab"){f.preventDefault();const S=Y[j];S&&(h(S.name+" "),C(0));return}if(f.key==="Enter"&&!f.shiftKey){const S=Y[j];if(S&&S.name!==v.toLowerCase().trim()){f.preventDefault(),h(""),ee(S.name);return}}if(f.key==="Escape"){f.preventDefault(),h("");return}}f.key==="Enter"&&!f.shiftKey&&(f.preventDefault(),W(f))},[Y,j,I,m,D,v,ee,W]),T=()=>{const f=q.current;f&&(f.style.height="auto",f.style.height=`${Math.min(f.scrollHeight,200)}px`)};return e.jsxs("div",{className:"flex flex-col gap-2",children:[K&&e.jsxs("div",{className:"rounded-md border border-amber-500/30 bg-amber-500/5 text-amber-700 dark:text-amber-300 px-2.5 py-1.5 text-xs flex items-center justify-between gap-2 animate-message",children:[e.jsxs("span",{children:["Pasted"," ",e.jsx("span",{className:"font-mono tabular-nums",children:K.chars.toLocaleString()})," chars (",e.jsx("span",{className:"font-mono tabular-nums",children:K.lines})," lines) — fenced code blocks render best with ",e.jsx("span",{className:"font-mono",children:"```"}),"."]}),e.jsx("button",{type:"button",onClick:()=>X(null),className:"text-amber-600/70 hover:text-amber-600 dark:text-amber-300/70 dark:hover:text-amber-300 shrink-0",title:"Dismiss",children:"×"})]}),a.length>0&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-2 text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsxs("span",{className:"text-[10px] uppercase tracking-wider text-muted-foreground font-medium",children:["Queued (",a.length,")"]}),e.jsx("button",{type:"button",onClick:c,className:"text-muted-foreground hover:text-destructive text-xs",children:"Clear all"})]}),e.jsx("ul",{className:"space-y-1",children:a.map((f,S)=>e.jsxs("li",{className:"flex items-start justify-between gap-2 rounded bg-background/60 border px-2 py-1",children:[e.jsx("span",{className:"truncate flex-1 min-w-0",children:f}),e.jsx("button",{type:"button",onClick:()=>l(S),className:"text-muted-foreground hover:text-destructive shrink-0",title:"Remove from queue",children:"×"})]},S))})]}),e.jsxs("form",{onSubmit:W,onDragEnter:f=>{!f.dataTransfer||!Array.from(f.dataTransfer.types).includes("Files")||(f.preventDefault(),V(!0))},onDragOver:f=>{!f.dataTransfer||!Array.from(f.dataTransfer.types).includes("Files")||(f.preventDefault(),f.dataTransfer.dropEffect="copy")},onDragLeave:f=>{f.currentTarget.contains(f.relatedTarget)||V(!1)},onDrop:f=>{if(!f.dataTransfer)return;const S=Array.from(f.dataTransfer.files??[]);if(S.length===0){V(!1);return}f.preventDefault(),V(!1);const g=q.current,E=(g==null?void 0:g.selectionStart)??v.length,Q=v.slice(0,E),_=v.slice(E),ce=Q.length>0&&!/\s$/.test(Q)?" ":"",te=S.map(ue=>`@${ue.name}`),U=te.join(" "),Z=_.length===0||!/^\s/.test(_)?" ":"",se=`${ce}${U}${Z}`,le=Q+se+_;h(le);const oe=Q.length+ce.length+te.slice(0,-1).join(" ").length+(te.length>1?1:0),re=S[S.length-1].name;requestAnimationFrame(()=>{if(g){const ue=Q.length+se.length-Z.length;g.focus(),g.setSelectionRange(ue,ue),g.style.height="auto",g.style.height=`${Math.min(g.scrollHeight,200)}px`}F({start:oe,query:re})})},className:k("flex items-end gap-2 relative rounded-lg transition-colors",G&&"ring-2 ring-primary ring-offset-2 ring-offset-background bg-primary/5"),children:[G&&e.jsxs("div",{className:"absolute inset-0 z-20 flex items-center justify-center pointer-events-none rounded-lg bg-primary/10 text-primary text-sm font-medium",children:["Drop file","(s)"," to attach as @-mention"]}),e.jsxs("div",{className:"relative flex-1",children:[I&&e.jsx(co,{query:I.query,onClose:()=>F(null),onPick:f=>{const S=v.slice(0,I.start),g=v.slice(I.start+1+I.query.length),E=`@${f} `,Q=S+E+g;h(Q),F(null),requestAnimationFrame(()=>{const _=q.current;if(_){const ie=S.length+E.length;_.focus(),_.setSelectionRange(ie,ie),_.style.height="auto",_.style.height=`${Math.min(_.scrollHeight,200)}px`}})}}),!I&&Y.length>0&&(()=>{const f={};Y.forEach((g,E)=>{f[g.category]||(f[g.category]=[]),f[g.category].push({cmd:g,idx:E})});const S=mo.filter(g=>{var E;return(E=f[g])==null?void 0:E.length});return e.jsxs("div",{className:"absolute bottom-full left-0 right-0 mb-2 rounded-lg border bg-popover shadow-md p-1 text-sm max-h-72 overflow-auto",children:[e.jsx("div",{className:"px-3 py-1 text-[10px] uppercase tracking-wider text-muted-foreground border-b mb-1",children:"↑/↓ select · Tab complete · Enter dispatch · Esc dismiss"}),S.map(g=>e.jsxs("div",{className:"mb-1",children:[e.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[10px] uppercase tracking-wider text-muted-foreground/70 font-semibold",children:g}),f[g].map(({cmd:E,idx:Q})=>{var _;return e.jsxs("button",{type:"button",onClick:()=>{h(""),ee(E.name)},onMouseEnter:()=>C(Q),className:k("w-full text-left px-3 py-1.5 rounded transition-colors flex items-center gap-3",Q===j?"bg-accent text-accent-foreground":"hover:bg-accent/40"),children:[e.jsx("span",{className:"font-mono shrink-0",children:E.name}),(_=E.aliases)!=null&&_.length?e.jsxs("span",{className:"text-xs text-muted-foreground/70 font-mono shrink-0",children:["(",E.aliases.join(", "),")"]}):null,e.jsxs("span",{className:"text-xs text-muted-foreground truncate",children:["— ",E.description]})]},E.name)})]},g))]})})(),e.jsx("textarea",{ref:q,value:v,onChange:f=>{const S=f.target.value;h(S),T(),D>=0&&R(-1);const g=f.target.selectionStart??S.length;F($t(S,g))},onSelect:f=>{const S=f.currentTarget;F($t(S.value,S.selectionStart))},onKeyDown:L,onPaste:f=>{var g;const S=((g=f.clipboardData)==null?void 0:g.getData("text"))??"";if(S.length>800){const E=S.split(`
71
+ `).length;X({chars:S.length,lines:E}),setTimeout(()=>X(null),4e3)}},placeholder:y!=null&&y.isConnected?s?"Agent is running — type to queue a follow-up…":"Message WrongStack… (type / for commands, @ for files)":"Connect to server first…",className:k("flex min-h-[44px] w-full resize-none rounded-lg border border-input bg-background px-4 py-3 pr-12","text-sm ring-offset-background placeholder:text-muted-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","disabled:cursor-not-allowed disabled:opacity-50","scrollbar-thin"),rows:1,disabled:!(y!=null&&y.isConnected)}),v.length>0&&(()=>{const f=v.length>=400,S=Math.ceil(v.length/4);let g="text-muted-foreground",E;if(N>0&&f){const _=(w+S+64)/N*100;_>=100?(g="text-red-600 dark:text-red-400 font-medium",E=`Projected ${Math.round(_)}% of ${N.toLocaleString()} ctx — will likely error or compact.`):_>=85?(g="text-amber-600 dark:text-amber-400 font-medium",E=`Projected ${Math.round(_)}% of ${N.toLocaleString()} ctx — getting tight.`):E=`≈ ${S.toLocaleString()} tokens · projected ${Math.round(_)}% of ${N.toLocaleString()} ctx.`}else f&&(E=`≈ ${S.toLocaleString()} tokens (4-char heuristic)`);return e.jsxs("span",{className:k("absolute bottom-1.5 right-12 text-xs tabular-nums",g),title:E,children:[v.length,f&&e.jsxs("span",{className:"ml-1 opacity-70",children:["· ≈",S>=1e3?`${(S/1e3).toFixed(1)}k`:S,"t"]})]})})()]}),e.jsx("div",{className:"flex gap-1",children:s?e.jsxs(e.Fragment,{children:[e.jsx(J,{type:"button",size:"icon",variant:"outline",onClick:O,className:"h-[44px] w-[44px] rounded-lg",title:"Stop run and edit the last prompt (reuse + rewrite)",children:e.jsx(At,{className:"h-4 w-4"})}),e.jsx(J,{type:"button",size:"icon",variant:"destructive",onClick:A,className:"h-[44px] w-[44px] rounded-lg",title:"Abort the current run",children:e.jsx(Ss,{className:"h-4 w-4 fill-current"})})]}):e.jsx(J,{type:"submit",size:"icon",disabled:!v.trim()||!(y!=null&&y.isConnected),className:"h-[44px] w-[44px] rounded-lg",children:e.jsx(Cs,{className:"h-4 w-4"})})})]})]})}function ho({wsStatus:s,wsConnected:t}){const n=B(l=>l.wsUrl),[r,a]=d.useState(Date.now());d.useEffect(()=>{if(s.state!=="reconnecting")return;const l=setInterval(()=>a(Date.now()),500);return()=>clearInterval(l)},[s.state]);const o=()=>ae(n).retryNow();if(s.state==="open"&&t)return e.jsx("div",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[11px] font-medium shrink-0 bg-green-500/10 text-green-600 dark:text-green-400",title:"Backend connected",children:e.jsx(It,{className:"h-3 w-3"})});if(s.state==="connecting")return e.jsxs("div",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[11px] font-medium shrink-0 bg-yellow-500/10 text-yellow-600 dark:text-yellow-400",title:"Connecting to backend",children:[e.jsx(fe,{className:"h-3 w-3 animate-spin"}),e.jsx("span",{children:"connecting"})]});if(s.state==="reconnecting"){const l=Math.max(0,Math.ceil((s.nextRetryAt-r)/1e3));return e.jsxs("button",{type:"button",onClick:o,className:k("flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[11px] font-medium shrink-0","bg-orange-500/10 text-orange-600 dark:text-orange-400 hover:bg-orange-500/20","transition-colors"),title:s.lastError?`Reconnecting — last error: ${s.lastError}. Click to retry now.`:"Reconnecting — click to retry now.",children:[e.jsx(fe,{className:"h-3 w-3 animate-spin"}),e.jsxs("span",{children:["retry #",s.attempt," in ",l,"s"]})]})}return e.jsxs("button",{type:"button",onClick:o,className:"flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[11px] font-medium shrink-0 bg-red-500/10 text-red-600 dark:text-red-400 hover:bg-red-500/20 transition-colors",title:s.state==="closed"&&s.error?`Disconnected: ${s.error}. Click to retry.`:"Disconnected. Click to retry.",children:[e.jsx(ut,{className:"h-3 w-3"}),e.jsxs("span",{className:"flex items-center gap-0.5",children:["offline",e.jsx(Ae,{className:"h-3 w-3 opacity-70"})]})]})}const fo=[{id:"balanced",name:"Balanced",description:"Default rolling compaction",thresholds:{warn:.6,soft:.75,hard:.9},preserveK:10,eliseThreshold:2e3}];function go(){const s=z(u=>u.contextMode),t=z(u=>u.contextModes),{listContextModes:n,switchContextMode:r}=de(),[a,o]=d.useState(!1),l=d.useRef(null);d.useEffect(()=>{a&&n()},[a,n]),d.useEffect(()=>{if(!a)return;const u=x=>{var p;(p=l.current)!=null&&p.contains(x.target)||o(!1)},m=x=>{x.key==="Escape"&&o(!1)};return document.addEventListener("mousedown",u),document.addEventListener("keydown",m),()=>{document.removeEventListener("mousedown",u),document.removeEventListener("keydown",m)}},[a]);const c=t.length>0?t:fo,i=c.find(u=>u.id===s)??c[0];return e.jsxs("div",{ref:l,className:"relative shrink-0",children:[e.jsxs("button",{type:"button",onClick:()=>o(u=>!u),className:k("flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium","bg-emerald-500/10 text-emerald-700 dark:text-emerald-300 hover:bg-emerald-500/15 transition-colors border border-transparent hover:border-emerald-500/30"),title:"Context-window mode",children:[e.jsx($s,{className:"h-3 w-3"}),"ctx: ",e.jsx("span",{className:"font-mono",children:s||i.id}),e.jsx(Ce,{className:"h-3 w-3 opacity-60"})]}),a&&e.jsxs("div",{className:"absolute top-full left-0 mt-1 w-80 rounded-md border bg-popover shadow-lg z-30 py-1",children:[e.jsx("div",{className:"px-3 py-1.5 text-[10px] uppercase tracking-wider text-muted-foreground border-b",children:"Context Window"}),c.map(u=>e.jsxs("button",{type:"button",onClick:()=>{r(u.id),o(!1)},className:k("w-full text-left px-3 py-2 hover:bg-accent/40 flex items-start gap-2",u.id===s&&"bg-accent/30"),children:[e.jsx(mt,{className:k("h-3.5 w-3.5 mt-0.5 shrink-0",u.id===s?"opacity-100 text-primary":"opacity-0")}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-xs font-mono",children:u.id}),u.thresholds&&e.jsxs("span",{className:"text-[10px] text-muted-foreground tabular-nums",children:[Math.round(u.thresholds.warn*100),"/",Math.round(u.thresholds.soft*100),"/",Math.round(u.thresholds.hard*100),"%"]})]}),e.jsx("div",{className:"text-[11px] text-muted-foreground leading-snug",children:u.description}),(u.preserveK||u.eliseThreshold)&&e.jsxs("div",{className:"mt-1 text-[10px] text-muted-foreground/80",children:["keep ",u.preserveK??"-"," recent · elide ",u.eliseThreshold??"-","+ tokens"]})]})]},u.id))]})]})}function bo(){const s=z(x=>x.cost),t=z(x=>x.inputCost),n=z(x=>x.outputCost),r=z(x=>x.cacheReadCost),a=M(x=>x.messages),[o,l]=d.useState(!1),c=d.useRef(null);d.useEffect(()=>{if(!o)return;const x=b=>{var y;(y=c.current)!=null&&y.contains(b.target)||l(!1)},p=b=>{b.key==="Escape"&&l(!1)};return document.addEventListener("mousedown",x),document.addEventListener("keydown",p),()=>{document.removeEventListener("mousedown",x),document.removeEventListener("keydown",p)}},[o]);const i=(()=>{const x=[];for(const p of a)p.role==="assistant"&&p.runSummary&&p.runSummary.costDelta>0&&x.push({id:p.id,preview:p.content.slice(0,80).replace(/\s+/g," ").trim()||"(empty)",cost:p.runSummary.costDelta,tools:p.runSummary.tools,ms:p.runSummary.durationMs,ts:p.timestamp});return x.sort((p,b)=>b.cost-p.cost),x.slice(0,5)})(),u=x=>x>=.01?`$${x.toFixed(4)}`:x>0?`$${x.toFixed(6).replace(/0+$/,"").replace(/\.$/,"")}`:"$0",m=t>0||n>0;return e.jsxs("div",{ref:c,className:"relative inline-block",children:[e.jsxs("button",{type:"button",onClick:()=>l(x=>!x),className:k("font-medium text-green-600 dark:text-green-400 hover:underline tabular-nums"),title:"Click for per-turn cost breakdown",children:["$",s.toFixed(4)]}),o&&e.jsxs("div",{className:"absolute right-0 top-full mt-1 z-30 w-80 rounded-md border bg-popover shadow-lg p-3 text-foreground",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium",children:"Cost breakdown"}),e.jsx("span",{className:"font-mono tabular-nums text-sm font-semibold text-green-600 dark:text-green-400",children:u(s)})]}),m?e.jsxs("div",{className:"text-[11px] text-muted-foreground font-mono mb-3 border-b pb-2",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"input /1M"}),e.jsxs("span",{children:["$",t.toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"output /1M"}),e.jsxs("span",{children:["$",n.toFixed(2)]})]}),r>0&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"cache /1M"}),e.jsxs("span",{children:["$",r.toFixed(2)]})]})]}):e.jsx("div",{className:"text-[11px] text-muted-foreground italic mb-3 border-b pb-2",children:"No pricing for the current model — cost figures are zero."}),i.length===0?e.jsx("div",{className:"text-xs text-muted-foreground italic",children:"No completed turns yet. Run a prompt to see per-turn cost here."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground/80 mb-1",children:["Top ",i.length," expensive turn",i.length===1?"":"s"]}),e.jsx("ul",{className:"space-y-1",children:i.map(x=>e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>{const p=document.querySelector(`[data-message-id="${x.id}"]`);p&&p.scrollIntoView({behavior:"smooth",block:"center"}),l(!1)},className:"w-full text-left rounded px-2 py-1.5 hover:bg-accent/40 transition-colors",children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[e.jsx("span",{className:"text-xs truncate",children:x.preview}),e.jsx("span",{className:"text-xs font-mono tabular-nums text-green-600 dark:text-green-400 shrink-0",children:u(x.cost)})]}),e.jsxs("div",{className:"text-[10px] text-muted-foreground font-mono mt-0.5",children:[x.tools," tool",x.tools===1?"":"s"," · ",(x.ms/1e3).toFixed(1),"s"]})]})},x.id))})]})]})]})}const yo=["path","file_path","pattern","command","cmd","url","query","description","content"];function vo(s,t){if(t==null)return"";if(typeof t!="object")return me(String(t),120);const n=t,r=(s??"").toLowerCase();if(/^todo(_?write)?$|^todos$/i.test(r)||Array.isArray(n.todos)){const o=n.todos??[];if(Array.isArray(o)){const l=o.filter(u=>u.status==="completed").length,c=o.filter(u=>u.status==="in_progress").length,i=[`${o.length} todo${o.length===1?"":"s"}`];return l>0&&i.push(`${l} done`),c>0&&i.push(`${c} in-progress`),i.join(" · ")}}if(/batch|parallel/.test(r)||Array.isArray(n.tool_uses)||Array.isArray(n.calls)){const o=n.tool_uses??n.calls??n.batch;if(Array.isArray(o)){const l=new Set;for(const u of o)u&&typeof u=="object"&&"name"in u&&l.add(String(u.name));const c=[...l].slice(0,3).join(", "),i=l.size>3?` +${l.size-3}`:"";return`${o.length} sub-tool${o.length===1?"":"s"}${c?` · ${c}${i}`:""}`}}if(/^(edit|str_replace|edit_file|patch)$/.test(r)){const o=Ve(n),l=typeof n.old_string=="string"?n.old_string:"",c=typeof n.new_string=="string"?n.new_string:"",i=l?l.split(`
72
+ `).length:0,u=c?c.split(`
73
+ `).length:0;return`edit ${o||"(file)"}${i||u?` (${i} → ${u} lines)`:""}`}if(/^(write|write_file|create_file|new_file)$/.test(r)){const o=Ve(n),l=typeof n.content=="string"?n.content:"",c=l?l.split(`
74
+ `).length:0;return`write ${o||"(file)"}${c?` · ${c} lines`:""}`}if(/^(bash|shell|exec|run|run_command|run_shell)$/.test(r)){const o=n.command??n.cmd??n.script;if(typeof o=="string")return`$ ${me(o,110)}`}if(/^(fetch|http|web|webfetch|curl|request)$/.test(r)){const o=n.url;if(typeof o=="string")return`${(n.method??"GET").toUpperCase()} ${me(o,100)}`}if(/^(grep|search|ripgrep)$/.test(r)){const o=n.pattern,l=n.path??n.glob??n.type;if(typeof o=="string")return l?`grep ${me(o,60)} in ${l}`:`grep ${me(o,100)}`}if(/^(glob|find)$/.test(r)){const o=n.pattern??n.glob;if(typeof o=="string")return`glob ${me(o,100)}`}if(/^(read|read_file|cat)$/.test(r)){const o=Ve(n),l=n.offset,c=n.limit;if(o&&(typeof l=="number"||typeof c=="number")){const i=l??0,u=typeof c=="number"?i+c:"";return`read ${o} (${i}…${u})`}if(o)return`read ${o}`}for(const o of yo){const l=n[o];if(typeof l=="string"&&l.length>0)return`${o}: ${me(l,100)}`}const a=wo(t);return me(a,120)}function me(s,t){return s.length>t?`${s.slice(0,t-1)}…`:s}function Ve(s){const t=s.file_path??s.path??s.filepath;return typeof t=="string"?t:""}function wo(s){try{return JSON.stringify(s)}catch{return String(s)}}const Zt=d.memo(function({oldText:t,newText:n,caption:r}){const a=d.useMemo(()=>jo(t,n),[t,n]);if(a===null)return e.jsx("div",{className:"text-xs text-muted-foreground italic px-3 py-2",children:"Diff omitted (file too large to render inline)."});const o=a.filter(c=>c.kind==="add").length,l=a.filter(c=>c.kind==="del").length;return e.jsxs("div",{className:"rounded-lg border bg-background/40 overflow-hidden text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b bg-muted/40",children:[e.jsx("span",{className:"font-mono text-muted-foreground truncate",children:r??"diff"}),e.jsxs("span",{className:"font-mono shrink-0",children:[e.jsxs("span",{className:"text-emerald-600 dark:text-emerald-400",children:["+",o]}),e.jsx("span",{className:"text-muted-foreground mx-1",children:"·"}),e.jsxs("span",{className:"text-rose-600 dark:text-rose-400",children:["-",l]})]})]}),e.jsx("div",{className:"font-mono leading-relaxed max-h-96 overflow-auto",children:a.map((c,i)=>e.jsxs("div",{className:k("flex",c.kind==="add"&&"bg-emerald-500/10",c.kind==="del"&&"bg-rose-500/10"),children:[e.jsx("span",{className:k("w-6 shrink-0 text-center select-none",c.kind==="add"&&"text-emerald-600 dark:text-emerald-400",c.kind==="del"&&"text-rose-600 dark:text-rose-400",c.kind==="ctx"&&"text-muted-foreground/40"),children:c.kind==="add"?"+":c.kind==="del"?"-":" "}),e.jsx("pre",{className:k("whitespace-pre-wrap break-all flex-1 px-2",c.kind==="ctx"&&"text-muted-foreground/70"),children:c.text||" "})]},i))})]})}),Tt=5e3;function jo(s,t){const n=s.split(`
75
+ `),r=t.split(`
76
+ `);if(n.length>Tt||r.length>Tt)return null;const a=n.length,o=r.length,l=Array.from({length:a+1},()=>new Array(o+1).fill(0));for(let m=a-1;m>=0;m--)for(let x=o-1;x>=0;x--)n[m]===r[x]?l[m][x]=l[m+1][x+1]+1:l[m][x]=Math.max(l[m+1][x],l[m][x+1]);const c=[];let i=0,u=0;for(;i<a&&u<o;)n[i]===r[u]?(c.push({kind:"ctx",text:n[i]}),i++,u++):l[i+1][u]>=l[i][u+1]?(c.push({kind:"del",text:n[i]}),i++):(c.push({kind:"add",text:r[u]}),u++);for(;i<a;)c.push({kind:"del",text:n[i++]});for(;u<o;)c.push({kind:"add",text:r[u++]});return c}function es(s,t){if(!s||typeof t!="object"||t===null)return null;const n=t,r=String(n.file_path??n.path??"");switch(s){case"edit":case"str_replace":case"edit_file":{const a=typeof n.old_string=="string"?n.old_string:"",o=typeof n.new_string=="string"?n.new_string:"";return!a&&!o?null:{oldText:a,newText:o,caption:`edit ${r}`}}case"write":case"write_file":case"create_file":return{oldText:"",newText:typeof n.content=="string"?n.content:"",caption:`write ${r} (new)`};default:return null}}const No=25,Je=12;function Qe({text:s,isError:t,className:n,wrapClass:r,showLineNumbers:a}){const o=d.useMemo(()=>s.split(`
77
+ `),[s]),l=o.length>No,[c,i]=d.useState(!l),u=c?s:o.slice(0,Je).join(`
78
+ `),m=!!a&&l&&c;return e.jsxs("div",{className:k("rounded-md border bg-background/40 overflow-hidden",n),children:[m?e.jsxs("div",{className:"flex max-h-96 overflow-auto",children:[e.jsx("pre",{"aria-hidden":!0,className:"text-xs font-mono leading-[1.4] py-2 pl-2 pr-2 text-muted-foreground/50 select-none border-r border-border/40 bg-muted/20 tabular-nums text-right whitespace-pre shrink-0",children:o.map((x,p)=>`${p+1}`).join(`
79
+ `)}),e.jsx("pre",{className:k("text-xs font-mono leading-[1.4] py-2 px-2 flex-1 whitespace-pre",t?"text-destructive":"text-foreground"),children:u})]}):e.jsx("pre",{className:k("text-xs font-mono p-2 max-h-96 overflow-auto",r,t?"text-destructive":"text-foreground"),children:u}),l&&e.jsx("button",{type:"button",onClick:()=>i(x=>!x),className:"w-full flex items-center justify-center gap-1 px-2 py-1 border-t bg-muted/30 text-[11px] text-muted-foreground hover:text-foreground transition-colors",children:c?e.jsxs(e.Fragment,{children:[e.jsx(Ts,{className:"h-3 w-3"}),"Collapse to first ",Je," lines"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ms,{className:"h-3 w-3"}),"Show all ",o.length," lines (",o.length-Je," more)"]})})]})}const ko=d.memo(function({toolName:t,result:n,isError:r,className:a}){const o=d.useMemo(()=>So(t,n),[t,n]);return o.kind==="json"?e.jsx(Co,{value:o.value,isError:r,className:a}):o.kind==="numbered"?e.jsx(Qe,{text:n,isError:r,className:a,wrapClass:"whitespace-pre"}):o.kind==="bash"?e.jsxs("div",{className:k("rounded-md border bg-background/40 overflow-hidden",a),children:[o.stdout&&e.jsx(Qe,{text:o.stdout,isError:r,className:"border-0 rounded-none bg-transparent",wrapClass:"whitespace-pre-wrap break-all",showLineNumbers:!0}),(o.exitCode!==void 0||o.duration)&&e.jsxs("div",{className:k("flex items-center gap-3 text-[11px] px-2 py-1 border-t bg-muted/30 tabular-nums",o.exitCode&&o.exitCode!==0?"text-destructive":"text-muted-foreground"),children:[o.exitCode!==void 0&&e.jsxs("span",{children:["exit code: ",e.jsx("span",{className:"font-mono",children:o.exitCode})]}),o.duration&&e.jsx("span",{children:o.duration})]})]}):e.jsx(Qe,{text:n,isError:r,className:a,wrapClass:"whitespace-pre-wrap break-all",showLineNumbers:!0})});function So(s,t){const n=t.trim();if(/^\s*\d+→/m.test(t.slice(0,200)))return{kind:"numbered"};if(n.startsWith("{")&&n.endsWith("}")||n.startsWith("[")&&n.endsWith("]"))try{const l=JSON.parse(n);if(typeof l=="object"&&l!==null)return{kind:"json",value:l}}catch{}const r=!!s&&/^(bash|shell|exec|run)/i.test(s),a=t.match(/(?:^|\n)\s*(?:\[?exit(?:\s*code)?\]?\s*[:=]?\s*)(\d+)\s*$/i),o=t.match(/(?:^|\s)(\d+\s*ms|\d+\.\d+s)\s*$/i);if(r||a){let l=t;return a&&(l=t.slice(0,a.index).trimEnd()),{kind:"bash",stdout:l,exitCode:a?Number(a[1]):void 0,duration:o==null?void 0:o[1]}}return{kind:"plain"}}function Co({value:s,isError:t,className:n}){const r=d.useMemo(()=>{try{return JSON.stringify(s,null,2)}catch{return String(s)}},[s]),a=r.split(`
80
+ `).length,[o,l]=d.useState(a<30);return e.jsxs("div",{className:k("rounded-md border bg-background/40 overflow-hidden",t&&"border-destructive/40",n),children:[e.jsxs("button",{type:"button",onClick:()=>l(c=>!c),className:"w-full flex items-center justify-between px-2 py-1 border-b bg-muted/30 text-[11px] text-muted-foreground hover:text-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[o?e.jsx(Ce,{className:"h-3 w-3"}):e.jsx(We,{className:"h-3 w-3"}),e.jsxs("span",{className:"font-mono",children:["JSON · ",a," lines"]})]}),e.jsx("span",{children:o?"collapse":"expand"})]}),o&&e.jsx("pre",{className:k("text-xs font-mono whitespace-pre p-2 max-h-96 overflow-auto",t?"text-destructive":"text-foreground"),children:r})]})}async function $o(s){var t;try{if(typeof navigator<"u"&&((t=navigator.clipboard)!=null&&t.writeText))return await navigator.clipboard.writeText(s),!0}catch{}try{const n=document.createElement("textarea");n.value=s,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select();const r=document.execCommand("copy");return document.body.removeChild(n),r}catch{return!1}}function To(s,t){if(typeof document>"u")return;const n=new Blob([t],{type:"text/plain;charset=utf-8"}),r=URL.createObjectURL(n),a=document.createElement("a");a.href=r,a.download=s,document.body.appendChild(a),a.click(),document.body.removeChild(a),setTimeout(()=>URL.revokeObjectURL(r),1e3)}function Mo(s){const t=(s??"").toLowerCase();return/bash|shell|exec|run/.test(t)?"log":(/grep|search|find/.test(t),"txt")}function Eo(s){if(s<1e3)return`${s} ms`;if(s<6e4)return`${(s/1e3).toFixed(s<1e4?2:1)}s`;const t=Math.floor(s/6e4),n=Math.floor(s%6e4/1e3);return`${t}m ${n}s`}const Do={code({inline:s,className:t,children:n,...r}){const a=/language-(\w+)/.exec(t??""),o=String(n??"").replace(/\n$/,"");return s||!a?e.jsx("code",{className:k("rounded bg-muted/60 px-1.5 py-0.5 text-[0.85em] font-mono",t),...r,children:n}):e.jsxs("div",{className:"not-prose relative my-3 rounded-lg border bg-muted/30 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b bg-muted/40 text-xs",children:[e.jsx("span",{className:"font-mono text-muted-foreground",children:a[1]}),e.jsx(tt,{text:o,label:""})]}),e.jsx("pre",{className:"overflow-x-auto p-3 text-xs leading-relaxed font-mono max-h-[40rem]",children:e.jsx("code",{children:o})})]})}};function tt({text:s,className:t,label:n="Copy"}){const[r,a]=d.useState(!1);return e.jsx("button",{type:"button",onClick:async o=>{o.stopPropagation(),await $o(s)&&(a(!0),setTimeout(()=>a(!1),1400))},className:k("inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors",t),title:n,children:r?e.jsxs(e.Fragment,{children:[e.jsx(mt,{className:"h-3 w-3 text-green-500"}),e.jsx("span",{children:"Copied"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Es,{className:"h-3 w-3"}),e.jsx("span",{children:n})]})})}function Ro(s){const t=s.split(`
81
+ `);for(let n=0;n<t.length;n++){const r=t[n];if(/^\s*at\s+\S+.*\(.*:\d+:\d+\)\s*$/.test(r)||/^\s*at\s+\S+\.\S+\(\S+\.java:\d+\)\s*$/.test(r)||/^\s+File "[^"]+", line \d+/.test(r))return n}return-1}function Lo({text:s}){const t=Ro(s),[n,r]=d.useState(!1);if(t===-1)return e.jsx("pre",{className:"whitespace-pre-wrap break-words font-mono text-xs leading-relaxed",children:s});const a=s.split(`
82
+ `),o=a.slice(0,t).join(`
83
+ `).trim(),l=a.slice(t).join(`
84
+ `),c=l.split(`
85
+ `).filter(i=>i.trim().length>0).length;return e.jsxs("div",{className:"space-y-2",children:[o&&e.jsx("pre",{className:"whitespace-pre-wrap break-words font-mono text-xs leading-relaxed",children:o}),e.jsxs("button",{type:"button",onClick:()=>r(i=>!i),className:"inline-flex items-center gap-1 text-xs text-destructive hover:text-destructive/80 font-medium",children:[n?"▾":"▸"," ",n?"Hide":"Show"," stack trace (",c," frame",c===1?"":"s",")"]}),n&&e.jsx("pre",{className:"whitespace-pre-wrap break-words font-mono text-[11px] leading-snug bg-destructive/5 border border-destructive/20 rounded p-2 max-h-80 overflow-auto",children:l})]})}function Ao({input:s}){const[t,n]=d.useState({});if(s==null||typeof s!="object"||Array.isArray(s))return e.jsx("pre",{className:"whitespace-pre-wrap break-all text-xs font-mono",children:JSON.stringify(s,null,2)});const r=Object.entries(s);return r.length===0?e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"(no params)"}):e.jsx("div",{className:"text-xs font-mono",children:r.map(([a,o])=>{if(o==null||typeof o=="string"||typeof o=="number"||typeof o=="boolean"){const u=o===null?"null":o===void 0?"undefined":typeof o=="string"?o:String(o),m=typeof o=="string"&&(u.length>80||u.includes(`
86
+ `));return e.jsxs("div",{className:k("py-0.5",m?"flex flex-col gap-0.5":"flex items-baseline gap-2"),children:[e.jsxs("span",{className:"text-muted-foreground shrink-0",children:[a,":"]}),e.jsx("span",{className:k("text-foreground",m?"whitespace-pre-wrap break-all bg-muted/40 rounded px-1.5 py-1":"truncate",typeof o=="string"?"":"text-amber-600 dark:text-amber-400"),title:typeof o=="string"&&!m?u:void 0,children:u})]},a)}const c=!!t[a],i=Array.isArray(o)?`[${o.length} item${o.length===1?"":"s"}]`:`{${Object.keys(o).length} key${Object.keys(o).length===1?"":"s"}}`;return e.jsxs("div",{className:"py-0.5",children:[e.jsxs("button",{type:"button",onClick:()=>n(u=>({...u,[a]:!u[a]})),className:"flex items-baseline gap-2 hover:bg-muted/30 rounded px-1 -mx-1",children:[e.jsx("span",{className:"text-muted-foreground/60 text-[10px]",children:c?"▾":"▸"}),e.jsxs("span",{className:"text-muted-foreground",children:[a,":"]}),e.jsx("span",{className:"text-violet-600 dark:text-violet-400",children:i})]}),c&&e.jsx("pre",{className:"ml-3 mt-1 whitespace-pre-wrap break-all text-[11px] bg-muted/40 rounded px-2 py-1.5",children:JSON.stringify(o,null,2)})]},a)})})}const Fe=d.memo(function({message:t,isFirst:n=!1,isContinuation:r=!1}){const[a,o]=d.useState({}),[l,c]=d.useState(!1),[i,u]=d.useState(""),[m,x]=d.useState(!1),p=t.role==="user",b=t.role==="tool";t.role;const y=M($=>$.truncateAfter),w=M($=>$.addMessage),N=M($=>$.setLoading),v=M($=>$.isLoading),h=B($=>$.wsUrl),j=P($=>$.pinnedIds),C=P($=>$.togglePin),D=P($=>$.compactMode),R=j.includes(t.id),I=z($=>$.inputCost),F=z($=>$.outputCost),K=z($=>$.cacheReadCost),X=(()=>{if(t.role!=="assistant"||v)return!1;const $=M.getState().messages;for(let W=$.length-1;W>=0;W--){const A=$[W];if(A.role==="assistant")return A.id===t.id}return!1})(),G=()=>{const $=M.getState().messages,W=$.findIndex(T=>T.id===t.id);if(W===-1)return;let A=-1;for(let T=W-1;T>=0;T--)if($[T].role==="user"){A=T;break}if(A===-1)return;const O=$[A];y(O.id),w({role:"user",content:O.content}),N(!0),ae(h).sendMessage(O.content)},V=$=>{o(W=>({...W,[$]:!W[$]}))},q=()=>{u(t.content),c(!0)},ee=()=>{c(!1),u("")},Y=()=>{const $=i.trim();if(!$){ee();return}y(t.id),w({role:"user",content:$}),N(!0),ae(h).sendMessage($),c(!1),u("")};return e.jsxs("div",{"data-message-id":t.id,"data-pinned":R?"1":void 0,className:k("group flex animate-message rounded-lg transition-shadow",D?"gap-2":"gap-3",p?"flex-row-reverse":"flex-row",R&&"ring-1 ring-amber-500/30 bg-amber-500/[0.02] px-1 -mx-1"),children:[r?e.jsx("div",{className:"flex-shrink-0 w-8 h-8","aria-hidden":!0}):e.jsx("div",{className:k("flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center","ring-2 ring-offset-2 ring-offset-background",p?"bg-primary text-primary-foreground ring-primary/20":b?"bg-secondary text-secondary-foreground ring-secondary/20":"bg-accent text-accent-foreground ring-accent/20"),children:p?e.jsx(Ds,{className:"h-4 w-4"}):b?e.jsx(Ne,{className:"h-4 w-4"}):e.jsx(pt,{className:"h-4 w-4"})}),e.jsxs("div",{className:k("flex flex-col gap-1.5 max-w-[85%]",p&&"items-end"),children:[n&&!r&&e.jsx("span",{className:k("text-xs font-medium px-1",p?"text-primary":b?"text-secondary":"text-muted-foreground"),children:p?"You":b?"Tool":"Assistant"}),b&&t.toolName&&e.jsxs("button",{type:"button",onClick:()=>V(t.id),className:k("flex items-center gap-2 text-sm font-medium cursor-pointer select-none","hover:bg-muted/50 rounded-lg px-2 py-1 -mx-2 transition-colors",t.isError?"text-destructive":"text-foreground"),children:[e.jsx("span",{className:"text-muted-foreground/50",children:a[t.id]?e.jsx(Ce,{className:"h-3 w-3"}):e.jsx(We,{className:"h-3 w-3"})}),e.jsx(Ne,{className:"h-3 w-3"}),e.jsx("span",{className:"font-mono",children:t.toolName}),t.toolResult===void 0?e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-amber-500 animate-pulse","aria-hidden":!0}):t.isError?e.jsx(nt,{className:"h-3 w-3 text-destructive"}):e.jsx(he,{className:"h-3 w-3 text-green-500"}),typeof t.toolDurationMs=="number"&&e.jsx("span",{className:"text-xs text-muted-foreground tabular-nums font-normal",children:Eo(t.toolDurationMs)})]}),e.jsx("div",{className:k("rounded-2xl",D?"px-3 py-1.5":"px-4 py-3",p?"bg-primary text-primary-foreground rounded-br-md":b?t.isError?"bg-destructive/5 border border-destructive/20 text-destructive":"bg-muted/80 text-foreground":"bg-card border text-foreground",t.isError&&!b&&"border-destructive/20"),children:b?(()=>{const $=!!a[t.id],W=t.toolInput!==void 0?vo(t.toolName,t.toolInput):"",A=t.toolResult?t.toolResult.split(`
87
+ `).length:0;return e.jsxs("div",{className:"space-y-1",children:[W&&!$&&e.jsx("div",{className:"text-xs text-muted-foreground font-mono truncate",children:W}),t.toolResult===void 0&&t.progressLines&&t.progressLines.length>0&&e.jsx("div",{className:"mt-1 rounded-md border border-amber-500/20 bg-amber-500/5 p-1.5 text-[11px] font-mono leading-snug max-h-32 overflow-auto",children:t.progressLines.slice(-6).map((O,L)=>e.jsx("div",{className:"truncate text-muted-foreground",children:O},L))}),$&&t.toolInput!==void 0&&(()=>{const O=es(t.toolName,t.toolInput);return O?e.jsx(Zt,{oldText:O.oldText,newText:O.newText,caption:O.caption}):e.jsxs("div",{className:"p-3 bg-muted/50 rounded-lg overflow-x-auto",children:[e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground mb-2 text-xs",children:[e.jsx(Oe,{className:"h-3 w-3"}),e.jsx("span",{children:"Input"})]}),e.jsx(Ao,{input:t.toolInput})]})})(),$&&t.toolResult!==void 0&&t.toolResult.length>0&&e.jsxs("div",{className:"relative group/tool",children:[e.jsx(ko,{toolName:t.toolName,result:t.toolResult,isError:t.isError}),e.jsxs("div",{className:"absolute top-1.5 right-1.5 flex items-center gap-1 opacity-0 group-hover/tool:opacity-100 transition-opacity",children:[e.jsx(tt,{text:t.toolResult,label:"",className:"bg-background/80 border rounded px-1.5 py-0.5"}),t.toolResult.split(`
88
+ `).length>5&&e.jsx("button",{type:"button",onClick:O=>{O.stopPropagation();const L=Mo(t.toolName),T=(t.toolName??"output").replace(/[^a-z0-9_-]+/gi,"-").toLowerCase();To(`${T}-${new Date().toISOString().replace(/[:.]/g,"-")}.${L}`,t.toolResult??"")},className:"inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground bg-background/80 border rounded px-1.5 py-0.5",title:"Download as file",children:e.jsx(Ye,{className:"h-3 w-3"})})]})]}),$&&t.toolResult!==void 0&&t.toolResult.length===0&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"(empty)"}),!$&&t.isError&&t.toolResult&&e.jsx("div",{className:"text-xs font-mono text-destructive truncate",children:t.toolResult.split(`
89
+ `)[0]}),(t.toolResult!==void 0&&t.toolResult.length>0||t.toolInput!==void 0&&Object.keys(t.toolInput??{}).length>0)&&e.jsx("button",{type:"button",onClick:()=>V(t.id),className:"text-xs text-muted-foreground hover:text-foreground transition-colors",children:$?"Hide details":`Show details${A>0?` (${A} line${A===1?"":"s"})`:""}`})]})})():l&&p?e.jsxs("div",{className:"flex flex-col gap-2 min-w-[280px]",children:[e.jsx("textarea",{value:i,onChange:$=>u($.target.value),onKeyDown:$=>{$.key==="Escape"?($.preventDefault(),ee()):$.key==="Enter"&&($.metaKey||$.ctrlKey)&&($.preventDefault(),Y())},rows:Math.min(8,Math.max(2,i.split(`
90
+ `).length)),className:"w-full resize-none rounded-md border bg-background text-foreground px-2 py-1.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-ring"}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[10px] text-primary-foreground/60",children:"⌘/Ctrl+Enter to save · Esc to cancel"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{type:"button",onClick:ee,className:"text-xs px-2 py-0.5 rounded border border-primary-foreground/30 hover:bg-primary-foreground/10",children:"Cancel"}),e.jsx("button",{type:"button",onClick:Y,disabled:!i.trim(),className:"text-xs px-2 py-0.5 rounded bg-primary-foreground text-primary disabled:opacity-50",children:"Save & resend"})]})]})]}):e.jsx("div",{className:"text-sm leading-relaxed markdown-content",children:t.content?m&&t.role==="assistant"?e.jsx("pre",{className:"whitespace-pre-wrap break-words font-mono text-xs leading-relaxed text-foreground/90 max-h-[40rem] overflow-auto",children:t.content}):t.role==="assistant"&&t.isError?e.jsx(Lo,{text:t.content}):e.jsx(Rs,{remarkPlugins:[Ls],components:Do,children:t.content}):t.streaming?e.jsx("span",{className:"inline-block animate-pulse text-muted-foreground",children:"Typing..."}):e.jsx("span",{className:"text-muted-foreground italic",children:"No content"})})}),e.jsxs("div",{className:k("flex items-center gap-2 px-1",p?"flex-row-reverse":"flex-row"),children:[e.jsx("span",{className:"text-xs text-muted-foreground/50",children:new Date(t.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),t.runSummary&&e.jsxs("span",{className:"text-[10px] text-muted-foreground/60 font-mono tabular-nums",title:[`Iterations: ${t.runSummary.iterations}`,`Tool calls: ${t.runSummary.tools}`,`Elapsed: ${(t.runSummary.durationMs/1e3).toFixed(2)}s`,t.runSummary.costDelta>0?`Cost: $${t.runSummary.costDelta.toFixed(4)}`:""].filter(Boolean).join(" · "),children:[t.runSummary.iterations," iter",t.runSummary.tools>0?` · ${t.runSummary.tools} tool${t.runSummary.tools===1?"":"s"}`:""," · ",t.runSummary.durationMs<6e4?`${(t.runSummary.durationMs/1e3).toFixed(1)}s`:`${Math.floor(t.runSummary.durationMs/6e4)}m ${Math.floor(t.runSummary.durationMs%6e4/1e3)}s`,t.runSummary.costDelta>0?` · $${t.runSummary.costDelta>=.01?t.runSummary.costDelta.toFixed(4):t.runSummary.costDelta.toFixed(6).replace(/0+$/,"").replace(/\.$/,"")}`:""]}),t.usage&&(t.usage.input>0||t.usage.output>0)&&(()=>{const $=t.usage,W=($.input*I+$.output*F+($.cacheRead??0)*K)/1e6,A=I>0||F>0,O=W>=.01?`$${W.toFixed(4)}`:W>0?`$${W.toFixed(6).replace(/0+$/,"").replace(/\.$/,"")}`:"";return e.jsxs("span",{className:"text-[10px] text-muted-foreground/60 font-mono tabular-nums",title:[`Input: ${$.input.toLocaleString()}`,`Output: ${$.output.toLocaleString()}`,$.cacheRead?`Cache read: ${$.cacheRead.toLocaleString()}`:"",A?`Cost: ${O}`:""].filter(Boolean).join(" · "),children:[$.input.toLocaleString(),"→",$.output.toLocaleString(),$.cacheRead?` · ${$.cacheRead.toLocaleString()} ↺`:"",A&&O?` · ${O}`:""]})})(),!b&&t.content&&!t.streaming&&e.jsx(tt,{text:t.content,label:"",className:"opacity-0 group-hover:opacity-100 transition-opacity"}),t.role==="assistant"&&t.content&&!t.streaming&&e.jsxs("button",{type:"button",onClick:()=>x($=>!$),title:m?"Show rendered markdown":"Show raw markdown source",className:k("text-xs inline-flex items-center gap-1 transition-opacity",m?"text-primary hover:text-primary/80 opacity-100":"opacity-0 group-hover:opacity-100 text-muted-foreground hover:text-foreground"),children:[e.jsx(As,{className:"h-3 w-3"}),e.jsx("span",{children:m?"Rendered":"Raw"})]}),p&&!l&&!v&&t.content&&e.jsxs("button",{type:"button",onClick:q,title:"Edit & resend this prompt",className:"opacity-0 group-hover:opacity-100 transition-opacity text-xs text-muted-foreground hover:text-foreground inline-flex items-center gap-1",children:[e.jsx(At,{className:"h-3 w-3"}),e.jsx("span",{children:"Edit"})]}),t.role==="assistant"&&t.content&&!t.streaming&&e.jsxs("button",{type:"button",onClick:()=>C(t.id),title:R?"Unpin":"Pin this answer",className:k("text-xs inline-flex items-center gap-1 transition-opacity",R?"text-amber-500 hover:text-amber-600 opacity-100":"opacity-0 group-hover:opacity-100 text-muted-foreground hover:text-foreground"),children:[R?e.jsx(Is,{className:"h-3 w-3"}):e.jsx(Pt,{className:"h-3 w-3"}),e.jsx("span",{children:R?"Pinned":"Pin"})]}),X&&t.content&&!t.streaming&&e.jsxs("button",{type:"button",onClick:G,title:"Regenerate this response",className:"opacity-0 group-hover:opacity-100 transition-opacity text-xs text-muted-foreground hover:text-foreground inline-flex items-center gap-1",children:[e.jsx(Ae,{className:"h-3 w-3"}),e.jsx("span",{children:"Retry"})]})]})]})]})});function Io(){const s=z(i=>i.mode),t=z(i=>i.modes),{listModes:n,switchMode:r}=de(),[a,o]=d.useState(!1),l=d.useRef(null);d.useEffect(()=>{a&&n()},[a,n]),d.useEffect(()=>{if(!a)return;const i=m=>{var x;(x=l.current)!=null&&x.contains(m.target)||o(!1)},u=m=>{m.key==="Escape"&&o(!1)};return document.addEventListener("mousedown",i),document.addEventListener("keydown",u),()=>{document.removeEventListener("mousedown",i),document.removeEventListener("keydown",u)}},[a]);const c=t.length>0?t:[{id:"default",name:"Default",description:"Standard agent behaviour"}];return e.jsxs("div",{ref:l,className:"relative shrink-0",children:[e.jsxs("button",{type:"button",onClick:()=>o(i=>!i),className:k("flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium","bg-accent/40 text-foreground hover:bg-accent transition-colors border border-transparent hover:border-primary/30"),title:"Active mode",children:["mode: ",e.jsx("span",{className:"font-mono",children:s||"default"}),e.jsx(Ce,{className:"h-3 w-3 opacity-60"})]}),a&&e.jsxs("div",{className:"absolute top-full left-0 mt-1 w-64 rounded-md border bg-popover shadow-lg z-30 py-1",children:[e.jsx("div",{className:"px-3 py-1.5 text-[10px] uppercase tracking-wider text-muted-foreground border-b",children:"Mode"}),c.map(i=>e.jsxs("button",{type:"button",onClick:()=>{r(i.id),o(!1)},className:k("w-full text-left px-3 py-2 hover:bg-accent/40 flex items-start gap-2",i.id===s&&"bg-accent/30"),children:[e.jsx(mt,{className:k("h-3.5 w-3.5 mt-0.5 shrink-0",i.id===s?"opacity-100 text-primary":"opacity-0")}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-xs font-mono",children:i.id}),i.description&&e.jsx("div",{className:"text-[11px] text-muted-foreground leading-snug",children:i.description})]})]},i.id))]})]})}function Po(){const s=P(m=>m.searchOpen),t=P(m=>m.setSearchOpen),n=P(m=>m.searchQuery),r=P(m=>m.setSearchQuery),a=M(m=>m.messages),o=d.useRef(null),[l,c]=d.useState(0);d.useEffect(()=>{s&&requestAnimationFrame(()=>{var m;return(m=o.current)==null?void 0:m.focus()})},[s]);const i=d.useMemo(()=>{const m=n.trim().toLowerCase();return m?a.filter(x=>x.role==="tool"?(x.toolName??"").toLowerCase().includes(m)||(x.toolResult??"").toLowerCase().includes(m)||JSON.stringify(x.toolInput??"").toLowerCase().includes(m):x.content.toLowerCase().includes(m)).map(x=>x.id):[]},[a,n]);if(d.useEffect(()=>{l>=i.length&&c(0)},[i,l]),d.useEffect(()=>{var j;const m=window,x=(j=m.CSS)==null?void 0:j.highlights,p=m.Highlight;if(!x||!p)return;const b=()=>{x.delete("chat-search"),x.delete("chat-search-active")},y=n.trim();if(!y||!s){b();return}const w=y.toLowerCase(),N=[],v=[],h=i[l];for(const C of document.querySelectorAll("[data-message-id]")){const R=C.dataset.messageId===h,I=document.createTreeWalker(C,NodeFilter.SHOW_TEXT);let F=I.nextNode();for(;F;){const K=F.nodeValue??"";if(K.length>0){const X=K.toLowerCase();let G=0;for(;G<=X.length-w.length;){const V=X.indexOf(w,G);if(V===-1)break;const q=document.createRange();q.setStart(F,V),q.setEnd(F,V+w.length),N.push(q),R&&v.push(q),G=V+w.length}}F=I.nextNode()}}return N.length>0?x.set("chat-search",new p(...N)):x.delete("chat-search"),v.length>0?x.set("chat-search-active",new p(...v)):x.delete("chat-search-active"),b},[n,i,l,s]),d.useEffect(()=>{const m=i[l];if(!m)return;const x=document.querySelector(`[data-message-id="${m}"]`);x&&x.scrollIntoView({behavior:"smooth",block:"center"})},[i,l]),!s)return null;const u=m=>{i.length!==0&&c(x=>(x+m+i.length)%i.length)};return e.jsx("div",{className:"absolute top-2 right-4 z-30 w-[28rem] max-w-[calc(100%-2rem)] rounded-lg border bg-popover shadow-xl",children:e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[e.jsx(je,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("input",{ref:o,value:n,onChange:m=>r(m.target.value),onKeyDown:m=>{m.key==="Escape"?(m.preventDefault(),t(!1)):m.key==="Enter"?(m.preventDefault(),u(m.shiftKey?-1:1)):m.key==="ArrowDown"?(m.preventDefault(),u(1)):m.key==="ArrowUp"&&(m.preventDefault(),u(-1))},placeholder:"Search in chat…",className:"flex-1 bg-transparent outline-none text-sm placeholder:text-muted-foreground"}),e.jsx("span",{className:"text-xs text-muted-foreground tabular-nums shrink-0",children:i.length===0?n?"0":"":`${l+1} / ${i.length}`}),e.jsx("button",{type:"button",onClick:()=>u(-1),disabled:i.length===0,className:k("p-1 rounded hover:bg-muted disabled:opacity-30 disabled:cursor-not-allowed"),title:"Previous hit",children:e.jsx(Ot,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button",onClick:()=>u(1),disabled:i.length===0,className:k("p-1 rounded hover:bg-muted disabled:opacity-30 disabled:cursor-not-allowed"),title:"Next hit",children:e.jsx(Ft,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button",onClick:()=>t(!1),className:"p-1 rounded hover:bg-muted text-muted-foreground",title:"Close (Esc)",children:e.jsx(be,{className:"h-3.5 w-3.5"})})]})})}const ts=d.createContext(void 0);function Oo({children:s,defaultTheme:t="system",storageKey:n="wrongstack-theme"}){const{setTheme:r}=B(),[a,o]=d.useState(()=>typeof window<"u"&&localStorage.getItem(n)||t);d.useEffect(()=>{const c=window.document.documentElement;if(c.classList.remove("light","dark"),a==="system"){const i=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";c.classList.add(i)}else c.classList.add(a)},[a]);const l={theme:a,setTheme:c=>{localStorage.setItem(n,c),o(c),r(c)}};return e.jsx(ts.Provider,{value:l,children:s})}function yt(){const s=d.useContext(ts);if(s===void 0)throw new Error("useTheme must be used within a ThemeProvider");return s}const Fo=[{value:"light",icon:lt,label:"Light"},{value:"dark",icon:ct,label:"Dark"},{value:"system",icon:dt,label:"System"}];function _o({className:s}){const{theme:t,setTheme:n}=yt();return e.jsx("div",{className:k("inline-flex items-center gap-0.5 rounded-lg border border-border bg-card/70 p-0.5 shadow-sm",s),role:"radiogroup","aria-label":"Theme",children:Fo.map(({value:r,icon:a,label:o})=>{const l=t===r;return e.jsx("button",{type:"button",role:"radio","aria-checked":l,title:`${o} theme`,"aria-label":`${o} theme`,onClick:()=>n(r),className:k("grid h-7 w-7 place-items-center rounded-md transition-all duration-150",l?"bg-primary/15 text-primary shadow-[inset_0_0_0_1px_hsl(var(--primary)/0.35)]":"text-muted-foreground hover:bg-accent hover:text-foreground"),children:e.jsx(a,{className:"h-3.5 w-3.5",strokeWidth:2.2})},r)})})}function Wo(s){if(s<1e3)return`${s}ms`;if(s<6e4)return`${(s/1e3).toFixed(s<1e4?2:1)}s`;const t=Math.floor(s/6e4),n=Math.floor(s%6e4/1e3);return`${t}m${n}s`}const Uo=d.memo(function({tools:t,defaultOpen:n=!1,isContinuation:r=!1}){const[a,o]=d.useState(n);if(t.length===1)return e.jsx(Fe,{message:t[0],isFirst:!0,isContinuation:r});const l=t.filter(p=>p.toolResult===void 0).length,c=t.filter(p=>p.isError).length,i=t.reduce((p,b)=>p+(b.toolDurationMs??0),0),u=Array.from(new Set(t.map(p=>p.toolName).filter(Boolean))),m=u.slice(0,3).join(", "),x=u.length>3?` +${u.length-3}`:"";return e.jsxs("div",{className:"flex gap-3 animate-message",children:[r?e.jsx("div",{className:"flex-shrink-0 w-8 h-8","aria-hidden":!0}):e.jsx("div",{className:"flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center bg-secondary text-secondary-foreground ring-2 ring-offset-2 ring-offset-background ring-secondary/20",children:e.jsx(Ne,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex flex-col gap-1.5 max-w-[85%] flex-1 min-w-0",children:[e.jsxs("button",{type:"button",onClick:()=>o(p=>!p),className:k("flex items-center gap-2 text-sm font-medium cursor-pointer select-none","hover:bg-muted/50 rounded-lg px-2 py-1.5 -mx-2 transition-colors","border border-border/40 bg-muted/30"),children:[a?e.jsx(Ce,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(We,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Ne,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("span",{className:"font-mono text-xs",children:[t.length," tool call",t.length===1?"":"s"]}),l>0?e.jsx(fe,{className:"h-3 w-3 animate-spin text-amber-500"}):c>0?e.jsx(nt,{className:"h-3 w-3 text-destructive"}):e.jsx(he,{className:"h-3 w-3 text-green-500"}),i>0&&e.jsx("span",{className:"text-xs text-muted-foreground tabular-nums font-normal",children:Wo(i)}),m&&e.jsxs("span",{className:"text-xs text-muted-foreground/80 font-mono truncate",children:["· ",m,x]})]}),a&&e.jsx("div",{className:"space-y-2 pl-3 border-l-2 border-border/40 ml-2",children:t.map(p=>e.jsx(Fe,{message:p,isFirst:!1},p.id))})]})]})}),Ko=[{icon:je,title:"Explore",hint:"Understand the code before changing it",tone:"text-blue-600 dark:text-blue-400 bg-blue-500/10 border-blue-500/20",prompts:["Walk me through this codebase: list the top-level packages, the role of each, and how they depend on one another. Highlight any cross-cutting abstractions I should understand first.","Find every place where the WebSocket protocol is defined or consumed (server handlers, client send/receive, type contracts). Show me the message-type table and any gaps where the type isn't enforced.","Locate the entrypoint that boots the agent for normal runs. Trace the call chain from CLI launch all the way to the first model call — what middleware, hooks, and tools are wired along the way?"]},{icon:Me,title:"Build",hint:"Add a feature end-to-end",tone:"text-emerald-600 dark:text-emerald-400 bg-emerald-500/10 border-emerald-500/20",prompts:["Add a slash command `/export` that dumps the current chat (messages + tool calls + usage) as a markdown file to ~/.wrongstack/exports/ and surfaces a 'saved to X' toast. Wire backend + ws-client + slash menu entry.","Create a notification toast system (Zustand store + portal-rendered <Toast/> component) and migrate every existing `key.operation_result` success/failure message to use it instead of dropping into chat.","Add structured JSON logging to the WebSocket server: each handler logs `{ts, level, type, payload}` to ~/.wrongstack/logs/webui.jsonl. Make it tail-friendly and respect the existing log.level config."]},{icon:Os,title:"Debug",hint:"Track a problem to its root cause",tone:"text-amber-600 dark:text-amber-400 bg-amber-500/10 border-amber-500/20",prompts:["Something feels off with token accounting — the cost chip and the per-message tally drift apart over a long session. Reproduce locally if you can, then propose a fix. Start by reading the TokenCounter + provider.response handler.","The WebSocket sometimes silently stops streaming text mid-response on lossy networks. Check the reconnect logic, message queue, and how we handle a half-completed text_delta stream after a reconnect.","I want to know why ctx % climbs so fast in long sessions. Use the existing /debug context breakdown to identify the largest contributors and propose three concrete pruning strategies (with token savings estimates)."]},{icon:Rt,title:"Refactor",hint:"Clean up without breaking behavior",tone:"text-violet-600 dark:text-violet-400 bg-violet-500/10 border-violet-500/20",prompts:["Find duplicated logic between packages/cli/src/webui-server.ts and packages/webui/src/server/index.ts. Extract the shared bits into a single source of truth (likely the webui package) and update the CLI to import it.","Look at the Zustand stores in packages/webui/src/stores/index.ts — anything that should be a derived selector instead of stored state? Anything persisted that shouldn't be? Propose a leaner shape and migration plan.","Audit the slash command dispatcher: pull each command's run logic into its own module under packages/webui/src/commands/, make the registry data-driven, and ensure /help auto-generates from the registry (not a hardcoded list)."]}],zo=[{name:"/help",hint:"list every slash command"},{name:"/diag",hint:"runtime diagnostics"},{name:"/stats",hint:"tokens · cache · cost · elapsed"},{name:"/tools",hint:"show registered tools"},{name:"/memory",hint:"show remembered notes"},{name:"/compact",hint:"shrink context"},{name:"/clear",hint:"wipe current context"},{name:"/new",hint:"fresh session"}];function Ge(s){var r;const t=document.querySelector("textarea");if(!t)return;const n=(r=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value"))==null?void 0:r.set;n==null||n.call(t,s),t.dispatchEvent(new Event("input",{bubbles:!0})),t.focus()}function qo(){const{projectName:s}=z(),{provider:t,model:n}=B(),r=B(w=>w.wsConnected),a=B(w=>w.wsUrl),o=P(w=>w.setCurrentView),[l,c]=d.useState(void 0);d.useEffect(()=>{if(!r)return;const w=ae(a),N=w.on("providers.saved",v=>{var j;const h=v.payload;c(((j=h.providers)==null?void 0:j.length)??0)});return w.listSavedProviders(),()=>{N()}},[r,a]);const u=P(w=>w.promptHistory).slice(0,6),{listSessions:m,resumeSession:x}=de(),p=ke(w=>w.entries);d.useEffect(()=>{r&&p.length===0&&m(10)},[r]);const b=P(w=>w.sessionNicknames),y=p.filter(w=>!w.isCurrent).slice(0,4);return e.jsxs("div",{className:"flex flex-col gap-8 py-8 px-2 max-w-5xl mx-auto w-full",children:[e.jsxs("div",{className:"flex flex-col items-center text-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-gradient-to-br from-primary via-primary to-primary/60 flex items-center justify-center shadow-lg shadow-primary/20",children:e.jsx(Ue,{className:"h-7 w-7 text-primary-foreground"})}),e.jsx("div",{className:"absolute -inset-3 bg-gradient-to-r from-transparent via-primary/10 to-transparent animate-pulse rounded-full -z-10"})]}),e.jsxs("div",{children:[e.jsxs("h2",{className:"text-2xl font-semibold tracking-tight",children:["Where do you want to start",s?e.jsxs(e.Fragment,{children:[" in ",e.jsx("span",{className:"text-primary",children:s})]}):"","?"]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-2 max-w-2xl mx-auto leading-relaxed",children:["WrongStack is connected to your project and ready to read, edit, run commands, search the codebase, track todos, and remember context across sessions. Pick a starting prompt below, write your own, or type ",e.jsx("span",{className:"font-mono text-foreground/80",children:"/"})," ","for the full command palette."]}),t&&n&&e.jsxs("p",{className:"text-xs text-muted-foreground/70 mt-2 font-mono",children:[t," / ",n]})]})]}),r&&l===0&&e.jsxs("button",{type:"button",onClick:()=>o("settings"),className:k("group rounded-xl border bg-gradient-to-br from-amber-500/10 via-amber-500/5 to-transparent","border-amber-500/30 hover:border-amber-500/50 transition-colors","p-4 flex items-center gap-4 text-left"),children:[e.jsx("span",{className:"flex items-center justify-center w-12 h-12 rounded-lg bg-amber-500/15 text-amber-600 dark:text-amber-400 shrink-0",children:e.jsx(Ps,{className:"h-6 w-6"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"text-base font-semibold mb-1",children:"No API key configured yet"}),e.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:"Register a provider in Settings before sending a message — otherwise the agent has nothing to talk to. Anthropic, OpenAI, Google, and any OpenAI-compatible endpoint all work."})]}),e.jsxs("span",{className:"flex items-center gap-1 text-xs text-amber-600 dark:text-amber-400 font-medium shrink-0 group-hover:translate-x-0.5 transition-transform",children:["Open Settings ",e.jsx(_t,{className:"h-3.5 w-3.5"})]})]}),e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:Ko.map(w=>{const N=w.icon;return e.jsxs("div",{className:"rounded-xl border bg-card/40 backdrop-blur-sm p-4 flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:k("flex items-center justify-center w-8 h-8 rounded-lg border",w.tone),children:e.jsx(N,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:w.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:w.hint})]})]}),e.jsx("div",{className:"flex flex-col gap-1.5",children:w.prompts.map((v,h)=>e.jsx("button",{type:"button",onClick:()=>Ge(v),className:"text-left text-xs leading-relaxed text-foreground/80 hover:text-foreground border border-transparent hover:border-border/60 rounded-lg px-3 py-2 hover:bg-muted/40 transition-colors line-clamp-3",title:v,children:v},h))})]},w.title)})}),y.length>0&&e.jsxs("div",{className:"rounded-xl border bg-muted/20 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Lt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium",children:"Pick back up"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:y.map(w=>e.jsxs("button",{type:"button",onClick:()=>x(w.id),className:"text-left rounded-lg border border-border/40 bg-background/60 hover:border-primary/40 hover:bg-accent/30 px-3 py-2 transition-colors group/sess",title:w.title,children:[e.jsx("div",{className:"text-sm font-medium truncate text-foreground group-hover/sess:text-primary",children:b[w.id]||w.title||"(empty)"}),e.jsxs("div",{className:"text-[10px] text-muted-foreground font-mono truncate mt-0.5",children:[w.provider,"/",w.model,w.tokenTotal>0&&e.jsxs("span",{className:"ml-2",children:["· ",w.tokenTotal.toLocaleString()," tok"]})]})]},w.id))})]}),u.length>0&&e.jsxs("div",{className:"rounded-xl border bg-muted/20 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Oe,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium",children:"Recent prompts"})]}),e.jsx("div",{className:"flex flex-col gap-1.5",children:u.filter(w=>!w.startsWith("/")).slice(0,5).map((w,N)=>e.jsx("button",{type:"button",onClick:()=>Ge(w),className:"text-left text-xs leading-relaxed text-muted-foreground hover:text-foreground border border-transparent hover:border-border/60 rounded-lg px-3 py-2 hover:bg-background/60 transition-colors line-clamp-2",title:w,children:w},N))})]}),e.jsxs("div",{className:"rounded-xl border bg-muted/20 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Wt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium",children:"Quick commands"})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:zo.map(w=>e.jsxs("button",{type:"button",onClick:()=>Ge(w.name),className:"text-left flex flex-col gap-0.5 rounded-md border border-border/40 bg-background/60 px-3 py-2 hover:border-primary/40 hover:bg-accent/40 transition-colors",children:[e.jsx("span",{className:"font-mono text-xs text-foreground",children:w.name}),e.jsx("span",{className:"text-[11px] text-muted-foreground truncate",children:w.hint})]},w.name))})]})]})}const Ke=d.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(Ut,{ref:r,className:k("relative overflow-hidden",s),...n,children:[e.jsx(Fs,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(ss,{}),e.jsx(_s,{})]}));Ke.displayName=Ut.displayName;const ss=d.forwardRef(({className:s,orientation:t="vertical",...n},r)=>e.jsx(Kt,{ref:r,orientation:t,className:k("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",s),...n,children:e.jsx(Ws,{className:"relative flex-1 rounded-full bg-border"})}));ss.displayName=Kt.displayName;function $e(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(s>=1e4?0:1)}k`:String(s)}function Ho(){const s=M(r=>r.thinkingBuffer);if(!s)return null;const n=s.split(`
91
+ `).slice(-6).join(`
92
+ `).trim();return e.jsxs("div",{className:"flex gap-3 animate-message",children:[e.jsx("div",{className:"flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center bg-violet-500/10 text-violet-600 dark:text-violet-400 ring-2 ring-offset-2 ring-offset-background ring-violet-500/20",children:e.jsx(Dt,{className:"h-4 w-4 animate-pulse"})}),e.jsxs("div",{className:"flex flex-col gap-1 max-w-[85%] min-w-0",children:[e.jsx("span",{className:"text-xs font-medium text-violet-600 dark:text-violet-400 px-1",children:"Thinking…"}),e.jsx("div",{className:"rounded-2xl rounded-bl-md px-3 py-2 bg-violet-500/[0.04] border border-violet-500/20 text-foreground/80",children:e.jsx("pre",{className:"whitespace-pre-wrap break-words font-sans text-xs leading-relaxed italic max-h-32 overflow-hidden",children:n||"…"})})]})]})}function Bo(){const{messages:s,isLoading:t}=M(),n=P(g=>g.setPaletteOpen),r=P(g=>g.setShortcutsOpen),a=P(g=>g.sidebarOpen),o=P(g=>g.toggleSidebar),l=P(g=>g.compactMode),{totalTokens:c,startTime:i,lastInputTokens:u,maxContext:m,projectName:x,iteration:p}=z(),{wsConnected:b,wsStatus:y,provider:w,model:N}=B(),{setCurrentView:v}=P(),h=d.useRef(null),j=m>0&&u>0?Math.min(100,Math.round(u/m*100)):0,C=j>=85?"bg-red-500/15 text-red-600 dark:text-red-400":j>=70?"bg-amber-500/15 text-amber-600 dark:text-amber-400":"bg-muted text-muted-foreground",[D,R]=d.useState(!0),[I,F]=d.useState(0),[K,X]=d.useState(!1),G=d.useRef(s.length),V=d.useCallback(()=>{var g;return((g=h.current)==null?void 0:g.querySelector("[data-radix-scroll-area-viewport]"))??null},[]);d.useEffect(()=>{const g=V();if(!g)return;const E=()=>{const _=g.scrollHeight-g.scrollTop-g.clientHeight<120;R(_),_&&(F(0),G.current=s.length);const ie=g.scrollTop>g.clientHeight&&g.scrollHeight>g.clientHeight*2.5;X(ie)};return g.addEventListener("scroll",E,{passive:!0}),()=>g.removeEventListener("scroll",E)},[V,s.length]),d.useEffect(()=>{const g=V();if(g)if(D)g.scrollTop=g.scrollHeight,G.current=s.length;else{const E=s.length-G.current;E>0&&F(E)}},[s,D,V]);const q=d.useCallback(()=>{const g=V();g&&(g.scrollTo({top:g.scrollHeight,behavior:"smooth"}),R(!0),F(0),G.current=s.length)},[V,s.length]),ee=d.useCallback(()=>{const g=V();g&&g.scrollTo({top:0,behavior:"smooth"})},[V]),[Y,$]=d.useState(null),[W,A]=d.useState(()=>Date.now()),O=d.useRef(null);d.useEffect(()=>{t&&Y===null&&$(Date.now()),!t&&Y!==null&&$(null)},[t,Y]),d.useEffect(()=>{if(!t)return;const g=setInterval(()=>A(Date.now()),500);return()=>clearInterval(g)},[t]);const L=g=>{if(!g)return"--";const E=Math.floor((Date.now()-g)/1e3);if(E<60)return`${E}s`;const Q=Math.floor(E/60),_=E%60;return`${Q}m ${_}s`},T=(()=>{if(!t)return"idle";const g=s[s.length-1];return(g==null?void 0:g.role)==="assistant"&&!!g.content&&g.streaming?"streaming":"thinking"})(),f=T==="idle"?"bg-muted text-muted-foreground":T==="streaming"?"bg-blue-500/10 text-blue-600 dark:text-blue-400":"bg-amber-500/10 text-amber-600 dark:text-amber-400",S=m>0&&u>0||c.input>0||!!i;return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("header",{className:"flex flex-col border-b bg-card shrink-0",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:[!a&&e.jsx(J,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",onClick:o,title:"Open sidebar (Ctrl+\\\\)",children:e.jsx(Us,{className:"h-4 w-4"})}),!a&&e.jsx("div",{className:"flex items-center gap-1.5 shrink-0 mr-1",children:e.jsx("div",{className:"w-5 h-5 rounded bg-primary flex items-center justify-center",children:e.jsx(Ue,{className:"h-3 w-3 text-primary-foreground"})})}),e.jsx(ho,{wsStatus:y,wsConnected:b}),e.jsxs("span",{className:k("flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[11px] font-medium shrink-0 tabular-nums",f),title:`Agent state: ${T}`,children:[T!=="idle"&&e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-current animate-pulse"}),e.jsx("span",{children:T})]}),x&&e.jsxs("span",{className:"flex items-center gap-1 text-[11px] text-muted-foreground shrink-0 min-w-0",title:`Project: ${x}`,children:[e.jsx(Ks,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate max-w-[12rem]",children:x})]}),e.jsxs("button",{type:"button",onClick:()=>P.getState().setModelSwitcherOpen(!0),className:"group flex items-center gap-1 px-2 py-0.5 rounded-md border bg-background/50 hover:bg-accent hover:border-primary/40 transition-colors text-[11px] min-w-0 shrink-0",title:"Change provider / model (Ctrl+M)",children:[e.jsx(Se,{className:"h-3 w-3 text-muted-foreground group-hover:text-foreground shrink-0"}),e.jsxs("span",{className:"font-mono truncate max-w-[16rem]",children:[e.jsx("span",{className:"text-muted-foreground",children:w||"no-provider"}),e.jsx("span",{className:"text-muted-foreground/40 mx-0.5",children:"/"}),e.jsx("span",{className:"font-medium",children:N||"no-model"})]})]}),e.jsx(Io,{}),e.jsx(go,{}),p&&e.jsxs("span",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[11px] font-medium bg-primary/10 text-primary shrink-0",title:"Agent iteration",children:[e.jsx(zs,{className:"h-3 w-3 animate-pulse"}),"iter ",p.index,p.max>0?`/${p.max}`:""]})]}),e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[e.jsx(J,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>n(!0),title:"Command palette (Ctrl+K)",children:e.jsx(qs,{className:"h-4 w-4"})}),e.jsx(_o,{className:"mx-0.5"}),e.jsx(J,{variant:"ghost",size:"icon",className:"h-7 w-7 font-mono text-xs",onClick:()=>r(!0),title:"Keyboard shortcuts (?)",children:"?"}),e.jsx(J,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>v("settings"),title:"Settings",children:e.jsx(it,{className:"h-4 w-4"})})]})]}),S&&e.jsxs("div",{className:"flex items-center justify-between gap-3 px-3 py-1 border-t bg-muted/20 text-[11px] text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1 tabular-nums",children:[m>0&&u>0&&e.jsxs("span",{className:k("flex items-center gap-1 px-1.5 py-0.5 rounded-full font-medium shrink-0",C),title:`Last input: ${u.toLocaleString()} / ${m.toLocaleString()} tokens`,children:["ctx ",j,"% · ",$e(u),"/",$e(m)]}),c.input>0&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"font-medium text-foreground",children:$e(c.input)}),e.jsx("span",{children:"in"})]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"font-medium text-foreground",children:$e(c.output)}),e.jsx("span",{children:"out"})]}),c.cacheRead&&c.cacheRead>0&&(()=>{const g=(c.cacheRead??0)+c.input,E=g>0?Math.round((c.cacheRead??0)/g*100):0;return e.jsxs("span",{className:"flex items-center gap-1",title:`Cache hit ratio: ${E}%`,children:[e.jsx("span",{className:"font-medium text-foreground",children:$e(c.cacheRead)}),e.jsxs("span",{children:["cache (",E,"%)"]})]})})(),e.jsx(bo,{})]})]}),i&&e.jsx("span",{className:"text-muted-foreground/70 tabular-nums shrink-0",children:L(i)})]})]}),e.jsxs("div",{className:"flex-1 relative overflow-hidden",children:[e.jsx(Po,{}),!D&&e.jsxs("button",{type:"button",onClick:q,className:k("absolute bottom-4 left-1/2 -translate-x-1/2 z-10","flex items-center gap-2 px-4 py-2 rounded-full shadow-lg","bg-primary text-primary-foreground text-xs font-medium","hover:bg-primary/90 transition-colors animate-message"),children:[e.jsx(Ft,{className:"h-3.5 w-3.5"}),I>0?`${I} new message${I===1?"":"s"}`:"Jump to latest"]}),K&&e.jsxs("button",{type:"button",onClick:ee,title:"Scroll to top (oldest)",className:k("absolute top-3 right-3 z-10","flex items-center gap-1 px-2.5 py-1 rounded-full shadow-md border","bg-background/90 backdrop-blur-sm text-[11px] text-muted-foreground","hover:text-foreground hover:bg-background transition-colors animate-message"),children:[e.jsx(Ot,{className:"h-3 w-3"}),e.jsx("span",{children:"Top"})]}),e.jsx(Ke,{className:"h-full",ref:h,children:e.jsxs("div",{className:k("mx-auto pb-8",l?"max-w-5xl p-3 space-y-3":"max-w-5xl p-4 space-y-6"),children:[s.length===0&&!t&&e.jsx(qo,{}),(()=>{const g=[];for(let U=0;U<s.length;U++){const H=s[U];if(H.role==="tool"){const Z=g[g.length-1];Z&&Z.kind==="tools"?Z.tools.push(H):g.push({kind:"tools",tools:[H],key:H.id})}else{const Z=s[U-1];g.push({kind:"msg",message:H,isFirst:!Z||Z.role!==H.role})}}const E=[];for(const U of g){if(U.kind==="msg"&&U.message.role==="user"){E.push({kind:"user",message:U.message,key:U.message.id});continue}const H=E[E.length-1];if(H&&H.kind==="agent")H.items.push(U);else{const Z=U.kind==="msg"?U.message.id:U.key;E.push({kind:"agent",items:[U],key:Z})}}let Q=null;const _=U=>{const H=new Date(U);return`${H.getFullYear()}-${H.getMonth()}-${H.getDate()}`},ie=U=>{const H=new Date(U),Z=new Date,se=new Date(Date.now()-864e5);return _(U)===_(Z.getTime())?"Today":_(U)===_(se.getTime())?"Yesterday":H.toLocaleDateString(void 0,{weekday:"short",month:"short",day:"numeric",year:H.getFullYear()===Z.getFullYear()?void 0:"numeric"})},ce=U=>{if(U.kind==="user")return U.message.timestamp;const H=U.items[0];return H.kind==="msg"?H.message.timestamp:H.tools[0].timestamp},te=[];for(let U=0;U<E.length;U++){const H=E[U],Z=ce(H),se=_(Z);if(se!==Q&&(te.push(e.jsxs("div",{className:"flex items-center gap-3 py-1 text-[11px] text-muted-foreground/70 uppercase tracking-wider font-medium",children:[e.jsx("div",{className:"flex-1 h-px bg-border/50"}),e.jsx("span",{children:ie(Z)}),e.jsx("div",{className:"flex-1 h-px bg-border/50"})]},`day-${se}-${U}`)),Q=se),H.kind==="user"){te.push(e.jsx(Fe,{message:H.message,isFirst:!0},H.key));continue}const le=U===E.length-1;te.push(e.jsx("div",{className:k(l?"space-y-1":"space-y-1.5"),children:H.items.map((oe,re)=>{const ue=re>0;if(oe.kind==="msg")return e.jsx(Fe,{message:oe.message,isFirst:!ue&&oe.isFirst,isContinuation:ue},oe.message.id);const ze=le&&re===H.items.length-1&&t&&oe.tools.some(cs=>cs.toolResult===void 0);return e.jsx(Uo,{tools:oe.tools,defaultOpen:ze,isContinuation:ue},oe.key)})},H.key))}return te})(),e.jsx(Ho,{}),t&&(()=>{const g=s[s.length-1],E=s.filter(U=>U.role==="tool"&&U.toolResult===void 0);let Q="Thinking…";if(E.length>0){const U=Array.from(new Set(E.map(se=>se.toolName).filter(Boolean))),H=U.slice(0,2).join(", "),Z=U.length>2?` +${U.length-2}`:"";Q=E.length===1?`Running ${H||"tool"}…`:`Running ${E.length} tools (${H}${Z})…`}else(g==null?void 0:g.role)==="assistant"&&g.content?Q="Writing reply…":(g==null?void 0:g.role)==="tool"&&g.toolResult!==void 0&&(Q="Thinking about the next step…");const _=Y?Math.max(0,Math.floor((W-Y)/1e3)):0,ie=_<60?`${_}s`:`${Math.floor(_/60)}m ${_%60}s`;let ce="";const te=(g==null?void 0:g.role)==="assistant"&&g.streaming&&g.content?g:null;if(te){const U=O.current;if(!U||U.id!==te.id)O.current={id:te.id,at:Date.now(),len:te.content.length};else{const H=Math.max(1,W-U.at),Z=Math.max(0,te.content.length-U.len);if(H>500&&Z>0){const se=Z*1e3/H;ce=se>=1e3?`${(se/1e3).toFixed(1)}k ch/s`:`${Math.round(se)} ch/s`}}}else O.current&&(O.current=null);return e.jsxs("div",{className:"flex gap-3 animate-message",children:[e.jsx("div",{className:"flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center bg-accent text-accent-foreground ring-2 ring-offset-2 ring-offset-background ring-accent/20",children:e.jsx(pt,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex flex-col gap-1.5",children:e.jsx("div",{className:"rounded-2xl px-4 py-3 bg-card border text-foreground",children:e.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[e.jsxs("span",{className:"flex gap-1",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-primary/70 animate-bounce [animation-delay:-0.3s]"}),e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-primary/70 animate-bounce [animation-delay:-0.15s]"}),e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-primary/70 animate-bounce"})]}),e.jsx("span",{className:"text-foreground/90",children:Q}),e.jsx("span",{className:"text-xs text-muted-foreground tabular-nums",children:ie}),p&&e.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:["· iter ",p.index,p.max>0?`/${p.max}`:""]}),ce&&e.jsxs("span",{className:"text-xs text-muted-foreground/80 tabular-nums",children:["· ",ce]})]})})})]})})()]})})]}),e.jsx("div",{className:"border-t bg-card/50 backdrop-blur supports-[backdrop-filter]:bg-card/50 p-4 shrink-0",children:e.jsxs("div",{className:"max-w-5xl mx-auto",children:[e.jsx(xo,{}),e.jsx("p",{className:"text-xs text-center text-muted-foreground/50 mt-2",children:"Press Enter to send, Shift+Enter for new line"})]})})]})}function Vo({sessionId:s,className:t}){const[n,r]=d.useState([]),[a,o]=d.useState(!1),[l,c]=d.useState(null),[i,u]=d.useState(null),[m,x]=d.useState(0),[p,b]=d.useState(!1),y=B(C=>C.wsUrl),w=ae(y);d.useEffect(()=>{const C=[];return C.push(w.on("collab.state",D=>{const R=D.payload;R.sessionId===s&&r(R.participants??[])})),C.push(w.on("collab.participant.joined",D=>{const R=D.payload;R.sessionId===s&&r(I=>I.some(F=>F.participantId===R.participantId)?I:[...I,{participantId:R.participantId,role:R.role,joinedAt:R.joinedAt}])})),C.push(w.on("collab.participant.left",D=>{const R=D.payload;if(R.sessionId!==s)return;const I=R.participantId;r(F=>F.filter(K=>K.participantId!==I))})),C.push(w.on("error",D=>{const R=D.payload;R.phase==="collab"&&(u(R.message),o(!1))})),C.push(w.on("collab.event",()=>{})),C.push(w.on("collab.annotation.added",D=>{var I;const R=D.payload;R.sessionId===s&&((I=R.annotation)!=null&&I.resolved||x(F=>F+1))})),C.push(w.on("collab.annotation.resolved",D=>{D.payload.sessionId===s&&x(I=>Math.max(0,I-1))})),C.push(w.on("collab.pause.granted",D=>{D.payload.sessionId===s&&b(!0)})),C.push(w.on("collab.pause.released",D=>{D.payload.sessionId===s&&b(!1)})),()=>{for(const D of C)D()}},[w,s]);const N=(C="observer")=>{u(null),w.send({type:"collab.join",payload:{sessionId:s,role:C}}),o(!0),c(C)},v=()=>{w.send({type:"collab.request_pause",payload:{sessionId:s}})},h=()=>{w.send({type:"collab.resume",payload:{sessionId:s}})},j=()=>{w.send({type:"collab.leave",payload:{sessionId:s}}),o(!1),r([])};return n.length===0&&!i?e.jsxs("div",{className:k("flex items-center gap-2 px-3 py-2 rounded-md border border-dashed border-border bg-card/40",t),children:[e.jsx(wt,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"No live observers"}),e.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[e.jsxs("button",{type:"button",onClick:()=>N("observer"),className:"inline-flex items-center gap-1 text-xs px-2 py-1 rounded bg-primary text-primary-foreground hover:bg-primary/90 transition-colors",title:"Join as a read-only observer (Phase 1)",children:[e.jsx(Hs,{className:"w-3 h-3"}),"observer"]}),e.jsxs("button",{type:"button",onClick:()=>N("annotator"),className:"inline-flex items-center gap-1 text-xs px-2 py-1 rounded border border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300 hover:bg-amber-500/20 transition-colors",title:"Join as an annotator — leave inline notes on tool calls (Phase 2)",children:[e.jsx(jt,{className:"w-3 h-3"}),"annotator"]}),e.jsxs("button",{type:"button",onClick:()=>N("controller"),className:"inline-flex items-center gap-1 text-xs px-2 py-1 rounded border border-rose-500/40 bg-rose-500/10 text-rose-700 dark:text-rose-300 hover:bg-rose-500/20 transition-colors",title:"Join as a controller — can pause the agent loop (Phase 3)",children:[e.jsx(qe,{className:"w-3 h-3"}),"controller"]})]})]}):i?e.jsxs("div",{className:k("flex items-center gap-2 px-3 py-2 rounded-md border border-destructive/50 bg-destructive/10",t),role:"alert",children:[e.jsxs("span",{className:"text-xs text-destructive",children:["Collab: ",i]}),e.jsx("button",{type:"button",onClick:()=>{u(null),o(!1)},className:"ml-auto text-xs underline text-destructive",children:"dismiss"})]}):e.jsxs("div",{className:k("flex items-center gap-2 px-3 py-2 rounded-md border border-emerald-500/40 bg-emerald-500/5",t),children:[e.jsxs("span",{className:"relative flex h-2 w-2","aria-label":"Live",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75 animate-ping"}),e.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-emerald-500"})]}),e.jsx(wt,{className:"w-4 h-4 text-emerald-700 dark:text-emerald-400"}),e.jsxs("span",{className:"text-xs font-medium text-emerald-700 dark:text-emerald-300",children:[n.length," ",n.length===1?"observer":"observers"]}),m>0&&e.jsxs("span",{title:`${m} open annotation(s) — annotators reviewing this session`,className:"ml-2 inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded bg-amber-500/15 text-amber-700 dark:text-amber-300 border border-amber-500/30",children:[e.jsx(jt,{className:"w-3 h-3"}),m," note",m===1?"":"s"]}),p&&e.jsxs("span",{title:"Agent loop is paused — a controller is reviewing",className:"ml-2 inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded bg-rose-500/15 text-rose-700 dark:text-rose-300 border border-rose-500/40",children:[e.jsx(qe,{className:"w-3 h-3"}),"paused"]}),e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[n.slice(0,3).map(C=>e.jsxs("span",{title:`Joined ${new Date(C.joinedAt).toLocaleTimeString()}`,className:"inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded bg-emerald-500/10 text-emerald-700 dark:text-emerald-300",children:[e.jsx(zt,{className:"w-3 h-3"}),C.role]},C.participantId)),n.length>3&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["+",n.length-3]})]}),a&&l==="controller"&&(p?e.jsxs("button",{type:"button",onClick:h,className:"ml-auto inline-flex items-center gap-1 text-xs px-2 py-1 rounded border border-rose-500/40 bg-rose-500/10 text-rose-700 dark:text-rose-300 hover:bg-rose-500/20 transition-colors",title:"Resume the agent loop",children:[e.jsx(Bs,{className:"w-3 h-3"}),"Resume"]}):e.jsxs("button",{type:"button",onClick:v,className:"ml-auto inline-flex items-center gap-1 text-xs px-2 py-1 rounded border border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300 hover:bg-amber-500/20 transition-colors",title:"Pause the agent before the next tool call",children:[e.jsx(qe,{className:"w-3 h-3"}),"Pause agent"]})),a&&l!=="controller"&&e.jsxs("button",{type:"button",onClick:j,className:"ml-auto inline-flex items-center gap-1 text-xs px-2 py-1 rounded border border-border hover:bg-muted transition-colors",title:"Leave the observer session",children:[e.jsx(Vs,{className:"w-3 h-3"}),"Leave"]})]})}const Mt=Gs,Jo=Js,ns=d.forwardRef(({className:s,...t},n)=>e.jsx(qt,{ref:n,className:k("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),...t}));ns.displayName=qt.displayName;const st=d.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(Jo,{children:[e.jsx(ns,{}),e.jsxs(Ht,{ref:r,className:k("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:[t,e.jsxs(Qs,{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:[e.jsx(be,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));st.displayName=Ht.displayName;const os=({className:s,...t})=>e.jsx("div",{className:k("flex flex-col space-y-1.5 text-center sm:text-left",s),...t});os.displayName="DialogHeader";const rs=({className:s,...t})=>e.jsx("div",{className:k("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});rs.displayName="DialogFooter";const as=d.forwardRef(({className:s,...t},n)=>e.jsx(Bt,{ref:n,className:k("text-lg font-semibold leading-none tracking-tight",s),...t}));as.displayName=Bt.displayName;const is=d.forwardRef(({className:s,...t},n)=>e.jsx(Vt,{ref:n,className:k("text-sm text-muted-foreground",s),...t}));is.displayName=Vt.displayName;function Qo(s){return/edit|write|create|patch/i.test(s)?Xs:/bash|shell|exec|run|command/i.test(s)?Ne:/fetch|http|web|curl|request/i.test(s)?De:Me}function Go({toolName:s,input:t}){const n=es(s,t);if(n)return e.jsx("div",{className:"rounded-lg overflow-hidden border",children:e.jsx(Zt,{oldText:n.oldText,newText:n.newText,caption:n.caption})});if(typeof t=="object"&&t!==null){const r=t,a=r.command??r.cmd??r.script;if(typeof a=="string"&&a.trim().length>0)return e.jsxs("div",{className:"rounded-lg border bg-background/40 overflow-hidden",children:[e.jsxs("div",{className:"px-3 py-1.5 text-[10px] uppercase tracking-wider text-muted-foreground border-b bg-muted/40 flex items-center gap-1.5",children:[e.jsx(Ne,{className:"h-3 w-3"}),e.jsx("span",{children:"Command"})]}),e.jsxs("pre",{className:"px-3 py-2 text-xs font-mono whitespace-pre-wrap break-all max-h-40 overflow-auto",children:["$",a]})]});const o=r.url;if(typeof o=="string"){const l=r.method??"GET";return e.jsxs("div",{className:"rounded-lg border bg-background/40 px-3 py-2 text-xs font-mono",children:[e.jsx("span",{className:"text-muted-foreground",children:l.toUpperCase()})," ",e.jsx("span",{className:"break-all",children:o})]})}}return e.jsxs("div",{className:"p-3 rounded-lg bg-muted/50 border text-xs font-mono",children:[e.jsx("div",{className:"text-muted-foreground mb-2",children:"Input:"}),e.jsx("pre",{className:"whitespace-pre-wrap break-all max-h-60 overflow-auto",children:JSON.stringify(t,null,2)})]})}function Yo(){const{showConfirmDialog:s,confirmInfo:t,hideConfirm:n}=P(),{sendConfirm:r}=de(),a=d.useRef(null),o=i=>{t&&r(t.id,i),n()};if(d.useEffect(()=>{var u;if(!s)return;const i=m=>{var b;const x=m.target,p=(b=x==null?void 0:x.tagName)==null?void 0:b.toLowerCase();p==="input"||p==="textarea"||(m.key==="y"||m.key==="Y"?(m.preventDefault(),o("yes")):m.key==="n"||m.key==="N"||m.key==="Escape"?(m.preventDefault(),o("no")):m.key==="a"||m.key==="A"?(m.preventDefault(),o("always")):(m.key==="d"||m.key==="D")&&(m.preventDefault(),o("deny")))};return window.addEventListener("keydown",i),(u=a.current)==null||u.focus(),()=>window.removeEventListener("keydown",i)},[s,t==null?void 0:t.id]),!t)return e.jsx(Mt,{open:s,onOpenChange:()=>n(),children:e.jsx(st,{})});const l=Qo(t.toolName),c=/edit|write/i.test(t.toolName);return e.jsx(Mt,{open:s,onOpenChange:()=>n(),children:e.jsxs(st,{className:"sm:max-w-2xl border-yellow-500/50",ref:a,tabIndex:-1,children:[e.jsxs(os,{children:[e.jsxs(as,{className:"flex items-center gap-2",children:[e.jsx(Ys,{className:"h-5 w-5 text-yellow-500 animate-pulse"}),"Approval required: ",t.toolName]}),e.jsxs(is,{children:["The agent wants to ",c?"modify a file":"run this tool",". Review the request below and decide whether to proceed."]})]}),e.jsxs("div",{className:"py-2 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-muted",children:[e.jsx(l,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium font-mono truncate",children:t.toolName}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[c?"File modification":"Tool execution"," — preview below"]})]})]}),t.input!==void 0&&e.jsx(Go,{toolName:t.toolName,input:t.input}),t.suggestedPattern&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/20",children:[e.jsx(ot,{className:"h-4 w-4 text-yellow-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm min-w-0",children:[e.jsx("div",{className:"font-medium text-yellow-800 dark:text-yellow-200",children:"Trust pattern suggestion"}),e.jsx("div",{className:"font-mono text-xs mt-1 break-all",children:t.suggestedPattern}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["Picking ",e.jsx("span",{className:"font-medium",children:"Always"})," will whitelist matching calls for this project."]})]})]})]}),e.jsxs(rs,{className:"gap-2 sm:gap-2 flex-wrap",children:[e.jsxs(J,{variant:"outline",size:"sm",onClick:()=>o("deny"),title:"Reject this and all future calls matching the pattern (d)",children:["Deny always ",e.jsx("kbd",{className:"ml-1 text-[10px] border rounded px-1 bg-background",children:"d"})]}),e.jsxs(J,{variant:"outline",size:"sm",onClick:()=>o("no"),title:"Reject this single call (Esc / n)",children:["No ",e.jsx("kbd",{className:"ml-1 text-[10px] border rounded px-1 bg-background",children:"n"})]}),e.jsxs(J,{variant:"outline",size:"sm",onClick:()=>o("always"),title:"Approve and remember the pattern for the project (a)",children:["Always ",e.jsx("kbd",{className:"ml-1 text-[10px] border rounded px-1 bg-background",children:"a"})]}),e.jsxs(J,{size:"sm",onClick:()=>o("yes"),title:"Approve this single call (y)",children:["Yes ",e.jsx("kbd",{className:"ml-1 text-[10px] border rounded px-1 bg-background/80",children:"y"})]})]})]})})}function Xo(){const s=B(m=>m.wsStatus),t=B(m=>m.wsUrl),[n,r]=d.useState(!1),[a,o]=d.useState(Date.now());if(d.useEffect(()=>{if(s.state!=="reconnecting")return;const m=setInterval(()=>o(Date.now()),500);return()=>clearInterval(m)},[s.state]),d.useEffect(()=>{s.state==="open"&&r(!1)},[s.state]),s.state==="open"||s.state==="connecting"||n)return null;const l=()=>ae(t).retryNow(),c=s.state==="reconnecting",i=s.state==="closed"?s.error:s.state==="reconnecting"?s.lastError:void 0,u=c?Math.max(0,Math.ceil((s.nextRetryAt-a)/1e3)):0;return e.jsxs("div",{className:k("flex items-center gap-3 px-4 py-2 border-b text-sm",c?"bg-orange-500/10 text-orange-700 dark:text-orange-300 border-orange-500/30":"bg-red-500/10 text-red-700 dark:text-red-300 border-red-500/30"),children:[c?e.jsx(fe,{className:"h-4 w-4 animate-spin shrink-0"}):e.jsx(ut,{className:"h-4 w-4 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:c?`Reconnecting to backend (attempt ${s.attempt}) — retrying in ${u}s`:"Disconnected from backend"}),i&&e.jsx("div",{className:"text-xs opacity-80 truncate",children:i})]}),e.jsxs("button",{type:"button",onClick:l,className:k("inline-flex items-center gap-1 px-2.5 py-1 rounded-md border text-xs font-medium","hover:bg-background/30 transition-colors shrink-0",c?"border-orange-500/40":"border-red-500/40"),title:"Retry connection now",children:[e.jsx(Ae,{className:"h-3 w-3"}),"Retry now"]}),e.jsx("button",{type:"button",onClick:()=>r(!0),className:"text-current/60 hover:text-current shrink-0",title:"Dismiss (chip in topbar still shows status)",children:e.jsx(be,{className:"h-4 w-4"})})]})}class Zo extends d.Component{constructor(){super(...arguments);ne(this,"state",{error:null});ne(this,"handleReset",()=>{this.setState({error:null})})}static getDerivedStateFromError(n){return{error:n}}componentDidCatch(n,r){var a,o;console.error("[ErrorBoundary]",n,r.componentStack),(o=(a=this.props).onError)==null||o.call(a,n,r)}render(){return this.state.error?e.jsx("div",{className:"flex items-center justify-center h-screen bg-background",children:e.jsxs("div",{className:"flex flex-col items-center gap-4 p-8 max-w-md text-center",children:[e.jsx(ot,{className:"h-12 w-12 text-destructive"}),e.jsx("h1",{className:"text-lg font-semibold",children:"Something went wrong"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"A rendering error occurred. Your session is still active on the server — reloading will pick up where you left off."}),e.jsx("pre",{className:"text-xs font-mono text-muted-foreground bg-muted/50 rounded p-3 max-h-32 overflow-auto w-full text-left",children:this.state.error.message}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(J,{size:"sm",variant:"outline",onClick:()=>window.location.reload(),children:[e.jsx(xt,{className:"h-4 w-4 mr-1"}),"Reload page"]}),e.jsx(J,{size:"sm",onClick:this.handleReset,children:"Try again"})]})]})}):this.props.children}}const er={running:{tone:"text-[hsl(var(--success))]",led:"text-[hsl(var(--success))]",label:"running",pulse:!0},completed:{tone:"text-muted-foreground",led:"text-[hsl(var(--success))]",label:"done",pulse:!1},failed:{tone:"text-destructive",led:"text-destructive",label:"failed",pulse:!1},timeout:{tone:"text-[hsl(var(--warning))]",led:"text-[hsl(var(--warning))]",label:"timeout",pulse:!1},stopped:{tone:"text-muted-foreground",led:"text-muted-foreground",label:"stopped",pulse:!1}};function tr(s){return s<=0?"$0":s>=.01?`$${s.toFixed(3)}`:`$${s.toFixed(5).replace(/0+$/,"").replace(/\.$/,"")}`}function sr({a:s}){const t=er[s.status],n=s.status==="running",r=s.currentTool??s.lastTool;return e.jsxs("div",{className:k("flex min-w-[15rem] max-w-[18rem] flex-col gap-1.5 rounded-lg border p-2.5 transition-colors",n?"border-primary/30 bg-primary/[0.04]":"border-border bg-card opacity-90"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:k("led shrink-0",t.led,t.pulse&&"led-pulse")}),e.jsx("span",{className:"truncate text-xs font-semibold text-foreground",title:s.name,children:s.name}),e.jsx("span",{className:k("ml-auto shrink-0 text-[10px] uppercase tracking-wider",t.tone),children:t.label})]}),s.model&&e.jsxs("div",{className:"flex items-center gap-1 text-[10px] text-muted-foreground min-w-0",children:[e.jsx(Se,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate font-mono",title:`${s.provider??""}/${s.model}`,children:s.model})]}),e.jsxs("div",{className:"tabular flex items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsxs("span",{title:"iteration",children:["L",s.iteration]}),e.jsx("span",{className:"text-border",children:"·"}),e.jsxs("span",{title:"tool calls",children:[s.toolCalls," tools"]}),e.jsx("span",{className:"text-border",children:"·"}),e.jsx("span",{className:"text-foreground/80",title:"cost so far",children:tr(s.costUsd)}),s.extensions>0&&e.jsxs("span",{className:"ml-auto inline-flex items-center gap-0.5 rounded bg-primary/15 px-1 text-[10px] text-primary",title:`Self-extended budget ${s.extensions}×`,children:[e.jsx(Ue,{className:"h-2.5 w-2.5"}),s.extensions]})]}),r&&e.jsxs("div",{className:k("flex items-center gap-1 text-[10px] truncate",n?"text-primary":"text-muted-foreground"),title:s.currentTool?`running ${r}`:`last ran ${r}`,children:[e.jsx(Me,{className:k("h-3 w-3 shrink-0",n&&"animate-pulse")}),e.jsx("span",{className:"truncate font-mono",children:r})]}),s.maxContext>0&&e.jsxs("div",{className:"flex items-center gap-1.5",title:`Context ${s.ctxPct}%`,children:[e.jsx("div",{className:"h-1 flex-1 overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:k("h-full rounded-full transition-all duration-500",s.ctxPct>=85?"bg-destructive":s.ctxPct>=70?"bg-[hsl(var(--warning))]":"bg-primary"),style:{width:`${Math.max(2,s.ctxPct)}%`}})}),e.jsxs("span",{className:"tabular text-[9px] text-muted-foreground",children:[s.ctxPct,"%"]})]}),s.error&&e.jsxs("div",{className:"truncate rounded bg-destructive/10 px-1.5 py-0.5 text-[10px] text-destructive",title:s.error.message,children:[s.error.kind,": ",s.error.message]})]})}function nr({className:s}){const t=ft(l=>l.agents),[n,r]=d.useState(!1),a=d.useMemo(()=>{const l=Array.from(t.values());return l.sort((c,i)=>{const u=c.status==="running"?0:1,m=i.status==="running"?0:1;return u!==m?u-m:c.startedAt-i.startedAt}),l},[t]);if(a.length===0)return null;const o=a.filter(l=>l.status==="running").length;return e.jsxs("div",{className:k("rounded-lg border border-border bg-card/50 backdrop-blur-sm",s),children:[e.jsxs("button",{type:"button",onClick:()=>r(l=>!l),className:"flex w-full items-center gap-2 px-3 py-2 text-left",children:[e.jsx(pt,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-xs font-semibold text-foreground",children:"Fleet"}),e.jsxs("span",{className:"tabular text-[10px] text-muted-foreground",children:[a.length," agent",a.length===1?"":"s",o>0&&e.jsxs("span",{className:"text-[hsl(var(--success))]",children:[" · ",o," active"]})]}),o>0&&e.jsx("span",{className:"led led-pulse text-[hsl(var(--success))]","aria-hidden":!0}),n?e.jsx(We,{className:"ml-auto h-4 w-4 text-muted-foreground"}):e.jsx(Ce,{className:"ml-auto h-4 w-4 text-muted-foreground"})]}),!n&&e.jsx("div",{className:"flex gap-2 overflow-x-auto px-3 pb-3 pt-0.5",children:a.map(l=>e.jsx(sr,{a:l},l.id))})]})}function or(){const s=P(h=>h.modelSwitcherOpen),t=P(h=>h.setModelSwitcherOpen),[n,r]=d.useState(""),[a,o]=d.useState(0),[l,c]=d.useState([]),[i,u]=d.useState({}),m=d.useRef(null),x=B(h=>h.wsUrl),p=B(h=>h.provider),b=B(h=>h.model),y=P(h=>h.paletteOpen),w=de();d.useEffect(()=>{const h=j=>{if((j.ctrlKey||j.metaKey)&&j.key.toLowerCase()==="m"&&!j.shiftKey&&!j.altKey){if(y)return;j.preventDefault(),t(!s);return}j.key==="Escape"&&s&&(j.preventDefault(),t(!1))};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[s,y]),d.useEffect(()=>{const h=ae(x),j=h.on("providers.saved",D=>{const R=D.payload;c(R.providers??[])}),C=h.on("provider.models",D=>{const R=D.payload;u(I=>({...I,[R.provider]:R.models}))});return()=>{j(),C()}},[x]),d.useEffect(()=>{s&&(r(""),o(0),w.listSavedProviders(),requestAnimationFrame(()=>{var h;return(h=m.current)==null?void 0:h.focus()}))},[s,w]),d.useEffect(()=>{if(s)for(const h of l)i[h.id]||w.listProviderModels(h.id)},[s,l,i,w]);const N=d.useMemo(()=>{const h=[];for(const D of l){const R=i[D.id]??[];for(const I of R)h.push({provider:D.id,model:I.id,modelName:I.name||I.id,contextWindow:I.contextWindow,isCurrent:D.id===p&&I.id===b})}const j=n.toLowerCase().trim();return(j?h.filter(D=>D.provider.toLowerCase().includes(j)||D.model.toLowerCase().includes(j)||D.modelName.toLowerCase().includes(j)):h).sort((D,R)=>D.isCurrent!==R.isCurrent?D.isCurrent?-1:1:D.provider.localeCompare(R.provider)||D.model.localeCompare(R.model))},[l,i,n,p,b]);d.useEffect(()=>{a>=N.length&&o(0)},[N.length,a]);const v=h=>{const j=N[h];j&&(w.switchModel(j.provider,j.model),t(!1))};return s?e.jsx("div",{className:"fixed inset-0 z-50 flex items-start justify-center bg-background/60 backdrop-blur-sm pt-[15vh]",onClick:h=>{h.target===h.currentTarget&&t(!1)},onKeyDown:h=>{h.key==="Escape"&&t(!1)},children:e.jsxs("div",{className:"w-full max-w-xl rounded-xl border bg-popover shadow-2xl overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b px-3 py-2",children:[e.jsx(je,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("input",{ref:m,value:n,onChange:h=>{r(h.target.value),o(0)},onKeyDown:h=>{h.key==="ArrowDown"?(h.preventDefault(),o(j=>Math.min(N.length-1,j+1))):h.key==="ArrowUp"?(h.preventDefault(),o(j=>Math.max(0,j-1))):h.key==="Enter"?(h.preventDefault(),v(a)):h.key==="Escape"&&(h.preventDefault(),t(!1))},placeholder:"Filter providers and models…",className:"flex-1 bg-transparent outline-none text-sm placeholder:text-muted-foreground"}),e.jsx("span",{className:"text-[10px] text-muted-foreground font-mono",children:"↑↓ · Enter · Esc"})]}),e.jsx("div",{className:"max-h-[50vh] overflow-y-auto py-1",children:N.length===0?e.jsx("div",{className:"px-4 py-8 text-center text-sm text-muted-foreground",children:l.length===0?"No saved providers — register a key in Settings first.":"Loading models…"}):N.map((h,j)=>e.jsxs("button",{type:"button",onClick:()=>v(j),onMouseEnter:()=>o(j),className:k("w-full flex items-center gap-3 px-3 py-2 text-left text-sm transition-colors",j===a?"bg-accent text-accent-foreground":"hover:bg-accent/40",h.isCurrent&&"font-medium"),children:[e.jsx(Se,{className:k("h-4 w-4 shrink-0",h.isCurrent?"text-primary":"text-muted-foreground")}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"truncate",children:[e.jsx("span",{className:"text-muted-foreground",children:h.provider}),e.jsx("span",{className:"mx-1 text-muted-foreground/40",children:"·"}),e.jsx("span",{children:h.modelName})]}),h.contextWindow&&e.jsxs("div",{className:"text-[10px] text-muted-foreground font-mono",children:[h.model," · ctx ",h.contextWindow.toLocaleString()]})]}),h.isCurrent?e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-primary font-semibold",children:"active"}):e.jsx(_t,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100"})]},`${h.provider}:${h.model}`))})]})}):null}const pe=d.forwardRef(({className:s,type:t,...n},r)=>e.jsx("input",{type:t,className:k("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",s),ref:r,...n}));pe.displayName="Input";const ls=Zs,vt=d.forwardRef(({className:s,...t},n)=>e.jsx(Jt,{ref:n,className:k("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",s),...t}));vt.displayName=Jt.displayName;const ve=d.forwardRef(({className:s,...t},n)=>e.jsx(Qt,{ref:n,className:k("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),...t}));ve.displayName=Qt.displayName;const we=d.forwardRef(({className:s,...t},n)=>e.jsx(Gt,{ref:n,className:k("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",s),...t}));we.displayName=Gt.displayName;function Et({label:s,hint:t,selector:n,onChange:r,configKey:a}){const o=P(u=>n?n(u):!1),l=B(u=>a?u[a]:!1),c=n?o:l,i=()=>{if(n)r==null||r();else if(a==="soundOnComplete"){const u=!B.getState().soundOnComplete;B.getState().setSoundOnComplete(u),u&&gt()}};return e.jsxs("div",{className:"flex items-start justify-between gap-3 py-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-sm font-medium",children:s}),t&&e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:t})]}),e.jsx("button",{type:"button",role:"switch","aria-checked":c,onClick:i,className:k("shrink-0 relative inline-flex h-5 w-9 rounded-full border transition-colors",c?"bg-primary border-primary":"bg-muted border-input hover:bg-muted/80"),children:e.jsx("span",{className:k("absolute top-0.5 left-0.5 h-3.5 w-3.5 rounded-full bg-background shadow transition-transform",c&&"translate-x-4")})})]})}const rr=["anthropic","openai","google","openai-compatible"];function ar({activeProvider:s,catalogProviders:t,isLoadingCatalog:n,savedProviders:r,isLoadingSaved:a,providerTab:o,setProviderTab:l,onSelectProvider:c,onAddKey:i,onDeleteKey:u,onSetActiveKey:m,onAddProvider:x,onRemoveProvider:p,catalogQuery:b,setCatalogQuery:y}){const[w,N]=d.useState(null),[v,h]=d.useState(""),[j,C]=d.useState(""),[D,R]=d.useState(!1),[I,F]=d.useState(!1),[K,X]=d.useState(""),[G,V]=d.useState("openai-compatible"),[q,ee]=d.useState(""),[Y,$]=d.useState(""),W=d.useCallback(T=>{!v.trim()||!j.trim()||(i(T,v.trim(),j.trim()),h(""),C(""),N(null))},[i,v,j]),A=d.useCallback(()=>{K.trim()&&(x(K.trim(),G,q||void 0,Y||void 0),X(""),V("openai-compatible"),ee(""),$(""),F(!1))},[x,K,G,q,Y]),O=b.trim()?t.filter(T=>{const f=b.trim().toLowerCase();return T.id.toLowerCase().includes(f)||T.name.toLowerCase().includes(f)||T.family.toLowerCase().includes(f)}):t,L=O.reduce((T,f)=>(T[f.family]||(T[f.family]=[]),T[f.family].push(f),T),{});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-2 mb-4",children:[e.jsxs(J,{variant:o==="catalog"?"default":"outline",size:"sm",onClick:()=>l("catalog"),children:[e.jsx(De,{className:"h-4 w-4 mr-1"}),"Catalog"]}),e.jsxs(J,{variant:o==="saved"?"default":"outline",size:"sm",onClick:()=>l("saved"),children:[e.jsx(He,{className:"h-4 w-4 mr-1"}),"Saved (",r.length,")"]})]}),o==="catalog"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(pe,{placeholder:`Search ${t.length} providers (name / id / family)…`,value:b,onChange:T=>y(T.target.value),className:"text-sm"}),n&&t.length===0?e.jsxs("div",{className:"flex items-center justify-center py-8",children:[e.jsx(fe,{className:"h-6 w-6 animate-spin text-muted-foreground"}),e.jsx("span",{className:"ml-2 text-muted-foreground",children:"Loading catalog..."})]}):O.length===0&&b?e.jsxs("div",{className:"text-center py-8 text-muted-foreground text-sm",children:['No providers match "',e.jsx("span",{className:"font-mono",children:b}),'".']}):e.jsx(e.Fragment,{children:rr.map(T=>{const f=L[T];return f!=null&&f.length?e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wider",children:T}),e.jsx("div",{className:"grid grid-cols-1 gap-2",children:f.map(S=>e.jsxs("button",{type:"button",onClick:()=>c(S.id),className:k("flex flex-col items-start p-3 rounded-lg border text-left transition-all",s===S.id?"border-primary bg-primary/5 ring-2 ring-primary/20":"border-border hover:bg-muted"),children:[e.jsxs("div",{className:"flex w-full justify-between items-start",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:S.name}),e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",S.id,")"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[S.hasApiKey&&e.jsxs("span",{className:"text-xs bg-green-500/10 text-green-600 px-2 py-0.5 rounded",children:[e.jsx(He,{className:"h-3 w-3 inline mr-1"}),"Configured"]}),S.envVars[0]&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["ENV: ",S.envVars[0]]}),s===S.id&&e.jsx(he,{className:"h-4 w-4 text-primary"})]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:[S.modelCount," models",S.apiBase&&` · ${S.apiBase}`]})]},S.id))})]},T):null})})]}),o==="saved"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage your API keys and provider configurations"}),e.jsxs(J,{size:"sm",variant:"outline",onClick:()=>F(!I),children:[e.jsx(Nt,{className:"h-4 w-4 mr-1"}),"Add Provider"]})]}),I&&e.jsxs("div",{className:"p-4 border rounded-lg space-y-3 bg-muted/50",children:[e.jsx("h4",{className:"font-medium",children:"Add Custom Provider"}),e.jsx(pe,{placeholder:"Provider ID (e.g. my-llm-server)",value:K,onChange:T=>X(T.target.value)}),e.jsxs("select",{className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm",value:G,onChange:T=>V(T.target.value),children:[e.jsx("option",{value:"anthropic",children:"Anthropic"}),e.jsx("option",{value:"openai",children:"OpenAI"}),e.jsx("option",{value:"openai-compatible",children:"OpenAI Compatible"}),e.jsx("option",{value:"google",children:"Google"})]}),e.jsx(pe,{placeholder:"Base URL (optional, e.g. http://localhost:11434/v1)",value:q,onChange:T=>ee(T.target.value)}),e.jsx(pe,{type:"password",placeholder:"API Key (optional)",value:Y,onChange:T=>$(T.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(J,{size:"sm",onClick:A,disabled:!K.trim(),children:"Add"}),e.jsx(J,{size:"sm",variant:"ghost",onClick:()=>F(!1),children:"Cancel"})]})]}),a?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(fe,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):r.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(He,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No saved providers yet"}),e.jsx("p",{className:"text-sm",children:"Add a provider to get started"})]}):r.map(T=>e.jsxs("div",{className:"border rounded-lg p-4 space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-start",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:T.id}),T.family&&e.jsx("span",{className:"text-xs text-muted-foreground",children:T.family})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(J,{size:"icon",variant:"ghost",onClick:()=>p(T.id),children:e.jsx(Ee,{className:"h-4 w-4 text-destructive"})})})]}),T.baseUrl&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsx(De,{className:"h-3 w-3 inline mr-1"}),T.baseUrl]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm font-medium",children:"API Keys"}),e.jsxs(J,{size:"sm",variant:"ghost",onClick:()=>N(w===T.id?null:T.id),children:[e.jsx(Nt,{className:"h-3 w-3 mr-1"}),"Add Key"]})]}),T.apiKeys.length===0&&!w&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"No keys configured"}),T.apiKeys.map(f=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-muted/50 rounded",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm font-medium",children:f.label}),f.isActive&&e.jsx("span",{className:"ml-2 text-xs bg-green-500/10 text-green-600 px-1.5 py-0.5 rounded",children:"Active"}),e.jsx("div",{className:"text-xs text-muted-foreground font-mono",children:f.maskedKey})]}),e.jsxs("div",{className:"flex gap-1",children:[!f.isActive&&e.jsx(J,{size:"sm",variant:"ghost",onClick:()=>m(T.id,f.label),children:"Set Active"}),e.jsx(J,{size:"icon",variant:"ghost",onClick:()=>u(T.id,f.label),children:e.jsx(Ee,{className:"h-3 w-3 text-destructive"})})]})]},f.label)),w===T.id&&e.jsxs("div",{className:"p-3 border rounded space-y-2 bg-background",children:[e.jsx(pe,{placeholder:"Key label (e.g. default, production)",value:v,onChange:f=>h(f.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{type:D?"text":"password",placeholder:"API key",value:j,onChange:f=>C(f.target.value)}),e.jsx(J,{size:"icon",variant:"ghost",onClick:()=>R(!D),children:D?e.jsx(en,{className:"h-4 w-4"}):e.jsx(zt,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(J,{size:"sm",onClick:()=>W(T.id),disabled:!v.trim()||!j.trim(),children:"Save Key"}),e.jsx(J,{size:"sm",variant:"ghost",onClick:()=>{N(null),h(""),C("")},children:"Cancel"})]})]})]})]},T.id))]})]})}function ir({provider:s,catalogModels:t,currentCatalogProvider:n,isLoadingModels:r,setIsLoadingModels:a,onModelSelect:o,refreshModels:l}){var i;const c=B(u=>u.model);return e.jsx("div",{className:"space-y-4",children:s?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:(n==null?void 0:n.name)||s}),e.jsx("p",{className:"text-xs text-muted-foreground",children:s})]}),e.jsx(J,{variant:"ghost",size:"sm",onClick:()=>{a(!0),l(s)},children:e.jsx(xt,{className:k("h-4 w-4",r&&"animate-spin")})})]}),r&&!t[s]?e.jsxs("div",{className:"flex items-center justify-center py-8",children:[e.jsx(fe,{className:"h-6 w-6 animate-spin text-muted-foreground"}),e.jsx("span",{className:"ml-2 text-muted-foreground",children:"Loading models..."})]}):e.jsxs("div",{className:"space-y-1",children:[(t[s]||[]).map(u=>e.jsxs("button",{type:"button",onClick:()=>o(u.id),className:k("w-full flex items-center justify-between p-3 rounded-lg border text-left transition-all",c===u.id?"border-primary bg-primary/5 ring-2 ring-primary/20":"border-border hover:bg-muted"),children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:u.name||u.id}),e.jsx("div",{className:"flex gap-2 mt-1",children:u.capabilities.map(m=>e.jsx("span",{className:"text-xs bg-muted px-1.5 py-0.5 rounded",children:m},m))})]}),e.jsxs("div",{className:"text-right text-xs text-muted-foreground",children:[u.contextWindow&&e.jsxs("div",{children:[u.contextWindow/1e3,"k context"]}),u.inputCost&&u.outputCost&&e.jsxs("div",{children:["$",u.inputCost,"/$",u.outputCost]}),c===u.id&&e.jsx(he,{className:"h-4 w-4 text-primary mt-1"})]})]},u.id)),((i=t[s])==null?void 0:i.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No models found for this provider. The catalog might be empty or still loading."})]})]}):e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Se,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"Select a provider first"})]})})}function lr(){const{setCurrentView:s}=P(),{provider:t,model:n,setProvider:r,setModel:a,wsConnected:o}=B(),{theme:l,setTheme:c}=yt(),i=de(),u=i.client,[m,x]=d.useState([]),[p,b]=d.useState({}),[y,w]=d.useState([]),[N,v]=d.useState(!1),[h,j]=d.useState(!1),[C,D]=d.useState(!1),[R,I]=d.useState("catalog"),[F,K]=d.useState(""),X=m.find(A=>A.id===t);d.useEffect(()=>{const A=g=>{if(g.type==="provider.catalog"){const E=g.payload;x(E.providers.sort((Q,_)=>Q.id.localeCompare(_.id))),v(!1)}},O=g=>{if(g.type==="provider.models"){const E=g.payload;b(Q=>({...Q,[E.provider]:E.models})),j(!1)}},L=g=>{if(g.type==="providers.saved"){const Q=g.payload.providers.sort((_,ie)=>_.id.localeCompare(ie.id));w(Q),D(!1),Q.length>0&&I("saved")}};if(!o||!u)return;const T=u.on("provider.catalog",A),f=u.on("provider.models",O),S=u.on("providers.saved",L);return v(!0),D(!0),u.listProviders(),u.listSavedProviders(),()=>{T==null||T(),f==null||f(),S==null||S()}},[o,u]);const G=d.useCallback(A=>{var O;r(A),p[A]||(j(!0),(O=i.listProviderModels)==null||O.call(i,A))},[p,r,i]),V=d.useCallback(A=>{var L;a(A);const O=B.getState().provider;(L=i.switchModel)==null||L.call(i,O,A),Le.success(`Switching to ${O} / ${A}…`)},[a,i]),q=d.useCallback((A,O,L)=>{var T;(T=i.addKey)==null||T.call(i,A,O,L)},[i]),ee=d.useCallback((A,O)=>{var L;(L=i.deleteKey)==null||L.call(i,A,O)},[i]),Y=d.useCallback((A,O)=>{var L;(L=i.setActiveKey)==null||L.call(i,A,O)},[i]),$=d.useCallback((A,O,L,T)=>{var f;(f=i.addProvider)==null||f.call(i,A,O,L,T)},[i]),W=d.useCallback(A=>{var O;(O=i.removeProvider)==null||O.call(i,A)},[i]);return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("header",{className:"flex items-center justify-between px-4 py-3 border-b bg-card shrink-0",children:[e.jsx("h1",{className:"text-lg font-semibold",children:"Settings"}),e.jsx(J,{variant:"ghost",size:"icon",onClick:()=>s("chat"),children:e.jsx(be,{className:"h-4 w-4"})})]}),e.jsx(Ke,{className:"flex-1",children:e.jsx("div",{className:"p-6 max-w-2xl mx-auto",children:e.jsxs(ls,{defaultValue:"provider",children:[e.jsxs(vt,{className:"w-full justify-start mb-6 grid grid-cols-4",children:[e.jsxs(ve,{value:"provider",className:"gap-2",children:[e.jsx(tn,{className:"h-4 w-4"}),"Provider"]}),e.jsxs(ve,{value:"model",className:"gap-2",children:[e.jsx(Se,{className:"h-4 w-4"}),"Model"]}),e.jsxs(ve,{value:"connection",className:"gap-2",children:[e.jsx(De,{className:"h-4 w-4"}),"Connection"]}),e.jsxs(ve,{value:"appearance",className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"}),"Appearance"]})]}),e.jsx(we,{value:"provider",className:"space-y-4",children:e.jsx(ar,{activeProvider:t,catalogProviders:m,isLoadingCatalog:N,savedProviders:y,isLoadingSaved:C,providerTab:R,setProviderTab:I,onSelectProvider:G,onAddKey:q,onDeleteKey:ee,onSetActiveKey:Y,onAddProvider:$,onRemoveProvider:W,catalogQuery:F,setCatalogQuery:K})}),e.jsx(we,{value:"model",className:"space-y-4",children:e.jsx(ir,{provider:t,catalogModels:p,currentCatalogProvider:X,isLoadingModels:h,setIsLoadingModels:j,onModelSelect:V,refreshModels:A=>{var O;return(O=i.listProviderModels)==null?void 0:O.call(i,A)}})}),e.jsxs(we,{value:"connection",className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{htmlFor:"websocket-url",className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(De,{className:"h-4 w-4 text-muted-foreground"}),"WebSocket Server URL"]}),e.jsx(pe,{id:"websocket-url",value:B.getState().wsUrl,onChange:A=>B.getState().setConfig({wsUrl:A.target.value}),placeholder:"ws://localhost:3457",className:"font-mono text-sm"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"URL of the WrongStack WebSocket server. The server runs alongside the CLI."})]}),e.jsxs("div",{className:"p-4 rounded-lg border bg-muted/50",children:[e.jsx("h4",{className:"text-sm font-medium mb-2",children:"Starting the WebSocket Server"}),e.jsxs("p",{className:"text-xs text-muted-foreground mb-3",children:["Standalone: run ",e.jsx("code",{className:"bg-muted px-1 py-0.5 rounded",children:"./dev.ps1"})," ","from the repo root, or set WS_HOST/WS_PORT before launching"," ",e.jsx("code",{className:"bg-muted px-1 py-0.5 rounded",children:"node packages/webui/dist/server/entry.js"}),". Or alongside the CLI:"," ",e.jsx("code",{className:"bg-muted px-1 py-0.5 rounded",children:"wstack --webui"}),"."]})]})]}),e.jsxs(we,{value:"appearance",className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold mb-3",children:"Theme"}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 max-w-md",children:[e.jsxs(J,{variant:l==="light"?"default":"outline",size:"sm",onClick:()=>c("light"),children:[e.jsx(lt,{className:"h-4 w-4 mr-1"}),"Light"]}),e.jsxs(J,{variant:l==="dark"?"default":"outline",size:"sm",onClick:()=>c("dark"),children:[e.jsx(ct,{className:"h-4 w-4 mr-1"}),"Dark"]}),e.jsxs(J,{variant:l==="system"?"default":"outline",size:"sm",onClick:()=>c("system"),children:[e.jsx(dt,{className:"h-4 w-4 mr-1"}),"System"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"System follows your OS-level light/dark preference."})]}),e.jsxs("div",{className:"pt-2 border-t",children:[e.jsx("h3",{className:"text-sm font-semibold mb-3 mt-3",children:"Preferences"}),e.jsx(Et,{label:"Compact density",hint:"Tighter spacing throughout the chat. Toggle anywhere with Ctrl+Shift+D.",selector:A=>A.compactMode,onChange:()=>P.getState().toggleCompactMode()}),e.jsx(Et,{label:"Sound on completion",hint:"Play a soft chime when a run finishes — useful when working in another tab.",selector:null,configKey:"soundOnComplete"})]})]})]})})})]})}const cr=[{section:"Global",items:[{keys:["Ctrl","K"],description:"Open command palette"},{keys:["?"],description:"Show this shortcuts overlay"},{keys:["Ctrl","\\"],description:"Toggle sidebar"},{keys:["Ctrl","/"],description:"Focus the message input"}]},{section:"Chat input",items:[{keys:["Enter"],description:"Send message"},{keys:["Shift","Enter"],description:"Insert a newline"},{keys:["↑"],description:"Recall previous prompt (in empty input)"},{keys:["↓"],description:"Recall next prompt"},{keys:["/"],description:"Open slash command popup"},{keys:["Tab"],description:"Autocomplete highlighted command"},{keys:["Esc"],description:"Dismiss popup / clear input"}]},{section:"Chat",items:[{keys:["Ctrl","F"],description:"Search within current chat"},{keys:["Ctrl","L"],description:"Clear context (same as /clear)"},{keys:["Ctrl","N"],description:"Start a new session (same as /new)"},{keys:["Ctrl","E"],description:"Export chat as markdown"},{keys:["Ctrl","M"],description:"Quick model switcher overlay"},{keys:["Ctrl","Shift","D"],description:"Toggle compact UI density"},{keys:["Esc"],description:"Abort the current run (when running)"}]},{section:"Chat navigation (when not typing)",items:[{keys:["j"],description:"Focus next message (alias: ↓)"},{keys:["k"],description:"Focus previous message (alias: ↑)"},{keys:["g"],description:"Jump to first message"},{keys:["Shift","G"],description:"Jump to last message"},{keys:["c"],description:"Copy focused message text"},{keys:["Esc"],description:"Clear focused message"}]}];function dr(){const s=P(n=>n.shortcutsOpen),t=P(n=>n.setShortcutsOpen);return d.useEffect(()=>{const n=r=>{var c;const a=r.target,o=(c=a==null?void 0:a.tagName)==null?void 0:c.toLowerCase();if(!(o==="input"||o==="textarea"||(a==null?void 0:a.isContentEditable))&&r.key==="?"&&!r.ctrlKey&&!r.metaKey&&!r.altKey){r.preventDefault(),t(!P.getState().shortcutsOpen);return}r.key==="Escape"&&P.getState().shortcutsOpen&&(r.preventDefault(),t(!1))};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[t]),s?e.jsx("div",{className:"fixed inset-0 z-50 bg-background/60 backdrop-blur-sm flex items-center justify-center px-4",onClick:()=>t(!1),onKeyDown:n=>{n.key==="Escape"&&t(!1)},children:e.jsxs("div",{onClick:n=>n.stopPropagation(),onKeyDown:n=>n.stopPropagation(),className:"w-full max-w-2xl rounded-xl border bg-popover shadow-2xl overflow-hidden flex flex-col max-h-[80vh]",children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("h2",{className:"text-sm font-semibold",children:"Keyboard shortcuts"})]}),e.jsx("button",{type:"button",onClick:()=>t(!1),className:"text-muted-foreground hover:text-foreground p-1 rounded hover:bg-muted",children:e.jsx(be,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"overflow-y-auto px-5 py-4 space-y-6",children:cr.map(n=>e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground mb-2",children:n.section}),e.jsx("div",{className:"grid grid-cols-1 gap-1.5",children:n.items.map(r=>e.jsxs("div",{className:"flex items-center justify-between gap-3 text-sm px-2 py-1.5 rounded hover:bg-muted/40",children:[e.jsx("span",{className:"text-foreground/80",children:r.description}),e.jsx("span",{className:"flex items-center gap-1 shrink-0",children:r.keys.map((a,o)=>e.jsxs("span",{className:"flex items-center gap-1",children:[o>0&&e.jsx("span",{className:"text-muted-foreground/40 text-xs",children:"+"}),e.jsx("kbd",{className:"font-mono text-[10px] border rounded px-1.5 py-0.5 bg-background",children:a})]},a))})]},r.description))})]},n.section))}),e.jsxs("div",{className:"border-t px-5 py-3 text-xs text-muted-foreground",children:["Press"," ",e.jsx("kbd",{className:"font-mono text-[10px] border rounded px-1 py-0.5 bg-background",children:"?"})," ","any time to reopen this list."]})]})}):null}function ur({formatDuration:s}){const{wsConnected:t,wsUrl:n,provider:r,model:a}=B(),{totalTokens:o,cost:l,session:c,todos:i}=z(),{messages:u}=M(),m=P(y=>y.pinnedIds),x=P(y=>y.unpinAll),p=P(y=>y.setCurrentView),b=m.map(y=>u.find(w=>w.id===y)).filter(y=>!!y&&y.content.length>0);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"px-4 py-3 border-b",children:[e.jsxs("div",{className:k("flex items-center gap-2 px-3 py-2 rounded-lg text-sm",t?"bg-green-500/10 text-green-600 dark:text-green-400":"bg-yellow-500/10 text-yellow-600 dark:text-yellow-400"),children:[t?e.jsx(It,{className:"h-4 w-4"}):e.jsx(ut,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:t?"Connected":"Disconnected"})]}),e.jsx("div",{className:"text-xs text-muted-foreground mt-2 px-1 font-mono",children:n})]}),e.jsxs("button",{type:"button",onClick:()=>p("settings"),className:"px-4 py-3 border-b text-left hover:bg-muted/40 transition-colors",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground mb-1",children:"Active model"}),e.jsxs("div",{className:"font-mono text-xs truncate",children:[e.jsx("span",{className:"text-muted-foreground",children:r||"—"}),e.jsx("span",{className:"text-muted-foreground/40 mx-1",children:"/"}),e.jsx("span",{className:"font-medium",children:a||"—"})]})]}),e.jsxs("div",{className:"px-4 py-3 border-b space-y-3",children:[e.jsxs("h3",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(rt,{className:"h-4 w-4 text-muted-foreground"}),"Session"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[e.jsxs("div",{className:"flex flex-col p-2 rounded-lg bg-muted/50",children:[e.jsx("span",{className:"text-muted-foreground",children:"Messages"}),e.jsx("span",{className:"text-lg font-semibold",children:u.length})]}),e.jsxs("div",{className:"flex flex-col p-2 rounded-lg bg-muted/50",children:[e.jsx("span",{className:"text-muted-foreground",children:"Duration"}),e.jsx("span",{className:"text-lg font-semibold",children:s((c==null?void 0:c.startedAt)??null)})]}),e.jsxs("div",{className:"flex flex-col p-2 rounded-lg bg-muted/50",children:[e.jsx("span",{className:"text-muted-foreground",children:"Input"}),e.jsx("span",{className:"text-lg font-semibold",children:o.input.toLocaleString()})]}),e.jsxs("div",{className:"flex flex-col p-2 rounded-lg bg-muted/50",children:[e.jsx("span",{className:"text-muted-foreground",children:"Output"}),e.jsx("span",{className:"text-lg font-semibold",children:o.output.toLocaleString()})]})]}),l>0&&e.jsxs("div",{className:"flex justify-between items-center p-2 rounded-lg bg-green-500/10",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Cost"}),e.jsxs("span",{className:"text-lg font-semibold text-green-600 dark:text-green-400",children:["$",l.toFixed(4)]})]})]}),i.length>0&&(()=>{const y=i.filter(h=>h.status==="completed").length,w=i.filter(h=>h.status==="in_progress").length,N=i.length>0?Math.round(y/i.length*100):0,v=y===i.length;return e.jsxs("div",{className:"px-4 py-3 border-b space-y-2.5",children:[e.jsxs("h3",{className:"text-sm font-medium flex items-center justify-between",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(nn,{className:"h-4 w-4 text-muted-foreground"}),"Plan"]}),e.jsxs("span",{className:"tabular text-[10px] text-muted-foreground",children:[y,"/",i.length]})]}),e.jsx("div",{className:k("relative h-1.5 w-full overflow-hidden rounded-full bg-muted",w>0&&"bar-sweep"),title:`${N}% complete`,children:e.jsx("div",{className:k("h-full rounded-full transition-all duration-500",v?"bg-[hsl(var(--success))]":"bg-primary"),style:{width:`${Math.max(N,w>0?4:0)}%`}})}),e.jsx("ul",{className:"space-y-0.5 max-h-56 overflow-y-auto pr-1 -mx-1",children:i.map(h=>{const j=h.status==="completed"?he:h.status==="in_progress"?on:Xe,C=h.status==="in_progress",D=h.status==="completed"?"text-[hsl(var(--success))] line-through opacity-60":C?"text-foreground":"text-muted-foreground";return e.jsxs("li",{className:k("flex items-start gap-2 text-xs leading-snug rounded-md px-1.5 py-1 transition-colors",C&&"bg-primary/10 ring-1 ring-inset ring-primary/20",D),children:[e.jsx(j,{className:k("h-3.5 w-3.5 mt-0.5 shrink-0",C&&"text-primary animate-pulse")}),e.jsx("span",{className:"break-words",children:C&&h.activeForm?h.activeForm:h.content})]},h.id)})})]})})(),b.length>0&&e.jsxs("div",{className:"px-4 py-3 border-b space-y-2",children:[e.jsxs("h3",{className:"text-sm font-medium flex items-center justify-between",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"h-4 w-4 text-amber-500"}),"Pinned"]}),e.jsx("button",{type:"button",onClick:x,className:"text-[10px] text-muted-foreground hover:text-destructive",children:"Clear"})]}),e.jsx("ul",{className:"space-y-1 max-h-48 overflow-y-auto pr-1",children:b.map(y=>{const w=y.content.replace(/\s+/g," ").slice(0,80);return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>{const N=document.querySelector(`[data-message-id="${y.id}"]`);N&&(N.scrollIntoView({behavior:"smooth",block:"center"}),N.classList.add("ring-2","ring-amber-500/60"),setTimeout(()=>{N.classList.remove("ring-2","ring-amber-500/60")},1600))},className:"w-full text-left text-xs px-2 py-1.5 rounded bg-muted/40 hover:bg-muted/70 border border-amber-500/20 leading-snug",title:y.content.slice(0,400),children:[w,y.content.length>80?"…":""]})},y.id)})})]})]})}function mr({wsConnected:s}){const t=M(r=>r.clearMessages),{client:n}=de();return e.jsxs("div",{className:"px-4 py-3 border-b space-y-2",children:[e.jsxs(J,{variant:"outline",size:"sm",className:"w-full justify-start text-destructive hover:text-destructive",onClick:()=>{var r;t(),(r=n==null?void 0:n.clearContext)==null||r.call(n)},children:[e.jsx(Ee,{className:"h-4 w-4 mr-2"}),"Clear context"]}),e.jsxs(J,{variant:"outline",size:"sm",className:"w-full justify-start",onClick:()=>{var r;return(r=n==null?void 0:n.newSession)==null?void 0:r.call(n)},disabled:!s,children:[e.jsx(Ae,{className:"h-4 w-4 mr-2"}),"New session"]}),e.jsxs(J,{variant:"outline",size:"sm",className:"w-full justify-start",onClick:()=>{var r;return(r=n==null?void 0:n.compactContext)==null?void 0:r.call(n)},disabled:!s,children:[e.jsx(rt,{className:"h-4 w-4 mr-2"}),"Compact context"]})]})}const pr=s=>{const t=Date.parse(s);if(Number.isNaN(t))return"";const n=Date.now()-t;if(n<6e4)return"just now";if(n<36e5)return`${Math.floor(n/6e4)}m ago`;if(n<864e5)return`${Math.floor(n/36e5)}h ago`;const r=Math.floor(n/864e5);return r<7?`${r}d ago`:new Date(t).toLocaleDateString()};function xr({historyQuery:s,setHistoryQuery:t,historyEntries:n,historyLoading:r,historyError:a,wsConnected:o,listSessions:l,resumeSession:c,deleteSession:i}){const u=P(h=>h.favoriteSessionIds),m=P(h=>h.toggleFavoriteSession),x=P(h=>h.sessionNicknames),p=P(h=>h.setSessionNickname),[b,y]=d.useState(null),[w,N]=d.useState(""),v=(()=>{const h=s.trim().toLowerCase(),j=h?n.filter(W=>W.title.toLowerCase().includes(h)||W.model.toLowerCase().includes(h)||W.provider.toLowerCase().includes(h)||W.id.toLowerCase().includes(h)):n,C=new Date;C.setHours(0,0,0,0);const D=C.getTime(),R=D-864e5,I=D-6*864e5,F={today:[],yesterday:[],week:[],older:[]};for(const W of j){const A=Date.parse(W.startedAt);if(Number.isNaN(A)){F.older.push(W);continue}A>=D?F.today.push(W):A>=R?F.yesterday.push(W):A>=I?F.week.push(W):F.older.push(W)}const K=new Set(u),X=j.filter(W=>K.has(W.id)),G=[];X.length&&G.push({label:"Favorites",rows:X,star:!0});const V=W=>W.filter(A=>!K.has(A.id)),q=V(F.today),ee=V(F.yesterday),Y=V(F.week),$=V(F.older);return q.length&&G.push({label:"Today",rows:q}),ee.length&&G.push({label:"Yesterday",rows:ee}),Y.length&&G.push({label:"This week",rows:Y}),$.length&&G.push({label:"Earlier",rows:$}),G})();return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b",children:[e.jsx("span",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Recent sessions"}),e.jsx("button",{type:"button",className:"h-6 w-6 inline-flex items-center justify-center rounded-md hover:bg-muted",onClick:()=>l(50),disabled:!o,title:"Refresh",children:r?e.jsx(fe,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(xt,{className:"h-3.5 w-3.5"})})]}),n.length>3&&e.jsx("div",{className:"px-3 py-2 border-b",children:e.jsxs("div",{className:"relative",children:[e.jsx(je,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground/60"}),e.jsx("input",{type:"text",value:s,onChange:h=>t(h.target.value),placeholder:"Filter title, model, provider…",className:"w-full pl-7 pr-7 py-1 text-xs rounded-md bg-muted/40 border border-transparent focus:bg-background focus:border-input focus:outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50"}),s&&e.jsx("button",{type:"button",onClick:()=>t(""),className:"absolute right-1 top-1/2 -translate-y-1/2 text-muted-foreground/60 hover:text-foreground p-0.5",title:"Clear filter",children:e.jsx(be,{className:"h-3 w-3"})})]})}),a&&e.jsx("div",{className:"px-4 py-2 text-xs text-destructive bg-destructive/5 border-b",children:a}),e.jsx(Ke,{className:"flex-1",children:n.length===0&&!r?e.jsxs("div",{className:"text-center text-muted-foreground py-8 px-4",children:[e.jsx(at,{className:"h-8 w-8 mx-auto mb-3 opacity-20"}),e.jsx("p",{className:"text-sm font-medium",children:"No history yet"}),e.jsx("p",{className:"text-xs mt-1",children:"Your conversations will appear here"})]}):v.length===0?e.jsxs("div",{className:"text-center text-muted-foreground py-8 px-4",children:[e.jsx(je,{className:"h-8 w-8 mx-auto mb-3 opacity-20"}),e.jsx("p",{className:"text-sm font-medium",children:"No matches"}),e.jsx("p",{className:"text-xs mt-1",children:"Try a different filter"})]}):e.jsx("div",{className:"p-2 space-y-3",children:v.map(h=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:k("sticky top-0 z-[1] px-1 pb-1 text-[10px] uppercase tracking-wider font-semibold bg-card/90 backdrop-blur-sm flex items-center gap-1",h.star?"text-amber-500":"text-muted-foreground/80"),children:[h.star&&e.jsx(kt,{className:"h-3 w-3 fill-current"}),h.label," ",e.jsxs("span",{className:"text-muted-foreground/50 font-normal normal-case ml-1",children:["(",h.rows.length,")"]})]}),h.rows.map(j=>e.jsxs("div",{className:k("group relative rounded-md border text-sm transition-colors",j.isCurrent?"bg-primary/5 border-primary/40":"bg-card border-border/60 hover:bg-muted/40 hover:border-primary/40"),children:[e.jsx("button",{type:"button",disabled:j.isCurrent||b===j.id,onClick:()=>c(j.id),onDoubleClick:C=>{C.stopPropagation(),y(j.id),N(x[j.id]??j.title??"")},className:"block w-full rounded-md px-3 py-2 pr-16 text-left disabled:cursor-default focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:e.jsxs("div",{className:"min-w-0 flex-1",children:[b===j.id?e.jsx("input",{value:w,onChange:C=>N(C.target.value),onClick:C=>C.stopPropagation(),onBlur:()=>{p(j.id,w),y(null)},onKeyDown:C=>{C.key==="Enter"?(C.preventDefault(),p(j.id,w),y(null)):C.key==="Escape"&&(C.preventDefault(),y(null))},placeholder:j.title||"Nickname",className:"w-full text-sm bg-background border border-input rounded px-1.5 py-0.5 focus:outline-none focus:ring-1 focus:ring-ring"}):e.jsx("div",{className:"font-medium truncate text-foreground",title:x[j.id]?`${x[j.id]} — original: ${j.title}`:`${j.title}
93
+
94
+ Double-click to rename`,children:x[j.id]||j.title||"(empty)"}),e.jsxs("div",{className:"text-[10px] text-muted-foreground font-mono truncate mt-0.5",children:[j.provider,"/",j.model]}),e.jsxs("div",{className:"flex items-center gap-2 text-[10px] text-muted-foreground/80 mt-0.5",children:[e.jsx("span",{children:pr(j.startedAt)}),j.tokenTotal>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsxs("span",{className:"tabular-nums",children:[j.tokenTotal.toLocaleString()," tok"]})]}),j.isCurrent&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsx("span",{className:"text-primary font-medium",children:"active"})]})]})]})}),e.jsxs("div",{className:"absolute right-2 top-2 flex items-center gap-1",children:[e.jsx("button",{type:"button",onClick:()=>m(j.id),className:k("transition-opacity hover:text-amber-500",u.includes(j.id)?"opacity-100 text-amber-500":"opacity-0 group-hover:opacity-100 text-muted-foreground"),title:u.includes(j.id)?"Unfavorite":"Mark as favorite",children:e.jsx(kt,{className:k("h-3.5 w-3.5",u.includes(j.id)&&"fill-current")})}),!j.isCurrent&&e.jsx("button",{type:"button",onClick:()=>{window.confirm(`Delete session "${j.title}"?`)&&i(j.id)},className:"opacity-0 group-hover:opacity-100 transition-opacity text-muted-foreground hover:text-destructive",title:"Delete session",children:e.jsx(Ee,{className:"h-3.5 w-3.5"})})]})]},j.id))]},h.label))})})]})}function hr(){const{toggleSidebar:s,currentView:t,setCurrentView:n}=P(),r=P(C=>C.sidebarWidth),a=P(C=>C.setSidebarWidth),{wsConnected:o,wsUrl:l}=B(),{entries:c,loading:i,error:u}=ke(),{listSessions:m,deleteSession:x,resumeSession:p,client:b}=de(),y=z(C=>C.session),[w,N]=d.useState(""),v=y==null?void 0:y.id;d.useEffect(()=>{var C;o&&((C=b==null?void 0:b.getTodos)==null||C.call(b))},[o,b]),d.useEffect(()=>{t==="history"&&o&&m(50)},[t,o,v,m]);const h=C=>{if(!C)return"--";const D=Math.floor((Date.now()-C)/1e3);return D<60?`${D}s`:`${Math.floor(D/60)}m`},j=C=>{C.preventDefault();const D=C.clientX,R=r,I=K=>{a(R+(K.clientX-D))},F=()=>{window.removeEventListener("mousemove",I),window.removeEventListener("mouseup",F),document.body.style.cursor="",document.body.style.userSelect=""};window.addEventListener("mousemove",I),window.addEventListener("mouseup",F),document.body.style.cursor="col-resize",document.body.style.userSelect="none"};return e.jsxs("aside",{style:{width:`${r}px`},className:"relative border-r bg-card flex flex-col shrink-0",children:[e.jsxs("div",{onMouseDown:j,onDoubleClick:()=>a(288),className:"group/handle absolute top-0 right-0 h-full w-2 cursor-col-resize z-10 flex items-center justify-end",title:"Drag to resize · double-click to reset",children:[e.jsx("div",{className:"h-full w-px bg-border group-hover/handle:bg-primary/60 group-hover/handle:w-0.5 transition-all"}),e.jsxs("div",{className:"absolute right-0 top-1/2 -translate-y-1/2 flex flex-col gap-0.5 opacity-0 group-hover/handle:opacity-100 transition-opacity pr-0.5",children:[e.jsx("span",{className:"h-1 w-1 rounded-full bg-primary/70"}),e.jsx("span",{className:"h-1 w-1 rounded-full bg-primary/70"}),e.jsx("span",{className:"h-1 w-1 rounded-full bg-primary/70"})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"relative w-7 h-7 rounded-md bg-primary flex items-center justify-center shadow-[0_0_0_1px_hsl(var(--primary)/0.4),0_2px_8px_-2px_hsl(var(--primary)/0.5)]",children:e.jsx(Ue,{className:"h-4 w-4 text-primary-foreground",strokeWidth:2.4})}),e.jsxs("div",{className:"flex flex-col leading-none",children:[e.jsx("span",{className:"text-sm font-semibold tracking-tight",children:"WrongStack"}),e.jsxs("span",{className:"flex items-center gap-1 text-[10px] text-muted-foreground mt-0.5",children:[e.jsx("span",{className:k("led",o?"text-[hsl(var(--success))] led-pulse":"text-[hsl(var(--warning))]")}),e.jsx("span",{className:"tabular font-medium uppercase tracking-wider",children:o?"online":"offline"})]})]})]}),e.jsx(J,{variant:"ghost",size:"icon",onClick:s,title:"Collapse sidebar (Ctrl+\\\\)",children:e.jsx(rn,{className:"h-4 w-4"})})]}),e.jsxs(ls,{value:t==="settings"?"chat":t,onValueChange:C=>n(C),className:"flex-1 flex flex-col",children:[e.jsxs(vt,{className:"w-full rounded-none bg-transparent p-2 h-auto grid grid-cols-2",children:[e.jsxs(ve,{value:"chat",className:"flex-col gap-1.5 py-2 data-[state=active]:bg-primary/10",children:[e.jsx(an,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Chat"})]}),e.jsxs(ve,{value:"history",className:"flex-col gap-1.5 py-2 data-[state=active]:bg-primary/10",children:[e.jsx(at,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"History"})]})]}),e.jsxs(we,{value:"chat",className:"flex-1 flex flex-col m-0 overflow-hidden",children:[e.jsx(ur,{formatDuration:h}),e.jsx(mr,{wsConnected:o}),e.jsx("div",{className:"flex-1"}),e.jsx("div",{className:"px-3 py-3 border-t",children:e.jsxs(J,{variant:"ghost",size:"sm",className:"w-full justify-start",onClick:()=>n("settings"),children:[e.jsx(it,{className:"h-4 w-4 mr-2"}),"Settings"]})})]}),e.jsx(we,{value:"history",className:"flex-1 m-0 flex flex-col overflow-hidden",children:e.jsx(xr,{historyQuery:w,setHistoryQuery:N,historyEntries:c,historyLoading:i,historyError:u,wsConnected:o,listSessions:m,resumeSession:p,deleteSession:x})})]})]})}function fr(){const[s,t]=d.useState([]),n=ae(),r=d.useRef(null);d.useEffect(()=>(n.send({type:"todos.get"}),r.current=n.on("todos.updated",i=>{const u=i==null?void 0:i.payload;u!=null&&u.todos&&t(u.todos)}),()=>{var i;(i=r.current)==null||i.call(r)}),[n]);const a=d.useCallback(i=>{n.removeTodo(i)},[n]),o=s.filter(i=>i.status==="pending"),l=s.filter(i=>i.status==="in_progress"),c=s.filter(i=>i.status==="completed");return e.jsxs("div",{className:"flex flex-col h-full bg-background",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-border flex items-center justify-between shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h2",{className:"text-sm font-semibold text-foreground",children:"TODOS"}),e.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:[c.length,"/",s.length]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[l.length>0&&e.jsxs("span",{className:"flex items-center gap-1 text-yellow-600 dark:text-yellow-400",children:[e.jsx(Oe,{className:"w-3 h-3"}),l.length]}),o.length>0&&e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Xe,{className:"w-3 h-3"}),o.length]}),c.length>0&&e.jsxs("span",{className:"flex items-center gap-1 text-emerald-600 dark:text-emerald-400",children:[e.jsx(he,{className:"w-3 h-3"}),c.length]})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:s.length===0?e.jsx("p",{className:"px-4 py-8 text-xs text-muted-foreground text-center",children:"No todos yet. The agent will create them as it plans work."}):e.jsx("div",{className:"py-1",children:s.map(i=>{const u=i.status==="in_progress"&&i.activeForm?i.activeForm:i.content,m=i.status==="in_progress",x=i.status==="completed";return e.jsxs("div",{className:`px-4 py-2 flex items-start gap-2.5 text-sm border-l-2 group ${m?"border-l-yellow-500 bg-yellow-50/40 dark:bg-yellow-950/20":x?"border-l-emerald-500 bg-emerald-50/30 dark:bg-emerald-950/15":"border-l-transparent"}`,children:[e.jsx("span",{className:"mt-0.5 shrink-0",children:x?e.jsx(he,{className:"w-3.5 h-3.5 text-emerald-500"}):m?e.jsx(Oe,{className:"w-3.5 h-3.5 text-yellow-500 animate-spin"}):e.jsx(Xe,{className:"w-3.5 h-3.5 text-muted-foreground/50"})}),e.jsx("span",{className:`leading-snug flex-1 ${m?"text-yellow-800 dark:text-yellow-200 font-medium":x?"text-muted-foreground line-through":"text-foreground"}`,children:u}),e.jsx("button",{type:"button",onClick:p=>{p.stopPropagation(),a(i.id)},className:"shrink-0 p-0.5 rounded opacity-0 group-hover:opacity-60 hover:opacity-100 hover:bg-muted transition-all",title:"Remove",children:e.jsx(be,{className:"w-3 h-3 text-muted-foreground"})})]},i.id)})})})]})}function gr(){const{theme:s}=yt(),{currentView:t,sidebarOpen:n,toggleSidebar:r,setSearchOpen:a,setSidebarOpen:o}=P(),l=M(p=>p.isLoading),c=z(p=>p.iteration),i=z(p=>p.projectName),u=z(p=>{var b;return(b=p.session)==null?void 0:b.title}),m=z(p=>{var b;return(b=p.session)==null?void 0:b.id}),x=P(p=>m?p.sessionNicknames[m]:void 0);return d.useEffect(()=>{if(typeof window>"u")return;const p=window.matchMedia("(max-width: 768px)"),b=()=>{p.matches&&P.getState().sidebarOpen&&o(!1)};return b(),p.addEventListener("change",b),()=>p.removeEventListener("change",b)},[o]),ro(),d.useEffect(()=>{const p=[];if(l){const N=c?` iter ${c.index}${c.max?`/${c.max}`:""}`:"";p.push(`●${N}`)}const b=(x==null?void 0:x.trim())||(u==null?void 0:u.trim()),y=i==null?void 0:i.trim();b&&p.push(b),y&&p.push(y),p.push("WrongStack");const w=p.filter(Boolean).join(" · ");return document.title=w,()=>{document.title="WrongStack"}},[l,c,i,u,x]),d.useEffect(()=>{const p=b=>{var h,j,C,D,R,I,F;const y=b.target,w=(h=y==null?void 0:y.tagName)==null?void 0:h.toLowerCase(),N=w==="input"||w==="textarea"||(y==null?void 0:y.isContentEditable),v=b.ctrlKey||b.metaKey;if(v&&b.key==="\\"){b.preventDefault(),r();return}if(v&&b.key.toLowerCase()==="f"){b.preventDefault(),a(!0);return}if(v&&b.key.toLowerCase()==="/"){b.preventDefault();const K=document.querySelector("textarea");K==null||K.focus();return}if(v&&!N&&(b.key.toLowerCase()==="l"?(b.preventDefault(),M.getState().clearMessages(),(C=(j=ae(B.getState().wsUrl))==null?void 0:j.clearContext)==null||C.call(j)):b.key.toLowerCase()==="n"?(b.preventDefault(),(R=(D=ae(B.getState().wsUrl))==null?void 0:D.newSession)==null||R.call(D)):b.key.toLowerCase()==="e"&&(b.preventDefault(),bt())),v&&b.shiftKey&&b.key.toLowerCase()==="d"&&(b.preventDefault(),P.getState().toggleCompactMode()),!N&&!v&&!b.altKey){const K=Array.from(document.querySelectorAll("[data-message-id]"));if(K.length===0)return;const X=document.querySelector('[data-message-id][data-focused="true"]'),G=X?K.indexOf(X):-1,V=q=>{for(const ee of K)ee.removeAttribute("data-focused");q.setAttribute("data-focused","true"),q.scrollIntoView({behavior:"smooth",block:"center"})};if(b.key==="j"||b.key==="ArrowDown"){const q=K[Math.min(K.length-1,Math.max(0,G+1))];q&&(b.preventDefault(),V(q));return}if(b.key==="k"||b.key==="ArrowUp"){const q=K[Math.max(0,G<=0?0:G-1)];q&&(b.preventDefault(),V(q));return}if(b.key==="g"&&!b.shiftKey){b.preventDefault(),V(K[0]);return}if(b.key==="G"||b.key==="g"&&b.shiftKey){b.preventDefault(),V(K[K.length-1]);return}if(b.key==="Escape"&&X){b.preventDefault(),X.removeAttribute("data-focused");return}if(b.key==="c"&&X){const q=((I=X.querySelector(".markdown-content"))==null?void 0:I.innerText)??X.innerText;q&&((F=navigator.clipboard)==null||F.writeText(q).catch(()=>{}),b.preventDefault());return}}};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[r,a]),e.jsxs("div",{className:k("flex h-screen",s),children:[n&&e.jsx(hr,{}),e.jsxs("main",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsx(Xo,{}),t==="chat"&&e.jsxs(e.Fragment,{children:[m&&e.jsxs("div",{className:"px-4 pt-2 space-y-2",children:[e.jsx(Vo,{sessionId:m}),e.jsx(nr,{}),e.jsx(fr,{})]}),e.jsx(Bo,{})]}),t==="settings"&&e.jsx(lr,{})]}),e.jsx(Yo,{}),e.jsx(io,{}),e.jsx(dr,{}),e.jsx(or,{}),e.jsx(Sn,{})]})}function br(){return e.jsx(Zo,{children:e.jsx(Oo,{defaultTheme:"system",children:e.jsx(gr,{})})})}ln.createRoot(document.getElementById("root")).render(e.jsx(cn.StrictMode,{children:e.jsx(br,{})}));