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