@wrongstack/webui 0.8.5 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{index-DjDDhHNu.js → index-B5qzSV8A.js} +25 -25
- package/dist/assets/index-BTevO8Vz.css +1 -0
- package/dist/index.css +117 -0
- package/dist/index.css.map +1 -1
- package/dist/index.html +2 -2
- package/dist/index.js +15 -0
- package/dist/index.js.map +1 -1
- package/dist/server/entry.js +206 -20
- package/dist/server/entry.js.map +1 -1
- package/dist/server/index.js +206 -20
- package/dist/server/index.js.map +1 -1
- package/package.json +5 -5
- package/dist/assets/index-aTQFIbqW.css +0 -1
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
var
|
|
2
|
-
<rect x="2" y="2" width="60" height="60" rx="14" fill="${
|
|
1
|
+
var gs=Object.defineProperty;var bs=(o,t,s)=>t in o?gs(o,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):o[t]=s;var de=(o,t,s)=>bs(o,typeof t!="symbol"?t+"":t,s);import{t as ys,c as vs,a as $e,j as e,r as c,X as Te,C as Ce,b as pt,T as xt,I as ws,p as Ve,H as js,W as Be,B as Pt,S as Ft,d as Ns,e as ks,f as Fe,R as Ke,D as it,g as lt,h as ct,i as ht,k as _e,l as ft,M as gt,m as bt,n as Ss,V as Cs,o as $s,A as _t,q as De,F as Ts,s as Ms,u as Es,v as Ds,P as Kt,w as Ls,x as Rs,y as Wt,L as we,z as yt,G as As,E as We,J as vt,K as wt,N as Is,O as Os,U as Ps,Q as Le,Y as Ut,Z as zt,_ as Fs,$ as _s,a0 as Ks,a1 as Ws,a2 as Ht,a3 as Us,a4 as Bt,a5 as qt,a6 as jt,a7 as zs,a8 as Vt,a9 as Hs,aa as Qt,ab as Gt,ac as Bs,ad as qs,ae as Jt,af as Vs,ag as Qs,ah as Gs,ai as Js,aj as Ys,ak as Yt,al as Xs,am as Xt,an as Zs,ao as Zt,ap as es,aq as en,ar as tn,as as sn,at as Ie,au as Nt,av as ts,aw as ss,ax as ns,ay as nn,az as on,aA as rn,aB as et,aC as an,aD as Tt,aE as ln,aF as cn,aG as dn,aH as un,aI as mn,aJ as pn,aK as xn,aL as Mt,aM as hn,aN as fn}from"./vendor-Dff2jyfM.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))a(n);new MutationObserver(n=>{for(const r of n)if(r.type==="childList")for(const i of r.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&a(i)}).observe(document,{childList:!0,subtree:!0});function s(n){const r={};return n.integrity&&(r.integrity=n.integrity),n.referrerPolicy&&(r.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?r.credentials="include":n.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function a(n){if(n.ep)return;n.ep=!0;const r=s(n);fetch(n.href,r)}})();function C(...o){return ys(vs(o))}const Ne=$e(o=>({toasts:[],push:t=>{const s=`toast_${Date.now()}_${Math.random().toString(36).slice(2,7)}`;return o(a=>({toasts:[...a.toasts,{...t,id:s}]})),s},dismiss:t=>o(s=>({toasts:s.toasts.filter(a=>a.id!==t)}))})),Ue={success:(o,t=3500)=>Ne.getState().push({message:o,variant:"success",ttl:t}),error:(o,t=6e3)=>Ne.getState().push({message:o,variant:"error",ttl:t}),warn:(o,t=4500)=>Ne.getState().push({message:o,variant:"warn",ttl:t}),info:(o,t=3500)=>Ne.getState().push({message:o,variant:"info",ttl:t}),dismiss:o=>Ne.getState().dismiss(o)};function gn({variant:o}){return o==="success"?e.jsx(Ce,{className:"h-4 w-4 text-green-500"}):o==="error"?e.jsx(pt,{className:"h-4 w-4 text-destructive"}):o==="warn"?e.jsx(xt,{className:"h-4 w-4 text-amber-500"}):e.jsx(ws,{className:"h-4 w-4 text-blue-500"})}function bn({entry:o}){const t=Ne(s=>s.dismiss);return c.useEffect(()=>{const s=setTimeout(()=>t(o.id),o.ttl);return()=>clearTimeout(s)},[o.id,o.ttl,t]),e.jsxs("div",{className:C("flex items-start gap-2 rounded-lg border bg-popover shadow-lg px-3 py-2 text-sm max-w-sm","animate-message",o.variant==="error"&&"border-destructive/40",o.variant==="warn"&&"border-amber-500/40",o.variant==="success"&&"border-green-500/40"),children:[e.jsx(gn,{variant:o.variant}),e.jsx("div",{className:"flex-1 min-w-0 whitespace-pre-wrap break-words leading-snug",children:o.message}),e.jsx("button",{type:"button",onClick:()=>t(o.id),className:"text-muted-foreground hover:text-foreground",title:"Dismiss",children:e.jsx(Te,{className:"h-3.5 w-3.5"})})]})}function yn(){const o=Ne(t=>t.toasts);return o.length===0?null:e.jsx("div",{className:"fixed bottom-4 right-4 z-[60] flex flex-col gap-2 pointer-events-auto",children:o.map(t=>e.jsx(bn,{entry:t},t.id))})}let ze=null;function vn(){if(typeof window>"u")return null;if(ze)return ze;const o=window.AudioContext||window.webkitAudioContext;if(!o)return null;try{ze=new o}catch{return null}return ze}function Pe(o,t,s){const a=vn();if(!a)return;const n=a.currentTime+t,r=a.createOscillator(),i=a.createGain();r.type="sine",r.frequency.value=o,i.gain.setValueAtTime(0,n),i.gain.linearRampToValueAtTime(.18,n+.01),i.gain.exponentialRampToValueAtTime(1e-4,n+s),r.connect(i).connect(a.destination),r.start(n),r.stop(n+s+.02)}function kt(){Pe(659.25,0,.18),Pe(880,.12,.24)}function wn(){Pe(523.25,0,.15),Pe(659.25,.1,.15),Pe(783.99,.2,.25)}const jn="#4f46e5";function Nn(o){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="${jn}" />
|
|
3
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
4
|
${o==="ready"?'<circle cx="50" cy="14" r="14" fill="#22c55e" stroke="#fff" stroke-width="3" />':o==="error"?'<circle cx="50" cy="14" r="14" fill="#ef4444" stroke="#fff" stroke-width="3" />':o==="running"?'<circle cx="50" cy="14" r="14" fill="#f59e0b" stroke="#fff" stroke-width="3" />':o==="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
|
|
5
|
+
</svg>`}function kn(o){return`data:image/svg+xml;charset=utf-8,${encodeURIComponent(o)}`}function Sn(){if(typeof document>"u")return null;let o=document.querySelector('link[rel="icon"]');return o||(o=document.createElement("link"),o.rel="icon",o.type="image/svg+xml",document.head.appendChild(o)),o}let He="idle";function Oe(o){He=o;const t=Sn();t&&(t.href=kn(Nn(o)))}let Et=!1;function Cn(){Et||typeof document>"u"||(Et=!0,document.addEventListener("visibilitychange",()=>{!document.hidden&&(He==="ready"||He==="error"||He==="attention")&&Oe("idle")}))}let ve="default";typeof window<"u"&&"Notification"in window?ve=Notification.permission:ve="unsupported";async function Dt(){if(ve==="unsupported"||ve==="granted"||ve==="denied")return ve;try{const o=await Notification.requestPermission();return ve=o,o}catch{return"denied"}}function tt(o,t,s){if(!(typeof document>"u"||!document.hidden)&&ve==="granted")try{const a=new Notification(o,{body:t,icon:"/favicon.ico",tag:s??"wrongstack-run",requireInteraction:s==="wrongstack-confirm"});a.onclick=()=>{window.focus(),a.close()}}catch{}}const St="ws_token";function $n(){try{return sessionStorage.getItem(St)}catch{return null}}function Tn(o){try{sessionStorage.setItem(St,o)}catch{}}function Mn(){try{sessionStorage.removeItem(St)}catch{}}class En{constructor(t){de(this,"ws",null);de(this,"url");de(this,"handlers",new Map);de(this,"reconnectAttempts",0);de(this,"maxReconnectAttempts",10);de(this,"reconnectDelay",1e3);de(this,"shouldReconnect",!0);de(this,"reconnectTimer",null);de(this,"messageQueue",[]);de(this,"pendingConfirms",new Map);de(this,"sessionId",null);de(this,"lastErrorText");de(this,"statusListeners",new Set);de(this,"currentStatus",{state:"connecting"});this.url=t??Dn()}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 s of this.statusListeners)try{s(t)}catch{}}async connect(){return new Promise((t,s)=>{var a;if(((a=this.ws)==null?void 0:a.readyState)===WebSocket.OPEN){t();return}this.setStatus({state:"connecting"});try{const n=$n(),r=n?`${this.url}${this.url.includes("?")?"&":"?"}token=${n}`:this.url;this.ws=new WebSocket(r),this.ws.binaryType="arraybuffer";const i=setTimeout(()=>{s(new Error("Connection timeout"))},1e4);let d=!1;this.ws.onopen=()=>{clearTimeout(i),d=!0,console.log("[WS Client] Connected"),this.reconnectAttempts=0,this.lastErrorText=void 0,this.setStatus({state:"open"}),this.flushMessageQueue(),t()},this.ws.onmessage=l=>{try{const u=JSON.parse(l.data);this.handleMessage(u)}catch(u){console.error("[WS Client] Failed to parse message",u)}},this.ws.onerror=l=>{console.error("[WS Client] Error",l),this.lastErrorText="Connection error (see browser devtools)",d||(clearTimeout(i),s(new Error(this.lastErrorText)))},this.ws.onclose=l=>{if(console.log("[WS Client] Disconnected",l.code,l.reason),!d){clearTimeout(i);const u=l.reason||`Closed with code ${l.code}`;this.lastErrorText=u,s(new Error(u));return}l.reason&&!this.lastErrorText?this.lastErrorText=`${l.reason} (code ${l.code})`:!this.lastErrorText&&l.code!==1e3&&(this.lastErrorText=`Closed with code ${l.code}`),this.attemptReconnect()}}catch(n){this.lastErrorText=n instanceof Error?n.message:String(n),this.setStatus({state:"closed",error:this.lastErrorText}),s(n)}})}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),s=Date.now()+t;console.log(`[WS Client] Reconnecting in ${t}ms (attempt ${this.reconnectAttempts})`),this.setStatus({state:"reconnecting",attempt:this.reconnectAttempts,nextRetryAt:s,lastError:this.lastErrorText}),this.reconnectTimer=setTimeout(async()=>{if(this.shouldReconnect)try{await this.connect()}catch(a){console.error("[WS Client] Reconnect failed",a)}},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 s=t.payload;this.pendingConfirms.set(s.id,{resolve:s.resolve});const a={...t,payload:{...s,resolve:()=>{}}};this.emit(a);return}if(t.type==="session.start"){const s=t.payload;this.sessionId=s.sessionId,s.wsToken&&Tn(s.wsToken)}this.emit(t)}emit(t){const s=this.handlers.get(t.type);if(s)for(const a of s)try{a(t)}catch(n){console.error(`[WS Client] Handler error for ${t.type}`,n)}}send(t){var s;((s=this.ws)==null?void 0:s.readyState)===WebSocket.OPEN?this.ws.send(JSON.stringify(t)):this.messageQueue.push(t)}on(t,s){let a=this.handlers.get(t);return a||(a=new Set,this.handlers.set(t,a)),a.add(s),()=>a==null?void 0:a.delete(s)}off(t,s){var a;(a=this.handlers.get(t))==null||a.delete(s)}sendMessage(t){const s=`msg_${Date.now()}_${crypto.randomUUID().slice(0,8)}`;return this.send({type:"user_message",payload:{id:s,content:t,timestamp:Date.now()}}),s}sendAbort(){this.send({type:"abort",payload:{}})}sendConfirm(t,s){const a=this.pendingConfirms.get(t);a&&(a.resolve(s),this.pendingConfirms.delete(t)),this.send({type:"tool.confirm_result",payload:{id:t,decision:s}})}switchModel(t,s){this.send({type:"model.switch",payload:{provider:t,model:s}})}listProviders(){this.send({type:"providers.list"})}listProviderModels(t){this.send({type:"provider.models",payload:{providerId:t}})}listSavedProviders(){this.send({type:"providers.saved"})}addKey(t,s,a){this.send({type:"key.add",payload:{providerId:t,label:s,apiKey:a}})}updateKey(t,s,a){this.send({type:"key.update",payload:{providerId:t,label:s,apiKey:a}})}deleteKey(t,s){this.send({type:"key.delete",payload:{providerId:t,label:s}})}setActiveKey(t,s){this.send({type:"key.set_active",payload:{providerId:t,label:s}})}addProvider(t,s,a,n){this.send({type:"provider.add",payload:{id:t,family:s,baseUrl:a,apiKey:n}})}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,s){this.send({type:"memory.remember",payload:{text:t,scope:s}})}forget(t,s){this.send({type:"memory.forget",payload:{text:t,scope:s}})}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,s){this.send({type:"files.list",payload:{query:t,limit:s}})}getTodos(){this.send({type:"todos.get"})}clearTodos(){this.send({type:"todos.clear"})}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,Mn()}get isConnected(){var t;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN}get currentSessionId(){return this.sessionId}}let st=null;function Dn(){var s;if(typeof window>"u"||!((s=window.location)!=null&&s.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`}function xe(o){return st||(st=new En(o)),st}function Ln(o){if(!o)return o;const t=o.split(/\n{2,}/),s=[];for(const n of t)s.length>0&&s[s.length-1].trim()===n.trim()||s.push(n);return s.map(n=>{const r=n.split(`
|
|
6
6
|
`),i=[];for(const d of r)i.length>0&&d.trim().length>0&&i[i.length-1].trim()===d.trim()||i.push(d);return i.join(`
|
|
7
7
|
`)}).join(`
|
|
8
8
|
|
|
9
|
-
`)}const T
|
|
9
|
+
`)}const T=$e()(Ve((o,t)=>({messages:[],currentAssistantMessageId:null,currentToolId:null,isLoading:!1,abortController:null,executions:new Map,queue:[],runStart:null,thinkingBuffer:"",thinkingStartedAt:null,addMessage:s=>{const a=`msg_${Date.now()}_${crypto.randomUUID().slice(0,8)}`,n={...s,id:a,timestamp:Date.now()};return o(r=>({messages:[...r.messages,n],currentAssistantMessageId:s.role==="assistant"?a:r.currentAssistantMessageId})),a},updateMessage:(s,a)=>{o(n=>({messages:n.messages.map(r=>r.id===s?{...r,...a}:r)}))},appendToMessage:(s,a)=>{o(n=>({messages:n.messages.map(r=>r.id===s?{...r,content:r.content+a}:r)}))},finalizeMessage:s=>{o(a=>({messages:a.messages.map(n=>n.id===s?{...n,content:Ln(n.content),streaming:!1}:n)}))},setToolResult:(s,a,n)=>{o(r=>({messages:r.messages.map(i=>i.id===s?{...i,toolResult:a,isError:!n,progressLines:void 0}:i)}))},appendToolProgress:(s,a)=>{o(n=>({messages:n.messages.map(r=>{if(r.id!==s)return r;const d=[...r.progressLines??[],a],l=d.length>30?d.slice(d.length-30):d;return{...r,progressLines:l}})}))},setLoading:s=>o({isLoading:s}),setAbortController:s=>o({abortController:s}),clearMessages:()=>o({messages:[],currentAssistantMessageId:null,currentToolId:null,executions:new Map}),setCurrentAssistantMessage:s=>o({currentAssistantMessageId:s}),setCurrentToolId:s=>o({currentToolId:s}),truncateAfter:s=>o(a=>{const n=a.messages.findIndex(r=>r.id===s);return n===-1?a:{messages:a.messages.slice(0,n),currentAssistantMessageId:null,currentToolId:null}}),addExecution:s=>{o(a=>{const n=new Map(a.executions);return n.set(s.id,s),{executions:n}})},updateExecution:(s,a)=>{o(n=>{const r=new Map(n.executions),i=r.get(s);return i&&r.set(s,{...i,...a}),{executions:r}})},enqueue:s=>o(a=>({queue:[...a.queue,s]})),dequeue:()=>{const{queue:s}=t();if(s.length===0)return null;const[a,...n]=s;return o({queue:n}),a},removeQueued:s=>o(a=>({queue:a.queue.filter((n,r)=>r!==s)})),clearQueue:()=>o({queue:[]}),setRunStart:s=>o({runStart:s}),appendThinking:s=>o(a=>({thinkingBuffer:a.thinkingBuffer+s,thinkingStartedAt:a.thinkingStartedAt??Date.now()})),clearThinking:()=>o({thinkingBuffer:"",thinkingStartedAt:null})}),{name:"wrongstack-chat",partialize:()=>({})})),q=$e()(Ve(o=>({provider:"anthropic",model:"claude-sonnet-4-20250514",wsUrl:(()=>{var s;if(typeof window>"u"||!((s=window.location)!=null&&s.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=>o({provider:t}),setModel:t=>o({model:t}),setConfig:t=>o(t),setTheme:t=>o({theme:t}),setWsConnected:t=>o({wsConnected:t}),setWsStatus:t=>o({wsStatus:t,wsConnected:t.state==="open"}),setSoundOnComplete:t=>o({soundOnComplete:t})}),{name:"wrongstack-config"})),W=$e()(Ve(o=>({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=>o({session:t}),updateUsage:t=>o(s=>{const a=t.input+(t.cacheRead??0)+(t.cacheWrite??0),n=t.cacheRead??0,r=t.cacheWrite??0;return{totalTokens:{input:s.totalTokens.input+t.input,output:s.totalTokens.output+t.output,cacheRead:(s.totalTokens.cacheRead??0)+n,cacheWrite:(s.totalTokens.cacheWrite??0)+r},lastInputTokens:a||s.lastInputTokens}}),addCost:t=>o(s=>({cost:s.cost+t})),startSession:t=>o({session:t,startTime:Date.now(),iteration:null,lastInputTokens:0,totalTokens:{input:0,output:0,cacheRead:0,cacheWrite:0},cost:0}),endSession:()=>o({session:null,startTime:null,iteration:null}),setEnv:t=>o(s=>({maxContext:t.maxContext??s.maxContext,projectName:t.projectName??s.projectName,mode:t.mode??s.mode,contextMode:t.contextMode??s.contextMode,inputCost:t.inputCost??s.inputCost,outputCost:t.outputCost??s.outputCost,cacheReadCost:t.cacheReadCost??s.cacheReadCost})),setIteration:t=>o({iteration:t}),setModes:t=>o({modes:t}),setContextModes:t=>o({contextModes:t}),setTodos:t=>o({todos:t})}),{name:"wrongstack-session",partialize:()=>({})})),I=$e()(Ve(o=>({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:()=>o(t=>({sidebarOpen:!t.sidebarOpen})),setSidebarOpen:t=>o({sidebarOpen:t}),setSettingsOpen:t=>o({settingsOpen:t}),setCurrentView:t=>o({currentView:t}),showConfirm:t=>o({showConfirmDialog:!0,confirmInfo:t}),hideConfirm:()=>o({showConfirmDialog:!1,confirmInfo:null}),setPaletteOpen:t=>o({paletteOpen:t}),setShortcutsOpen:t=>o({shortcutsOpen:t}),setSearchOpen:t=>o({searchOpen:t,searchQuery:""}),setSearchQuery:t=>o({searchQuery:t}),pushPrompt:t=>o(s=>{const a=t.trim();if(!a)return s;const n=s.promptHistory.filter(r=>r!==a);return{promptHistory:[a,...n].slice(0,50)}}),setSidebarWidth:t=>o({sidebarWidth:Math.max(200,Math.min(480,Math.round(t)))}),togglePin:t=>o(s=>({pinnedIds:s.pinnedIds.includes(t)?s.pinnedIds.filter(n=>n!==t):[...s.pinnedIds,t]})),unpinAll:()=>o({pinnedIds:[]}),toggleCompactMode:()=>o(t=>({compactMode:!t.compactMode})),setModelSwitcherOpen:t=>o({modelSwitcherOpen:t}),toggleFavoriteSession:t=>o(s=>({favoriteSessionIds:s.favoriteSessionIds.includes(t)?s.favoriteSessionIds.filter(n=>n!==t):[...s.favoriteSessionIds,t]})),setSessionNickname:(t,s)=>o(a=>{const n=s.trim(),r={...a.sessionNicknames};return n?r[t]=n:delete r[t],{sessionNicknames:r}})}),{name:"wrongstack-ui",partialize:o=>({sidebarOpen:o.sidebarOpen,sidebarWidth:o.sidebarWidth,promptHistory:o.promptHistory,pinnedIds:o.pinnedIds,compactMode:o.compactMode,favoriteSessionIds:o.favoriteSessionIds,sessionNicknames:o.sessionNicknames})})),Re=$e()(o=>({entries:[],loading:!1,error:null,setEntries:(t,s=null)=>o({entries:t,error:s,loading:!1}),setLoading:t=>o({loading:t}),removeEntry:t=>o(s=>({entries:s.entries.filter(a=>a.id!==t)})),clearHistory:()=>o({entries:[]})})),Lt=$e()(o=>({worktrees:[],baseBranch:"",activity:[],setSnapshot:(t,s)=>o({worktrees:t,baseBranch:s}),pushEvent:t=>o(s=>({activity:[...s.activity,t].slice(-40)}))}));function Rn(o){const t=[],s=(a,n)=>{t.push(o.on(a,n))};return s("session.start",a=>{var l;const n=a.payload,r=(l=W.getState().session)==null?void 0:l.id,i=!r||r!==n.sessionId;W.getState().startSession({id:n.sessionId,startedAt:Date.now(),model:n.model,provider:n.provider}),W.getState().setEnv({maxContext:n.maxContext,projectName:n.projectName,mode:n.mode,contextMode:n.contextMode,inputCost:n.inputCost,outputCost:n.outputCost,cacheReadCost:n.cacheReadCost}),q.getState().setConfig({provider:n.provider,model:n.model}),(i||n.reset)&&T.getState().clearMessages();const d=n.replayMessages;if(d&&d.length>0){const u=T.getState();for(const m of d)if(m.role==="user"||m.role==="assistant"||m.role==="system"){let x="";if(typeof m.content=="string")x=m.content;else if(Array.isArray(m.content)){for(const p of m.content)if(p.type==="text"&&typeof p.text=="string")x+=(x?`
|
|
10
10
|
`:"")+p.text;else if(p.type==="tool_use")x&&(u.addMessage({role:m.role,content:x}),x=""),u.addMessage({role:"tool",content:"",toolName:String(p.name??"tool"),toolInput:p.input,toolUseId:String(p.id??"")});else if(p.type==="tool_result"){const f=T.getState().messages;let w;for(let N=f.length-1;N>=0;N--)if(f[N].toolUseId===String(p.tool_use_id??"")){w=f[N];break}w&&u.setToolResult(w.id,typeof p.content=="string"?p.content:JSON.stringify(p.content),!p.is_error)}}x&&u.addMessage({role:m.role,content:x})}}}),s("context.debug",a=>{const n=a.payload,r=u=>u.toLocaleString(),i=[...n.tools.breakdown].sort((u,m)=>m.tokens-u.tokens).slice(0,8),d=[...n.messages.breakdown].sort((u,m)=>m.tokens-u.tokens).slice(0,8),l=["📊 **Context breakdown** (heuristic — 4 chars/token)","",`**Total estimate:** ${r(n.total)} tokens`,`• System prompt: ${r(n.systemPrompt)}`,`• Tool schemas: ${r(n.tools.total)} (${n.tools.count} tools)`,`• Messages: ${r(n.messages.total)} (${n.messages.count} messages)`,"","**Top tool schemas:**",...i.map(u=>` · ${u.name}: ${r(u.tokens)}`),"","**Top messages:**",...d.map(u=>` · #${u.index} ${u.role}: ${r(u.tokens)} — ${u.preview||"(empty)"}`)];T.getState().addMessage({role:"assistant",content:l.join(`
|
|
11
|
-
`)})}),s("key.operation_result",a=>{const n=a.payload;n.success?Ue.success(n.message):Ue.error(n.message)}),s("context.compacted",a=>{const n=a.payload;let r=n.reductions.length?n.reductions.map(i=>`${i.phase}: ${i.saved}`).join(", "):"no-op";n.repaired&&(r+=`; repaired ${n.repaired.removedToolUses.length} tool_use, ${n.repaired.removedToolResults.length} tool_result, ${n.repaired.removedMessages} empty messages`),T.getState().addMessage({role:"assistant",content:`🗜️ Context compacted: ${n.before} → ${n.after} tokens (saved ~${n.saved}). ${r}`}),W.setState({lastInputTokens:n.after})}),s("provider.response",a=>{const n=a.payload,r=n==null?void 0:n.usage;if(!r)return;const i=(r.input??0)+(r.cacheWrite??0)-(r.cacheRead??0);i>0&&W.setState({lastInputTokens:i})}),s("context.repaired",a=>{const n=a.payload,r=n.removedToolUses.length+n.removedToolResults.length+n.removedMessages,i=n.beforeMessages!==void 0&&n.afterMessages!==void 0?` Messages: ${n.beforeMessages} -> ${n.afterMessages}.`:"";T.getState().addMessage({role:"assistant",content:`Context repaired: removed ${r} orphan protocol item(s).${i} tool_use ${n.removedToolUses.length}, tool_result ${n.removedToolResults.length}.`})}),s("session.end",()=>{
|
|
11
|
+
`)})}),s("key.operation_result",a=>{const n=a.payload;n.success?Ue.success(n.message):Ue.error(n.message)}),s("context.compacted",a=>{const n=a.payload;let r=n.reductions.length?n.reductions.map(i=>`${i.phase}: ${i.saved}`).join(", "):"no-op";n.repaired&&(r+=`; repaired ${n.repaired.removedToolUses.length} tool_use, ${n.repaired.removedToolResults.length} tool_result, ${n.repaired.removedMessages} empty messages`),T.getState().addMessage({role:"assistant",content:`🗜️ Context compacted: ${n.before} → ${n.after} tokens (saved ~${n.saved}). ${r}`}),W.setState({lastInputTokens:n.after})}),s("provider.response",a=>{const n=a.payload,r=n==null?void 0:n.usage;if(!r)return;const i=(r.input??0)+(r.cacheWrite??0)-(r.cacheRead??0);i>0&&W.setState({lastInputTokens:i})}),s("context.repaired",a=>{const n=a.payload,r=n.removedToolUses.length+n.removedToolResults.length+n.removedMessages,i=n.beforeMessages!==void 0&&n.afterMessages!==void 0?` Messages: ${n.beforeMessages} -> ${n.afterMessages}.`:"";T.getState().addMessage({role:"assistant",content:`Context repaired: removed ${r} orphan protocol item(s).${i} tool_use ${n.removedToolUses.length}, tool_result ${n.removedToolResults.length}.`})}),s("session.end",()=>{q.getState().setWsConnected(!1)}),s("iteration.started",a=>{const n=a.payload;W.getState().setIteration({index:n.index,max:n.maxIterations??0}),T.getState().setLoading(!0),typeof document<"u"&&document.hidden&&Oe("running"),T.getState().runStart===null&&T.getState().setRunStart({at:Date.now(),cost:W.getState().cost}),T.getState().setCurrentAssistantMessage(null)}),s("provider.text_delta",a=>{const n=a.payload;T.getState().clearThinking();let r=T.getState().currentAssistantMessageId;r||(r=T.getState().addMessage({role:"assistant",content:"",streaming:!0}),T.getState().setCurrentAssistantMessage(r)),T.getState().appendToMessage(r,n.text)}),s("provider.thinking_delta",a=>{const n=a.payload;n.text&&T.getState().appendThinking(n.text)}),s("tool.started",a=>{const n=a.payload,r=T.getState().messages.find(d=>d.toolUseId===n.id);if(r){T.getState().setCurrentToolId(r.id);return}T.getState().clearThinking(),T.getState().setCurrentAssistantMessage(null);const i=T.getState().addMessage({role:"tool",content:"",toolName:n.name,toolInput:n.input,toolUseId:n.id});T.getState().setCurrentToolId(i),T.getState().addExecution({id:n.id,name:n.name,input:n.input,ok:!0,startedAt:Date.now()})}),s("tool.progress",a=>{var u,m;const n=a.payload,r=(((u=n.event)==null?void 0:u.text)??"").trim();if(!r)return;const d=T.getState().messages.find(x=>x.toolUseId===n.id);if(!d)return;const l=((m=n.event)==null?void 0:m.type)==="warning"?"⚠ ":"";T.getState().appendToolProgress(d.id,l+r)}),s("tool.executed",a=>{const n=a.payload,{messages:r,currentToolId:i}=T.getState(),d=n.id?r.find(l=>l.toolUseId===n.id):i?r.find(l=>l.id===i):void 0;(d==null?void 0:d.toolResult)===void 0&&(d&&(T.getState().setToolResult(d.id,n.output??"",n.ok),T.getState().updateMessage(d.id,{toolDurationMs:n.durationMs})),n.id&&T.getState().updateExecution(n.id,{completedAt:Date.now(),durationMs:n.durationMs,output:n.output,ok:n.ok}),i&&d&&d.id===i&&T.getState().setCurrentToolId(null))}),s("provider.response",a=>{const n=a.payload;W.getState().updateUsage(n.usage);const{inputCost:r,outputCost:i,cacheReadCost:d}=W.getState(),l=(n.usage.input*r+n.usage.output*i+(n.usage.cacheRead??0)*d)/1e6;l>0&&W.getState().addCost(l),n.stopReason!=="tool_use"&&n.stopReason!=="tool_call"&&T.getState().setLoading(!1);const u=T.getState().currentAssistantMessageId;u&&(T.getState().finalizeMessage(u),n.usage.output>0&&T.getState().updateMessage(u,{usage:n.usage})),T.getState().setCurrentAssistantMessage(null),T.getState().clearThinking()}),s("tool.confirm_needed",a=>{const n=a.payload;I.getState().showConfirm({id:n.id,toolName:n.toolName,input:n.input,suggestedPattern:n.suggestedPattern});try{wn()}catch{}Dt(),tt("WrongStack needs approval",`Tool "${n.toolName}" is waiting for your decision.`,"wrongstack-confirm"),typeof document<"u"&&document.hidden&&Oe("attention")}),s("run.result",a=>{const n=a.payload;W.getState().setIteration(null),T.getState().setLoading(!1),T.getState().setCurrentAssistantMessage(null),T.getState().clearThinking();const r=T.getState().runStart;if(r&&n.status==="done"){const d=T.getState().messages;let l=-1,u=0;for(let m=d.length-1;m>=0;m--){const x=d[m];if(x.role==="assistant"&&l===-1&&x.content&&(l=m),x.role==="tool"&&x.timestamp>=r.at&&(u+=1),x.role==="user"&&x.timestamp<=r.at)break}if(l!==-1){const m=W.getState().cost;T.getState().updateMessage(d[l].id,{runSummary:{iterations:n.iterations,tools:u,durationMs:Date.now()-r.at,costDelta:Math.max(0,m-r.cost)}})}}if(T.getState().setRunStart(null),n.status!=="done"&&n.error)T.getState().addMessage({role:"assistant",content:`Error: ${n.error.message}`,isError:!0}),Ue.error(`Run ended: ${n.error.message}`),tt("WrongStack run failed",n.error.message),typeof document<"u"&&document.hidden&&Oe("error");else if(n.status==="done"&&(typeof document<"u"&&document.hidden&&(Ue.success(`Run completed in ${n.iterations} iteration${n.iterations===1?"":"s"}`),tt("WrongStack run finished",`Completed in ${n.iterations} iteration${n.iterations===1?"":"s"}.`),Oe("ready")),Dt(),q.getState().soundOnComplete))try{kt()}catch{}const i=T.getState().dequeue();if(i){const d=xe(q.getState().wsUrl);T.getState().addMessage({role:"user",content:i}),T.getState().setLoading(!0),d.sendMessage(i)}}),s("tools.list",a=>{const n=a.payload,r=[`🛠️ **Registered tools** (${n.tools.length})`,"",...n.tools.map(i=>`• \`${i.name}\`${i.params.length?` (${i.params.join(", ")})`:""} — ${i.description||"_no description_"}`)];T.getState().addMessage({role:"assistant",content:r.join(`
|
|
12
12
|
`)})}),s("memory.list",a=>{var i;const n=a.payload,r=(i=n.text)==null?void 0:i.trim();T.getState().addMessage({role:"assistant",content:n.error?`Memory read failed: ${n.error}`:r?`🧠 **Memory**
|
|
13
13
|
|
|
14
14
|
${r}`:`🧠 **Memory**
|
|
@@ -18,8 +18,8 @@ _empty — nothing remembered yet_`})}),s("skills.list",a=>{const n=a.payload;if
|
|
|
18
18
|
_disabled (config.features.skills = false)_`});return}const r=[`🎯 **Skills** (${n.skills.length})`,"",...n.skills.length===0?["_none registered_"]:n.skills.map(i=>`• \`${i.name}\`${i.version?` v${i.version}`:""} _(${i.source})_ — ${i.description||i.trigger||"_no description_"}`)];n.error&&r.push("",`⚠ ${n.error}`),T.getState().addMessage({role:"assistant",content:r.join(`
|
|
19
19
|
`)})}),s("diag.get",a=>{const n=a.payload,r=["🩺 **Runtime diagnostics**","",`**Provider:** \`${n.provider}\` / \`${n.model}\``,`**Mode:** \`${n.mode}\``,`**Session:** \`${n.sessionId}\``,`**CWD:** \`${n.cwd}\``,"",`**Tools:** ${n.tools.count}`,`**Messages:** ${n.messages} · **Todos:** ${n.todos}`,`**Usage:** ${n.usage.input.toLocaleString()} in · ${n.usage.output.toLocaleString()} out${n.usage.cacheRead?` · ${n.usage.cacheRead.toLocaleString()} cache`:""}`,"",`**Features:** memory=${n.features.memory?"✓":"✗"} · skills=${n.features.skills?"✓":"✗"} · modelsRegistry=${n.features.modelsRegistry?"✓":"✗"}`];T.getState().addMessage({role:"assistant",content:r.join(`
|
|
20
20
|
`)})}),s("stats.get",a=>{const n=a.payload,r=Math.floor(n.elapsedMs/1e3),i=r<60?`${r}s`:r<3600?`${Math.floor(r/60)}m ${r%60}s`:`${Math.floor(r/3600)}h ${Math.floor(r%3600/60)}m`,d=["📈 **Session stats**","",`**Session:** \`${n.sessionId}\``,`**Provider/Model:** \`${n.provider}\` / \`${n.model}\``,`**Elapsed:** ${i}`,"",`**Usage:** ${n.usage.input.toLocaleString()} in · ${n.usage.output.toLocaleString()} out`,...n.cache&&n.cache.readTokens>0?[`**Cache:** ${n.cache.readTokens.toLocaleString()} read · ${n.cache.writeTokens.toLocaleString()} write · hit ratio ${(n.cache.hitRatio*100).toFixed(1)}%`]:[],`**Cost:** $${n.cost.toFixed(4)}`,"",`**Messages:** ${n.messages} · **Files read:** ${n.readFiles} · **Tools available:** ${n.tools}`];T.getState().addMessage({role:"assistant",content:d.join(`
|
|
21
|
-
`)})}),s("todos.updated",a=>{const n=a.payload;W.getState().setTodos(n.todos??[])}),s("modes.list",a=>{const n=a.payload;W.getState().setModes(n.modes.map(r=>({id:r.id,name:r.name,description:r.description}))),W.getState().setEnv({mode:n.activeId})}),s("context.modes.list",a=>{const n=a.payload;W.getState().setContextModes(n.modes.map(r=>({id:r.id,name:r.name,description:r.description,thresholds:r.thresholds,preserveK:r.preserveK,eliseThreshold:r.eliseThreshold}))),W.getState().setEnv({contextMode:n.activeId})}),s("context.mode.changed",a=>{const n=a.payload;W.getState().setEnv({contextMode:n.id})}),s("sessions.list",a=>{const n=a.payload;Le.getState().setEntries(n.sessions??[],n.error??null)}),s("error",a=>{const n=a.payload;T.getState().addMessage({role:"assistant",content:`[${n.phase}] ${n.message}`,isError:!0}),T.getState().setLoading(!1)}),()=>{for(const a of t)a()}}function Rn(){const{autoConnect:o,wsUrl:t}=B(),s=B(n=>n.setWsStatus),a=c.useRef(!1);c.useEffect(()=>{if(!o)return;Sn();const n=xe(t),r=n.onStatus(d=>s(d));if(n.connect().catch(d=>{console.error("[WS] Connection failed:",d)}),a.current)return()=>{r()};a.current=!0;const i=Ln(n);return()=>{i(),r()}},[o,t,s])}function ge(){const{wsUrl:o}=B(),t=xe(o),s=c.useCallback(L=>t.isConnected?t.sendMessage(L):null,[t]),a=c.useCallback(()=>t.sendAbort(),[t]),{hideConfirm:n}=I(),r=c.useCallback((L,Y)=>{t.sendConfirm(L,Y),n()},[t,n]),i=c.useCallback((L,Y)=>t.switchModel(L,Y),[t]),d=c.useCallback(()=>t.listProviders(),[t]),l=c.useCallback(L=>t.listProviderModels(L),[t]),u=c.useCallback(()=>t.listSavedProviders(),[t]),m=c.useCallback((L,Y,b)=>t.addKey(L,Y,b),[t]),x=c.useCallback((L,Y,b)=>t.updateKey(L,Y,b),[t]),p=c.useCallback((L,Y)=>t.deleteKey(L,Y),[t]),f=c.useCallback((L,Y)=>t.setActiveKey(L,Y),[t]),w=c.useCallback((L,Y,b,M)=>t.addProvider(L,Y,b,M),[t]),N=c.useCallback(L=>t.removeProvider(L),[t]),$=c.useCallback(L=>{Le.getState().setLoading(!0),t.listSessions(L)},[t]),v=c.useCallback(L=>{Le.getState().removeEntry(L),t.deleteSession(L)},[t]),y=c.useCallback(L=>t.resumeSessionById(L),[t]),E=c.useCallback(()=>t.saveSession(),[t]),se=c.useCallback(()=>t.listTools(),[t]),F=c.useCallback(()=>t.listMemory(),[t]),_=c.useCallback(()=>t.listSkills(),[t]),V=c.useCallback(()=>t.getDiag(),[t]),U=c.useCallback(()=>t.getStats(),[t]),J=c.useCallback(()=>t.listModes(),[t]),ne=c.useCallback(L=>t.switchMode(L),[t]),ie=c.useCallback(()=>t.listContextModes(),[t]),X=c.useCallback(L=>t.switchContextMode(L),[t]),z=c.useCallback(()=>t.repairContext(),[t]),re=c.useCallback(L=>{t.send({type:"autophase.toggleAutonomous",payload:{autonomous:L}})},[t]),Q=c.useCallback((L,Y,b=!0)=>{t.send({type:"autophase.start",payload:{title:L,phases:Y,autonomous:b}})},[t]),S=c.useCallback(()=>{t.send({type:"autophase.pause",payload:{}})},[t]),Z=c.useCallback(()=>{t.send({type:"autophase.resume",payload:{}})},[t]),O=c.useCallback(()=>{t.send({type:"autophase.stop",payload:{}})},[t]),ee=c.useCallback(L=>{t.send({type:"autophase.selectPhase",payload:{phaseId:L}})},[t]);return{client:t,sendMessage:s,sendAbort:a,sendConfirm:r,switchModel:i,listProviders:d,listProviderModels:l,listSavedProviders:u,addKey:m,updateKey:x,deleteKey:p,setActiveKey:f,addProvider:w,removeProvider:N,listSessions:$,deleteSession:v,resumeSession:y,saveSession:E,listTools:se,listMemory:F,listSkills:_,getDiag:V,getStats:U,listModes:J,switchMode:ne,listContextModes:ie,switchContextMode:X,repairContext:z,toggleAutoPhaseAutonomous:re,startAutoPhase:Q,pauseAutoPhase:S,resumeAutoPhase:Z,stopAutoPhase:O,selectAutoPhase:ee}}function An(){const o=I($=>$.paletteOpen),t=I($=>$.setPaletteOpen),s=I($=>$.setCurrentView),a=B($=>$.setTheme),{entries:n}=Le(),{addMessage:r,clearMessages:i}=T(),d=ge(),[l,u]=c.useState(""),[m,x]=c.useState(0),p=c.useRef(null);c.useEffect(()=>{o&&(u(""),x(0),requestAnimationFrame(()=>{var $;return($=p.current)==null?void 0:$.focus()}))},[o]),c.useEffect(()=>{const $=v=>{if((v.ctrlKey||v.metaKey)&&v.key.toLowerCase()==="k"){v.preventDefault(),t(!I.getState().paletteOpen);return}v.key==="Escape"&&I.getState().paletteOpen&&(v.preventDefault(),t(!1))};return window.addEventListener("keydown",$),()=>window.removeEventListener("keydown",$)},[t]);const f=c.useMemo(()=>{const $=[{id:"help",category:"Command",label:"Show slash commands",icon:ws,keywords:["help","commands","?"],run:()=>{r({role:"assistant",content:"Type `/` in the message box to see every slash command."})}},{id:"tools",category:"Command",label:"List tools",icon:qe,keywords:["tools","list"],run:()=>d.listTools()},{id:"memory",category:"Command",label:"Show memory",icon:Ot,keywords:["memory","remember","notes"],run:()=>d.listMemory()},{id:"skills",category:"Command",label:"List skills",icon:Pt,keywords:["skills"],run:()=>d.listSkills()},{id:"diag",category:"Command",label:"Runtime diagnostics",icon:js,keywords:["diag","diagnostics","debug"],run:()=>d.getDiag()},{id:"stats",category:"Command",label:"Session stats (tokens, cache, cost)",icon:Ns,keywords:["stats","tokens","cost","cache"],run:()=>d.getStats()},{id:"clear",category:"Session",label:"Clear context",hint:"Wipe in-memory context, keep session id",icon:Fe,keywords:["clear","reset","wipe"],run:()=>{var v,y;i(),(y=(v=d.client)==null?void 0:v.clearContext)==null||y.call(v)}},{id:"new",category:"Session",label:"New session",hint:"Brand-new on disk + memory",icon:Ke,keywords:["new","fresh","session"],run:()=>{var v,y;return(y=(v=d.client)==null?void 0:v.newSession)==null?void 0:y.call(v)}},{id:"compact",category:"Session",label:"Compact context",icon:it,keywords:["compact","shrink","context"],run:()=>{var v,y;return(y=(v=d.client)==null?void 0:v.compactContext)==null?void 0:y.call(v)}},{id:"repair-context",category:"Session",label:"Repair context",hint:"Remove orphan tool protocol blocks",icon:qe,keywords:["repair","context","tool_use","tool_result"],run:()=>{var v,y;return(y=(v=d.client)==null?void 0:v.repairContext)==null?void 0:y.call(v)}},{id:"export",category:"Session",label:"Export chat as markdown",icon:lt,keywords:["export","save","markdown","download"],run:()=>Ct()},{id:"export-html",category:"Session",label:"Export chat as HTML",hint:"Self-contained, opens in any browser",icon:lt,keywords:["export","html","download","archive"],run:()=>On()},{id:"history",category:"Command",label:"Open history",icon:ct,keywords:["history","sessions"],run:()=>s("history")},{id:"settings",category:"Command",label:"Open settings",icon:ht,keywords:["settings","config"],run:()=>s("settings")},{id:"model",category:"Command",label:"Change provider/model",icon:_e,keywords:["model","provider","change"],run:()=>s("settings")},{id:"theme-light",category:"Theme",label:"Theme: Light",icon:ft,keywords:["theme","light","mode"],run:()=>a("light")},{id:"theme-dark",category:"Theme",label:"Theme: Dark",icon:gt,keywords:["theme","dark","mode"],run:()=>a("dark")},{id:"theme-system",category:"Theme",label:"Theme: Follow system",icon:bt,keywords:["theme","system","auto"],run:()=>a("system")},{id:"compact-toggle",category:"Command",label:"Toggle compact density",icon:ks,hint:"Ctrl+Shift+D",keywords:["compact","dense","density","size"],run:()=>I.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?Ss:Cs,hint:"Chime when a run finishes",keywords:["sound","audio","chime","notify","beep"],run:()=>{const v=!B.getState().soundOnComplete;B.getState().setSoundOnComplete(v),v&&kt()}}];for(const v of n.slice(0,10))v.isCurrent||$.push({id:`resume-${v.id}`,category:"Session",label:`Resume: ${v.title||"(empty)"}`,hint:`${v.provider}/${v.model}`,icon:Ft,keywords:["resume",v.title,v.id,v.provider,v.model],run:()=>d.resumeSession(v.id)});return $},[n,d,s,a,r,i]),w=c.useMemo(()=>{const $=l.toLowerCase().trim();return $?f.filter(v=>[v.label,v.hint??"",v.category,...v.keywords??[]].join(" ").toLowerCase().includes($)):f},[f,l]);if(c.useEffect(()=>{m>=w.length&&x(0)},[w.length,m]),!o)return null;const N=$=>{$&&(t(!1),$.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:$=>{$.key==="Escape"&&t(!1)},children:e.jsxs("div",{onClick:$=>$.stopPropagation(),onKeyDown:$=>$.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(Ee,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("input",{ref:p,value:l,onChange:$=>u($.target.value),placeholder:"Search commands, sessions, settings…",className:"flex-1 bg-transparent outline-none text-sm placeholder:text-muted-foreground",onKeyDown:$=>{$.key==="ArrowDown"?($.preventDefault(),x(v=>(v+1)%Math.max(1,w.length))):$.key==="ArrowUp"?($.preventDefault(),x(v=>(v-1+Math.max(1,w.length))%Math.max(1,w.length))):$.key==="Enter"&&($.preventDefault(),N(w[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:w.length===0?e.jsxs("div",{className:"px-4 py-8 text-center text-sm text-muted-foreground",children:['No matches for "',l,'"']}):In(w,m,N,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 In(o,t,s,a){const n={};return o.forEach((r,i)=>{n[r.category]||(n[r.category]=[]),n[r.category].push({item:r,globalIdx:i})}),e.jsx("div",{className:"p-1",children:Object.entries(n).map(([r,i])=>e.jsxs("div",{children:[e.jsx("div",{className:"px-3 pt-2 pb-1 text-[10px] uppercase tracking-wider text-muted-foreground",children:r}),i.map(({item:d,globalIdx:l})=>{const u=d.icon,m=l===t;return e.jsxs("button",{type:"button",onMouseEnter:()=>a(l),onClick:()=>s(d),className:C("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:d.label}),d.hint&&e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:d.hint})]}),m&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"↵"})]},d.id)})]},r))})}function Ct(){const o=T.getState().messages,t=[],s=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-");t.push("# WrongStack chat export"),t.push(`*Exported: ${new Date().toISOString()}*`),t.push("");for(const i of o)if(i.role==="user")t.push("## 👤 User"),t.push(""),t.push(i.content),t.push("");else if(i.role==="assistant")t.push("## 🤖 Assistant"),t.push(""),t.push(i.content),t.push("");else if(i.role==="tool"){const d=i.isError?"❌":i.toolResult!==void 0?"✅":"⏳";t.push(`### 🔧 Tool: \`${i.toolName??"unknown"}\` ${d}`),i.toolInput!==void 0&&(t.push("```json"),t.push(JSON.stringify(i.toolInput,null,2)),t.push("```")),i.toolResult&&(t.push("<details><summary>Output</summary>"),t.push(""),t.push("```"),t.push(i.toolResult),t.push("```"),t.push("</details>")),t.push("")}const a=new Blob([t.join(`
|
|
22
|
-
`)],{type:"text/markdown"}),n=URL.createObjectURL(a),r=document.createElement("a");r.href=n,r.download=`wrongstack-chat-${s}.md`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(n)}function
|
|
21
|
+
`)})}),s("todos.updated",a=>{const n=a.payload;W.getState().setTodos(n.todos??[])}),s("modes.list",a=>{const n=a.payload;W.getState().setModes(n.modes.map(r=>({id:r.id,name:r.name,description:r.description}))),W.getState().setEnv({mode:n.activeId})}),s("context.modes.list",a=>{const n=a.payload;W.getState().setContextModes(n.modes.map(r=>({id:r.id,name:r.name,description:r.description,thresholds:r.thresholds,preserveK:r.preserveK,eliseThreshold:r.eliseThreshold}))),W.getState().setEnv({contextMode:n.activeId})}),s("context.mode.changed",a=>{const n=a.payload;W.getState().setEnv({contextMode:n.id})}),s("sessions.list",a=>{const n=a.payload;Re.getState().setEntries(n.sessions??[],n.error??null)}),s("error",a=>{const n=a.payload;T.getState().addMessage({role:"assistant",content:`[${n.phase}] ${n.message}`,isError:!0}),T.getState().setLoading(!1)}),s("worktree.state",a=>{const n=a.payload;Lt.getState().setSnapshot(n.worktrees??[],n.baseBranch??"")}),s("worktree.event",a=>{const n=a.payload;Lt.getState().pushEvent(n)}),()=>{for(const a of t)a()}}function An(){const{autoConnect:o,wsUrl:t}=q(),s=q(n=>n.setWsStatus),a=c.useRef(!1);c.useEffect(()=>{if(!o)return;Cn();const n=xe(t),r=n.onStatus(d=>s(d));if(n.connect().catch(d=>{console.error("[WS] Connection failed:",d)}),a.current)return()=>{r()};a.current=!0;const i=Rn(n);return()=>{i(),r()}},[o,t,s])}function ge(){const{wsUrl:o}=q(),t=xe(o),s=c.useCallback(L=>t.isConnected?t.sendMessage(L):null,[t]),a=c.useCallback(()=>t.sendAbort(),[t]),{hideConfirm:n}=I(),r=c.useCallback((L,Y)=>{t.sendConfirm(L,Y),n()},[t,n]),i=c.useCallback((L,Y)=>t.switchModel(L,Y),[t]),d=c.useCallback(()=>t.listProviders(),[t]),l=c.useCallback(L=>t.listProviderModels(L),[t]),u=c.useCallback(()=>t.listSavedProviders(),[t]),m=c.useCallback((L,Y,b)=>t.addKey(L,Y,b),[t]),x=c.useCallback((L,Y,b)=>t.updateKey(L,Y,b),[t]),p=c.useCallback((L,Y)=>t.deleteKey(L,Y),[t]),f=c.useCallback((L,Y)=>t.setActiveKey(L,Y),[t]),w=c.useCallback((L,Y,b,M)=>t.addProvider(L,Y,b,M),[t]),N=c.useCallback(L=>t.removeProvider(L),[t]),$=c.useCallback(L=>{Re.getState().setLoading(!0),t.listSessions(L)},[t]),v=c.useCallback(L=>{Re.getState().removeEntry(L),t.deleteSession(L)},[t]),y=c.useCallback(L=>t.resumeSessionById(L),[t]),E=c.useCallback(()=>t.saveSession(),[t]),se=c.useCallback(()=>t.listTools(),[t]),F=c.useCallback(()=>t.listMemory(),[t]),_=c.useCallback(()=>t.listSkills(),[t]),V=c.useCallback(()=>t.getDiag(),[t]),U=c.useCallback(()=>t.getStats(),[t]),J=c.useCallback(()=>t.listModes(),[t]),ne=c.useCallback(L=>t.switchMode(L),[t]),ie=c.useCallback(()=>t.listContextModes(),[t]),X=c.useCallback(L=>t.switchContextMode(L),[t]),z=c.useCallback(()=>t.repairContext(),[t]),re=c.useCallback(L=>{t.send({type:"autophase.toggleAutonomous",payload:{autonomous:L}})},[t]),Q=c.useCallback((L,Y,b=!0)=>{t.send({type:"autophase.start",payload:{title:L,phases:Y,autonomous:b}})},[t]),S=c.useCallback(()=>{t.send({type:"autophase.pause",payload:{}})},[t]),Z=c.useCallback(()=>{t.send({type:"autophase.resume",payload:{}})},[t]),O=c.useCallback(()=>{t.send({type:"autophase.stop",payload:{}})},[t]),ee=c.useCallback(L=>{t.send({type:"autophase.selectPhase",payload:{phaseId:L}})},[t]);return{client:t,sendMessage:s,sendAbort:a,sendConfirm:r,switchModel:i,listProviders:d,listProviderModels:l,listSavedProviders:u,addKey:m,updateKey:x,deleteKey:p,setActiveKey:f,addProvider:w,removeProvider:N,listSessions:$,deleteSession:v,resumeSession:y,saveSession:E,listTools:se,listMemory:F,listSkills:_,getDiag:V,getStats:U,listModes:J,switchMode:ne,listContextModes:ie,switchContextMode:X,repairContext:z,toggleAutoPhaseAutonomous:re,startAutoPhase:Q,pauseAutoPhase:S,resumeAutoPhase:Z,stopAutoPhase:O,selectAutoPhase:ee}}function In(){const o=I($=>$.paletteOpen),t=I($=>$.setPaletteOpen),s=I($=>$.setCurrentView),a=q($=>$.setTheme),{entries:n}=Re(),{addMessage:r,clearMessages:i}=T(),d=ge(),[l,u]=c.useState(""),[m,x]=c.useState(0),p=c.useRef(null);c.useEffect(()=>{o&&(u(""),x(0),requestAnimationFrame(()=>{var $;return($=p.current)==null?void 0:$.focus()}))},[o]),c.useEffect(()=>{const $=v=>{if((v.ctrlKey||v.metaKey)&&v.key.toLowerCase()==="k"){v.preventDefault(),t(!I.getState().paletteOpen);return}v.key==="Escape"&&I.getState().paletteOpen&&(v.preventDefault(),t(!1))};return window.addEventListener("keydown",$),()=>window.removeEventListener("keydown",$)},[t]);const f=c.useMemo(()=>{const $=[{id:"help",category:"Command",label:"Show slash commands",icon:js,keywords:["help","commands","?"],run:()=>{r({role:"assistant",content:"Type `/` in the message box to see every slash command."})}},{id:"tools",category:"Command",label:"List tools",icon:Be,keywords:["tools","list"],run:()=>d.listTools()},{id:"memory",category:"Command",label:"Show memory",icon:Pt,keywords:["memory","remember","notes"],run:()=>d.listMemory()},{id:"skills",category:"Command",label:"List skills",icon:Ft,keywords:["skills"],run:()=>d.listSkills()},{id:"diag",category:"Command",label:"Runtime diagnostics",icon:Ns,keywords:["diag","diagnostics","debug"],run:()=>d.getDiag()},{id:"stats",category:"Command",label:"Session stats (tokens, cache, cost)",icon:ks,keywords:["stats","tokens","cost","cache"],run:()=>d.getStats()},{id:"clear",category:"Session",label:"Clear context",hint:"Wipe in-memory context, keep session id",icon:Fe,keywords:["clear","reset","wipe"],run:()=>{var v,y;i(),(y=(v=d.client)==null?void 0:v.clearContext)==null||y.call(v)}},{id:"new",category:"Session",label:"New session",hint:"Brand-new on disk + memory",icon:Ke,keywords:["new","fresh","session"],run:()=>{var v,y;return(y=(v=d.client)==null?void 0:v.newSession)==null?void 0:y.call(v)}},{id:"compact",category:"Session",label:"Compact context",icon:it,keywords:["compact","shrink","context"],run:()=>{var v,y;return(y=(v=d.client)==null?void 0:v.compactContext)==null?void 0:y.call(v)}},{id:"repair-context",category:"Session",label:"Repair context",hint:"Remove orphan tool protocol blocks",icon:Be,keywords:["repair","context","tool_use","tool_result"],run:()=>{var v,y;return(y=(v=d.client)==null?void 0:v.repairContext)==null?void 0:y.call(v)}},{id:"export",category:"Session",label:"Export chat as markdown",icon:lt,keywords:["export","save","markdown","download"],run:()=>Ct()},{id:"export-html",category:"Session",label:"Export chat as HTML",hint:"Self-contained, opens in any browser",icon:lt,keywords:["export","html","download","archive"],run:()=>Pn()},{id:"history",category:"Command",label:"Open history",icon:ct,keywords:["history","sessions"],run:()=>s("history")},{id:"settings",category:"Command",label:"Open settings",icon:ht,keywords:["settings","config"],run:()=>s("settings")},{id:"model",category:"Command",label:"Change provider/model",icon:_e,keywords:["model","provider","change"],run:()=>s("settings")},{id:"theme-light",category:"Theme",label:"Theme: Light",icon:ft,keywords:["theme","light","mode"],run:()=>a("light")},{id:"theme-dark",category:"Theme",label:"Theme: Dark",icon:gt,keywords:["theme","dark","mode"],run:()=>a("dark")},{id:"theme-system",category:"Theme",label:"Theme: Follow system",icon:bt,keywords:["theme","system","auto"],run:()=>a("system")},{id:"compact-toggle",category:"Command",label:"Toggle compact density",icon:Ss,hint:"Ctrl+Shift+D",keywords:["compact","dense","density","size"],run:()=>I.getState().toggleCompactMode()},{id:"sound-toggle",category:"Command",label:q.getState().soundOnComplete?"Sound on completion: ON — turn off":"Sound on completion: OFF — turn on",icon:q.getState().soundOnComplete?Cs:$s,hint:"Chime when a run finishes",keywords:["sound","audio","chime","notify","beep"],run:()=>{const v=!q.getState().soundOnComplete;q.getState().setSoundOnComplete(v),v&&kt()}}];for(const v of n.slice(0,10))v.isCurrent||$.push({id:`resume-${v.id}`,category:"Session",label:`Resume: ${v.title||"(empty)"}`,hint:`${v.provider}/${v.model}`,icon:_t,keywords:["resume",v.title,v.id,v.provider,v.model],run:()=>d.resumeSession(v.id)});return $},[n,d,s,a,r,i]),w=c.useMemo(()=>{const $=l.toLowerCase().trim();return $?f.filter(v=>[v.label,v.hint??"",v.category,...v.keywords??[]].join(" ").toLowerCase().includes($)):f},[f,l]);if(c.useEffect(()=>{m>=w.length&&x(0)},[w.length,m]),!o)return null;const N=$=>{$&&(t(!1),$.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:$=>{$.key==="Escape"&&t(!1)},children:e.jsxs("div",{onClick:$=>$.stopPropagation(),onKeyDown:$=>$.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(De,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("input",{ref:p,value:l,onChange:$=>u($.target.value),placeholder:"Search commands, sessions, settings…",className:"flex-1 bg-transparent outline-none text-sm placeholder:text-muted-foreground",onKeyDown:$=>{$.key==="ArrowDown"?($.preventDefault(),x(v=>(v+1)%Math.max(1,w.length))):$.key==="ArrowUp"?($.preventDefault(),x(v=>(v-1+Math.max(1,w.length))%Math.max(1,w.length))):$.key==="Enter"&&($.preventDefault(),N(w[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:w.length===0?e.jsxs("div",{className:"px-4 py-8 text-center text-sm text-muted-foreground",children:['No matches for "',l,'"']}):On(w,m,N,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 On(o,t,s,a){const n={};return o.forEach((r,i)=>{n[r.category]||(n[r.category]=[]),n[r.category].push({item:r,globalIdx:i})}),e.jsx("div",{className:"p-1",children:Object.entries(n).map(([r,i])=>e.jsxs("div",{children:[e.jsx("div",{className:"px-3 pt-2 pb-1 text-[10px] uppercase tracking-wider text-muted-foreground",children:r}),i.map(({item:d,globalIdx:l})=>{const u=d.icon,m=l===t;return e.jsxs("button",{type:"button",onMouseEnter:()=>a(l),onClick:()=>s(d),className:C("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:d.label}),d.hint&&e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:d.hint})]}),m&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"↵"})]},d.id)})]},r))})}function Ct(){const o=T.getState().messages,t=[],s=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-");t.push("# WrongStack chat export"),t.push(`*Exported: ${new Date().toISOString()}*`),t.push("");for(const i of o)if(i.role==="user")t.push("## 👤 User"),t.push(""),t.push(i.content),t.push("");else if(i.role==="assistant")t.push("## 🤖 Assistant"),t.push(""),t.push(i.content),t.push("");else if(i.role==="tool"){const d=i.isError?"❌":i.toolResult!==void 0?"✅":"⏳";t.push(`### 🔧 Tool: \`${i.toolName??"unknown"}\` ${d}`),i.toolInput!==void 0&&(t.push("```json"),t.push(JSON.stringify(i.toolInput,null,2)),t.push("```")),i.toolResult&&(t.push("<details><summary>Output</summary>"),t.push(""),t.push("```"),t.push(i.toolResult),t.push("```"),t.push("</details>")),t.push("")}const a=new Blob([t.join(`
|
|
22
|
+
`)],{type:"text/markdown"}),n=URL.createObjectURL(a),r=document.createElement("a");r.href=n,r.download=`wrongstack-chat-${s}.md`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(n)}function Pn(){var u,m,x;const o=T.getState().messages,t=W.getState(),s=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),a=p=>p.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),n=o.map(p=>{if(p.role==="tool"){const $=p.isError?"❌":p.toolResult!==void 0?"✅":"⏳";return`
|
|
23
23
|
<section class="bubble tool ${p.isError?"error":""}">
|
|
24
24
|
<header><span class="icon">🔧</span><code>${a(p.toolName??"tool")}</code> ${$}</header>
|
|
25
25
|
${p.toolInput!==void 0?`<details><summary>Input</summary><pre>${a(JSON.stringify(p.toolInput,null,2))}</pre></details>`:""}
|
|
@@ -64,31 +64,31 @@ _disabled (config.features.skills = false)_`});return}const r=[`🎯 **Skills**
|
|
|
64
64
|
Exported ${new Date().toISOString()}${(x=t.session)!=null&&x.provider?` · ${escape(t.session.provider)}/${escape(t.session.model)}`:""} · ${o.length} message${o.length===1?"":"s"}
|
|
65
65
|
</div>
|
|
66
66
|
${n.join("")}
|
|
67
|
-
</body></html>`,i=new Blob([r],{type:"text/html;charset=utf-8"}),d=URL.createObjectURL(i),l=document.createElement("a");l.href=d,l.download=`wrongstack-chat-${s}.html`,document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(d)}function
|
|
68
|
-
`)}),!0}case"/clear":return a(),(K=w==null?void 0:w.clearContext)==null||K.call(w),!0;case"/new":return(ce=w==null?void 0:w.newSession)==null||ce.call(w),!0;case"/compact":case"/compact!":return(G=w==null?void 0:w.compactContext)==null||G.call(w,g==="/compact!"),!0;case"/repair":return(ue=w==null?void 0:w.repairContext)==null||ue.call(w),!0;case"/debug":case"/context":return(me=w==null?void 0:w.debugContext)==null||me.call(w),!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(R.toLowerCase()==="clear")return(ae=w==null?void 0:w.clearTodos)==null||ae.call(w),!0;const A=W.getState().todos;if(A.length===0)return s({role:"assistant",content:"✅ **Todos** — _empty. Ask the agent to plan something and they'll show up here._"}),!0;const
|
|
69
|
-
`)}),!0}case"/export":return Ct(),s({role:"assistant",content:"📥 Chat exported to your downloads folder."}),!0;case"/abort":case"/stop":return f(),t(!1),!0;case"/settings":case"/model":return l("settings"),!0;default:return!1}},[s,a,w,f,t,l,x]),Q=v.startsWith("/")&&!v.includes(" ")?
|
|
70
|
-
`)===-1){b.preventDefault();const j=Math.min(m.length-1,F+1);_(j);const R=m[j]??"";y(R),requestAnimationFrame(()=>{const g=z.current;g&&(g.style.height="auto",g.style.height=`${Math.min(g.scrollHeight,200)}px`,g.setSelectionRange(R.length,R.length))});return}}if(b.key==="ArrowDown"&&F>=0){b.preventDefault();const M=F-1;if(M<0)_(-1),y("");else{_(M);const h=m[M]??"";y(h),requestAnimationFrame(()=>{const j=z.current;j&&(j.style.height="auto",j.style.height=`${Math.min(j.scrollHeight,200)}px`,j.setSelectionRange(h.length,h.length))})}return}}if(Q.length>0){if(b.key==="ArrowDown"){b.preventDefault(),se(M=>(M+1)%Q.length);return}if(b.key==="ArrowUp"){b.preventDefault(),se(M=>(M-1+Q.length)%Q.length);return}if(b.key==="Tab"){b.preventDefault();const M=Q[E];M&&(y(M.name+" "),se(0));return}if(b.key==="Enter"&&!b.shiftKey){const M=Q[E];if(M&&M.name!==v.toLowerCase().trim()){b.preventDefault(),y(""),re(M.name);return}}if(b.key==="Escape"){b.preventDefault(),y("");return}}b.key==="Enter"&&!b.shiftKey&&(b.preventDefault(),Z(b))},[Q,E,V,m,F,v,re,Z]),Y=()=>{const b=z.current;b&&(b.style.height="auto",b.style.height=`${Math.min(b.scrollHeight,200)}px`)};return e.jsxs("div",{className:"flex flex-col gap-2",children:[J&&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:J.chars.toLocaleString()})," chars (",e.jsx("span",{className:"font-mono tabular-nums",children:J.lines})," lines) — fenced code blocks render best with ",e.jsx("span",{className:"font-mono",children:"```"}),"."]}),e.jsx("button",{type:"button",onClick:()=>ne(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:"×"})]}),n.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 (",n.length,")"]}),e.jsx("button",{type:"button",onClick:d,className:"text-muted-foreground hover:text-destructive text-xs",children:"Clear all"})]}),e.jsx("ul",{className:"space-y-1",children:n.map((b,M)=>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:b}),e.jsx("button",{type:"button",onClick:()=>i(M),className:"text-muted-foreground hover:text-destructive shrink-0",title:"Remove from queue",children:"×"})]},M))})]}),e.jsxs("form",{onSubmit:Z,onDragEnter:b=>{!b.dataTransfer||!Array.from(b.dataTransfer.types).includes("Files")||(b.preventDefault(),X(!0))},onDragOver:b=>{!b.dataTransfer||!Array.from(b.dataTransfer.types).includes("Files")||(b.preventDefault(),b.dataTransfer.dropEffect="copy")},onDragLeave:b=>{b.currentTarget.contains(b.relatedTarget)||X(!1)},onDrop:b=>{if(!b.dataTransfer)return;const M=Array.from(b.dataTransfer.files??[]);if(M.length===0){X(!1);return}b.preventDefault(),X(!1);const h=z.current,j=(h==null?void 0:h.selectionStart)??v.length,R=v.slice(0,j),g=v.slice(j),ce=R.length>0&&!/\s$/.test(R)?" ":"",G=M.map(pe=>`@${pe.name}`),ue=G.join(" "),ae=g.length===0||!/^\s/.test(g)?" ":"",D=`${ce}${ue}${ae}`,A=R+D+g;y(A);const
|
|
71
|
-
`).length;ne({chars:M.length,lines:j}),setTimeout(()=>ne(null),4e3)}},placeholder:w!=null&&w.isConnected?o?"Agent is running — type to queue a follow-up…":"Message WrongStack… (type / for commands, @ for files)":"Connect to server first…",className:C("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:!(w!=null&&w.isConnected)}),v.length>0&&(()=>{const b=v.length>=400,M=Math.ceil(v.length/4);let h="text-muted-foreground",j;if($>0&&b){const g=(N+M+64)/$*100;g>=100?(h="text-red-600 dark:text-red-400 font-medium",j=`Projected ${Math.round(g)}% of ${$.toLocaleString()} ctx — will likely error or compact.`):g>=85?(h="text-amber-600 dark:text-amber-400 font-medium",j=`Projected ${Math.round(g)}% of ${$.toLocaleString()} ctx — getting tight.`):j=`≈ ${M.toLocaleString()} tokens · projected ${Math.round(g)}% of ${$.toLocaleString()} ctx.`}else b&&(j=`≈ ${M.toLocaleString()} tokens (4-char heuristic)`);return e.jsxs("span",{className:C("absolute bottom-1.5 right-12 text-xs tabular-nums",h),title:j,children:[v.length,b&&e.jsxs("span",{className:"ml-1 opacity-70",children:["· ≈",M>=1e3?`${(M/1e3).toFixed(1)}k`:M,"t"]})]})})()]}),e.jsx("div",{className:"flex gap-1",children:o?e.jsxs(e.Fragment,{children:[e.jsx(H,{type:"button",size:"icon",variant:"outline",onClick:ee,className:"h-[44px] w-[44px] rounded-lg",title:"Stop run and edit the last prompt (reuse + rewrite)",children:e.jsx(_t,{className:"h-4 w-4"})}),e.jsx(H,{type:"button",size:"icon",variant:"destructive",onClick:O,className:"h-[44px] w-[44px] rounded-lg",title:"Abort the current run",children:e.jsx(Ds,{className:"h-4 w-4 fill-current"})})]}):e.jsx(H,{type:"submit",size:"icon",disabled:!v.trim()||!(w!=null&&w.isConnected),className:"h-[44px] w-[44px] rounded-lg",children:e.jsx(Ls,{className:"h-4 w-4"})})})]})]})}function Un({wsStatus:o,wsConnected:t}){const s=B(i=>i.wsUrl),[a,n]=c.useState(Date.now());c.useEffect(()=>{if(o.state!=="reconnecting")return;const i=setInterval(()=>n(Date.now()),500);return()=>clearInterval(i)},[o.state]);const r=()=>xe(s).retryNow();if(o.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(Kt,{className:"h-3 w-3"})});if(o.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(we,{className:"h-3 w-3 animate-spin"}),e.jsx("span",{children:"connecting"})]});if(o.state==="reconnecting"){const i=Math.max(0,Math.ceil((o.nextRetryAt-a)/1e3));return e.jsxs("button",{type:"button",onClick:r,className:C("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:o.lastError?`Reconnecting — last error: ${o.lastError}. Click to retry now.`:"Reconnecting — click to retry now.",children:[e.jsx(we,{className:"h-3 w-3 animate-spin"}),e.jsxs("span",{children:["retry #",o.attempt," in ",i,"s"]})]})}return e.jsxs("button",{type:"button",onClick:r,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:o.state==="closed"&&o.error?`Disconnected: ${o.error}. Click to retry.`:"Disconnected. Click to retry.",children:[e.jsx(yt,{className:"h-3 w-3"}),e.jsxs("span",{className:"flex items-center gap-0.5",children:["offline",e.jsx(Ke,{className:"h-3 w-3 opacity-70"})]})]})}const zn=[{id:"balanced",name:"Balanced",description:"Default rolling compaction",thresholds:{warn:.6,soft:.75,hard:.9},preserveK:10,eliseThreshold:2e3}];function Hn(){const o=W(u=>u.contextMode),t=W(u=>u.contextModes),{listContextModes:s,switchContextMode:a}=ge(),[n,r]=c.useState(!1),i=c.useRef(null);c.useEffect(()=>{n&&s()},[n,s]),c.useEffect(()=>{if(!n)return;const u=x=>{var p;(p=i.current)!=null&&p.contains(x.target)||r(!1)},m=x=>{x.key==="Escape"&&r(!1)};return document.addEventListener("mousedown",u),document.addEventListener("keydown",m),()=>{document.removeEventListener("mousedown",u),document.removeEventListener("keydown",m)}},[n]);const d=t.length>0?t:zn,l=d.find(u=>u.id===o)??d[0];return e.jsxs("div",{ref:i,className:"relative shrink-0",children:[e.jsxs("button",{type:"button",onClick:()=>r(u=>!u),className:C("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(Rs,{className:"h-3 w-3"}),"ctx: ",e.jsx("span",{className:"font-mono",children:o||l.id}),e.jsx(We,{className:"h-3 w-3 opacity-60"})]}),n&&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"}),d.map(u=>e.jsxs("button",{type:"button",onClick:()=>{a(u.id),r(!1)},className:C("w-full text-left px-3 py-2 hover:bg-accent/40 flex items-start gap-2",u.id===o&&"bg-accent/30"),children:[e.jsx(vt,{className:C("h-3.5 w-3.5 mt-0.5 shrink-0",u.id===o?"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 qn(){const o=W(x=>x.cost),t=W(x=>x.inputCost),s=W(x=>x.outputCost),a=W(x=>x.cacheReadCost),n=T(x=>x.messages),[r,i]=c.useState(!1),d=c.useRef(null);c.useEffect(()=>{if(!r)return;const x=f=>{var w;(w=d.current)!=null&&w.contains(f.target)||i(!1)},p=f=>{f.key==="Escape"&&i(!1)};return document.addEventListener("mousedown",x),document.addEventListener("keydown",p),()=>{document.removeEventListener("mousedown",x),document.removeEventListener("keydown",p)}},[r]);const l=(()=>{const x=[];for(const p of n)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,f)=>f.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||s>0;return e.jsxs("div",{ref:d,className:"relative inline-block",children:[e.jsxs("button",{type:"button",onClick:()=>i(x=>!x),className:C("font-medium text-green-600 dark:text-green-400 hover:underline tabular-nums"),title:"Click for per-turn cost breakdown",children:["$",o.toFixed(4)]}),r&&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(o)})]}),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:["$",s.toFixed(2)]})]}),a>0&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"cache /1M"}),e.jsxs("span",{children:["$",a.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."}),l.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 ",l.length," expensive turn",l.length===1?"":"s"]}),e.jsx("ul",{className:"space-y-1",children:l.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"}),i(!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 Bn=["path","file_path","pattern","command","cmd","url","query","description","content"];function Vn(o,t){if(t==null)return"";if(typeof t!="object")return be(String(t),120);const s=t,a=(o??"").toLowerCase();if(/^todo(_?write)?$|^todos$/i.test(a)||Array.isArray(s.todos)){const r=s.todos??[];if(Array.isArray(r)){const i=r.filter(u=>u.status==="completed").length,d=r.filter(u=>u.status==="in_progress").length,l=[`${r.length} todo${r.length===1?"":"s"}`];return i>0&&l.push(`${i} done`),d>0&&l.push(`${d} in-progress`),l.join(" · ")}}if(/batch|parallel/.test(a)||Array.isArray(s.tool_uses)||Array.isArray(s.calls)){const r=s.tool_uses??s.calls??s.batch;if(Array.isArray(r)){const i=new Set;for(const u of r)u&&typeof u=="object"&&"name"in u&&i.add(String(u.name));const d=[...i].slice(0,3).join(", "),l=i.size>3?` +${i.size-3}`:"";return`${r.length} sub-tool${r.length===1?"":"s"}${d?` · ${d}${l}`:""}`}}if(/^(edit|str_replace|edit_file|patch)$/.test(a)){const r=nt(s),i=typeof s.old_string=="string"?s.old_string:"",d=typeof s.new_string=="string"?s.new_string:"",l=i?i.split(`
|
|
67
|
+
</body></html>`,i=new Blob([r],{type:"text/html;charset=utf-8"}),d=URL.createObjectURL(i),l=document.createElement("a");l.href=d,l.download=`wrongstack-chat-${s}.html`,document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(d)}function Fn({query:o,onPick:t,onClose:s}){const a=ge(),n=q(x=>x.wsUrl),[r,i]=c.useState([]),[d,l]=c.useState(0),u=c.useRef(null),m=c.useRef(null);return c.useEffect(()=>{const p=xe(n).on("files.list",f=>{var N;const w=f.payload;i(w.files??[]),l(0),(N=m.current)==null||N.resolve(w.files??[]),m.current=null});return()=>p()},[n]),c.useEffect(()=>(u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{a.client.listFiles(o,50)},80),()=>{u.current&&clearTimeout(u.current)}),[o,a.client]),c.useEffect(()=>{const x=p=>{if(p.key==="ArrowDown")p.preventDefault(),l(f=>(f+1)%Math.max(1,r.length));else if(p.key==="ArrowUp")p.preventDefault(),l(f=>(f-1+Math.max(1,r.length))%Math.max(1,r.length));else if(p.key==="Enter"||p.key==="Tab"){if(r.length===0)return;p.preventDefault(),t(r[d])}else p.key==="Escape"&&(p.preventDefault(),s())};return window.addEventListener("keydown",x,!0),()=>window.removeEventListener("keydown",x,!0)},[r,d,t,s]),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 ",o&&`· "${o}"`]}),e.jsx("span",{children:"↑/↓ select · ↵ insert · Esc dismiss"})]}),r.length===0?e.jsx("div",{className:"px-3 py-2 text-xs text-muted-foreground italic",children:o?`No files match "${o}"`:"Searching project…"}):r.map((x,p)=>e.jsxs("button",{type:"button",onClick:()=>t(x),onMouseEnter:()=>l(p),className:C("w-full text-left px-3 py-1.5 rounded transition-colors flex items-center gap-2 font-mono text-xs",p===d?"bg-accent text-accent-foreground":"hover:bg-accent/40"),children:[x.includes("/")?e.jsx(Ts,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}):e.jsx(Ms,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),e.jsx("span",{className:"truncate",children:x})]},x))]})}const _n=Ds("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"}}),H=c.forwardRef(({className:o,variant:t,size:s,asChild:a=!1,...n},r)=>{const i=a?Es:"button";return e.jsx(i,{className:C(_n({variant:t,size:s,className:o})),ref:r,...n})});H.displayName="Button";const dt=[{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)"}],Kn=["Run","Session","Inspect","App"];function Rt(o,t){let s=t-1;for(;s>=0;){const a=o[s];if(a==="@"){const n=s>0?o[s-1]:"";return s===0||/\s/.test(n??"")?{start:s,query:o.slice(s+1,t)}:null}if(/\s/.test(a))return null;s--}return null}function Wn(o){const t=o.toLowerCase();return t==="/"||t===""?dt:dt.filter(s=>{var a;return s.name.startsWith(t)||(((a=s.aliases)==null?void 0:a.some(n=>n.startsWith(t)))??!1)})}function Un(){const{isLoading:o,setLoading:t,addMessage:s,clearMessages:a}=T(),n=T(b=>b.queue),r=T(b=>b.enqueue),i=T(b=>b.removeQueued),d=T(b=>b.clearQueue),{setCurrentView:l}=I(),u=I(b=>b.pushPrompt),m=I(b=>b.promptHistory),x=ge(),{sendMessage:p,sendAbort:f,client:w}=x,N=W(b=>b.lastInputTokens),$=W(b=>b.maxContext),[v,y]=c.useState(""),[E,se]=c.useState(0),[F,_]=c.useState(-1),[V,U]=c.useState(null),[J,ne]=c.useState(null),[ie,X]=c.useState(!1),z=c.useRef(null),re=c.useCallback(b=>{var K,ce,G,ue,me,ae;const M=b.trim(),h=M.indexOf(" "),j=(h===-1?M:M.slice(0,h)).toLowerCase(),R=h===-1?"":M.slice(h+1).trim(),g=j;switch(g){case"/help":{const D=["📖 **Slash commands**","",...dt.map(A=>{var B;return`• \`${A.name}\`${(B=A.aliases)!=null&&B.length?` (${A.aliases.map(te=>`\`${te}\``).join(", ")})`:""} — ${A.description}`})];return s({role:"assistant",content:D.join(`
|
|
68
|
+
`)}),!0}case"/clear":return a(),(K=w==null?void 0:w.clearContext)==null||K.call(w),!0;case"/new":return(ce=w==null?void 0:w.newSession)==null||ce.call(w),!0;case"/compact":case"/compact!":return(G=w==null?void 0:w.compactContext)==null||G.call(w,g==="/compact!"),!0;case"/repair":return(ue=w==null?void 0:w.repairContext)==null||ue.call(w),!0;case"/debug":case"/context":return(me=w==null?void 0:w.debugContext)==null||me.call(w),!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(R.toLowerCase()==="clear")return(ae=w==null?void 0:w.clearTodos)==null||ae.call(w),!0;const A=W.getState().todos;if(A.length===0)return s({role:"assistant",content:"✅ **Todos** — _empty. Ask the agent to plan something and they'll show up here._"}),!0;const B=[`✅ **Todos** (${A.filter(te=>te.status==="completed").length}/${A.length} done)`,""];for(const te of A){const pe=te.status==="completed"?"[x]":te.status==="in_progress"?"[~]":"[ ]",oe=te.status==="in_progress"&&te.activeForm?te.activeForm:te.content;B.push(`- ${pe} ${oe}`)}return B.push("","_Use `/todos clear` to wipe the list._"),s({role:"assistant",content:B.join(`
|
|
69
|
+
`)}),!0}case"/export":return Ct(),s({role:"assistant",content:"📥 Chat exported to your downloads folder."}),!0;case"/abort":case"/stop":return f(),t(!1),!0;case"/settings":case"/model":return l("settings"),!0;default:return!1}},[s,a,w,f,t,l,x]),Q=v.startsWith("/")&&!v.includes(" ")?Wn(v):[];c.useEffect(()=>{E>=Q.length&&se(0)},[Q.length,E]);const S=c.useCallback(()=>{const b=z.current;b&&(b.value="",b.style.height="auto",b.style.height=`${Math.min(b.scrollHeight,200)}px`,o||b.focus())},[o]),Z=c.useCallback(async b=>{if(b.preventDefault(),!v.trim())return;const M=v.trim();if(M.startsWith("/")&&re(M)){u(M),y(""),_(-1),S();return}if(y(""),_(-1),S(),u(M),S(),o){r(M);return}try{w!=null&&w.isConnected?(s({role:"user",content:M}),t(!0),p(M)):console.error("WebSocket not connected")}catch(h){console.error("Failed to send:",h),t(!1)}},[v,o,r,w,p,t,s,re,u,S]),O=c.useCallback(()=>{f(),t(!1)},[f,t]),ee=c.useCallback(()=>{f(),t(!1);const b=T.getState().messages;for(let M=b.length-1;M>=0;M--){const h=b[M];if(h.role==="user"&&h.content){y(h.content),requestAnimationFrame(()=>{const j=z.current;j&&(j.style.height="auto",j.style.height=`${Math.min(j.scrollHeight,200)}px`,j.focus(),j.setSelectionRange(h.content.length,h.content.length))});return}}},[f,t]),L=c.useCallback(b=>{if(Q.length===0&&!V&&m.length>0){if(b.key==="ArrowUp"){const M=b.currentTarget,h=M.value.slice(0,M.selectionStart);if(F>=0||h.indexOf(`
|
|
70
|
+
`)===-1){b.preventDefault();const j=Math.min(m.length-1,F+1);_(j);const R=m[j]??"";y(R),requestAnimationFrame(()=>{const g=z.current;g&&(g.style.height="auto",g.style.height=`${Math.min(g.scrollHeight,200)}px`,g.setSelectionRange(R.length,R.length))});return}}if(b.key==="ArrowDown"&&F>=0){b.preventDefault();const M=F-1;if(M<0)_(-1),y("");else{_(M);const h=m[M]??"";y(h),requestAnimationFrame(()=>{const j=z.current;j&&(j.style.height="auto",j.style.height=`${Math.min(j.scrollHeight,200)}px`,j.setSelectionRange(h.length,h.length))})}return}}if(Q.length>0){if(b.key==="ArrowDown"){b.preventDefault(),se(M=>(M+1)%Q.length);return}if(b.key==="ArrowUp"){b.preventDefault(),se(M=>(M-1+Q.length)%Q.length);return}if(b.key==="Tab"){b.preventDefault();const M=Q[E];M&&(y(M.name+" "),se(0));return}if(b.key==="Enter"&&!b.shiftKey){const M=Q[E];if(M&&M.name!==v.toLowerCase().trim()){b.preventDefault(),y(""),re(M.name);return}}if(b.key==="Escape"){b.preventDefault(),y("");return}}b.key==="Enter"&&!b.shiftKey&&(b.preventDefault(),Z(b))},[Q,E,V,m,F,v,re,Z]),Y=()=>{const b=z.current;b&&(b.style.height="auto",b.style.height=`${Math.min(b.scrollHeight,200)}px`)};return e.jsxs("div",{className:"flex flex-col gap-2",children:[J&&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:J.chars.toLocaleString()})," chars (",e.jsx("span",{className:"font-mono tabular-nums",children:J.lines})," lines) — fenced code blocks render best with ",e.jsx("span",{className:"font-mono",children:"```"}),"."]}),e.jsx("button",{type:"button",onClick:()=>ne(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:"×"})]}),n.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 (",n.length,")"]}),e.jsx("button",{type:"button",onClick:d,className:"text-muted-foreground hover:text-destructive text-xs",children:"Clear all"})]}),e.jsx("ul",{className:"space-y-1",children:n.map((b,M)=>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:b}),e.jsx("button",{type:"button",onClick:()=>i(M),className:"text-muted-foreground hover:text-destructive shrink-0",title:"Remove from queue",children:"×"})]},M))})]}),e.jsxs("form",{onSubmit:Z,onDragEnter:b=>{!b.dataTransfer||!Array.from(b.dataTransfer.types).includes("Files")||(b.preventDefault(),X(!0))},onDragOver:b=>{!b.dataTransfer||!Array.from(b.dataTransfer.types).includes("Files")||(b.preventDefault(),b.dataTransfer.dropEffect="copy")},onDragLeave:b=>{b.currentTarget.contains(b.relatedTarget)||X(!1)},onDrop:b=>{if(!b.dataTransfer)return;const M=Array.from(b.dataTransfer.files??[]);if(M.length===0){X(!1);return}b.preventDefault(),X(!1);const h=z.current,j=(h==null?void 0:h.selectionStart)??v.length,R=v.slice(0,j),g=v.slice(j),ce=R.length>0&&!/\s$/.test(R)?" ":"",G=M.map(pe=>`@${pe.name}`),ue=G.join(" "),ae=g.length===0||!/^\s/.test(g)?" ":"",D=`${ce}${ue}${ae}`,A=R+D+g;y(A);const B=R.length+ce.length+G.slice(0,-1).join(" ").length+(G.length>1?1:0),te=M[M.length-1].name;requestAnimationFrame(()=>{if(h){const pe=R.length+D.length-ae.length;h.focus(),h.setSelectionRange(pe,pe),h.style.height="auto",h.style.height=`${Math.min(h.scrollHeight,200)}px`}U({start:B,query:te})})},className:C("flex items-end gap-2 relative rounded-lg transition-colors",ie&&"ring-2 ring-primary ring-offset-2 ring-offset-background bg-primary/5"),children:[ie&&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:[V&&e.jsx(Fn,{query:V.query,onClose:()=>U(null),onPick:b=>{const M=v.slice(0,V.start),h=v.slice(V.start+1+V.query.length),j=`@${b} `,R=M+j+h;y(R),U(null),requestAnimationFrame(()=>{const g=z.current;if(g){const K=M.length+j.length;g.focus(),g.setSelectionRange(K,K),g.style.height="auto",g.style.height=`${Math.min(g.scrollHeight,200)}px`}})}}),!V&&Q.length>0&&(()=>{const b={};Q.forEach((h,j)=>{b[h.category]||(b[h.category]=[]),b[h.category].push({cmd:h,idx:j})});const M=Kn.filter(h=>{var j;return(j=b[h])==null?void 0:j.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"}),M.map(h=>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:h}),b[h].map(({cmd:j,idx:R})=>{var g;return e.jsxs("button",{type:"button",onClick:()=>{y(""),re(j.name)},onMouseEnter:()=>se(R),className:C("w-full text-left px-3 py-1.5 rounded transition-colors flex items-center gap-3",R===E?"bg-accent text-accent-foreground":"hover:bg-accent/40"),children:[e.jsx("span",{className:"font-mono shrink-0",children:j.name}),(g=j.aliases)!=null&&g.length?e.jsxs("span",{className:"text-xs text-muted-foreground/70 font-mono shrink-0",children:["(",j.aliases.join(", "),")"]}):null,e.jsxs("span",{className:"text-xs text-muted-foreground truncate",children:["— ",j.description]})]},j.name)})]},h))]})})(),e.jsx("textarea",{ref:z,value:v,onChange:b=>{const M=b.target.value;y(M),Y(),F>=0&&_(-1);const h=b.target.selectionStart??M.length;U(Rt(M,h))},onSelect:b=>{const M=b.currentTarget;U(Rt(M.value,M.selectionStart))},onKeyDown:L,onPaste:b=>{var h;const M=((h=b.clipboardData)==null?void 0:h.getData("text"))??"";if(M.length>800){const j=M.split(`
|
|
71
|
+
`).length;ne({chars:M.length,lines:j}),setTimeout(()=>ne(null),4e3)}},placeholder:w!=null&&w.isConnected?o?"Agent is running — type to queue a follow-up…":"Message WrongStack… (type / for commands, @ for files)":"Connect to server first…",className:C("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:!(w!=null&&w.isConnected)}),v.length>0&&(()=>{const b=v.length>=400,M=Math.ceil(v.length/4);let h="text-muted-foreground",j;if($>0&&b){const g=(N+M+64)/$*100;g>=100?(h="text-red-600 dark:text-red-400 font-medium",j=`Projected ${Math.round(g)}% of ${$.toLocaleString()} ctx — will likely error or compact.`):g>=85?(h="text-amber-600 dark:text-amber-400 font-medium",j=`Projected ${Math.round(g)}% of ${$.toLocaleString()} ctx — getting tight.`):j=`≈ ${M.toLocaleString()} tokens · projected ${Math.round(g)}% of ${$.toLocaleString()} ctx.`}else b&&(j=`≈ ${M.toLocaleString()} tokens (4-char heuristic)`);return e.jsxs("span",{className:C("absolute bottom-1.5 right-12 text-xs tabular-nums",h),title:j,children:[v.length,b&&e.jsxs("span",{className:"ml-1 opacity-70",children:["· ≈",M>=1e3?`${(M/1e3).toFixed(1)}k`:M,"t"]})]})})()]}),e.jsx("div",{className:"flex gap-1",children:o?e.jsxs(e.Fragment,{children:[e.jsx(H,{type:"button",size:"icon",variant:"outline",onClick:ee,className:"h-[44px] w-[44px] rounded-lg",title:"Stop run and edit the last prompt (reuse + rewrite)",children:e.jsx(Kt,{className:"h-4 w-4"})}),e.jsx(H,{type:"button",size:"icon",variant:"destructive",onClick:O,className:"h-[44px] w-[44px] rounded-lg",title:"Abort the current run",children:e.jsx(Ls,{className:"h-4 w-4 fill-current"})})]}):e.jsx(H,{type:"submit",size:"icon",disabled:!v.trim()||!(w!=null&&w.isConnected),className:"h-[44px] w-[44px] rounded-lg",children:e.jsx(Rs,{className:"h-4 w-4"})})})]})]})}function zn({wsStatus:o,wsConnected:t}){const s=q(i=>i.wsUrl),[a,n]=c.useState(Date.now());c.useEffect(()=>{if(o.state!=="reconnecting")return;const i=setInterval(()=>n(Date.now()),500);return()=>clearInterval(i)},[o.state]);const r=()=>xe(s).retryNow();if(o.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(Wt,{className:"h-3 w-3"})});if(o.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(we,{className:"h-3 w-3 animate-spin"}),e.jsx("span",{children:"connecting"})]});if(o.state==="reconnecting"){const i=Math.max(0,Math.ceil((o.nextRetryAt-a)/1e3));return e.jsxs("button",{type:"button",onClick:r,className:C("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:o.lastError?`Reconnecting — last error: ${o.lastError}. Click to retry now.`:"Reconnecting — click to retry now.",children:[e.jsx(we,{className:"h-3 w-3 animate-spin"}),e.jsxs("span",{children:["retry #",o.attempt," in ",i,"s"]})]})}return e.jsxs("button",{type:"button",onClick:r,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:o.state==="closed"&&o.error?`Disconnected: ${o.error}. Click to retry.`:"Disconnected. Click to retry.",children:[e.jsx(yt,{className:"h-3 w-3"}),e.jsxs("span",{className:"flex items-center gap-0.5",children:["offline",e.jsx(Ke,{className:"h-3 w-3 opacity-70"})]})]})}const Hn=[{id:"balanced",name:"Balanced",description:"Default rolling compaction",thresholds:{warn:.6,soft:.75,hard:.9},preserveK:10,eliseThreshold:2e3}];function Bn(){const o=W(u=>u.contextMode),t=W(u=>u.contextModes),{listContextModes:s,switchContextMode:a}=ge(),[n,r]=c.useState(!1),i=c.useRef(null);c.useEffect(()=>{n&&s()},[n,s]),c.useEffect(()=>{if(!n)return;const u=x=>{var p;(p=i.current)!=null&&p.contains(x.target)||r(!1)},m=x=>{x.key==="Escape"&&r(!1)};return document.addEventListener("mousedown",u),document.addEventListener("keydown",m),()=>{document.removeEventListener("mousedown",u),document.removeEventListener("keydown",m)}},[n]);const d=t.length>0?t:Hn,l=d.find(u=>u.id===o)??d[0];return e.jsxs("div",{ref:i,className:"relative shrink-0",children:[e.jsxs("button",{type:"button",onClick:()=>r(u=>!u),className:C("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(As,{className:"h-3 w-3"}),"ctx: ",e.jsx("span",{className:"font-mono",children:o||l.id}),e.jsx(We,{className:"h-3 w-3 opacity-60"})]}),n&&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"}),d.map(u=>e.jsxs("button",{type:"button",onClick:()=>{a(u.id),r(!1)},className:C("w-full text-left px-3 py-2 hover:bg-accent/40 flex items-start gap-2",u.id===o&&"bg-accent/30"),children:[e.jsx(vt,{className:C("h-3.5 w-3.5 mt-0.5 shrink-0",u.id===o?"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 qn(){const o=W(x=>x.cost),t=W(x=>x.inputCost),s=W(x=>x.outputCost),a=W(x=>x.cacheReadCost),n=T(x=>x.messages),[r,i]=c.useState(!1),d=c.useRef(null);c.useEffect(()=>{if(!r)return;const x=f=>{var w;(w=d.current)!=null&&w.contains(f.target)||i(!1)},p=f=>{f.key==="Escape"&&i(!1)};return document.addEventListener("mousedown",x),document.addEventListener("keydown",p),()=>{document.removeEventListener("mousedown",x),document.removeEventListener("keydown",p)}},[r]);const l=(()=>{const x=[];for(const p of n)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,f)=>f.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||s>0;return e.jsxs("div",{ref:d,className:"relative inline-block",children:[e.jsxs("button",{type:"button",onClick:()=>i(x=>!x),className:C("font-medium text-green-600 dark:text-green-400 hover:underline tabular-nums"),title:"Click for per-turn cost breakdown",children:["$",o.toFixed(4)]}),r&&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(o)})]}),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:["$",s.toFixed(2)]})]}),a>0&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"cache /1M"}),e.jsxs("span",{children:["$",a.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."}),l.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 ",l.length," expensive turn",l.length===1?"":"s"]}),e.jsx("ul",{className:"space-y-1",children:l.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"}),i(!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 Vn=["path","file_path","pattern","command","cmd","url","query","description","content"];function Qn(o,t){if(t==null)return"";if(typeof t!="object")return be(String(t),120);const s=t,a=(o??"").toLowerCase();if(/^todo(_?write)?$|^todos$/i.test(a)||Array.isArray(s.todos)){const r=s.todos??[];if(Array.isArray(r)){const i=r.filter(u=>u.status==="completed").length,d=r.filter(u=>u.status==="in_progress").length,l=[`${r.length} todo${r.length===1?"":"s"}`];return i>0&&l.push(`${i} done`),d>0&&l.push(`${d} in-progress`),l.join(" · ")}}if(/batch|parallel/.test(a)||Array.isArray(s.tool_uses)||Array.isArray(s.calls)){const r=s.tool_uses??s.calls??s.batch;if(Array.isArray(r)){const i=new Set;for(const u of r)u&&typeof u=="object"&&"name"in u&&i.add(String(u.name));const d=[...i].slice(0,3).join(", "),l=i.size>3?` +${i.size-3}`:"";return`${r.length} sub-tool${r.length===1?"":"s"}${d?` · ${d}${l}`:""}`}}if(/^(edit|str_replace|edit_file|patch)$/.test(a)){const r=nt(s),i=typeof s.old_string=="string"?s.old_string:"",d=typeof s.new_string=="string"?s.new_string:"",l=i?i.split(`
|
|
72
72
|
`).length:0,u=d?d.split(`
|
|
73
73
|
`).length:0;return`edit ${r||"(file)"}${l||u?` (${l} → ${u} lines)`:""}`}if(/^(write|write_file|create_file|new_file)$/.test(a)){const r=nt(s),i=typeof s.content=="string"?s.content:"",d=i?i.split(`
|
|
74
|
-
`).length:0;return`write ${r||"(file)"}${d?` · ${d} lines`:""}`}if(/^(bash|shell|exec|run|run_command|run_shell)$/.test(a)){const r=s.command??s.cmd??s.script;if(typeof r=="string")return`$ ${be(r,110)}`}if(/^(fetch|http|web|webfetch|curl|request)$/.test(a)){const r=s.url;if(typeof r=="string")return`${(s.method??"GET").toUpperCase()} ${be(r,100)}`}if(/^(grep|search|ripgrep)$/.test(a)){const r=s.pattern,i=s.path??s.glob??s.type;if(typeof r=="string")return i?`grep ${be(r,60)} in ${i}`:`grep ${be(r,100)}`}if(/^(glob|find)$/.test(a)){const r=s.pattern??s.glob;if(typeof r=="string")return`glob ${be(r,100)}`}if(/^(read|read_file|cat)$/.test(a)){const r=nt(s),i=s.offset,d=s.limit;if(r&&(typeof i=="number"||typeof d=="number")){const l=i??0,u=typeof d=="number"?l+d:"";return`read ${r} (${l}…${u})`}if(r)return`read ${r}`}for(const r of
|
|
74
|
+
`).length:0;return`write ${r||"(file)"}${d?` · ${d} lines`:""}`}if(/^(bash|shell|exec|run|run_command|run_shell)$/.test(a)){const r=s.command??s.cmd??s.script;if(typeof r=="string")return`$ ${be(r,110)}`}if(/^(fetch|http|web|webfetch|curl|request)$/.test(a)){const r=s.url;if(typeof r=="string")return`${(s.method??"GET").toUpperCase()} ${be(r,100)}`}if(/^(grep|search|ripgrep)$/.test(a)){const r=s.pattern,i=s.path??s.glob??s.type;if(typeof r=="string")return i?`grep ${be(r,60)} in ${i}`:`grep ${be(r,100)}`}if(/^(glob|find)$/.test(a)){const r=s.pattern??s.glob;if(typeof r=="string")return`glob ${be(r,100)}`}if(/^(read|read_file|cat)$/.test(a)){const r=nt(s),i=s.offset,d=s.limit;if(r&&(typeof i=="number"||typeof d=="number")){const l=i??0,u=typeof d=="number"?l+d:"";return`read ${r} (${l}…${u})`}if(r)return`read ${r}`}for(const r of Vn){const i=s[r];if(typeof i=="string"&&i.length>0)return`${r}: ${be(i,100)}`}const n=Gn(t);return be(n,120)}function be(o,t){return o.length>t?`${o.slice(0,t-1)}…`:o}function nt(o){const t=o.file_path??o.path??o.filepath;return typeof t=="string"?t:""}function Gn(o){try{return JSON.stringify(o)}catch{return String(o)}}const os=c.memo(function({oldText:t,newText:s,caption:a}){const n=c.useMemo(()=>Jn(t,s),[t,s]);if(n===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 r=n.filter(d=>d.kind==="add").length,i=n.filter(d=>d.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:a??"diff"}),e.jsxs("span",{className:"font-mono shrink-0",children:[e.jsxs("span",{className:"text-emerald-600 dark:text-emerald-400",children:["+",r]}),e.jsx("span",{className:"text-muted-foreground mx-1",children:"·"}),e.jsxs("span",{className:"text-rose-600 dark:text-rose-400",children:["-",i]})]})]}),e.jsx("div",{className:"font-mono leading-relaxed max-h-96 overflow-auto",children:n.map((d,l)=>e.jsxs("div",{className:C("flex",d.kind==="add"&&"bg-emerald-500/10",d.kind==="del"&&"bg-rose-500/10"),children:[e.jsx("span",{className:C("w-6 shrink-0 text-center select-none",d.kind==="add"&&"text-emerald-600 dark:text-emerald-400",d.kind==="del"&&"text-rose-600 dark:text-rose-400",d.kind==="ctx"&&"text-muted-foreground/40"),children:d.kind==="add"?"+":d.kind==="del"?"-":" "}),e.jsx("pre",{className:C("whitespace-pre-wrap break-all flex-1 px-2",d.kind==="ctx"&&"text-muted-foreground/70"),children:d.text||" "})]},l))})]})}),At=5e3;function Jn(o,t){const s=o.split(`
|
|
75
75
|
`),a=t.split(`
|
|
76
|
-
`);if(s.length>
|
|
77
|
-
`),[o]),i=r.length>
|
|
76
|
+
`);if(s.length>At||a.length>At)return null;const n=s.length,r=a.length,i=Array.from({length:n+1},()=>new Array(r+1).fill(0));for(let m=n-1;m>=0;m--)for(let x=r-1;x>=0;x--)s[m]===a[x]?i[m][x]=i[m+1][x+1]+1:i[m][x]=Math.max(i[m+1][x],i[m][x+1]);const d=[];let l=0,u=0;for(;l<n&&u<r;)s[l]===a[u]?(d.push({kind:"ctx",text:s[l]}),l++,u++):i[l+1][u]>=i[l][u+1]?(d.push({kind:"del",text:s[l]}),l++):(d.push({kind:"add",text:a[u]}),u++);for(;l<n;)d.push({kind:"del",text:s[l++]});for(;u<r;)d.push({kind:"add",text:a[u++]});return d}function rs(o,t){if(!o||typeof t!="object"||t===null)return null;const s=t,a=String(s.file_path??s.path??"");switch(o){case"edit":case"str_replace":case"edit_file":{const n=typeof s.old_string=="string"?s.old_string:"",r=typeof s.new_string=="string"?s.new_string:"";return!n&&!r?null:{oldText:n,newText:r,caption:`edit ${a}`}}case"write":case"write_file":case"create_file":return{oldText:"",newText:typeof s.content=="string"?s.content:"",caption:`write ${a} (new)`};default:return null}}const Yn=25,ot=12;function rt({text:o,isError:t,className:s,wrapClass:a,showLineNumbers:n}){const r=c.useMemo(()=>o.split(`
|
|
77
|
+
`),[o]),i=r.length>Yn,[d,l]=c.useState(!i),u=d?o:r.slice(0,ot).join(`
|
|
78
78
|
`),m=!!n&&i&&d;return e.jsxs("div",{className:C("rounded-md border bg-background/40 overflow-hidden",s),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:r.map((x,p)=>`${p+1}`).join(`
|
|
79
|
-
`)}),e.jsx("pre",{className:C("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:C("text-xs font-mono p-2 max-h-96 overflow-auto",a,t?"text-destructive":"text-foreground"),children:u}),i&&e.jsx("button",{type:"button",onClick:()=>l(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:d?e.jsxs(e.Fragment,{children:[e.jsx(
|
|
80
|
-
`).length,[r,i]=c.useState(n<30);return e.jsxs("div",{className:C("rounded-md border bg-background/40 overflow-hidden",t&&"border-destructive/40",s),children:[e.jsxs("button",{type:"button",onClick:()=>i(d=>!d),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:[r?e.jsx(We,{className:"h-3 w-3"}):e.jsx(wt,{className:"h-3 w-3"}),e.jsxs("span",{className:"font-mono",children:["JSON · ",n," lines"]})]}),e.jsx("span",{children:r?"collapse":"expand"})]}),r&&e.jsx("pre",{className:C("text-xs font-mono whitespace-pre p-2 max-h-96 overflow-auto",t?"text-destructive":"text-foreground"),children:a})]})}async function
|
|
81
|
-
`);for(let s=0;s<t.length;s++){const a=t[s];if(/^\s*at\s+\S+.*\(.*:\d+:\d+\)\s*$/.test(a)||/^\s*at\s+\S+\.\S+\(\S+\.java:\d+\)\s*$/.test(a)||/^\s+File "[^"]+", line \d+/.test(a))return s}return-1}function
|
|
79
|
+
`)}),e.jsx("pre",{className:C("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:C("text-xs font-mono p-2 max-h-96 overflow-auto",a,t?"text-destructive":"text-foreground"),children:u}),i&&e.jsx("button",{type:"button",onClick:()=>l(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:d?e.jsxs(e.Fragment,{children:[e.jsx(Is,{className:"h-3 w-3"}),"Collapse to first ",ot," lines"]}):e.jsxs(e.Fragment,{children:[e.jsx(Os,{className:"h-3 w-3"}),"Show all ",r.length," lines (",r.length-ot," more)"]})})]})}const Xn=c.memo(function({toolName:t,result:s,isError:a,className:n}){const r=c.useMemo(()=>Zn(t,s),[t,s]);return r.kind==="json"?e.jsx(eo,{value:r.value,isError:a,className:n}):r.kind==="numbered"?e.jsx(rt,{text:s,isError:a,className:n,wrapClass:"whitespace-pre"}):r.kind==="bash"?e.jsxs("div",{className:C("rounded-md border bg-background/40 overflow-hidden",n),children:[r.stdout&&e.jsx(rt,{text:r.stdout,isError:a,className:"border-0 rounded-none bg-transparent",wrapClass:"whitespace-pre-wrap break-all",showLineNumbers:!0}),(r.exitCode!==void 0||r.duration)&&e.jsxs("div",{className:C("flex items-center gap-3 text-[11px] px-2 py-1 border-t bg-muted/30 tabular-nums",r.exitCode&&r.exitCode!==0?"text-destructive":"text-muted-foreground"),children:[r.exitCode!==void 0&&e.jsxs("span",{children:["exit code: ",e.jsx("span",{className:"font-mono",children:r.exitCode})]}),r.duration&&e.jsx("span",{children:r.duration})]})]}):e.jsx(rt,{text:s,isError:a,className:n,wrapClass:"whitespace-pre-wrap break-all",showLineNumbers:!0})});function Zn(o,t){const s=t.trim();if(/^\s*\d+→/m.test(t.slice(0,200)))return{kind:"numbered"};if(s.startsWith("{")&&s.endsWith("}")||s.startsWith("[")&&s.endsWith("]"))try{const i=JSON.parse(s);if(typeof i=="object"&&i!==null)return{kind:"json",value:i}}catch{}const a=!!o&&/^(bash|shell|exec|run)/i.test(o),n=t.match(/(?:^|\n)\s*(?:\[?exit(?:\s*code)?\]?\s*[:=]?\s*)(\d+)\s*$/i),r=t.match(/(?:^|\s)(\d+\s*ms|\d+\.\d+s)\s*$/i);if(a||n){let i=t;return n&&(i=t.slice(0,n.index).trimEnd()),{kind:"bash",stdout:i,exitCode:n?Number(n[1]):void 0,duration:r==null?void 0:r[1]}}return{kind:"plain"}}function eo({value:o,isError:t,className:s}){const a=c.useMemo(()=>{try{return JSON.stringify(o,null,2)}catch{return String(o)}},[o]),n=a.split(`
|
|
80
|
+
`).length,[r,i]=c.useState(n<30);return e.jsxs("div",{className:C("rounded-md border bg-background/40 overflow-hidden",t&&"border-destructive/40",s),children:[e.jsxs("button",{type:"button",onClick:()=>i(d=>!d),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:[r?e.jsx(We,{className:"h-3 w-3"}):e.jsx(wt,{className:"h-3 w-3"}),e.jsxs("span",{className:"font-mono",children:["JSON · ",n," lines"]})]}),e.jsx("span",{children:r?"collapse":"expand"})]}),r&&e.jsx("pre",{className:C("text-xs font-mono whitespace-pre p-2 max-h-96 overflow-auto",t?"text-destructive":"text-foreground"),children:a})]})}async function to(o){var t;try{if(typeof navigator<"u"&&((t=navigator.clipboard)!=null&&t.writeText))return await navigator.clipboard.writeText(o),!0}catch{}try{const s=document.createElement("textarea");s.value=o,s.style.position="fixed",s.style.opacity="0",document.body.appendChild(s),s.select();const a=document.execCommand("copy");return document.body.removeChild(s),a}catch{return!1}}const so={code({inline:o,className:t,children:s,...a}){const n=/language-(\w+)/.exec(t??""),r=String(s??"").replace(/\n$/,"");return o||!n?e.jsx("code",{className:C("rounded bg-muted/60 px-1.5 py-0.5 text-[0.85em] font-mono",t),...a,children:s}):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:n[1]}),e.jsx(ut,{text:r,label:""})]}),e.jsx("pre",{className:"overflow-x-auto p-3 text-xs leading-relaxed font-mono max-h-[40rem]",children:e.jsx("code",{children:r})})]})}};function ut({text:o,className:t,label:s="Copy"}){const[a,n]=c.useState(!1);return e.jsx("button",{type:"button",onClick:async r=>{r.stopPropagation(),await to(o)&&(n(!0),setTimeout(()=>n(!1),1400))},className:C("inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors",t),title:s,children:a?e.jsxs(e.Fragment,{children:[e.jsx(vt,{className:"h-3 w-3 text-green-500"}),e.jsx("span",{children:"Copied"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Us,{className:"h-3 w-3"}),e.jsx("span",{children:s})]})})}function no(o,t){if(typeof document>"u")return;const s=new Blob([t],{type:"text/plain;charset=utf-8"}),a=URL.createObjectURL(s),n=document.createElement("a");n.href=a,n.download=o,document.body.appendChild(n),n.click(),document.body.removeChild(n),setTimeout(()=>URL.revokeObjectURL(a),1e3)}function oo(o){const t=(o??"").toLowerCase();return/bash|shell|exec|run/.test(t)?"log":(/grep|search|find/.test(t),"txt")}function ro(o){const t=o.split(`
|
|
81
|
+
`);for(let s=0;s<t.length;s++){const a=t[s];if(/^\s*at\s+\S+.*\(.*:\d+:\d+\)\s*$/.test(a)||/^\s*at\s+\S+\.\S+\(\S+\.java:\d+\)\s*$/.test(a)||/^\s+File "[^"]+", line \d+/.test(a))return s}return-1}function ao({text:o}){const t=ro(o),[s,a]=c.useState(!1);if(t===-1)return e.jsx("pre",{className:"whitespace-pre-wrap break-words font-mono text-xs leading-relaxed",children:o});const n=o.split(`
|
|
82
82
|
`),r=n.slice(0,t).join(`
|
|
83
83
|
`).trim(),i=n.slice(t).join(`
|
|
84
84
|
`),d=i.split(`
|
|
85
|
-
`).filter(l=>l.trim().length>0).length;return e.jsxs("div",{className:"space-y-2",children:[r&&e.jsx("pre",{className:"whitespace-pre-wrap break-words font-mono text-xs leading-relaxed",children:r}),e.jsxs("button",{type:"button",onClick:()=>a(l=>!l),className:"inline-flex items-center gap-1 text-xs text-destructive hover:text-destructive/80 font-medium",children:[s?"▾":"▸"," ",s?"Hide":"Show"," stack trace (",d," frame",d===1?"":"s",")"]}),s&&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:i})]})}function
|
|
86
|
-
`));return e.jsxs("div",{className:C("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:[n,":"]}),e.jsx("span",{className:C("text-foreground",m?"whitespace-pre-wrap break-all bg-muted/40 rounded px-1.5 py-1":"truncate",typeof r=="string"?"":"text-amber-600 dark:text-amber-400"),title:typeof r=="string"&&!m?u:void 0,children:u})]},n)}const d=!!t[n],l=Array.isArray(r)?`[${r.length} item${r.length===1?"":"s"}]`:`{${Object.keys(r).length} key${Object.keys(r).length===1?"":"s"}}`;return e.jsxs("div",{className:"py-0.5",children:[e.jsxs("button",{type:"button",onClick:()=>s(u=>({...u,[n]:!u[n]})),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:d?"▾":"▸"}),e.jsxs("span",{className:"text-muted-foreground",children:[n,":"]}),e.jsx("span",{className:"text-violet-600 dark:text-violet-400",children:l})]}),d&&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(r,null,2)})]},n)})})}function
|
|
87
|
-
`).length:0;return e.jsxs("div",{className:"space-y-1",children:[Z&&!S&&e.jsx("div",{className:"text-xs text-muted-foreground font-mono truncate",children:Z}),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((ee,L)=>e.jsx("div",{className:"truncate text-muted-foreground",children:ee},L))}),S&&t.toolInput!==void 0&&(()=>{const ee=
|
|
88
|
-
`).length>5&&e.jsx("button",{type:"button",onClick:ee=>{ee.stopPropagation();const L=
|
|
85
|
+
`).filter(l=>l.trim().length>0).length;return e.jsxs("div",{className:"space-y-2",children:[r&&e.jsx("pre",{className:"whitespace-pre-wrap break-words font-mono text-xs leading-relaxed",children:r}),e.jsxs("button",{type:"button",onClick:()=>a(l=>!l),className:"inline-flex items-center gap-1 text-xs text-destructive hover:text-destructive/80 font-medium",children:[s?"▾":"▸"," ",s?"Hide":"Show"," stack trace (",d," frame",d===1?"":"s",")"]}),s&&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:i})]})}function io({input:o}){const[t,s]=c.useState({});if(o==null||typeof o!="object"||Array.isArray(o))return e.jsx("pre",{className:"whitespace-pre-wrap break-all text-xs font-mono",children:JSON.stringify(o,null,2)});const a=Object.entries(o);return a.length===0?e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"(no params)"}):e.jsx("div",{className:"text-xs font-mono",children:a.map(([n,r])=>{if(r==null||typeof r=="string"||typeof r=="number"||typeof r=="boolean"){const u=r===null?"null":r===void 0?"undefined":typeof r=="string"?r:String(r),m=typeof r=="string"&&(u.length>80||u.includes(`
|
|
86
|
+
`));return e.jsxs("div",{className:C("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:[n,":"]}),e.jsx("span",{className:C("text-foreground",m?"whitespace-pre-wrap break-all bg-muted/40 rounded px-1.5 py-1":"truncate",typeof r=="string"?"":"text-amber-600 dark:text-amber-400"),title:typeof r=="string"&&!m?u:void 0,children:u})]},n)}const d=!!t[n],l=Array.isArray(r)?`[${r.length} item${r.length===1?"":"s"}]`:`{${Object.keys(r).length} key${Object.keys(r).length===1?"":"s"}}`;return e.jsxs("div",{className:"py-0.5",children:[e.jsxs("button",{type:"button",onClick:()=>s(u=>({...u,[n]:!u[n]})),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:d?"▾":"▸"}),e.jsxs("span",{className:"text-muted-foreground",children:[n,":"]}),e.jsx("span",{className:"text-violet-600 dark:text-violet-400",children:l})]}),d&&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(r,null,2)})]},n)})})}function lo(o){if(o<1e3)return`${o} ms`;if(o<6e4)return`${(o/1e3).toFixed(o<1e4?2:1)}s`;const t=Math.floor(o/6e4),s=Math.floor(o%6e4/1e3);return`${t}m ${s}s`}const qe=c.memo(function({message:t,isFirst:s=!1,isContinuation:a=!1}){const[n,r]=c.useState({}),[i,d]=c.useState(!1),[l,u]=c.useState(""),[m,x]=c.useState(!1),p=t.role==="user",f=t.role==="tool";t.role;const w=T(S=>S.truncateAfter),N=T(S=>S.addMessage),$=T(S=>S.setLoading),v=T(S=>S.isLoading),y=q(S=>S.wsUrl),E=I(S=>S.pinnedIds),se=I(S=>S.togglePin),F=I(S=>S.compactMode),_=E.includes(t.id),V=W(S=>S.inputCost),U=W(S=>S.outputCost),J=W(S=>S.cacheReadCost),ne=(()=>{if(t.role!=="assistant"||v)return!1;const S=T.getState().messages;for(let Z=S.length-1;Z>=0;Z--){const O=S[Z];if(O.role==="assistant")return O.id===t.id}return!1})(),ie=()=>{const S=T.getState().messages,Z=S.findIndex(Y=>Y.id===t.id);if(Z===-1)return;let O=-1;for(let Y=Z-1;Y>=0;Y--)if(S[Y].role==="user"){O=Y;break}if(O===-1)return;const ee=S[O];w(ee.id),N({role:"user",content:ee.content}),$(!0),xe(y).sendMessage(ee.content)},X=S=>{r(Z=>({...Z,[S]:!Z[S]}))},z=()=>{u(t.content),d(!0)},re=()=>{d(!1),u("")},Q=()=>{const S=l.trim();if(!S){re();return}w(t.id),N({role:"user",content:S}),$(!0),xe(y).sendMessage(S),d(!1),u("")};return e.jsxs("div",{"data-message-id":t.id,"data-pinned":_?"1":void 0,className:C("group flex animate-message rounded-lg transition-shadow",F?"gap-2":"gap-3",p?"flex-row-reverse":"flex-row",_&&"ring-1 ring-amber-500/30 bg-amber-500/[0.02] px-1 -mx-1"),children:[a?e.jsx("div",{className:"flex-shrink-0 w-8 h-8","aria-hidden":!0}):e.jsx("div",{className:C("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":f?"bg-secondary text-secondary-foreground ring-secondary/20":"bg-accent text-accent-foreground ring-accent/20"),children:p?e.jsx(Ps,{className:"h-4 w-4"}):f?e.jsx(Le,{className:"h-4 w-4"}):e.jsx(Ut,{className:"h-4 w-4"})}),e.jsxs("div",{className:C("flex flex-col gap-1.5 max-w-[85%]",p&&"items-end"),children:[s&&!a&&e.jsx("span",{className:C("text-xs font-medium px-1",p?"text-primary":f?"text-secondary":"text-muted-foreground"),children:p?"You":f?"Tool":"Assistant"}),f&&t.toolName&&e.jsxs("button",{type:"button",onClick:()=>X(t.id),className:C("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:n[t.id]?e.jsx(We,{className:"h-3 w-3"}):e.jsx(wt,{className:"h-3 w-3"})}),e.jsx(Le,{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(pt,{className:"h-3 w-3 text-destructive"}):e.jsx(Ce,{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:lo(t.toolDurationMs)})]}),e.jsx("div",{className:C("rounded-2xl",F?"px-3 py-1.5":"px-4 py-3",p?"bg-primary text-primary-foreground rounded-br-md":f?t.isError?"bg-destructive/5 border border-destructive/20 text-destructive":"bg-muted/80 text-foreground":"bg-card border text-foreground",t.isError&&!f&&"border-destructive/20"),children:f?(()=>{const S=!!n[t.id],Z=t.toolInput!==void 0?Qn(t.toolName,t.toolInput):"",O=t.toolResult?t.toolResult.split(`
|
|
87
|
+
`).length:0;return e.jsxs("div",{className:"space-y-1",children:[Z&&!S&&e.jsx("div",{className:"text-xs text-muted-foreground font-mono truncate",children:Z}),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((ee,L)=>e.jsx("div",{className:"truncate text-muted-foreground",children:ee},L))}),S&&t.toolInput!==void 0&&(()=>{const ee=rs(t.toolName,t.toolInput);return ee?e.jsx(os,{oldText:ee.oldText,newText:ee.newText,caption:ee.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(zt,{className:"h-3 w-3"}),e.jsx("span",{children:"Input"})]}),e.jsx(io,{input:t.toolInput})]})})(),S&&t.toolResult!==void 0&&t.toolResult.length>0&&e.jsxs("div",{className:"relative group/tool",children:[e.jsx(Xn,{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(ut,{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:ee=>{ee.stopPropagation();const L=oo(t.toolName),Y=(t.toolName??"output").replace(/[^a-z0-9_-]+/gi,"-").toLowerCase();no(`${Y}-${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(lt,{className:"h-3 w-3"})})]})]}),S&&t.toolResult!==void 0&&t.toolResult.length===0&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"(empty)"}),!S&&t.isError&&t.toolResult&&e.jsx("div",{className:"text-xs font-mono text-destructive truncate",children:t.toolResult.split(`
|
|
89
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:()=>X(t.id),className:"text-xs text-muted-foreground hover:text-foreground transition-colors",children:S?"Hide details":`Show details${O>0?` (${O} line${O===1?"":"s"})`:""}`})]})})():i&&p?e.jsxs("div",{className:"flex flex-col gap-2 min-w-[280px]",children:[e.jsx("textarea",{value:l,onChange:S=>u(S.target.value),onKeyDown:S=>{S.key==="Escape"?(S.preventDefault(),re()):S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&(S.preventDefault(),Q())},rows:Math.min(8,Math.max(2,l.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:re,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:Q,disabled:!l.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(ro,{text:t.content}):e.jsx(Ps,{remarkPlugins:[Fs],components:to,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:C("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 S=t.usage,Z=(S.input*V+S.output*U+(S.cacheRead??0)*J)/1e6,O=V>0||U>0,ee=Z>=.01?`$${Z.toFixed(4)}`:Z>0?`$${Z.toFixed(6).replace(/0+$/,"").replace(/\.$/,"")}`:"";return e.jsxs("span",{className:"text-[10px] text-muted-foreground/60 font-mono tabular-nums",title:[`Input: ${S.input.toLocaleString()}`,`Output: ${S.output.toLocaleString()}`,S.cacheRead?`Cache read: ${S.cacheRead.toLocaleString()}`:"",O?`Cost: ${ee}`:""].filter(Boolean).join(" · "),children:[S.input.toLocaleString(),"→",S.output.toLocaleString(),S.cacheRead?` · ${S.cacheRead.toLocaleString()} ↺`:"",O&&ee?` · ${ee}`:""]})})(),!f&&t.content&&!t.streaming&&e.jsx(ut,{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(S=>!S),title:m?"Show rendered markdown":"Show raw markdown source",className:C("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(_s,{className:"h-3 w-3"}),e.jsx("span",{children:m?"Rendered":"Raw"})]}),p&&!i&&!v&&t.content&&e.jsxs("button",{type:"button",onClick:z,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(_t,{className:"h-3 w-3"}),e.jsx("span",{children:"Edit"})]}),t.role==="assistant"&&t.content&&!t.streaming&&e.jsxs("button",{type:"button",onClick:()=>se(t.id),title:_?"Unpin":"Pin this answer",className:C("text-xs inline-flex items-center gap-1 transition-opacity",_?"text-amber-500 hover:text-amber-600 opacity-100":"opacity-0 group-hover:opacity-100 text-muted-foreground hover:text-foreground"),children:[_?e.jsx(Ks,{className:"h-3 w-3"}):e.jsx(zt,{className:"h-3 w-3"}),e.jsx("span",{children:_?"Pinned":"Pin"})]}),ne&&t.content&&!t.streaming&&e.jsxs("button",{type:"button",onClick:ie,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(Ke,{className:"h-3 w-3"}),e.jsx("span",{children:"Retry"})]})]})]})]})});function lo(){const o=W(l=>l.mode),t=W(l=>l.modes),{listModes:s,switchMode:a}=ge(),[n,r]=c.useState(!1),i=c.useRef(null);c.useEffect(()=>{n&&s()},[n,s]),c.useEffect(()=>{if(!n)return;const l=m=>{var x;(x=i.current)!=null&&x.contains(m.target)||r(!1)},u=m=>{m.key==="Escape"&&r(!1)};return document.addEventListener("mousedown",l),document.addEventListener("keydown",u),()=>{document.removeEventListener("mousedown",l),document.removeEventListener("keydown",u)}},[n]);const d=t.length>0?t:[{id:"default",name:"Default",description:"Standard agent behaviour"}];return e.jsxs("div",{ref:i,className:"relative shrink-0",children:[e.jsxs("button",{type:"button",onClick:()=>r(l=>!l),className:C("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:o||"default"}),e.jsx(We,{className:"h-3 w-3 opacity-60"})]}),n&&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"}),d.map(l=>e.jsxs("button",{type:"button",onClick:()=>{a(l.id),r(!1)},className:C("w-full text-left px-3 py-2 hover:bg-accent/40 flex items-start gap-2",l.id===o&&"bg-accent/30"),children:[e.jsx(vt,{className:C("h-3.5 w-3.5 mt-0.5 shrink-0",l.id===o?"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:l.id}),l.description&&e.jsx("div",{className:"text-[11px] text-muted-foreground leading-snug",children:l.description})]})]},l.id))]})]})}function co(){const o=I(m=>m.searchOpen),t=I(m=>m.setSearchOpen),s=I(m=>m.searchQuery),a=I(m=>m.setSearchQuery),n=T(m=>m.messages),r=c.useRef(null),[i,d]=c.useState(0);c.useEffect(()=>{o&&requestAnimationFrame(()=>{var m;return(m=r.current)==null?void 0:m.focus()})},[o]);const l=c.useMemo(()=>{const m=s.trim().toLowerCase();return m?n.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):[]},[n,s]);if(c.useEffect(()=>{i>=l.length&&d(0)},[l,i]),c.useEffect(()=>{var E;const m=window,x=(E=m.CSS)==null?void 0:E.highlights,p=m.Highlight;if(!x||!p)return;const f=()=>{x.delete("chat-search"),x.delete("chat-search-active")},w=s.trim();if(!w||!o){f();return}const N=w.toLowerCase(),$=[],v=[],y=l[i];for(const se of document.querySelectorAll("[data-message-id]")){const _=se.dataset.messageId===y,V=document.createTreeWalker(se,NodeFilter.SHOW_TEXT);let U=V.nextNode();for(;U;){const J=U.nodeValue??"";if(J.length>0){const ne=J.toLowerCase();let ie=0;for(;ie<=ne.length-N.length;){const X=ne.indexOf(N,ie);if(X===-1)break;const z=document.createRange();z.setStart(U,X),z.setEnd(U,X+N.length),$.push(z),_&&v.push(z),ie=X+N.length}}U=V.nextNode()}}return $.length>0?x.set("chat-search",new p(...$)):x.delete("chat-search"),v.length>0?x.set("chat-search-active",new p(...v)):x.delete("chat-search-active"),f},[s,l,i,o]),c.useEffect(()=>{const m=l[i];if(!m)return;const x=document.querySelector(`[data-message-id="${m}"]`);x&&x.scrollIntoView({behavior:"smooth",block:"center"})},[l,i]),!o)return null;const u=m=>{l.length!==0&&d(x=>(x+m+l.length)%l.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(Ee,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("input",{ref:r,value:s,onChange:m=>a(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:l.length===0?s?"0":"":`${i+1} / ${l.length}`}),e.jsx("button",{type:"button",onClick:()=>u(-1),disabled:l.length===0,className:C("p-1 rounded hover:bg-muted disabled:opacity-30 disabled:cursor-not-allowed"),title:"Previous hit",children:e.jsx(Ht,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button",onClick:()=>u(1),disabled:l.length===0,className:C("p-1 rounded hover:bg-muted disabled:opacity-30 disabled:cursor-not-allowed"),title:"Next hit",children:e.jsx(qt,{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($e,{className:"h-3.5 w-3.5"})})]})})}function uo(o){if(o<1e3)return`${o}ms`;if(o<6e4)return`${(o/1e3).toFixed(o<1e4?2:1)}s`;const t=Math.floor(o/6e4),s=Math.floor(o%6e4/1e3);return`${t}m${s}s`}const mo=c.memo(function({tools:t,defaultOpen:s=!1,isContinuation:a=!1}){const[n,r]=c.useState(s);if(t.length===1)return e.jsx(Be,{message:t[0],isFirst:!0,isContinuation:a});const i=t.filter(p=>p.toolResult===void 0).length,d=t.filter(p=>p.isError).length,l=t.reduce((p,f)=>p+(f.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:[a?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(De,{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:()=>r(p=>!p),className:C("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:[n?e.jsx(We,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(wt,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(De,{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"]}),i>0?e.jsx(we,{className:"h-3 w-3 animate-spin text-amber-500"}):d>0?e.jsx(pt,{className:"h-3 w-3 text-destructive"}):e.jsx(Ce,{className:"h-3 w-3 text-green-500"}),l>0&&e.jsx("span",{className:"text-xs text-muted-foreground tabular-nums font-normal",children:uo(l)}),m&&e.jsxs("span",{className:"text-xs text-muted-foreground/80 font-mono truncate",children:["· ",m,x]})]}),n&&e.jsx("div",{className:"space-y-2 pl-3 border-l-2 border-border/40 ml-2",children:t.map(p=>e.jsx(Be,{message:p,isFirst:!1},p.id))})]})]})}),po=[{icon:Ee,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:qe,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:zs,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:Pt,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)."]}],xo=[{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 at(o){var a;const t=document.querySelector("textarea");if(!t)return;const s=(a=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value"))==null?void 0:a.set;s==null||s.call(t,o),t.dispatchEvent(new Event("input",{bubbles:!0})),t.focus()}function ho(){const{projectName:o}=W(),{provider:t,model:s}=B(),a=B(N=>N.wsConnected),n=B(N=>N.wsUrl),r=I(N=>N.setCurrentView),[i,d]=c.useState(void 0);c.useEffect(()=>{if(!a)return;const N=xe(n),$=N.on("providers.saved",v=>{var E;const y=v.payload;d(((E=y.providers)==null?void 0:E.length)??0)});return N.listSavedProviders(),()=>{$()}},[a,n]);const u=I(N=>N.promptHistory).slice(0,6),{listSessions:m,resumeSession:x}=ge(),p=Le(N=>N.entries);c.useEffect(()=>{a&&p.length===0&&m(10)},[a]);const f=I(N=>N.sessionNicknames),w=p.filter(N=>!N.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(jt,{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",o?e.jsxs(e.Fragment,{children:[" in ",e.jsx("span",{className:"text-primary",children:o})]}):"","?"]}),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&&s&&e.jsxs("p",{className:"text-xs text-muted-foreground/70 mt-2 font-mono",children:[t," / ",s]})]})]}),a&&i===0&&e.jsxs("button",{type:"button",onClick:()=>r("settings"),className:C("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(Us,{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(Bt,{className:"h-3.5 w-3.5"})]})]}),e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:po.map(N=>{const $=N.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:C("flex items-center justify-center w-8 h-8 rounded-lg border",N.tone),children:e.jsx($,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:N.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:N.hint})]})]}),e.jsx("div",{className:"flex flex-col gap-1.5",children:N.prompts.map((v,y)=>e.jsx("button",{type:"button",onClick:()=>at(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},y))})]},N.title)})}),w.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(Ft,{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:w.map(N=>e.jsxs("button",{type:"button",onClick:()=>x(N.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:N.title,children:[e.jsx("div",{className:"text-sm font-medium truncate text-foreground group-hover/sess:text-primary",children:f[N.id]||N.title||"(empty)"}),e.jsxs("div",{className:"text-[10px] text-muted-foreground font-mono truncate mt-0.5",children:[N.provider,"/",N.model,N.tokenTotal>0&&e.jsxs("span",{className:"ml-2",children:["· ",N.tokenTotal.toLocaleString()," tok"]})]})]},N.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(Ut,{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(N=>!N.startsWith("/")).slice(0,5).map((N,$)=>e.jsx("button",{type:"button",onClick:()=>at(N),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:N,children: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(Vt,{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:xo.map(N=>e.jsxs("button",{type:"button",onClick:()=>at(N.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:N.name}),e.jsx("span",{className:"text-[11px] text-muted-foreground truncate",children:N.hint})]},N.name))})]})]})}const Qe=c.forwardRef(({className:o,children:t,...s},a)=>e.jsxs(Qt,{ref:a,className:C("relative overflow-hidden",o),...s,children:[e.jsx(Hs,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(rs,{}),e.jsx(qs,{})]}));Qe.displayName=Qt.displayName;const rs=c.forwardRef(({className:o,orientation:t="vertical",...s},a)=>e.jsx(Gt,{ref:a,orientation:t,className:C("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]",o),...s,children:e.jsx(Bs,{className:"relative flex-1 rounded-full bg-border"})}));rs.displayName=Gt.displayName;function Ae(o){return o>=1e6?`${(o/1e6).toFixed(1)}M`:o>=1e3?`${(o/1e3).toFixed(o>=1e4?0:1)}k`:String(o)}function fo(){const o=T(a=>a.thinkingBuffer);if(!o)return null;const s=o.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:re,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:Q,disabled:!l.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(ao,{text:t.content}):e.jsx(Fs,{remarkPlugins:[_s],components:so,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:C("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 S=t.usage,Z=(S.input*V+S.output*U+(S.cacheRead??0)*J)/1e6,O=V>0||U>0,ee=Z>=.01?`$${Z.toFixed(4)}`:Z>0?`$${Z.toFixed(6).replace(/0+$/,"").replace(/\.$/,"")}`:"";return e.jsxs("span",{className:"text-[10px] text-muted-foreground/60 font-mono tabular-nums",title:[`Input: ${S.input.toLocaleString()}`,`Output: ${S.output.toLocaleString()}`,S.cacheRead?`Cache read: ${S.cacheRead.toLocaleString()}`:"",O?`Cost: ${ee}`:""].filter(Boolean).join(" · "),children:[S.input.toLocaleString(),"→",S.output.toLocaleString(),S.cacheRead?` · ${S.cacheRead.toLocaleString()} ↺`:"",O&&ee?` · ${ee}`:""]})})(),!f&&t.content&&!t.streaming&&e.jsx(ut,{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(S=>!S),title:m?"Show rendered markdown":"Show raw markdown source",className:C("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(Ks,{className:"h-3 w-3"}),e.jsx("span",{children:m?"Rendered":"Raw"})]}),p&&!i&&!v&&t.content&&e.jsxs("button",{type:"button",onClick:z,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(Kt,{className:"h-3 w-3"}),e.jsx("span",{children:"Edit"})]}),t.role==="assistant"&&t.content&&!t.streaming&&e.jsxs("button",{type:"button",onClick:()=>se(t.id),title:_?"Unpin":"Pin this answer",className:C("text-xs inline-flex items-center gap-1 transition-opacity",_?"text-amber-500 hover:text-amber-600 opacity-100":"opacity-0 group-hover:opacity-100 text-muted-foreground hover:text-foreground"),children:[_?e.jsx(Ws,{className:"h-3 w-3"}):e.jsx(Ht,{className:"h-3 w-3"}),e.jsx("span",{children:_?"Pinned":"Pin"})]}),ne&&t.content&&!t.streaming&&e.jsxs("button",{type:"button",onClick:ie,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(Ke,{className:"h-3 w-3"}),e.jsx("span",{children:"Retry"})]})]})]})]})});function co(){const o=W(l=>l.mode),t=W(l=>l.modes),{listModes:s,switchMode:a}=ge(),[n,r]=c.useState(!1),i=c.useRef(null);c.useEffect(()=>{n&&s()},[n,s]),c.useEffect(()=>{if(!n)return;const l=m=>{var x;(x=i.current)!=null&&x.contains(m.target)||r(!1)},u=m=>{m.key==="Escape"&&r(!1)};return document.addEventListener("mousedown",l),document.addEventListener("keydown",u),()=>{document.removeEventListener("mousedown",l),document.removeEventListener("keydown",u)}},[n]);const d=t.length>0?t:[{id:"default",name:"Default",description:"Standard agent behaviour"}];return e.jsxs("div",{ref:i,className:"relative shrink-0",children:[e.jsxs("button",{type:"button",onClick:()=>r(l=>!l),className:C("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:o||"default"}),e.jsx(We,{className:"h-3 w-3 opacity-60"})]}),n&&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"}),d.map(l=>e.jsxs("button",{type:"button",onClick:()=>{a(l.id),r(!1)},className:C("w-full text-left px-3 py-2 hover:bg-accent/40 flex items-start gap-2",l.id===o&&"bg-accent/30"),children:[e.jsx(vt,{className:C("h-3.5 w-3.5 mt-0.5 shrink-0",l.id===o?"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:l.id}),l.description&&e.jsx("div",{className:"text-[11px] text-muted-foreground leading-snug",children:l.description})]})]},l.id))]})]})}function uo(){const o=I(m=>m.searchOpen),t=I(m=>m.setSearchOpen),s=I(m=>m.searchQuery),a=I(m=>m.setSearchQuery),n=T(m=>m.messages),r=c.useRef(null),[i,d]=c.useState(0);c.useEffect(()=>{o&&requestAnimationFrame(()=>{var m;return(m=r.current)==null?void 0:m.focus()})},[o]);const l=c.useMemo(()=>{const m=s.trim().toLowerCase();return m?n.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):[]},[n,s]);if(c.useEffect(()=>{i>=l.length&&d(0)},[l,i]),c.useEffect(()=>{var E;const m=window,x=(E=m.CSS)==null?void 0:E.highlights,p=m.Highlight;if(!x||!p)return;const f=()=>{x.delete("chat-search"),x.delete("chat-search-active")},w=s.trim();if(!w||!o){f();return}const N=w.toLowerCase(),$=[],v=[],y=l[i];for(const se of document.querySelectorAll("[data-message-id]")){const _=se.dataset.messageId===y,V=document.createTreeWalker(se,NodeFilter.SHOW_TEXT);let U=V.nextNode();for(;U;){const J=U.nodeValue??"";if(J.length>0){const ne=J.toLowerCase();let ie=0;for(;ie<=ne.length-N.length;){const X=ne.indexOf(N,ie);if(X===-1)break;const z=document.createRange();z.setStart(U,X),z.setEnd(U,X+N.length),$.push(z),_&&v.push(z),ie=X+N.length}}U=V.nextNode()}}return $.length>0?x.set("chat-search",new p(...$)):x.delete("chat-search"),v.length>0?x.set("chat-search-active",new p(...v)):x.delete("chat-search-active"),f},[s,l,i,o]),c.useEffect(()=>{const m=l[i];if(!m)return;const x=document.querySelector(`[data-message-id="${m}"]`);x&&x.scrollIntoView({behavior:"smooth",block:"center"})},[l,i]),!o)return null;const u=m=>{l.length!==0&&d(x=>(x+m+l.length)%l.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(De,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("input",{ref:r,value:s,onChange:m=>a(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:l.length===0?s?"0":"":`${i+1} / ${l.length}`}),e.jsx("button",{type:"button",onClick:()=>u(-1),disabled:l.length===0,className:C("p-1 rounded hover:bg-muted disabled:opacity-30 disabled:cursor-not-allowed"),title:"Previous hit",children:e.jsx(Bt,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button",onClick:()=>u(1),disabled:l.length===0,className:C("p-1 rounded hover:bg-muted disabled:opacity-30 disabled:cursor-not-allowed"),title:"Next hit",children:e.jsx(qt,{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(Te,{className:"h-3.5 w-3.5"})})]})})}function mo(o){if(o<1e3)return`${o}ms`;if(o<6e4)return`${(o/1e3).toFixed(o<1e4?2:1)}s`;const t=Math.floor(o/6e4),s=Math.floor(o%6e4/1e3);return`${t}m${s}s`}const po=c.memo(function({tools:t,defaultOpen:s=!1,isContinuation:a=!1}){const[n,r]=c.useState(s);if(t.length===1)return e.jsx(qe,{message:t[0],isFirst:!0,isContinuation:a});const i=t.filter(p=>p.toolResult===void 0).length,d=t.filter(p=>p.isError).length,l=t.reduce((p,f)=>p+(f.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:[a?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(Le,{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:()=>r(p=>!p),className:C("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:[n?e.jsx(We,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(wt,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Le,{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"]}),i>0?e.jsx(we,{className:"h-3 w-3 animate-spin text-amber-500"}):d>0?e.jsx(pt,{className:"h-3 w-3 text-destructive"}):e.jsx(Ce,{className:"h-3 w-3 text-green-500"}),l>0&&e.jsx("span",{className:"text-xs text-muted-foreground tabular-nums font-normal",children:mo(l)}),m&&e.jsxs("span",{className:"text-xs text-muted-foreground/80 font-mono truncate",children:["· ",m,x]})]}),n&&e.jsx("div",{className:"space-y-2 pl-3 border-l-2 border-border/40 ml-2",children:t.map(p=>e.jsx(qe,{message:p,isFirst:!1},p.id))})]})]})}),xo=[{icon:De,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:Be,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:Hs,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:Ft,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)."]}],ho=[{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 at(o){var a;const t=document.querySelector("textarea");if(!t)return;const s=(a=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value"))==null?void 0:a.set;s==null||s.call(t,o),t.dispatchEvent(new Event("input",{bubbles:!0})),t.focus()}function fo(){const{projectName:o}=W(),{provider:t,model:s}=q(),a=q(N=>N.wsConnected),n=q(N=>N.wsUrl),r=I(N=>N.setCurrentView),[i,d]=c.useState(void 0);c.useEffect(()=>{if(!a)return;const N=xe(n),$=N.on("providers.saved",v=>{var E;const y=v.payload;d(((E=y.providers)==null?void 0:E.length)??0)});return N.listSavedProviders(),()=>{$()}},[a,n]);const u=I(N=>N.promptHistory).slice(0,6),{listSessions:m,resumeSession:x}=ge(),p=Re(N=>N.entries);c.useEffect(()=>{a&&p.length===0&&m(10)},[a]);const f=I(N=>N.sessionNicknames),w=p.filter(N=>!N.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(jt,{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",o?e.jsxs(e.Fragment,{children:[" in ",e.jsx("span",{className:"text-primary",children:o})]}):"","?"]}),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&&s&&e.jsxs("p",{className:"text-xs text-muted-foreground/70 mt-2 font-mono",children:[t," / ",s]})]})]}),a&&i===0&&e.jsxs("button",{type:"button",onClick:()=>r("settings"),className:C("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(zs,{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(Vt,{className:"h-3.5 w-3.5"})]})]}),e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:xo.map(N=>{const $=N.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:C("flex items-center justify-center w-8 h-8 rounded-lg border",N.tone),children:e.jsx($,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:N.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:N.hint})]})]}),e.jsx("div",{className:"flex flex-col gap-1.5",children:N.prompts.map((v,y)=>e.jsx("button",{type:"button",onClick:()=>at(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},y))})]},N.title)})}),w.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(_t,{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:w.map(N=>e.jsxs("button",{type:"button",onClick:()=>x(N.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:N.title,children:[e.jsx("div",{className:"text-sm font-medium truncate text-foreground group-hover/sess:text-primary",children:f[N.id]||N.title||"(empty)"}),e.jsxs("div",{className:"text-[10px] text-muted-foreground font-mono truncate mt-0.5",children:[N.provider,"/",N.model,N.tokenTotal>0&&e.jsxs("span",{className:"ml-2",children:["· ",N.tokenTotal.toLocaleString()," tok"]})]})]},N.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(zt,{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(N=>!N.startsWith("/")).slice(0,5).map((N,$)=>e.jsx("button",{type:"button",onClick:()=>at(N),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:N,children: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(Qt,{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:ho.map(N=>e.jsxs("button",{type:"button",onClick:()=>at(N.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:N.name}),e.jsx("span",{className:"text-[11px] text-muted-foreground truncate",children:N.hint})]},N.name))})]})]})}const Qe=c.forwardRef(({className:o,children:t,...s},a)=>e.jsxs(Gt,{ref:a,className:C("relative overflow-hidden",o),...s,children:[e.jsx(Bs,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(as,{}),e.jsx(qs,{})]}));Qe.displayName=Gt.displayName;const as=c.forwardRef(({className:o,orientation:t="vertical",...s},a)=>e.jsx(Jt,{ref:a,orientation:t,className:C("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]",o),...s,children:e.jsx(Vs,{className:"relative flex-1 rounded-full bg-border"})}));as.displayName=Jt.displayName;function Ae(o){return o>=1e6?`${(o/1e6).toFixed(1)}M`:o>=1e3?`${(o/1e3).toFixed(o>=1e4?0:1)}k`:String(o)}function go(){const o=T(a=>a.thinkingBuffer);if(!o)return null;const s=o.split(`
|
|
91
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(Ot,{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:s||"…"})})]})]})}function go(){const{messages:o,isLoading:t}=T(),s=I(g=>g.setPaletteOpen),a=I(g=>g.setShortcutsOpen),n=I(g=>g.sidebarOpen),r=I(g=>g.toggleSidebar),i=I(g=>g.compactMode),d=B(g=>g.setTheme),l=B(g=>g.theme),{totalTokens:u,cost:m,startTime:x,lastInputTokens:p,maxContext:f,projectName:w,iteration:N}=W(),{wsConnected:$,wsStatus:v,provider:y,model:E}=B(),{setCurrentView:se}=I(),F=c.useRef(null),_=f>0&&p>0?Math.min(100,Math.round(p/f*100)):0,V=_>=85?"bg-red-500/15 text-red-600 dark:text-red-400":_>=70?"bg-amber-500/15 text-amber-600 dark:text-amber-400":"bg-muted text-muted-foreground",[U,J]=c.useState(!0),[ne,ie]=c.useState(0),[X,z]=c.useState(!1),re=c.useRef(o.length),Q=c.useCallback(()=>{var g;return((g=F.current)==null?void 0:g.querySelector("[data-radix-scroll-area-viewport]"))??null},[]);c.useEffect(()=>{const g=Q();if(!g)return;const K=()=>{const G=g.scrollHeight-g.scrollTop-g.clientHeight<120;J(G),G&&(ie(0),re.current=o.length);const ue=g.scrollTop>g.clientHeight&&g.scrollHeight>g.clientHeight*2.5;z(ue)};return g.addEventListener("scroll",K,{passive:!0}),()=>g.removeEventListener("scroll",K)},[Q,o.length]),c.useEffect(()=>{const g=Q();if(g)if(U)g.scrollTop=g.scrollHeight,re.current=o.length;else{const K=o.length-re.current;K>0&&ie(K)}},[o,U,Q]);const S=c.useCallback(()=>{const g=Q();g&&(g.scrollTo({top:g.scrollHeight,behavior:"smooth"}),J(!0),ie(0),re.current=o.length)},[Q,o.length]),Z=c.useCallback(()=>{const g=Q();g&&g.scrollTo({top:0,behavior:"smooth"})},[Q]),[O,ee]=c.useState(null),[L,Y]=c.useState(()=>Date.now()),b=c.useRef(null);c.useEffect(()=>{t&&O===null&&ee(Date.now()),!t&&O!==null&&ee(null)},[t,O]),c.useEffect(()=>{if(!t)return;const g=setInterval(()=>Y(Date.now()),500);return()=>clearInterval(g)},[t]);const M=g=>{if(!g)return"--";const K=Math.floor((Date.now()-g)/1e3);if(K<60)return`${K}s`;const ce=Math.floor(K/60),G=K%60;return`${ce}m ${G}s`},h=(()=>{if(!t)return"idle";const g=o[o.length-1];return(g==null?void 0:g.role)==="assistant"&&!!g.content&&g.streaming?"streaming":"thinking"})(),j=h==="idle"?"bg-muted text-muted-foreground":h==="streaming"?"bg-blue-500/10 text-blue-600 dark:text-blue-400":"bg-amber-500/10 text-amber-600 dark:text-amber-400",R=f>0&&p>0||u.input>0||!!x;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:[!n&&e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",onClick:r,title:"Open sidebar (Ctrl+\\\\)",children:e.jsx(Vs,{className:"h-4 w-4"})}),!n&&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(jt,{className:"h-3 w-3 text-primary-foreground"})})}),e.jsx(Un,{wsStatus:v,wsConnected:$}),e.jsxs("span",{className:C("flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[11px] font-medium shrink-0 tabular-nums",j),title:`Agent state: ${h}`,children:[h!=="idle"&&e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-current animate-pulse"}),e.jsx("span",{children:h})]}),w&&e.jsxs("span",{className:"flex items-center gap-1 text-[11px] text-muted-foreground shrink-0 min-w-0",title:`Project: ${w}`,children:[e.jsx(Qs,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate max-w-[12rem]",children:w})]}),e.jsxs("button",{type:"button",onClick:()=>I.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(_e,{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:y||"no-provider"}),e.jsx("span",{className:"text-muted-foreground/40 mx-0.5",children:"/"}),e.jsx("span",{className:"font-medium",children:E||"no-model"})]})]}),e.jsx(lo,{}),e.jsx(Hn,{}),N&&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(Gs,{className:"h-3 w-3 animate-pulse"}),"iter ",N.index,N.max>0?`/${N.max}`:""]})]}),e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>s(!0),title:"Command palette (Ctrl+K)",children:e.jsx(Js,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>{d(l==="light"?"dark":l==="dark"?"system":"light")},title:`Theme: ${l} (click to cycle)`,children:l==="light"?e.jsx(ft,{className:"h-4 w-4"}):l==="dark"?e.jsx(gt,{className:"h-4 w-4"}):e.jsx(bt,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7 font-mono text-xs",onClick:()=>a(!0),title:"Keyboard shortcuts (?)",children:"?"}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>se("settings"),title:"Settings",children:e.jsx(ht,{className:"h-4 w-4"})})]})]}),R&&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:[f>0&&p>0&&e.jsxs("span",{className:C("flex items-center gap-1 px-1.5 py-0.5 rounded-full font-medium shrink-0",V),title:`Last input: ${p.toLocaleString()} / ${f.toLocaleString()} tokens`,children:["ctx ",_,"% · ",Ae(p),"/",Ae(f)]}),u.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:Ae(u.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:Ae(u.output)}),e.jsx("span",{children:"out"})]}),u.cacheRead&&u.cacheRead>0&&(()=>{const g=(u.cacheRead??0)+u.input,K=g>0?Math.round((u.cacheRead??0)/g*100):0;return e.jsxs("span",{className:"flex items-center gap-1",title:`Cache hit ratio: ${K}%`,children:[e.jsx("span",{className:"font-medium text-foreground",children:Ae(u.cacheRead)}),e.jsxs("span",{children:["cache (",K,"%)"]})]})})(),e.jsx(qn,{})]})]}),x&&e.jsx("span",{className:"text-muted-foreground/70 tabular-nums shrink-0",children:M(x)})]})]}),e.jsxs("div",{className:"flex-1 relative overflow-hidden",children:[e.jsx(co,{}),!U&&e.jsxs("button",{type:"button",onClick:S,className:C("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(qt,{className:"h-3.5 w-3.5"}),ne>0?`${ne} new message${ne===1?"":"s"}`:"Jump to latest"]}),X&&e.jsxs("button",{type:"button",onClick:Z,title:"Scroll to top (oldest)",className:C("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(Ht,{className:"h-3 w-3"}),e.jsx("span",{children:"Top"})]}),e.jsx(Qe,{className:"h-full",ref:F,children:e.jsxs("div",{className:C("mx-auto pb-8",i?"max-w-5xl p-3 space-y-3":"max-w-5xl p-4 space-y-6"),children:[o.length===0&&!t&&e.jsx(ho,{}),(()=>{const g=[];for(let D=0;D<o.length;D++){const A=o[D];if(A.role==="tool"){const q=g[g.length-1];q&&q.kind==="tools"?q.tools.push(A):g.push({kind:"tools",tools:[A],key:A.id})}else{const q=o[D-1];g.push({kind:"msg",message:A,isFirst:!q||q.role!==A.role})}}const K=[];for(const D of g){if(D.kind==="msg"&&D.message.role==="user"){K.push({kind:"user",message:D.message,key:D.message.id});continue}const A=K[K.length-1];if(A&&A.kind==="agent")A.items.push(D);else{const q=D.kind==="msg"?D.message.id:D.key;K.push({kind:"agent",items:[D],key:q})}}let ce=null;const G=D=>{const A=new Date(D);return`${A.getFullYear()}-${A.getMonth()}-${A.getDate()}`},ue=D=>{const A=new Date(D),q=new Date,te=new Date(Date.now()-864e5);return G(D)===G(q.getTime())?"Today":G(D)===G(te.getTime())?"Yesterday":A.toLocaleDateString(void 0,{weekday:"short",month:"short",day:"numeric",year:A.getFullYear()===q.getFullYear()?void 0:"numeric"})},me=D=>{if(D.kind==="user")return D.message.timestamp;const A=D.items[0];return A.kind==="msg"?A.message.timestamp:A.tools[0].timestamp},ae=[];for(let D=0;D<K.length;D++){const A=K[D],q=me(A),te=G(q);if(te!==ce&&(ae.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:ue(q)}),e.jsx("div",{className:"flex-1 h-px bg-border/50"})]},`day-${te}-${D}`)),ce=te),A.kind==="user"){ae.push(e.jsx(Be,{message:A.message,isFirst:!0},A.key));continue}const pe=D===K.length-1;ae.push(e.jsx("div",{className:C(i?"space-y-1":"space-y-1.5"),children:A.items.map((oe,he)=>{const Te=he>0;if(oe.kind==="msg")return e.jsx(Be,{message:oe.message,isFirst:!Te&&oe.isFirst,isContinuation:Te},oe.message.id);const k=pe&&he===A.items.length-1&&t&&oe.tools.some(P=>P.toolResult===void 0);return e.jsx(mo,{tools:oe.tools,defaultOpen:k,isContinuation:Te},oe.key)})},A.key))}return ae})(),e.jsx(fo,{}),t&&(()=>{const g=o[o.length-1],K=o.filter(D=>D.role==="tool"&&D.toolResult===void 0);let ce="Thinking…";if(K.length>0){const D=Array.from(new Set(K.map(te=>te.toolName).filter(Boolean))),A=D.slice(0,2).join(", "),q=D.length>2?` +${D.length-2}`:"";ce=K.length===1?`Running ${A||"tool"}…`:`Running ${K.length} tools (${A}${q})…`}else(g==null?void 0:g.role)==="assistant"&&g.content?ce="Writing reply…":(g==null?void 0:g.role)==="tool"&&g.toolResult!==void 0&&(ce="Thinking about the next step…");const G=O?Math.max(0,Math.floor((L-O)/1e3)):0,ue=G<60?`${G}s`:`${Math.floor(G/60)}m ${G%60}s`;let me="";const ae=(g==null?void 0:g.role)==="assistant"&&g.streaming&&g.content?g:null;if(ae){const D=b.current;if(!D||D.id!==ae.id)b.current={id:ae.id,at:Date.now(),len:ae.content.length};else{const A=Math.max(1,L-D.at),q=Math.max(0,ae.content.length-D.len);if(A>500&&q>0){const te=q*1e3/A;me=te>=1e3?`${(te/1e3).toFixed(1)}k ch/s`:`${Math.round(te)} ch/s`}}}else b.current&&(b.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(Wt,{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:ce}),e.jsx("span",{className:"text-xs text-muted-foreground tabular-nums",children:ue}),N&&e.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:["· iter ",N.index,N.max>0?`/${N.max}`:""]}),me&&e.jsxs("span",{className:"text-xs text-muted-foreground/80 tabular-nums",children:["· ",me]})]})})})]})})()]})})]}),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(Wn,{}),e.jsx("p",{className:"text-xs text-center text-muted-foreground/50 mt-2",children:"Press Enter to send, Shift+Enter for new line"})]})})]})}const At=Zs,bo=Ys,as=c.forwardRef(({className:o,...t},s)=>e.jsx(Jt,{ref:s,className:C("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",o),...t}));as.displayName=Jt.displayName;const mt=c.forwardRef(({className:o,children:t,...s},a)=>e.jsxs(bo,{children:[e.jsx(as,{}),e.jsxs(Yt,{ref:a,className:C("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",o),...s,children:[t,e.jsxs(Xs,{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($e,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));mt.displayName=Yt.displayName;const is=({className:o,...t})=>e.jsx("div",{className:C("flex flex-col space-y-1.5 text-center sm:text-left",o),...t});is.displayName="DialogHeader";const ls=({className:o,...t})=>e.jsx("div",{className:C("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",o),...t});ls.displayName="DialogFooter";const cs=c.forwardRef(({className:o,...t},s)=>e.jsx(Xt,{ref:s,className:C("text-lg font-semibold leading-none tracking-tight",o),...t}));cs.displayName=Xt.displayName;const ds=c.forwardRef(({className:o,...t},s)=>e.jsx(Zt,{ref:s,className:C("text-sm text-muted-foreground",o),...t}));ds.displayName=Zt.displayName;function yo(o){return/edit|write|create|patch/i.test(o)?tn:/bash|shell|exec|run|command/i.test(o)?De:/fetch|http|web|curl|request/i.test(o)?Ie:qe}function vo({toolName:o,input:t}){const s=os(o,t);if(s)return e.jsx("div",{className:"rounded-lg overflow-hidden border",children:e.jsx(ns,{oldText:s.oldText,newText:s.newText,caption:s.caption})});if(typeof t=="object"&&t!==null){const a=t,n=a.command??a.cmd??a.script;if(typeof n=="string"&&n.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(De,{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:["$",n]})]});const r=a.url;if(typeof r=="string"){const i=a.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:i.toUpperCase()})," ",e.jsx("span",{className:"break-all",children:r})]})}}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 wo(){const{showConfirmDialog:o,confirmInfo:t,hideConfirm:s}=I(),{sendConfirm:a}=ge(),n=c.useRef(null),r=l=>{t&&a(t.id,l),s()};if(c.useEffect(()=>{var u;if(!o)return;const l=m=>{var f;const x=m.target,p=(f=x==null?void 0:x.tagName)==null?void 0:f.toLowerCase();p==="input"||p==="textarea"||(m.key==="y"||m.key==="Y"?(m.preventDefault(),r("yes")):m.key==="n"||m.key==="N"||m.key==="Escape"?(m.preventDefault(),r("no")):m.key==="a"||m.key==="A"?(m.preventDefault(),r("always")):(m.key==="d"||m.key==="D")&&(m.preventDefault(),r("deny")))};return window.addEventListener("keydown",l),(u=n.current)==null||u.focus(),()=>window.removeEventListener("keydown",l)},[o,t==null?void 0:t.id]),!t)return e.jsx(At,{open:o,onOpenChange:()=>s(),children:e.jsx(mt,{})});const i=yo(t.toolName),d=/edit|write/i.test(t.toolName);return e.jsx(At,{open:o,onOpenChange:()=>s(),children:e.jsxs(mt,{className:"sm:max-w-2xl border-yellow-500/50",ref:n,tabIndex:-1,children:[e.jsxs(is,{children:[e.jsxs(cs,{className:"flex items-center gap-2",children:[e.jsx(en,{className:"h-5 w-5 text-yellow-500 animate-pulse"}),"Approval required: ",t.toolName]}),e.jsxs(ds,{children:["The agent wants to ",d?"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(i,{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:[d?"File modification":"Tool execution"," — preview below"]})]})]}),t.input!==void 0&&e.jsx(vo,{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(xt,{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(ls,{className:"gap-2 sm:gap-2 flex-wrap",children:[e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>r("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(H,{variant:"outline",size:"sm",onClick:()=>r("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(H,{variant:"outline",size:"sm",onClick:()=>r("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(H,{size:"sm",onClick:()=>r("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 jo(){const o=B(m=>m.wsStatus),t=B(m=>m.wsUrl),[s,a]=c.useState(!1),[n,r]=c.useState(Date.now());if(c.useEffect(()=>{if(o.state!=="reconnecting")return;const m=setInterval(()=>r(Date.now()),500);return()=>clearInterval(m)},[o.state]),c.useEffect(()=>{o.state==="open"&&a(!1)},[o.state]),o.state==="open"||o.state==="connecting"||s)return null;const i=()=>xe(t).retryNow(),d=o.state==="reconnecting",l=o.state==="closed"?o.error:o.state==="reconnecting"?o.lastError:void 0,u=d?Math.max(0,Math.ceil((o.nextRetryAt-n)/1e3)):0;return e.jsxs("div",{className:C("flex items-center gap-3 px-4 py-2 border-b text-sm",d?"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:[d?e.jsx(we,{className:"h-4 w-4 animate-spin shrink-0"}):e.jsx(yt,{className:"h-4 w-4 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:d?`Reconnecting to backend (attempt ${o.attempt}) — retrying in ${u}s`:"Disconnected from backend"}),l&&e.jsx("div",{className:"text-xs opacity-80 truncate",children:l})]}),e.jsxs("button",{type:"button",onClick:i,className:C("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",d?"border-orange-500/40":"border-red-500/40"),title:"Retry connection now",children:[e.jsx(Ke,{className:"h-3 w-3"}),"Retry now"]}),e.jsx("button",{type:"button",onClick:()=>a(!0),className:"text-current/60 hover:text-current shrink-0",title:"Dismiss (chip in topbar still shows status)",children:e.jsx($e,{className:"h-4 w-4"})})]})}class No extends c.Component{constructor(){super(...arguments);de(this,"state",{error:null});de(this,"handleReset",()=>{this.setState({error:null})})}static getDerivedStateFromError(s){return{error:s}}componentDidCatch(s,a){var n,r;console.error("[ErrorBoundary]",s,a.componentStack),(r=(n=this.props).onError)==null||r.call(n,s,a)}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(xt,{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(H,{size:"sm",variant:"outline",onClick:()=>window.location.reload(),children:[e.jsx(Nt,{className:"h-4 w-4 mr-1"}),"Reload page"]}),e.jsx(H,{size:"sm",onClick:this.handleReset,children:"Try again"})]})]})}):this.props.children}}function ko(){const o=I(y=>y.modelSwitcherOpen),t=I(y=>y.setModelSwitcherOpen),[s,a]=c.useState(""),[n,r]=c.useState(0),[i,d]=c.useState([]),[l,u]=c.useState({}),m=c.useRef(null),x=B(y=>y.wsUrl),p=B(y=>y.provider),f=B(y=>y.model),w=I(y=>y.paletteOpen),N=ge();c.useEffect(()=>{const y=E=>{if((E.ctrlKey||E.metaKey)&&E.key.toLowerCase()==="m"&&!E.shiftKey&&!E.altKey){if(w)return;E.preventDefault(),t(!o);return}E.key==="Escape"&&o&&(E.preventDefault(),t(!1))};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[o,w]),c.useEffect(()=>{const y=xe(x),E=y.on("providers.saved",F=>{const _=F.payload;d(_.providers??[])}),se=y.on("provider.models",F=>{const _=F.payload;u(V=>({...V,[_.provider]:_.models}))});return()=>{E(),se()}},[x]),c.useEffect(()=>{o&&(a(""),r(0),N.listSavedProviders(),requestAnimationFrame(()=>{var y;return(y=m.current)==null?void 0:y.focus()}))},[o,N]),c.useEffect(()=>{if(o)for(const y of i)l[y.id]||N.listProviderModels(y.id)},[o,i,l,N]);const $=c.useMemo(()=>{const y=[];for(const F of i){const _=l[F.id]??[];for(const V of _)y.push({provider:F.id,model:V.id,modelName:V.name||V.id,contextWindow:V.contextWindow,isCurrent:F.id===p&&V.id===f})}const E=s.toLowerCase().trim();return(E?y.filter(F=>F.provider.toLowerCase().includes(E)||F.model.toLowerCase().includes(E)||F.modelName.toLowerCase().includes(E)):y).sort((F,_)=>F.isCurrent!==_.isCurrent?F.isCurrent?-1:1:F.provider.localeCompare(_.provider)||F.model.localeCompare(_.model))},[i,l,s,p,f]);c.useEffect(()=>{n>=$.length&&r(0)},[$.length,n]);const v=y=>{const E=$[y];E&&(N.switchModel(E.provider,E.model),t(!1))};return o?e.jsx("div",{className:"fixed inset-0 z-50 flex items-start justify-center bg-background/60 backdrop-blur-sm pt-[15vh]",onClick:y=>{y.target===y.currentTarget&&t(!1)},onKeyDown:y=>{y.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(Ee,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("input",{ref:m,value:s,onChange:y=>{a(y.target.value),r(0)},onKeyDown:y=>{y.key==="ArrowDown"?(y.preventDefault(),r(E=>Math.min($.length-1,E+1))):y.key==="ArrowUp"?(y.preventDefault(),r(E=>Math.max(0,E-1))):y.key==="Enter"?(y.preventDefault(),v(n)):y.key==="Escape"&&(y.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:$.length===0?e.jsx("div",{className:"px-4 py-8 text-center text-sm text-muted-foreground",children:i.length===0?"No saved providers — register a key in Settings first.":"Loading models…"}):$.map((y,E)=>e.jsxs("button",{type:"button",onClick:()=>v(E),onMouseEnter:()=>r(E),className:C("w-full flex items-center gap-3 px-3 py-2 text-left text-sm transition-colors",E===n?"bg-accent text-accent-foreground":"hover:bg-accent/40",y.isCurrent&&"font-medium"),children:[e.jsx(_e,{className:C("h-4 w-4 shrink-0",y.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:y.provider}),e.jsx("span",{className:"mx-1 text-muted-foreground/40",children:"·"}),e.jsx("span",{children:y.modelName})]}),y.contextWindow&&e.jsxs("div",{className:"text-[10px] text-muted-foreground font-mono",children:[y.model," · ctx ",y.contextWindow.toLocaleString()]})]}),y.isCurrent?e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-primary font-semibold",children:"active"}):e.jsx(Bt,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100"})]},`${y.provider}:${y.model}`))})]})}):null}const us=c.createContext(void 0);function So({children:o,defaultTheme:t="system",storageKey:s="wrongstack-theme"}){const{theme:a,setTheme:n}=B(),[r,i]=c.useState(()=>typeof window<"u"&&localStorage.getItem(s)||t);c.useEffect(()=>{const l=window.document.documentElement;if(l.classList.remove("light","dark"),r==="system"){const u=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";l.classList.add(u)}else l.classList.add(r)},[r]);const d={theme:r,setTheme:l=>{localStorage.setItem(s,l),i(l),n(l)}};return e.jsx(us.Provider,{value:d,children:o})}function ms(){const o=c.useContext(us);if(o===void 0)throw new Error("useTheme must be used within a ThemeProvider");return o}const ye=c.forwardRef(({className:o,type:t,...s},a)=>e.jsx("input",{type:t,className:C("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",o),ref:a,...s}));ye.displayName="Input";const ps=sn,$t=c.forwardRef(({className:o,...t},s)=>e.jsx(es,{ref:s,className:C("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",o),...t}));$t.displayName=es.displayName;const ke=c.forwardRef(({className:o,...t},s)=>e.jsx(ts,{ref:s,className:C("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",o),...t}));ke.displayName=ts.displayName;const Se=c.forwardRef(({className:o,...t},s)=>e.jsx(ss,{ref:s,className:C("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",o),...t}));Se.displayName=ss.displayName;function Co(){var Te;const{setCurrentView:o}=I(),{provider:t,model:s,setProvider:a,setModel:n,wsConnected:r}=B(),{theme:i,setTheme:d}=ms(),l=ge(),u=l.client;l.listProviders,l.listSavedProviders;const[m,x]=c.useState([]),[p,f]=c.useState({}),[w,N]=c.useState([]),[$,v]=c.useState(!1),[y,E]=c.useState(!1),[se,F]=c.useState(!1),[_,V]=c.useState(null),[U,J]=c.useState("catalog"),[ne,ie]=c.useState(null),[X,z]=c.useState(""),[re,Q]=c.useState(""),[S,Z]=c.useState(!1),[O,ee]=c.useState(!1),[L,Y]=c.useState(""),[b,M]=c.useState("openai-compatible"),[h,j]=c.useState(""),[R,g]=c.useState(""),K=m.find(k=>k.id===t);c.useEffect(()=>{const k=fe=>{if(fe.type==="provider.catalog"){const je=fe.payload;x(je.providers.sort((Me,Ze)=>Me.id.localeCompare(Ze.id))),v(!1)}},P=fe=>{if(fe.type==="provider.models"){const je=fe.payload;f(Me=>({...Me,[je.provider]:je.models})),E(!1)}},le=fe=>{if(fe.type==="providers.saved"){const Me=fe.payload.providers.sort((Ze,hs)=>Ze.id.localeCompare(hs.id));N(Me),F(!1),Me.length>0&&J("saved")}},xs=fe=>{if(fe.type==="key.operation_result"){const je=fe.payload;V(je),setTimeout(()=>V(null),3e3),u.listSavedProviders()}};if(!r||!u)return;const Ge=u.on("provider.catalog",k),Je=u.on("provider.models",P),Ye=u.on("providers.saved",le),Xe=u.on("key.operation_result",xs);return v(!0),F(!0),u.listProviders(),u.listSavedProviders(),()=>{Ge==null||Ge(),Je==null||Je(),Ye==null||Ye(),Xe==null||Xe()}},[r,u]);const ce=c.useCallback(k=>{var P;a(k),p[k]||(E(!0),(P=l.listProviderModels)==null||P.call(l,k))},[p,a,l]),G=c.useCallback(k=>{var le;n(k);const P=B.getState().provider;(le=l.switchModel)==null||le.call(l,P,k),V({success:!0,message:`Switching to ${P} / ${k}…`})},[n,l]),ue=c.useCallback(k=>{var P;!X.trim()||!re.trim()||((P=l.addKey)==null||P.call(l,k,X.trim(),re.trim()),z(""),Q(""),ie(null))},[l,X,re]),me=c.useCallback((k,P)=>{var le;(le=l.deleteKey)==null||le.call(l,k,P)},[l]),ae=c.useCallback((k,P)=>{var le;(le=l.setActiveKey)==null||le.call(l,k,P)},[l]),D=c.useCallback(()=>{var k;L.trim()&&((k=l.addProvider)==null||k.call(l,L.trim(),b,h||void 0,R||void 0),Y(""),M("openai-compatible"),j(""),g(""),ee(!1))},[l,L,b,h,R]),A=c.useCallback(k=>{var P;(P=l.removeProvider)==null||P.call(l,k)},[l]),[q,te]=c.useState(""),pe=["anthropic","openai","google","openai-compatible"],oe=q.trim()?m.filter(k=>{const P=q.trim().toLowerCase();return k.id.toLowerCase().includes(P)||k.name.toLowerCase().includes(P)||k.family.toLowerCase().includes(P)}):m,he=oe.reduce((k,P)=>(k[P.family]||(k[P.family]=[]),k[P.family].push(P),k),{});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(H,{variant:"ghost",size:"icon",onClick:()=>o("chat"),children:e.jsx($e,{className:"h-4 w-4"})})]}),e.jsx(Qe,{className:"flex-1",children:e.jsx("div",{className:"p-6 max-w-2xl mx-auto",children:e.jsxs(ps,{defaultValue:"provider",children:[e.jsxs($t,{className:"w-full justify-start mb-6 grid grid-cols-4",children:[e.jsxs(ke,{value:"provider",className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"}),"Provider"]}),e.jsxs(ke,{value:"model",className:"gap-2",children:[e.jsx(_e,{className:"h-4 w-4"}),"Model"]}),e.jsxs(ke,{value:"connection",className:"gap-2",children:[e.jsx(Ie,{className:"h-4 w-4"}),"Connection"]}),e.jsxs(ke,{value:"appearance",className:"gap-2",children:[e.jsx(on,{className:"h-4 w-4"}),"Appearance"]})]}),e.jsxs(Se,{value:"provider",className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-2 mb-4",children:[e.jsxs(H,{variant:U==="catalog"?"default":"outline",size:"sm",onClick:()=>J("catalog"),children:[e.jsx(Ie,{className:"h-4 w-4 mr-1"}),"Catalog"]}),e.jsxs(H,{variant:U==="saved"?"default":"outline",size:"sm",onClick:()=>J("saved"),children:[e.jsx(et,{className:"h-4 w-4 mr-1"}),"Saved (",w.length,")"]})]}),_&&e.jsxs("div",{className:C("p-3 rounded-lg mb-4 flex items-center gap-2",_.success?"bg-green-500/10 text-green-600":"bg-red-500/10 text-red-600"),children:[_.success?e.jsx(Ce,{className:"h-4 w-4"}):e.jsx(rn,{className:"h-4 w-4"}),_.message]}),U==="catalog"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(ye,{placeholder:`Search ${m.length} providers (name / id / family)…`,value:q,onChange:k=>te(k.target.value),className:"text-sm"}),$&&m.length===0?e.jsxs("div",{className:"flex items-center justify-center py-8",children:[e.jsx(we,{className:"h-6 w-6 animate-spin text-muted-foreground"}),e.jsx("span",{className:"ml-2 text-muted-foreground",children:"Loading catalog..."})]}):oe.length===0&&q?e.jsxs("div",{className:"text-center py-8 text-muted-foreground text-sm",children:['No providers match "',e.jsx("span",{className:"font-mono",children:q}),'".']}):e.jsx(e.Fragment,{children:pe.map(k=>{const P=he[k];return P!=null&&P.length?e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wider",children:k}),e.jsx("div",{className:"grid grid-cols-1 gap-2",children:P.map(le=>e.jsxs("button",{type:"button",onClick:()=>ce(le.id),className:C("flex flex-col items-start p-3 rounded-lg border text-left transition-all",t===le.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:le.name}),e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",le.id,")"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[le.hasApiKey&&e.jsxs("span",{className:"text-xs bg-green-500/10 text-green-600 px-2 py-0.5 rounded",children:[e.jsx(et,{className:"h-3 w-3 inline mr-1"}),"Configured"]}),le.envVars[0]&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["ENV: ",le.envVars[0]]}),t===le.id&&e.jsx(Ce,{className:"h-4 w-4 text-primary"})]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:[le.modelCount," models",le.apiBase&&` · ${le.apiBase}`]})]},le.id))})]},k):null})})]}),U==="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(H,{size:"sm",variant:"outline",onClick:()=>ee(!O),children:[e.jsx(Tt,{className:"h-4 w-4 mr-1"}),"Add Provider"]})]}),O&&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(ye,{placeholder:"Provider ID (e.g. my-llm-server)",value:L,onChange:k=>Y(k.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:b,onChange:k=>M(k.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(ye,{placeholder:"Base URL (optional, e.g. http://localhost:11434/v1)",value:h,onChange:k=>j(k.target.value)}),e.jsx(ye,{type:"password",placeholder:"API Key (optional)",value:R,onChange:k=>g(k.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{size:"sm",onClick:D,disabled:!L.trim(),children:"Add"}),e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>ee(!1),children:"Cancel"})]})]}),se?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(we,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):w.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(et,{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"})]}):w.map(k=>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:k.id}),k.family&&e.jsx("span",{className:"text-xs text-muted-foreground",children:k.family})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(H,{size:"icon",variant:"ghost",onClick:()=>A(k.id),children:e.jsx(Fe,{className:"h-4 w-4 text-destructive"})})})]}),k.baseUrl&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsx(Ie,{className:"h-3 w-3 inline mr-1"}),k.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(H,{size:"sm",variant:"ghost",onClick:()=>ie(ne===k.id?null:k.id),children:[e.jsx(Tt,{className:"h-3 w-3 mr-1"}),"Add Key"]})]}),k.apiKeys.length===0&&!ne&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"No keys configured"}),k.apiKeys.map(P=>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:P.label}),P.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:P.maskedKey})]}),e.jsxs("div",{className:"flex gap-1",children:[!P.isActive&&e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>ae(k.id,P.label),children:"Set Active"}),e.jsx(H,{size:"icon",variant:"ghost",onClick:()=>me(k.id,P.label),children:e.jsx(Fe,{className:"h-3 w-3 text-destructive"})})]})]},P.label)),ne===k.id&&e.jsxs("div",{className:"p-3 border rounded space-y-2 bg-background",children:[e.jsx(ye,{placeholder:"Key label (e.g. default, production)",value:X,onChange:P=>z(P.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{type:S?"text":"password",placeholder:"API key",value:re,onChange:P=>Q(P.target.value)}),e.jsx(H,{size:"icon",variant:"ghost",onClick:()=>Z(!S),children:S?e.jsx(an,{className:"h-4 w-4"}):e.jsx(ln,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{size:"sm",onClick:()=>ue(k.id),disabled:!X.trim()||!re.trim(),children:"Save Key"}),e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>{ie(null),z(""),Q("")},children:"Cancel"})]})]})]})]},k.id))]})]}),e.jsx(Se,{value:"model",className:"space-y-4",children:t?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:(K==null?void 0:K.name)||t}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t})]}),e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>{var k;E(!0),(k=l.listProviderModels)==null||k.call(l,t)},children:e.jsx(Nt,{className:C("h-4 w-4",y&&"animate-spin")})})]}),y&&!p[t]?e.jsxs("div",{className:"flex items-center justify-center py-8",children:[e.jsx(we,{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:[(p[t]||[]).map(k=>e.jsxs("button",{type:"button",onClick:()=>G(k.id),className:C("w-full flex items-center justify-between p-3 rounded-lg border text-left transition-all",s===k.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:k.name||k.id}),e.jsx("div",{className:"flex gap-2 mt-1",children:k.capabilities.map(P=>e.jsx("span",{className:"text-xs bg-muted px-1.5 py-0.5 rounded",children:P},P))})]}),e.jsxs("div",{className:"text-right text-xs text-muted-foreground",children:[k.contextWindow&&e.jsxs("div",{children:[k.contextWindow/1e3,"k context"]}),k.inputCost&&k.outputCost&&e.jsxs("div",{children:["$",k.inputCost,"/$",k.outputCost]}),s===k.id&&e.jsx(Ce,{className:"h-4 w-4 text-primary mt-1"})]})]},k.id)),((Te=p[t])==null?void 0:Te.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(_e,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"Select a provider first"})]})}),e.jsxs(Se,{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(Ie,{className:"h-4 w-4 text-muted-foreground"}),"WebSocket Server URL"]}),e.jsx(ye,{id:"websocket-url",value:B.getState().wsUrl,onChange:k=>B.getState().setConfig({wsUrl:k.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(Se,{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(H,{variant:i==="light"?"default":"outline",size:"sm",onClick:()=>d("light"),children:[e.jsx(ft,{className:"h-4 w-4 mr-1"}),"Light"]}),e.jsxs(H,{variant:i==="dark"?"default":"outline",size:"sm",onClick:()=>d("dark"),children:[e.jsx(gt,{className:"h-4 w-4 mr-1"}),"Dark"]}),e.jsxs(H,{variant:i==="system"?"default":"outline",size:"sm",onClick:()=>d("system"),children:[e.jsx(bt,{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(It,{label:"Compact density",hint:"Tighter spacing throughout the chat. Toggle anywhere with Ctrl+Shift+D.",selector:k=>k.compactMode,onChange:()=>I.getState().toggleCompactMode()}),e.jsx(It,{label:"Sound on completion",hint:"Play a soft chime when a run finishes — useful when working in another tab.",selector:null,configKey:"soundOnComplete"})]})]})]})})})]})}function It({label:o,hint:t,selector:s,onChange:a,configKey:n}){const r=I(u=>s?s(u):!1),i=B(u=>n?u[n]:!1),d=s?r:i,l=()=>{if(s)a==null||a();else if(n==="soundOnComplete"){const u=!B.getState().soundOnComplete;B.getState().setSoundOnComplete(u),u&&kt()}};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:o}),t&&e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:t})]}),e.jsx("button",{type:"button",role:"switch","aria-checked":d,onClick:l,className:C("shrink-0 relative inline-flex h-5 w-9 rounded-full border transition-colors",d?"bg-primary border-primary":"bg-muted border-input hover:bg-muted/80"),children:e.jsx("span",{className:C("absolute top-0.5 left-0.5 h-3.5 w-3.5 rounded-full bg-background shadow transition-transform",d&&"translate-x-4")})})]})}const $o=[{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 To(){const o=I(s=>s.shortcutsOpen),t=I(s=>s.setShortcutsOpen);return c.useEffect(()=>{const s=a=>{var d;const n=a.target,r=(d=n==null?void 0:n.tagName)==null?void 0:d.toLowerCase();if(!(r==="input"||r==="textarea"||(n==null?void 0:n.isContentEditable))&&a.key==="?"&&!a.ctrlKey&&!a.metaKey&&!a.altKey){a.preventDefault(),t(!I.getState().shortcutsOpen);return}a.key==="Escape"&&I.getState().shortcutsOpen&&(a.preventDefault(),t(!1))};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[t]),o?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:s=>{s.key==="Escape"&&t(!1)},children:e.jsxs("div",{onClick:s=>s.stopPropagation(),onKeyDown:s=>s.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(Vt,{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($e,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"overflow-y-auto px-5 py-4 space-y-6",children:$o.map(s=>e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground mb-2",children:s.section}),e.jsx("div",{className:"grid grid-cols-1 gap-1.5",children:s.items.map(a=>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:a.description}),e.jsx("span",{className:"flex items-center gap-1 shrink-0",children:a.keys.map((n,r)=>e.jsxs("span",{className:"flex items-center gap-1",children:[r>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:n})]},n))})]},a.description))})]},s.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 Mo(){const{toggleSidebar:o,currentView:t,setCurrentView:s}=I(),a=I(h=>h.sidebarWidth),n=I(h=>h.setSidebarWidth),{totalTokens:r,cost:i,session:d,todos:l}=W(),{messages:u,clearMessages:m}=T(),x=I(h=>h.pinnedIds),p=I(h=>h.unpinAll),[f,w]=c.useState(""),N=I(h=>h.favoriteSessionIds),$=I(h=>h.toggleFavoriteSession),v=I(h=>h.sessionNicknames),y=I(h=>h.setSessionNickname),[E,se]=c.useState(null),[F,_]=c.useState(""),V=x.map(h=>u.find(j=>j.id===h)).filter(h=>!!h&&h.content.length>0),{wsConnected:U,wsUrl:J,provider:ne,model:ie}=B(),{entries:X,loading:z,error:re}=Le(),{listSessions:Q,deleteSession:S,resumeSession:Z,client:O}=ge();c.useEffect(()=>{var h;U&&((h=O==null?void 0:O.getTodos)==null||h.call(O))},[U,O]);const ee=d==null?void 0:d.id;c.useEffect(()=>{t==="history"&&U&&Q(50)},[t,U,ee,Q]);const L=h=>{if(!h)return"--";const j=Math.floor((Date.now()-h)/1e3);return j<60?`${j}s`:`${Math.floor(j/60)}m`},Y=h=>{const j=Date.parse(h);if(Number.isNaN(j))return"";const R=Date.now()-j;if(R<6e4)return"just now";if(R<36e5)return`${Math.floor(R/6e4)}m ago`;if(R<864e5)return`${Math.floor(R/36e5)}h ago`;const g=Math.floor(R/864e5);return g<7?`${g}d ago`:new Date(j).toLocaleDateString()},b=(()=>{const h=f.trim().toLowerCase(),j=h?X.filter(oe=>oe.title.toLowerCase().includes(h)||oe.model.toLowerCase().includes(h)||oe.provider.toLowerCase().includes(h)||oe.id.toLowerCase().includes(h)):X,R=new Date;R.setHours(0,0,0,0);const g=R.getTime(),K=g-864e5,ce=g-6*864e5,G={today:[],yesterday:[],week:[],older:[]};for(const oe of j){const he=Date.parse(oe.startedAt);if(Number.isNaN(he)){G.older.push(oe);continue}he>=g?G.today.push(oe):he>=K?G.yesterday.push(oe):he>=ce?G.week.push(oe):G.older.push(oe)}const ue=new Set(N),me=j.filter(oe=>ue.has(oe.id)),ae=[];me.length&&ae.push({label:"Favorites",rows:me,star:!0});const D=oe=>oe.filter(he=>!ue.has(he.id)),A=D(G.today),q=D(G.yesterday),te=D(G.week),pe=D(G.older);return A.length&&ae.push({label:"Today",rows:A}),q.length&&ae.push({label:"Yesterday",rows:q}),te.length&&ae.push({label:"This week",rows:te}),pe.length&&ae.push({label:"Earlier",rows:pe}),ae})(),M=h=>{h.preventDefault();const j=h.clientX,R=a,g=ce=>{n(R+(ce.clientX-j))},K=()=>{window.removeEventListener("mousemove",g),window.removeEventListener("mouseup",K),document.body.style.cursor="",document.body.style.userSelect=""};window.addEventListener("mousemove",g),window.addEventListener("mouseup",K),document.body.style.cursor="col-resize",document.body.style.userSelect="none"};return e.jsxs("aside",{style:{width:`${a}px`},className:"relative border-r bg-card flex flex-col shrink-0",children:[e.jsxs("div",{onMouseDown:M,onDoubleClick:()=>n(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",children:[e.jsx("div",{className:"w-6 h-6 rounded bg-primary flex items-center justify-center",children:e.jsx(jt,{className:"h-4 w-4 text-primary-foreground"})}),e.jsx("span",{className:"text-sm font-semibold tracking-tight",children:"WrongStack"})]}),e.jsx(H,{variant:"ghost",size:"icon",onClick:o,children:e.jsx(cn,{className:"h-4 w-4"})})]}),e.jsxs(ps,{value:t==="settings"?"chat":t,onValueChange:h=>s(h),className:"flex-1 flex flex-col",children:[e.jsxs($t,{className:"w-full rounded-none bg-transparent p-2 h-auto grid grid-cols-2",children:[e.jsxs(ke,{value:"chat",className:"flex-col gap-1.5 py-2 data-[state=active]:bg-primary/10",children:[e.jsx(dn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Chat"})]}),e.jsxs(ke,{value:"history",className:"flex-col gap-1.5 py-2 data-[state=active]:bg-primary/10",children:[e.jsx(ct,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"History"})]})]}),e.jsxs(Se,{value:"chat",className:"flex-1 flex flex-col m-0 overflow-hidden",children:[e.jsxs("div",{className:"px-4 py-3 border-b",children:[e.jsxs("div",{className:C("flex items-center gap-2 px-3 py-2 rounded-lg text-sm",U?"bg-green-500/10 text-green-600 dark:text-green-400":"bg-yellow-500/10 text-yellow-600 dark:text-yellow-400"),children:[U?e.jsx(Kt,{className:"h-4 w-4"}):e.jsx(yt,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:U?"Connected":"Disconnected"})]}),e.jsx("div",{className:"text-xs text-muted-foreground mt-2 px-1 font-mono",children:J})]}),e.jsxs("button",{type:"button",onClick:()=>s("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:ne||"—"}),e.jsx("span",{className:"text-muted-foreground/40 mx-1",children:"/"}),e.jsx("span",{className:"font-medium",children:ie||"—"})]})]}),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(it,{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:L((d==null?void 0:d.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:r.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:r.output.toLocaleString()})]})]}),i>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:["$",i.toFixed(4)]})]})]}),l.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(un,{className:"h-4 w-4 text-muted-foreground"}),"Todos"]}),e.jsxs("span",{className:"text-[10px] text-muted-foreground tabular-nums",children:[l.filter(h=>h.status==="completed").length,"/",l.length]})]}),e.jsx("ul",{className:"space-y-1 max-h-48 overflow-y-auto pr-1",children:l.map(h=>{const j=h.status==="completed"?Ce:h.status==="in_progress"?mn:pn,R=h.status==="completed"?"text-green-600 dark:text-green-400 line-through opacity-70":h.status==="in_progress"?"text-amber-600 dark:text-amber-400":"text-muted-foreground";return e.jsxs("li",{className:C("flex items-start gap-2 text-xs leading-snug",R),children:[e.jsx(j,{className:"h-3.5 w-3.5 mt-0.5 shrink-0"}),e.jsx("span",{className:"break-words",children:h.status==="in_progress"&&h.activeForm?h.activeForm:h.content})]},h.id)})})]}),V.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(zt,{className:"h-4 w-4 text-amber-500"}),"Pinned"]}),e.jsx("button",{type:"button",onClick:p,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:V.map(h=>{const j=h.content.replace(/\s+/g," ").slice(0,80);return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>{const R=document.querySelector(`[data-message-id="${h.id}"]`);R&&(R.scrollIntoView({behavior:"smooth",block:"center"}),R.classList.add("ring-2","ring-amber-500/60"),setTimeout(()=>{R.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:h.content.slice(0,400),children:[j,h.content.length>80?"…":""]})},h.id)})})]}),e.jsxs("div",{className:"px-4 py-3 border-b space-y-2",children:[e.jsxs(H,{variant:"outline",size:"sm",className:"w-full justify-start text-destructive hover:text-destructive",onClick:()=>{var h;m(),(h=O==null?void 0:O.clearContext)==null||h.call(O)},children:[e.jsx(Fe,{className:"h-4 w-4 mr-2"}),"Clear context"]}),e.jsxs(H,{variant:"outline",size:"sm",className:"w-full justify-start",onClick:()=>{var h;return(h=O==null?void 0:O.newSession)==null?void 0:h.call(O)},disabled:!U,children:[e.jsx(Ke,{className:"h-4 w-4 mr-2"}),"New session"]}),e.jsxs(H,{variant:"outline",size:"sm",className:"w-full justify-start",onClick:()=>{var h;return(h=O==null?void 0:O.compactContext)==null?void 0:h.call(O)},disabled:!U,children:[e.jsx(it,{className:"h-4 w-4 mr-2"}),"Compact context"]})]}),e.jsx("div",{className:"flex-1"}),e.jsx("div",{className:"px-3 py-3 border-t",children:e.jsxs(H,{variant:"ghost",size:"sm",className:"w-full justify-start",onClick:()=>s("settings"),children:[e.jsx(ht,{className:"h-4 w-4 mr-2"}),"Settings"]})})]}),e.jsxs(Se,{value:"history",className:"flex-1 m-0 flex flex-col overflow-hidden",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(H,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>Q(50),disabled:!U,title:"Refresh",children:z?e.jsx(we,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Nt,{className:"h-3.5 w-3.5"})})]}),X.length>3&&e.jsx("div",{className:"px-3 py-2 border-b",children:e.jsxs("div",{className:"relative",children:[e.jsx(Ee,{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:f,onChange:h=>w(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"}),f&&e.jsx("button",{type:"button",onClick:()=>w(""),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($e,{className:"h-3 w-3"})})]})}),re&&e.jsx("div",{className:"px-4 py-2 text-xs text-destructive bg-destructive/5 border-b",children:re}),e.jsx(Qe,{className:"flex-1",children:X.length===0&&!z?e.jsxs("div",{className:"text-center text-muted-foreground py-8 px-4",children:[e.jsx(ct,{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"})]}):b.length===0?e.jsxs("div",{className:"text-center text-muted-foreground py-8 px-4",children:[e.jsx(Ee,{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:b.map(h=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:C("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(Mt,{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:C("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||E===j.id,onClick:()=>Z(j.id),onDoubleClick:R=>{R.stopPropagation(),se(j.id),_(v[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:[E===j.id?e.jsx("input",{value:F,onChange:R=>_(R.target.value),onClick:R=>R.stopPropagation(),onBlur:()=>{y(j.id,F),se(null)},onKeyDown:R=>{R.key==="Enter"?(R.preventDefault(),y(j.id,F),se(null)):R.key==="Escape"&&(R.preventDefault(),se(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:v[j.id]?`${v[j.id]} — original: ${j.title}`:`${j.title}
|
|
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(Pt,{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:s||"…"})})]})]})}function bo(){const{messages:o,isLoading:t}=T(),s=I(g=>g.setPaletteOpen),a=I(g=>g.setShortcutsOpen),n=I(g=>g.sidebarOpen),r=I(g=>g.toggleSidebar),i=I(g=>g.compactMode),d=q(g=>g.setTheme),l=q(g=>g.theme),{totalTokens:u,cost:m,startTime:x,lastInputTokens:p,maxContext:f,projectName:w,iteration:N}=W(),{wsConnected:$,wsStatus:v,provider:y,model:E}=q(),{setCurrentView:se}=I(),F=c.useRef(null),_=f>0&&p>0?Math.min(100,Math.round(p/f*100)):0,V=_>=85?"bg-red-500/15 text-red-600 dark:text-red-400":_>=70?"bg-amber-500/15 text-amber-600 dark:text-amber-400":"bg-muted text-muted-foreground",[U,J]=c.useState(!0),[ne,ie]=c.useState(0),[X,z]=c.useState(!1),re=c.useRef(o.length),Q=c.useCallback(()=>{var g;return((g=F.current)==null?void 0:g.querySelector("[data-radix-scroll-area-viewport]"))??null},[]);c.useEffect(()=>{const g=Q();if(!g)return;const K=()=>{const G=g.scrollHeight-g.scrollTop-g.clientHeight<120;J(G),G&&(ie(0),re.current=o.length);const ue=g.scrollTop>g.clientHeight&&g.scrollHeight>g.clientHeight*2.5;z(ue)};return g.addEventListener("scroll",K,{passive:!0}),()=>g.removeEventListener("scroll",K)},[Q,o.length]),c.useEffect(()=>{const g=Q();if(g)if(U)g.scrollTop=g.scrollHeight,re.current=o.length;else{const K=o.length-re.current;K>0&&ie(K)}},[o,U,Q]);const S=c.useCallback(()=>{const g=Q();g&&(g.scrollTo({top:g.scrollHeight,behavior:"smooth"}),J(!0),ie(0),re.current=o.length)},[Q,o.length]),Z=c.useCallback(()=>{const g=Q();g&&g.scrollTo({top:0,behavior:"smooth"})},[Q]),[O,ee]=c.useState(null),[L,Y]=c.useState(()=>Date.now()),b=c.useRef(null);c.useEffect(()=>{t&&O===null&&ee(Date.now()),!t&&O!==null&&ee(null)},[t,O]),c.useEffect(()=>{if(!t)return;const g=setInterval(()=>Y(Date.now()),500);return()=>clearInterval(g)},[t]);const M=g=>{if(!g)return"--";const K=Math.floor((Date.now()-g)/1e3);if(K<60)return`${K}s`;const ce=Math.floor(K/60),G=K%60;return`${ce}m ${G}s`},h=(()=>{if(!t)return"idle";const g=o[o.length-1];return(g==null?void 0:g.role)==="assistant"&&!!g.content&&g.streaming?"streaming":"thinking"})(),j=h==="idle"?"bg-muted text-muted-foreground":h==="streaming"?"bg-blue-500/10 text-blue-600 dark:text-blue-400":"bg-amber-500/10 text-amber-600 dark:text-amber-400",R=f>0&&p>0||u.input>0||!!x;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:[!n&&e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",onClick:r,title:"Open sidebar (Ctrl+\\\\)",children:e.jsx(Qs,{className:"h-4 w-4"})}),!n&&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(jt,{className:"h-3 w-3 text-primary-foreground"})})}),e.jsx(zn,{wsStatus:v,wsConnected:$}),e.jsxs("span",{className:C("flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[11px] font-medium shrink-0 tabular-nums",j),title:`Agent state: ${h}`,children:[h!=="idle"&&e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-current animate-pulse"}),e.jsx("span",{children:h})]}),w&&e.jsxs("span",{className:"flex items-center gap-1 text-[11px] text-muted-foreground shrink-0 min-w-0",title:`Project: ${w}`,children:[e.jsx(Gs,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate max-w-[12rem]",children:w})]}),e.jsxs("button",{type:"button",onClick:()=>I.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(_e,{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:y||"no-provider"}),e.jsx("span",{className:"text-muted-foreground/40 mx-0.5",children:"/"}),e.jsx("span",{className:"font-medium",children:E||"no-model"})]})]}),e.jsx(co,{}),e.jsx(Bn,{}),N&&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(Js,{className:"h-3 w-3 animate-pulse"}),"iter ",N.index,N.max>0?`/${N.max}`:""]})]}),e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>s(!0),title:"Command palette (Ctrl+K)",children:e.jsx(Ys,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>{d(l==="light"?"dark":l==="dark"?"system":"light")},title:`Theme: ${l} (click to cycle)`,children:l==="light"?e.jsx(ft,{className:"h-4 w-4"}):l==="dark"?e.jsx(gt,{className:"h-4 w-4"}):e.jsx(bt,{className:"h-4 w-4"})}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7 font-mono text-xs",onClick:()=>a(!0),title:"Keyboard shortcuts (?)",children:"?"}),e.jsx(H,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>se("settings"),title:"Settings",children:e.jsx(ht,{className:"h-4 w-4"})})]})]}),R&&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:[f>0&&p>0&&e.jsxs("span",{className:C("flex items-center gap-1 px-1.5 py-0.5 rounded-full font-medium shrink-0",V),title:`Last input: ${p.toLocaleString()} / ${f.toLocaleString()} tokens`,children:["ctx ",_,"% · ",Ae(p),"/",Ae(f)]}),u.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:Ae(u.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:Ae(u.output)}),e.jsx("span",{children:"out"})]}),u.cacheRead&&u.cacheRead>0&&(()=>{const g=(u.cacheRead??0)+u.input,K=g>0?Math.round((u.cacheRead??0)/g*100):0;return e.jsxs("span",{className:"flex items-center gap-1",title:`Cache hit ratio: ${K}%`,children:[e.jsx("span",{className:"font-medium text-foreground",children:Ae(u.cacheRead)}),e.jsxs("span",{children:["cache (",K,"%)"]})]})})(),e.jsx(qn,{})]})]}),x&&e.jsx("span",{className:"text-muted-foreground/70 tabular-nums shrink-0",children:M(x)})]})]}),e.jsxs("div",{className:"flex-1 relative overflow-hidden",children:[e.jsx(uo,{}),!U&&e.jsxs("button",{type:"button",onClick:S,className:C("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(qt,{className:"h-3.5 w-3.5"}),ne>0?`${ne} new message${ne===1?"":"s"}`:"Jump to latest"]}),X&&e.jsxs("button",{type:"button",onClick:Z,title:"Scroll to top (oldest)",className:C("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(Bt,{className:"h-3 w-3"}),e.jsx("span",{children:"Top"})]}),e.jsx(Qe,{className:"h-full",ref:F,children:e.jsxs("div",{className:C("mx-auto pb-8",i?"max-w-5xl p-3 space-y-3":"max-w-5xl p-4 space-y-6"),children:[o.length===0&&!t&&e.jsx(fo,{}),(()=>{const g=[];for(let D=0;D<o.length;D++){const A=o[D];if(A.role==="tool"){const B=g[g.length-1];B&&B.kind==="tools"?B.tools.push(A):g.push({kind:"tools",tools:[A],key:A.id})}else{const B=o[D-1];g.push({kind:"msg",message:A,isFirst:!B||B.role!==A.role})}}const K=[];for(const D of g){if(D.kind==="msg"&&D.message.role==="user"){K.push({kind:"user",message:D.message,key:D.message.id});continue}const A=K[K.length-1];if(A&&A.kind==="agent")A.items.push(D);else{const B=D.kind==="msg"?D.message.id:D.key;K.push({kind:"agent",items:[D],key:B})}}let ce=null;const G=D=>{const A=new Date(D);return`${A.getFullYear()}-${A.getMonth()}-${A.getDate()}`},ue=D=>{const A=new Date(D),B=new Date,te=new Date(Date.now()-864e5);return G(D)===G(B.getTime())?"Today":G(D)===G(te.getTime())?"Yesterday":A.toLocaleDateString(void 0,{weekday:"short",month:"short",day:"numeric",year:A.getFullYear()===B.getFullYear()?void 0:"numeric"})},me=D=>{if(D.kind==="user")return D.message.timestamp;const A=D.items[0];return A.kind==="msg"?A.message.timestamp:A.tools[0].timestamp},ae=[];for(let D=0;D<K.length;D++){const A=K[D],B=me(A),te=G(B);if(te!==ce&&(ae.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:ue(B)}),e.jsx("div",{className:"flex-1 h-px bg-border/50"})]},`day-${te}-${D}`)),ce=te),A.kind==="user"){ae.push(e.jsx(qe,{message:A.message,isFirst:!0},A.key));continue}const pe=D===K.length-1;ae.push(e.jsx("div",{className:C(i?"space-y-1":"space-y-1.5"),children:A.items.map((oe,he)=>{const Me=he>0;if(oe.kind==="msg")return e.jsx(qe,{message:oe.message,isFirst:!Me&&oe.isFirst,isContinuation:Me},oe.message.id);const k=pe&&he===A.items.length-1&&t&&oe.tools.some(P=>P.toolResult===void 0);return e.jsx(po,{tools:oe.tools,defaultOpen:k,isContinuation:Me},oe.key)})},A.key))}return ae})(),e.jsx(go,{}),t&&(()=>{const g=o[o.length-1],K=o.filter(D=>D.role==="tool"&&D.toolResult===void 0);let ce="Thinking…";if(K.length>0){const D=Array.from(new Set(K.map(te=>te.toolName).filter(Boolean))),A=D.slice(0,2).join(", "),B=D.length>2?` +${D.length-2}`:"";ce=K.length===1?`Running ${A||"tool"}…`:`Running ${K.length} tools (${A}${B})…`}else(g==null?void 0:g.role)==="assistant"&&g.content?ce="Writing reply…":(g==null?void 0:g.role)==="tool"&&g.toolResult!==void 0&&(ce="Thinking about the next step…");const G=O?Math.max(0,Math.floor((L-O)/1e3)):0,ue=G<60?`${G}s`:`${Math.floor(G/60)}m ${G%60}s`;let me="";const ae=(g==null?void 0:g.role)==="assistant"&&g.streaming&&g.content?g:null;if(ae){const D=b.current;if(!D||D.id!==ae.id)b.current={id:ae.id,at:Date.now(),len:ae.content.length};else{const A=Math.max(1,L-D.at),B=Math.max(0,ae.content.length-D.len);if(A>500&&B>0){const te=B*1e3/A;me=te>=1e3?`${(te/1e3).toFixed(1)}k ch/s`:`${Math.round(te)} ch/s`}}}else b.current&&(b.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(Ut,{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:ce}),e.jsx("span",{className:"text-xs text-muted-foreground tabular-nums",children:ue}),N&&e.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:["· iter ",N.index,N.max>0?`/${N.max}`:""]}),me&&e.jsxs("span",{className:"text-xs text-muted-foreground/80 tabular-nums",children:["· ",me]})]})})})]})})()]})})]}),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(Un,{}),e.jsx("p",{className:"text-xs text-center text-muted-foreground/50 mt-2",children:"Press Enter to send, Shift+Enter for new line"})]})})]})}const It=en,yo=Xs,is=c.forwardRef(({className:o,...t},s)=>e.jsx(Yt,{ref:s,className:C("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",o),...t}));is.displayName=Yt.displayName;const mt=c.forwardRef(({className:o,children:t,...s},a)=>e.jsxs(yo,{children:[e.jsx(is,{}),e.jsxs(Xt,{ref:a,className:C("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",o),...s,children:[t,e.jsxs(Zs,{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(Te,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));mt.displayName=Xt.displayName;const ls=({className:o,...t})=>e.jsx("div",{className:C("flex flex-col space-y-1.5 text-center sm:text-left",o),...t});ls.displayName="DialogHeader";const cs=({className:o,...t})=>e.jsx("div",{className:C("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",o),...t});cs.displayName="DialogFooter";const ds=c.forwardRef(({className:o,...t},s)=>e.jsx(Zt,{ref:s,className:C("text-lg font-semibold leading-none tracking-tight",o),...t}));ds.displayName=Zt.displayName;const us=c.forwardRef(({className:o,...t},s)=>e.jsx(es,{ref:s,className:C("text-sm text-muted-foreground",o),...t}));us.displayName=es.displayName;function vo(o){return/edit|write|create|patch/i.test(o)?sn:/bash|shell|exec|run|command/i.test(o)?Le:/fetch|http|web|curl|request/i.test(o)?Ie:Be}function wo({toolName:o,input:t}){const s=rs(o,t);if(s)return e.jsx("div",{className:"rounded-lg overflow-hidden border",children:e.jsx(os,{oldText:s.oldText,newText:s.newText,caption:s.caption})});if(typeof t=="object"&&t!==null){const a=t,n=a.command??a.cmd??a.script;if(typeof n=="string"&&n.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(Le,{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:["$",n]})]});const r=a.url;if(typeof r=="string"){const i=a.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:i.toUpperCase()})," ",e.jsx("span",{className:"break-all",children:r})]})}}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 jo(){const{showConfirmDialog:o,confirmInfo:t,hideConfirm:s}=I(),{sendConfirm:a}=ge(),n=c.useRef(null),r=l=>{t&&a(t.id,l),s()};if(c.useEffect(()=>{var u;if(!o)return;const l=m=>{var f;const x=m.target,p=(f=x==null?void 0:x.tagName)==null?void 0:f.toLowerCase();p==="input"||p==="textarea"||(m.key==="y"||m.key==="Y"?(m.preventDefault(),r("yes")):m.key==="n"||m.key==="N"||m.key==="Escape"?(m.preventDefault(),r("no")):m.key==="a"||m.key==="A"?(m.preventDefault(),r("always")):(m.key==="d"||m.key==="D")&&(m.preventDefault(),r("deny")))};return window.addEventListener("keydown",l),(u=n.current)==null||u.focus(),()=>window.removeEventListener("keydown",l)},[o,t==null?void 0:t.id]),!t)return e.jsx(It,{open:o,onOpenChange:()=>s(),children:e.jsx(mt,{})});const i=vo(t.toolName),d=/edit|write/i.test(t.toolName);return e.jsx(It,{open:o,onOpenChange:()=>s(),children:e.jsxs(mt,{className:"sm:max-w-2xl border-yellow-500/50",ref:n,tabIndex:-1,children:[e.jsxs(ls,{children:[e.jsxs(ds,{className:"flex items-center gap-2",children:[e.jsx(tn,{className:"h-5 w-5 text-yellow-500 animate-pulse"}),"Approval required: ",t.toolName]}),e.jsxs(us,{children:["The agent wants to ",d?"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(i,{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:[d?"File modification":"Tool execution"," — preview below"]})]})]}),t.input!==void 0&&e.jsx(wo,{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(xt,{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(cs,{className:"gap-2 sm:gap-2 flex-wrap",children:[e.jsxs(H,{variant:"outline",size:"sm",onClick:()=>r("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(H,{variant:"outline",size:"sm",onClick:()=>r("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(H,{variant:"outline",size:"sm",onClick:()=>r("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(H,{size:"sm",onClick:()=>r("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 No(){const o=q(m=>m.wsStatus),t=q(m=>m.wsUrl),[s,a]=c.useState(!1),[n,r]=c.useState(Date.now());if(c.useEffect(()=>{if(o.state!=="reconnecting")return;const m=setInterval(()=>r(Date.now()),500);return()=>clearInterval(m)},[o.state]),c.useEffect(()=>{o.state==="open"&&a(!1)},[o.state]),o.state==="open"||o.state==="connecting"||s)return null;const i=()=>xe(t).retryNow(),d=o.state==="reconnecting",l=o.state==="closed"?o.error:o.state==="reconnecting"?o.lastError:void 0,u=d?Math.max(0,Math.ceil((o.nextRetryAt-n)/1e3)):0;return e.jsxs("div",{className:C("flex items-center gap-3 px-4 py-2 border-b text-sm",d?"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:[d?e.jsx(we,{className:"h-4 w-4 animate-spin shrink-0"}):e.jsx(yt,{className:"h-4 w-4 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:d?`Reconnecting to backend (attempt ${o.attempt}) — retrying in ${u}s`:"Disconnected from backend"}),l&&e.jsx("div",{className:"text-xs opacity-80 truncate",children:l})]}),e.jsxs("button",{type:"button",onClick:i,className:C("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",d?"border-orange-500/40":"border-red-500/40"),title:"Retry connection now",children:[e.jsx(Ke,{className:"h-3 w-3"}),"Retry now"]}),e.jsx("button",{type:"button",onClick:()=>a(!0),className:"text-current/60 hover:text-current shrink-0",title:"Dismiss (chip in topbar still shows status)",children:e.jsx(Te,{className:"h-4 w-4"})})]})}class ko extends c.Component{constructor(){super(...arguments);de(this,"state",{error:null});de(this,"handleReset",()=>{this.setState({error:null})})}static getDerivedStateFromError(s){return{error:s}}componentDidCatch(s,a){var n,r;console.error("[ErrorBoundary]",s,a.componentStack),(r=(n=this.props).onError)==null||r.call(n,s,a)}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(xt,{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(H,{size:"sm",variant:"outline",onClick:()=>window.location.reload(),children:[e.jsx(Nt,{className:"h-4 w-4 mr-1"}),"Reload page"]}),e.jsx(H,{size:"sm",onClick:this.handleReset,children:"Try again"})]})]})}):this.props.children}}function So(){const o=I(y=>y.modelSwitcherOpen),t=I(y=>y.setModelSwitcherOpen),[s,a]=c.useState(""),[n,r]=c.useState(0),[i,d]=c.useState([]),[l,u]=c.useState({}),m=c.useRef(null),x=q(y=>y.wsUrl),p=q(y=>y.provider),f=q(y=>y.model),w=I(y=>y.paletteOpen),N=ge();c.useEffect(()=>{const y=E=>{if((E.ctrlKey||E.metaKey)&&E.key.toLowerCase()==="m"&&!E.shiftKey&&!E.altKey){if(w)return;E.preventDefault(),t(!o);return}E.key==="Escape"&&o&&(E.preventDefault(),t(!1))};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[o,w]),c.useEffect(()=>{const y=xe(x),E=y.on("providers.saved",F=>{const _=F.payload;d(_.providers??[])}),se=y.on("provider.models",F=>{const _=F.payload;u(V=>({...V,[_.provider]:_.models}))});return()=>{E(),se()}},[x]),c.useEffect(()=>{o&&(a(""),r(0),N.listSavedProviders(),requestAnimationFrame(()=>{var y;return(y=m.current)==null?void 0:y.focus()}))},[o,N]),c.useEffect(()=>{if(o)for(const y of i)l[y.id]||N.listProviderModels(y.id)},[o,i,l,N]);const $=c.useMemo(()=>{const y=[];for(const F of i){const _=l[F.id]??[];for(const V of _)y.push({provider:F.id,model:V.id,modelName:V.name||V.id,contextWindow:V.contextWindow,isCurrent:F.id===p&&V.id===f})}const E=s.toLowerCase().trim();return(E?y.filter(F=>F.provider.toLowerCase().includes(E)||F.model.toLowerCase().includes(E)||F.modelName.toLowerCase().includes(E)):y).sort((F,_)=>F.isCurrent!==_.isCurrent?F.isCurrent?-1:1:F.provider.localeCompare(_.provider)||F.model.localeCompare(_.model))},[i,l,s,p,f]);c.useEffect(()=>{n>=$.length&&r(0)},[$.length,n]);const v=y=>{const E=$[y];E&&(N.switchModel(E.provider,E.model),t(!1))};return o?e.jsx("div",{className:"fixed inset-0 z-50 flex items-start justify-center bg-background/60 backdrop-blur-sm pt-[15vh]",onClick:y=>{y.target===y.currentTarget&&t(!1)},onKeyDown:y=>{y.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(De,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("input",{ref:m,value:s,onChange:y=>{a(y.target.value),r(0)},onKeyDown:y=>{y.key==="ArrowDown"?(y.preventDefault(),r(E=>Math.min($.length-1,E+1))):y.key==="ArrowUp"?(y.preventDefault(),r(E=>Math.max(0,E-1))):y.key==="Enter"?(y.preventDefault(),v(n)):y.key==="Escape"&&(y.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:$.length===0?e.jsx("div",{className:"px-4 py-8 text-center text-sm text-muted-foreground",children:i.length===0?"No saved providers — register a key in Settings first.":"Loading models…"}):$.map((y,E)=>e.jsxs("button",{type:"button",onClick:()=>v(E),onMouseEnter:()=>r(E),className:C("w-full flex items-center gap-3 px-3 py-2 text-left text-sm transition-colors",E===n?"bg-accent text-accent-foreground":"hover:bg-accent/40",y.isCurrent&&"font-medium"),children:[e.jsx(_e,{className:C("h-4 w-4 shrink-0",y.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:y.provider}),e.jsx("span",{className:"mx-1 text-muted-foreground/40",children:"·"}),e.jsx("span",{children:y.modelName})]}),y.contextWindow&&e.jsxs("div",{className:"text-[10px] text-muted-foreground font-mono",children:[y.model," · ctx ",y.contextWindow.toLocaleString()]})]}),y.isCurrent?e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-primary font-semibold",children:"active"}):e.jsx(Vt,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100"})]},`${y.provider}:${y.model}`))})]})}):null}const ms=c.createContext(void 0);function Co({children:o,defaultTheme:t="system",storageKey:s="wrongstack-theme"}){const{theme:a,setTheme:n}=q(),[r,i]=c.useState(()=>typeof window<"u"&&localStorage.getItem(s)||t);c.useEffect(()=>{const l=window.document.documentElement;if(l.classList.remove("light","dark"),r==="system"){const u=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";l.classList.add(u)}else l.classList.add(r)},[r]);const d={theme:r,setTheme:l=>{localStorage.setItem(s,l),i(l),n(l)}};return e.jsx(ms.Provider,{value:d,children:o})}function ps(){const o=c.useContext(ms);if(o===void 0)throw new Error("useTheme must be used within a ThemeProvider");return o}const ye=c.forwardRef(({className:o,type:t,...s},a)=>e.jsx("input",{type:t,className:C("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",o),ref:a,...s}));ye.displayName="Input";const xs=nn,$t=c.forwardRef(({className:o,...t},s)=>e.jsx(ts,{ref:s,className:C("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",o),...t}));$t.displayName=ts.displayName;const ke=c.forwardRef(({className:o,...t},s)=>e.jsx(ss,{ref:s,className:C("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",o),...t}));ke.displayName=ss.displayName;const Se=c.forwardRef(({className:o,...t},s)=>e.jsx(ns,{ref:s,className:C("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",o),...t}));Se.displayName=ns.displayName;function $o(){var Me;const{setCurrentView:o}=I(),{provider:t,model:s,setProvider:a,setModel:n,wsConnected:r}=q(),{theme:i,setTheme:d}=ps(),l=ge(),u=l.client;l.listProviders,l.listSavedProviders;const[m,x]=c.useState([]),[p,f]=c.useState({}),[w,N]=c.useState([]),[$,v]=c.useState(!1),[y,E]=c.useState(!1),[se,F]=c.useState(!1),[_,V]=c.useState(null),[U,J]=c.useState("catalog"),[ne,ie]=c.useState(null),[X,z]=c.useState(""),[re,Q]=c.useState(""),[S,Z]=c.useState(!1),[O,ee]=c.useState(!1),[L,Y]=c.useState(""),[b,M]=c.useState("openai-compatible"),[h,j]=c.useState(""),[R,g]=c.useState(""),K=m.find(k=>k.id===t);c.useEffect(()=>{const k=fe=>{if(fe.type==="provider.catalog"){const je=fe.payload;x(je.providers.sort((Ee,Ze)=>Ee.id.localeCompare(Ze.id))),v(!1)}},P=fe=>{if(fe.type==="provider.models"){const je=fe.payload;f(Ee=>({...Ee,[je.provider]:je.models})),E(!1)}},le=fe=>{if(fe.type==="providers.saved"){const Ee=fe.payload.providers.sort((Ze,fs)=>Ze.id.localeCompare(fs.id));N(Ee),F(!1),Ee.length>0&&J("saved")}},hs=fe=>{if(fe.type==="key.operation_result"){const je=fe.payload;V(je),setTimeout(()=>V(null),3e3),u.listSavedProviders()}};if(!r||!u)return;const Ge=u.on("provider.catalog",k),Je=u.on("provider.models",P),Ye=u.on("providers.saved",le),Xe=u.on("key.operation_result",hs);return v(!0),F(!0),u.listProviders(),u.listSavedProviders(),()=>{Ge==null||Ge(),Je==null||Je(),Ye==null||Ye(),Xe==null||Xe()}},[r,u]);const ce=c.useCallback(k=>{var P;a(k),p[k]||(E(!0),(P=l.listProviderModels)==null||P.call(l,k))},[p,a,l]),G=c.useCallback(k=>{var le;n(k);const P=q.getState().provider;(le=l.switchModel)==null||le.call(l,P,k),V({success:!0,message:`Switching to ${P} / ${k}…`})},[n,l]),ue=c.useCallback(k=>{var P;!X.trim()||!re.trim()||((P=l.addKey)==null||P.call(l,k,X.trim(),re.trim()),z(""),Q(""),ie(null))},[l,X,re]),me=c.useCallback((k,P)=>{var le;(le=l.deleteKey)==null||le.call(l,k,P)},[l]),ae=c.useCallback((k,P)=>{var le;(le=l.setActiveKey)==null||le.call(l,k,P)},[l]),D=c.useCallback(()=>{var k;L.trim()&&((k=l.addProvider)==null||k.call(l,L.trim(),b,h||void 0,R||void 0),Y(""),M("openai-compatible"),j(""),g(""),ee(!1))},[l,L,b,h,R]),A=c.useCallback(k=>{var P;(P=l.removeProvider)==null||P.call(l,k)},[l]),[B,te]=c.useState(""),pe=["anthropic","openai","google","openai-compatible"],oe=B.trim()?m.filter(k=>{const P=B.trim().toLowerCase();return k.id.toLowerCase().includes(P)||k.name.toLowerCase().includes(P)||k.family.toLowerCase().includes(P)}):m,he=oe.reduce((k,P)=>(k[P.family]||(k[P.family]=[]),k[P.family].push(P),k),{});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(H,{variant:"ghost",size:"icon",onClick:()=>o("chat"),children:e.jsx(Te,{className:"h-4 w-4"})})]}),e.jsx(Qe,{className:"flex-1",children:e.jsx("div",{className:"p-6 max-w-2xl mx-auto",children:e.jsxs(xs,{defaultValue:"provider",children:[e.jsxs($t,{className:"w-full justify-start mb-6 grid grid-cols-4",children:[e.jsxs(ke,{value:"provider",className:"gap-2",children:[e.jsx(on,{className:"h-4 w-4"}),"Provider"]}),e.jsxs(ke,{value:"model",className:"gap-2",children:[e.jsx(_e,{className:"h-4 w-4"}),"Model"]}),e.jsxs(ke,{value:"connection",className:"gap-2",children:[e.jsx(Ie,{className:"h-4 w-4"}),"Connection"]}),e.jsxs(ke,{value:"appearance",className:"gap-2",children:[e.jsx(rn,{className:"h-4 w-4"}),"Appearance"]})]}),e.jsxs(Se,{value:"provider",className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-2 mb-4",children:[e.jsxs(H,{variant:U==="catalog"?"default":"outline",size:"sm",onClick:()=>J("catalog"),children:[e.jsx(Ie,{className:"h-4 w-4 mr-1"}),"Catalog"]}),e.jsxs(H,{variant:U==="saved"?"default":"outline",size:"sm",onClick:()=>J("saved"),children:[e.jsx(et,{className:"h-4 w-4 mr-1"}),"Saved (",w.length,")"]})]}),_&&e.jsxs("div",{className:C("p-3 rounded-lg mb-4 flex items-center gap-2",_.success?"bg-green-500/10 text-green-600":"bg-red-500/10 text-red-600"),children:[_.success?e.jsx(Ce,{className:"h-4 w-4"}):e.jsx(an,{className:"h-4 w-4"}),_.message]}),U==="catalog"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(ye,{placeholder:`Search ${m.length} providers (name / id / family)…`,value:B,onChange:k=>te(k.target.value),className:"text-sm"}),$&&m.length===0?e.jsxs("div",{className:"flex items-center justify-center py-8",children:[e.jsx(we,{className:"h-6 w-6 animate-spin text-muted-foreground"}),e.jsx("span",{className:"ml-2 text-muted-foreground",children:"Loading catalog..."})]}):oe.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:pe.map(k=>{const P=he[k];return P!=null&&P.length?e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wider",children:k}),e.jsx("div",{className:"grid grid-cols-1 gap-2",children:P.map(le=>e.jsxs("button",{type:"button",onClick:()=>ce(le.id),className:C("flex flex-col items-start p-3 rounded-lg border text-left transition-all",t===le.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:le.name}),e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",le.id,")"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[le.hasApiKey&&e.jsxs("span",{className:"text-xs bg-green-500/10 text-green-600 px-2 py-0.5 rounded",children:[e.jsx(et,{className:"h-3 w-3 inline mr-1"}),"Configured"]}),le.envVars[0]&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["ENV: ",le.envVars[0]]}),t===le.id&&e.jsx(Ce,{className:"h-4 w-4 text-primary"})]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:[le.modelCount," models",le.apiBase&&` · ${le.apiBase}`]})]},le.id))})]},k):null})})]}),U==="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(H,{size:"sm",variant:"outline",onClick:()=>ee(!O),children:[e.jsx(Tt,{className:"h-4 w-4 mr-1"}),"Add Provider"]})]}),O&&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(ye,{placeholder:"Provider ID (e.g. my-llm-server)",value:L,onChange:k=>Y(k.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:b,onChange:k=>M(k.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(ye,{placeholder:"Base URL (optional, e.g. http://localhost:11434/v1)",value:h,onChange:k=>j(k.target.value)}),e.jsx(ye,{type:"password",placeholder:"API Key (optional)",value:R,onChange:k=>g(k.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{size:"sm",onClick:D,disabled:!L.trim(),children:"Add"}),e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>ee(!1),children:"Cancel"})]})]}),se?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(we,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):w.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(et,{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"})]}):w.map(k=>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:k.id}),k.family&&e.jsx("span",{className:"text-xs text-muted-foreground",children:k.family})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(H,{size:"icon",variant:"ghost",onClick:()=>A(k.id),children:e.jsx(Fe,{className:"h-4 w-4 text-destructive"})})})]}),k.baseUrl&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsx(Ie,{className:"h-3 w-3 inline mr-1"}),k.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(H,{size:"sm",variant:"ghost",onClick:()=>ie(ne===k.id?null:k.id),children:[e.jsx(Tt,{className:"h-3 w-3 mr-1"}),"Add Key"]})]}),k.apiKeys.length===0&&!ne&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"No keys configured"}),k.apiKeys.map(P=>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:P.label}),P.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:P.maskedKey})]}),e.jsxs("div",{className:"flex gap-1",children:[!P.isActive&&e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>ae(k.id,P.label),children:"Set Active"}),e.jsx(H,{size:"icon",variant:"ghost",onClick:()=>me(k.id,P.label),children:e.jsx(Fe,{className:"h-3 w-3 text-destructive"})})]})]},P.label)),ne===k.id&&e.jsxs("div",{className:"p-3 border rounded space-y-2 bg-background",children:[e.jsx(ye,{placeholder:"Key label (e.g. default, production)",value:X,onChange:P=>z(P.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{type:S?"text":"password",placeholder:"API key",value:re,onChange:P=>Q(P.target.value)}),e.jsx(H,{size:"icon",variant:"ghost",onClick:()=>Z(!S),children:S?e.jsx(ln,{className:"h-4 w-4"}):e.jsx(cn,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{size:"sm",onClick:()=>ue(k.id),disabled:!X.trim()||!re.trim(),children:"Save Key"}),e.jsx(H,{size:"sm",variant:"ghost",onClick:()=>{ie(null),z(""),Q("")},children:"Cancel"})]})]})]})]},k.id))]})]}),e.jsx(Se,{value:"model",className:"space-y-4",children:t?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:(K==null?void 0:K.name)||t}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t})]}),e.jsx(H,{variant:"ghost",size:"sm",onClick:()=>{var k;E(!0),(k=l.listProviderModels)==null||k.call(l,t)},children:e.jsx(Nt,{className:C("h-4 w-4",y&&"animate-spin")})})]}),y&&!p[t]?e.jsxs("div",{className:"flex items-center justify-center py-8",children:[e.jsx(we,{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:[(p[t]||[]).map(k=>e.jsxs("button",{type:"button",onClick:()=>G(k.id),className:C("w-full flex items-center justify-between p-3 rounded-lg border text-left transition-all",s===k.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:k.name||k.id}),e.jsx("div",{className:"flex gap-2 mt-1",children:k.capabilities.map(P=>e.jsx("span",{className:"text-xs bg-muted px-1.5 py-0.5 rounded",children:P},P))})]}),e.jsxs("div",{className:"text-right text-xs text-muted-foreground",children:[k.contextWindow&&e.jsxs("div",{children:[k.contextWindow/1e3,"k context"]}),k.inputCost&&k.outputCost&&e.jsxs("div",{children:["$",k.inputCost,"/$",k.outputCost]}),s===k.id&&e.jsx(Ce,{className:"h-4 w-4 text-primary mt-1"})]})]},k.id)),((Me=p[t])==null?void 0:Me.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(_e,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"Select a provider first"})]})}),e.jsxs(Se,{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(Ie,{className:"h-4 w-4 text-muted-foreground"}),"WebSocket Server URL"]}),e.jsx(ye,{id:"websocket-url",value:q.getState().wsUrl,onChange:k=>q.getState().setConfig({wsUrl:k.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(Se,{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(H,{variant:i==="light"?"default":"outline",size:"sm",onClick:()=>d("light"),children:[e.jsx(ft,{className:"h-4 w-4 mr-1"}),"Light"]}),e.jsxs(H,{variant:i==="dark"?"default":"outline",size:"sm",onClick:()=>d("dark"),children:[e.jsx(gt,{className:"h-4 w-4 mr-1"}),"Dark"]}),e.jsxs(H,{variant:i==="system"?"default":"outline",size:"sm",onClick:()=>d("system"),children:[e.jsx(bt,{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(Ot,{label:"Compact density",hint:"Tighter spacing throughout the chat. Toggle anywhere with Ctrl+Shift+D.",selector:k=>k.compactMode,onChange:()=>I.getState().toggleCompactMode()}),e.jsx(Ot,{label:"Sound on completion",hint:"Play a soft chime when a run finishes — useful when working in another tab.",selector:null,configKey:"soundOnComplete"})]})]})]})})})]})}function Ot({label:o,hint:t,selector:s,onChange:a,configKey:n}){const r=I(u=>s?s(u):!1),i=q(u=>n?u[n]:!1),d=s?r:i,l=()=>{if(s)a==null||a();else if(n==="soundOnComplete"){const u=!q.getState().soundOnComplete;q.getState().setSoundOnComplete(u),u&&kt()}};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:o}),t&&e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:t})]}),e.jsx("button",{type:"button",role:"switch","aria-checked":d,onClick:l,className:C("shrink-0 relative inline-flex h-5 w-9 rounded-full border transition-colors",d?"bg-primary border-primary":"bg-muted border-input hover:bg-muted/80"),children:e.jsx("span",{className:C("absolute top-0.5 left-0.5 h-3.5 w-3.5 rounded-full bg-background shadow transition-transform",d&&"translate-x-4")})})]})}const To=[{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 Mo(){const o=I(s=>s.shortcutsOpen),t=I(s=>s.setShortcutsOpen);return c.useEffect(()=>{const s=a=>{var d;const n=a.target,r=(d=n==null?void 0:n.tagName)==null?void 0:d.toLowerCase();if(!(r==="input"||r==="textarea"||(n==null?void 0:n.isContentEditable))&&a.key==="?"&&!a.ctrlKey&&!a.metaKey&&!a.altKey){a.preventDefault(),t(!I.getState().shortcutsOpen);return}a.key==="Escape"&&I.getState().shortcutsOpen&&(a.preventDefault(),t(!1))};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[t]),o?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:s=>{s.key==="Escape"&&t(!1)},children:e.jsxs("div",{onClick:s=>s.stopPropagation(),onKeyDown:s=>s.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(Qt,{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(Te,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"overflow-y-auto px-5 py-4 space-y-6",children:To.map(s=>e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground mb-2",children:s.section}),e.jsx("div",{className:"grid grid-cols-1 gap-1.5",children:s.items.map(a=>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:a.description}),e.jsx("span",{className:"flex items-center gap-1 shrink-0",children:a.keys.map((n,r)=>e.jsxs("span",{className:"flex items-center gap-1",children:[r>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:n})]},n))})]},a.description))})]},s.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 Eo(){const{toggleSidebar:o,currentView:t,setCurrentView:s}=I(),a=I(h=>h.sidebarWidth),n=I(h=>h.setSidebarWidth),{totalTokens:r,cost:i,session:d,todos:l}=W(),{messages:u,clearMessages:m}=T(),x=I(h=>h.pinnedIds),p=I(h=>h.unpinAll),[f,w]=c.useState(""),N=I(h=>h.favoriteSessionIds),$=I(h=>h.toggleFavoriteSession),v=I(h=>h.sessionNicknames),y=I(h=>h.setSessionNickname),[E,se]=c.useState(null),[F,_]=c.useState(""),V=x.map(h=>u.find(j=>j.id===h)).filter(h=>!!h&&h.content.length>0),{wsConnected:U,wsUrl:J,provider:ne,model:ie}=q(),{entries:X,loading:z,error:re}=Re(),{listSessions:Q,deleteSession:S,resumeSession:Z,client:O}=ge();c.useEffect(()=>{var h;U&&((h=O==null?void 0:O.getTodos)==null||h.call(O))},[U,O]);const ee=d==null?void 0:d.id;c.useEffect(()=>{t==="history"&&U&&Q(50)},[t,U,ee,Q]);const L=h=>{if(!h)return"--";const j=Math.floor((Date.now()-h)/1e3);return j<60?`${j}s`:`${Math.floor(j/60)}m`},Y=h=>{const j=Date.parse(h);if(Number.isNaN(j))return"";const R=Date.now()-j;if(R<6e4)return"just now";if(R<36e5)return`${Math.floor(R/6e4)}m ago`;if(R<864e5)return`${Math.floor(R/36e5)}h ago`;const g=Math.floor(R/864e5);return g<7?`${g}d ago`:new Date(j).toLocaleDateString()},b=(()=>{const h=f.trim().toLowerCase(),j=h?X.filter(oe=>oe.title.toLowerCase().includes(h)||oe.model.toLowerCase().includes(h)||oe.provider.toLowerCase().includes(h)||oe.id.toLowerCase().includes(h)):X,R=new Date;R.setHours(0,0,0,0);const g=R.getTime(),K=g-864e5,ce=g-6*864e5,G={today:[],yesterday:[],week:[],older:[]};for(const oe of j){const he=Date.parse(oe.startedAt);if(Number.isNaN(he)){G.older.push(oe);continue}he>=g?G.today.push(oe):he>=K?G.yesterday.push(oe):he>=ce?G.week.push(oe):G.older.push(oe)}const ue=new Set(N),me=j.filter(oe=>ue.has(oe.id)),ae=[];me.length&&ae.push({label:"Favorites",rows:me,star:!0});const D=oe=>oe.filter(he=>!ue.has(he.id)),A=D(G.today),B=D(G.yesterday),te=D(G.week),pe=D(G.older);return A.length&&ae.push({label:"Today",rows:A}),B.length&&ae.push({label:"Yesterday",rows:B}),te.length&&ae.push({label:"This week",rows:te}),pe.length&&ae.push({label:"Earlier",rows:pe}),ae})(),M=h=>{h.preventDefault();const j=h.clientX,R=a,g=ce=>{n(R+(ce.clientX-j))},K=()=>{window.removeEventListener("mousemove",g),window.removeEventListener("mouseup",K),document.body.style.cursor="",document.body.style.userSelect=""};window.addEventListener("mousemove",g),window.addEventListener("mouseup",K),document.body.style.cursor="col-resize",document.body.style.userSelect="none"};return e.jsxs("aside",{style:{width:`${a}px`},className:"relative border-r bg-card flex flex-col shrink-0",children:[e.jsxs("div",{onMouseDown:M,onDoubleClick:()=>n(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",children:[e.jsx("div",{className:"w-6 h-6 rounded bg-primary flex items-center justify-center",children:e.jsx(jt,{className:"h-4 w-4 text-primary-foreground"})}),e.jsx("span",{className:"text-sm font-semibold tracking-tight",children:"WrongStack"})]}),e.jsx(H,{variant:"ghost",size:"icon",onClick:o,children:e.jsx(dn,{className:"h-4 w-4"})})]}),e.jsxs(xs,{value:t==="settings"?"chat":t,onValueChange:h=>s(h),className:"flex-1 flex flex-col",children:[e.jsxs($t,{className:"w-full rounded-none bg-transparent p-2 h-auto grid grid-cols-2",children:[e.jsxs(ke,{value:"chat",className:"flex-col gap-1.5 py-2 data-[state=active]:bg-primary/10",children:[e.jsx(un,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Chat"})]}),e.jsxs(ke,{value:"history",className:"flex-col gap-1.5 py-2 data-[state=active]:bg-primary/10",children:[e.jsx(ct,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"History"})]})]}),e.jsxs(Se,{value:"chat",className:"flex-1 flex flex-col m-0 overflow-hidden",children:[e.jsxs("div",{className:"px-4 py-3 border-b",children:[e.jsxs("div",{className:C("flex items-center gap-2 px-3 py-2 rounded-lg text-sm",U?"bg-green-500/10 text-green-600 dark:text-green-400":"bg-yellow-500/10 text-yellow-600 dark:text-yellow-400"),children:[U?e.jsx(Wt,{className:"h-4 w-4"}):e.jsx(yt,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:U?"Connected":"Disconnected"})]}),e.jsx("div",{className:"text-xs text-muted-foreground mt-2 px-1 font-mono",children:J})]}),e.jsxs("button",{type:"button",onClick:()=>s("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:ne||"—"}),e.jsx("span",{className:"text-muted-foreground/40 mx-1",children:"/"}),e.jsx("span",{className:"font-medium",children:ie||"—"})]})]}),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(it,{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:L((d==null?void 0:d.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:r.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:r.output.toLocaleString()})]})]}),i>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:["$",i.toFixed(4)]})]})]}),l.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(mn,{className:"h-4 w-4 text-muted-foreground"}),"Todos"]}),e.jsxs("span",{className:"text-[10px] text-muted-foreground tabular-nums",children:[l.filter(h=>h.status==="completed").length,"/",l.length]})]}),e.jsx("ul",{className:"space-y-1 max-h-48 overflow-y-auto pr-1",children:l.map(h=>{const j=h.status==="completed"?Ce:h.status==="in_progress"?pn:xn,R=h.status==="completed"?"text-green-600 dark:text-green-400 line-through opacity-70":h.status==="in_progress"?"text-amber-600 dark:text-amber-400":"text-muted-foreground";return e.jsxs("li",{className:C("flex items-start gap-2 text-xs leading-snug",R),children:[e.jsx(j,{className:"h-3.5 w-3.5 mt-0.5 shrink-0"}),e.jsx("span",{className:"break-words",children:h.status==="in_progress"&&h.activeForm?h.activeForm:h.content})]},h.id)})})]}),V.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(Ht,{className:"h-4 w-4 text-amber-500"}),"Pinned"]}),e.jsx("button",{type:"button",onClick:p,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:V.map(h=>{const j=h.content.replace(/\s+/g," ").slice(0,80);return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>{const R=document.querySelector(`[data-message-id="${h.id}"]`);R&&(R.scrollIntoView({behavior:"smooth",block:"center"}),R.classList.add("ring-2","ring-amber-500/60"),setTimeout(()=>{R.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:h.content.slice(0,400),children:[j,h.content.length>80?"…":""]})},h.id)})})]}),e.jsxs("div",{className:"px-4 py-3 border-b space-y-2",children:[e.jsxs(H,{variant:"outline",size:"sm",className:"w-full justify-start text-destructive hover:text-destructive",onClick:()=>{var h;m(),(h=O==null?void 0:O.clearContext)==null||h.call(O)},children:[e.jsx(Fe,{className:"h-4 w-4 mr-2"}),"Clear context"]}),e.jsxs(H,{variant:"outline",size:"sm",className:"w-full justify-start",onClick:()=>{var h;return(h=O==null?void 0:O.newSession)==null?void 0:h.call(O)},disabled:!U,children:[e.jsx(Ke,{className:"h-4 w-4 mr-2"}),"New session"]}),e.jsxs(H,{variant:"outline",size:"sm",className:"w-full justify-start",onClick:()=>{var h;return(h=O==null?void 0:O.compactContext)==null?void 0:h.call(O)},disabled:!U,children:[e.jsx(it,{className:"h-4 w-4 mr-2"}),"Compact context"]})]}),e.jsx("div",{className:"flex-1"}),e.jsx("div",{className:"px-3 py-3 border-t",children:e.jsxs(H,{variant:"ghost",size:"sm",className:"w-full justify-start",onClick:()=>s("settings"),children:[e.jsx(ht,{className:"h-4 w-4 mr-2"}),"Settings"]})})]}),e.jsxs(Se,{value:"history",className:"flex-1 m-0 flex flex-col overflow-hidden",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(H,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>Q(50),disabled:!U,title:"Refresh",children:z?e.jsx(we,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Nt,{className:"h-3.5 w-3.5"})})]}),X.length>3&&e.jsx("div",{className:"px-3 py-2 border-b",children:e.jsxs("div",{className:"relative",children:[e.jsx(De,{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:f,onChange:h=>w(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"}),f&&e.jsx("button",{type:"button",onClick:()=>w(""),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(Te,{className:"h-3 w-3"})})]})}),re&&e.jsx("div",{className:"px-4 py-2 text-xs text-destructive bg-destructive/5 border-b",children:re}),e.jsx(Qe,{className:"flex-1",children:X.length===0&&!z?e.jsxs("div",{className:"text-center text-muted-foreground py-8 px-4",children:[e.jsx(ct,{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"})]}):b.length===0?e.jsxs("div",{className:"text-center text-muted-foreground py-8 px-4",children:[e.jsx(De,{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:b.map(h=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:C("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(Mt,{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:C("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||E===j.id,onClick:()=>Z(j.id),onDoubleClick:R=>{R.stopPropagation(),se(j.id),_(v[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:[E===j.id?e.jsx("input",{value:F,onChange:R=>_(R.target.value),onClick:R=>R.stopPropagation(),onBlur:()=>{y(j.id,F),se(null)},onKeyDown:R=>{R.key==="Enter"?(R.preventDefault(),y(j.id,F),se(null)):R.key==="Escape"&&(R.preventDefault(),se(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:v[j.id]?`${v[j.id]} — original: ${j.title}`:`${j.title}
|
|
93
93
|
|
|
94
|
-
Double-click to rename`,children:v[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:Y(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:()=>$(j.id),className:C("transition-opacity hover:text-amber-500",N.includes(j.id)?"opacity-100 text-amber-500":"opacity-0 group-hover:opacity-100 text-muted-foreground"),title:N.includes(j.id)?"Unfavorite":"Mark as favorite",children:e.jsx(Mt,{className:C("h-3.5 w-3.5",N.includes(j.id)&&"fill-current")})}),!j.isCurrent&&e.jsx("button",{type:"button",onClick:()=>{window.confirm(`Delete session "${j.title}"?`)&&S(j.id)},className:"opacity-0 group-hover:opacity-100 transition-opacity text-muted-foreground hover:text-destructive",title:"Delete session",children:e.jsx(Fe,{className:"h-3.5 w-3.5"})})]})]},j.id))]},h.label))})})]})]})]})}function
|
|
94
|
+
Double-click to rename`,children:v[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:Y(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:()=>$(j.id),className:C("transition-opacity hover:text-amber-500",N.includes(j.id)?"opacity-100 text-amber-500":"opacity-0 group-hover:opacity-100 text-muted-foreground"),title:N.includes(j.id)?"Unfavorite":"Mark as favorite",children:e.jsx(Mt,{className:C("h-3.5 w-3.5",N.includes(j.id)&&"fill-current")})}),!j.isCurrent&&e.jsx("button",{type:"button",onClick:()=>{window.confirm(`Delete session "${j.title}"?`)&&S(j.id)},className:"opacity-0 group-hover:opacity-100 transition-opacity text-muted-foreground hover:text-destructive",title:"Delete session",children:e.jsx(Fe,{className:"h-3.5 w-3.5"})})]})]},j.id))]},h.label))})})]})]})]})}function Do(){const{theme:o}=ps(),{currentView:t,sidebarOpen:s,toggleSidebar:a,setSearchOpen:n,setSidebarOpen:r}=I(),i=T(p=>p.isLoading),d=W(p=>p.iteration),l=W(p=>p.projectName),u=W(p=>{var f;return(f=p.session)==null?void 0:f.title}),m=W(p=>{var f;return(f=p.session)==null?void 0:f.id}),x=I(p=>m?p.sessionNicknames[m]:void 0);return c.useEffect(()=>{if(typeof window>"u")return;const p=window.matchMedia("(max-width: 768px)"),f=()=>{p.matches&&I.getState().sidebarOpen&&r(!1)};return f(),p.addEventListener("change",f),()=>p.removeEventListener("change",f)},[r]),An(),c.useEffect(()=>{const p=[];if(i){const $=d?` iter ${d.index}${d.max?`/${d.max}`:""}`:"";p.push(`●${$}`)}const f=(x==null?void 0:x.trim())||(u==null?void 0:u.trim()),w=l==null?void 0:l.trim();f&&p.push(f),w&&p.push(w),p.push("WrongStack");const N=p.filter(Boolean).join(" · ");return document.title=N,()=>{document.title="WrongStack"}},[i,d,l,u,x]),c.useEffect(()=>{const p=f=>{var y,E,se,F,_,V,U;const w=f.target,N=(y=w==null?void 0:w.tagName)==null?void 0:y.toLowerCase(),$=N==="input"||N==="textarea"||(w==null?void 0:w.isContentEditable),v=f.ctrlKey||f.metaKey;if(v&&f.key==="\\"){f.preventDefault(),a();return}if(v&&f.key.toLowerCase()==="f"){f.preventDefault(),n(!0);return}if(v&&f.key.toLowerCase()==="/"){f.preventDefault();const J=document.querySelector("textarea");J==null||J.focus();return}if(v&&!$&&(f.key.toLowerCase()==="l"?(f.preventDefault(),T.getState().clearMessages(),(se=(E=xe(q.getState().wsUrl))==null?void 0:E.clearContext)==null||se.call(E)):f.key.toLowerCase()==="n"?(f.preventDefault(),(_=(F=xe(q.getState().wsUrl))==null?void 0:F.newSession)==null||_.call(F)):f.key.toLowerCase()==="e"&&(f.preventDefault(),Ct())),v&&f.shiftKey&&f.key.toLowerCase()==="d"&&(f.preventDefault(),I.getState().toggleCompactMode()),!$&&!v&&!f.altKey){const J=Array.from(document.querySelectorAll("[data-message-id]"));if(J.length===0)return;const ne=document.querySelector('[data-message-id][data-focused="true"]'),ie=ne?J.indexOf(ne):-1,X=z=>{for(const re of J)re.removeAttribute("data-focused");z.setAttribute("data-focused","true"),z.scrollIntoView({behavior:"smooth",block:"center"})};if(f.key==="j"||f.key==="ArrowDown"){const z=J[Math.min(J.length-1,Math.max(0,ie+1))];z&&(f.preventDefault(),X(z));return}if(f.key==="k"||f.key==="ArrowUp"){const z=J[Math.max(0,ie<=0?0:ie-1)];z&&(f.preventDefault(),X(z));return}if(f.key==="g"&&!f.shiftKey){f.preventDefault(),X(J[0]);return}if(f.key==="G"||f.key==="g"&&f.shiftKey){f.preventDefault(),X(J[J.length-1]);return}if(f.key==="Escape"&&ne){f.preventDefault(),ne.removeAttribute("data-focused");return}if(f.key==="c"&&ne){const z=((V=ne.querySelector(".markdown-content"))==null?void 0:V.innerText)??ne.innerText;z&&((U=navigator.clipboard)==null||U.writeText(z).catch(()=>{}),f.preventDefault());return}}};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[a,n]),e.jsxs("div",{className:C("flex h-screen",o),children:[s&&e.jsx(Eo,{}),e.jsxs("main",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsx(No,{}),t==="chat"&&e.jsx(bo,{}),t==="settings"&&e.jsx($o,{})]}),e.jsx(jo,{}),e.jsx(In,{}),e.jsx(Mo,{}),e.jsx(So,{}),e.jsx(yn,{})]})}function Lo(){return e.jsx(ko,{children:e.jsx(Co,{defaultTheme:"system",children:e.jsx(Do,{})})})}hn.createRoot(document.getElementById("root")).render(e.jsx(fn.StrictMode,{children:e.jsx(Lo,{})}));
|