openfox 1.6.34 → 1.6.35
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/{chunk-UZ4B76EB.js → chunk-7EIVES5U.js} +2 -2
- package/dist/{chunk-XV3QONGQ.js → chunk-NPSBNNGO.js} +2 -2
- package/dist/cli/dev.js +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/package.json +1 -1
- package/dist/{serve-6OXPB3M7.js → serve-MMDVRY46.js} +2 -2
- package/dist/server/index.js +1 -1
- package/dist/web/assets/{index-BxGLv0sd.js → index-DH6wDW66.js} +3 -3
- package/dist/web/assets/{index-BNzGnHOk.css → index-DTKU-xoU.css} +1 -1
- package/dist/web/index.html +2 -2
- package/dist/web/sw.js +1 -1
- package/package.json +1 -1
|
@@ -54,7 +54,7 @@ Error generating stack: `+h.message+`
|
|
|
54
54
|
*
|
|
55
55
|
* This source code is licensed under the MIT license found in the
|
|
56
56
|
* LICENSE file in the root directory of this source tree.
|
|
57
|
-
*/var kx;function c1(){if(kx)return Md;kx=1;var e=Zl();function r(m,b){return m===b&&(m!==0||1/m===1/b)||m!==m&&b!==b}var i=typeof Object.is=="function"?Object.is:r,s=e.useState,c=e.useEffect,u=e.useLayoutEffect,f=e.useDebugValue;function l(m,b){var _=b(),k=s({inst:{value:_,getSnapshot:b}}),C=k[0].inst,y=k[1];return u(function(){C.value=_,C.getSnapshot=b,d(C)&&y({inst:C})},[m,_,b]),c(function(){return d(C)&&y({inst:C}),m(function(){d(C)&&y({inst:C})})},[m]),f(_),_}function d(m){var b=m.getSnapshot;m=m.value;try{var _=b();return!i(m,_)}catch{return!0}}function p(m,b){return b()}var g=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?p:l;return Md.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:g,Md}var Ex;function u1(){return Ex||(Ex=1,Od.exports=c1()),Od.exports}var d1=u1();const h1=JS.useInsertionEffect,f1=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",p1=f1?H.useLayoutEffect:H.useEffect,m1=h1||p1,vb=e=>{const r=H.useRef([e,(...i)=>r[0](...i)]).current;return m1(()=>{r[0]=e}),r[1]},g1="popstate",jh="pushState",Nh="replaceState",x1="hashchange",jx=[g1,jh,Nh,x1],v1=e=>{for(const r of jx)addEventListener(r,e);return()=>{for(const r of jx)removeEventListener(r,e)}},bb=(e,r)=>d1.useSyncExternalStore(v1,e,r),Nx=()=>location.search,b1=({ssrSearch:e}={})=>bb(Nx,e!=null?()=>e:Nx),Tx=()=>location.pathname,y1=({ssrPath:e}={})=>bb(Tx,e!=null?()=>e:Tx),_1=(e,{replace:r=!1,state:i=null}={})=>history[r?Nh:jh](i,"",e),S1=(e={})=>[y1(e),_1],Ax=Symbol.for("wouter_v3");if(typeof history<"u"&&typeof window[Ax]>"u"){for(const e of[jh,Nh]){const r=history[e];history[e]=function(){const i=r.apply(this,arguments),s=new Event(e);return s.arguments=arguments,dispatchEvent(s),i}}Object.defineProperty(window,Ax,{value:!0})}const w1=(e,r)=>r.toLowerCase().indexOf(e.toLowerCase())?"~"+r:r.slice(e.length)||"/",yb=(e="")=>e==="/"?"":e,C1=(e,r)=>e[0]==="~"?e.slice(1):yb(r)+e,k1=(e="",r)=>w1(Dx(yb(e)),Dx(r)),Dx=e=>{try{return decodeURI(e)}catch{return e}},_b={hook:S1,searchHook:b1,parser:l1,base:"",ssrPath:void 0,ssrSearch:void 0,ssrContext:void 0,hrefs:e=>e,aroundNav:(e,r,i)=>e(r,i)},Sb=H.createContext(_b),zs=()=>H.useContext(Sb),wb={},Cb=H.createContext(wb),E1=()=>H.useContext(Cb),Ql=e=>{const[r,i]=e.hook(e);return[k1(e.base,r),vb((s,c)=>e.aroundNav(i,C1(s,e.base),c))]},dr=()=>Ql(zs()),Th=(e,r,i,s)=>{const{pattern:c,keys:u}=r instanceof RegExp?{keys:!1,pattern:r}:e(r||"*",s),f=c.exec(i)||[],[l,...d]=f;return l!==void 0?[!0,(()=>{const p=u!==!1?Object.fromEntries(u.map((m,b)=>[m,d[b]])):f.groups;let g={...d};return p&&Object.assign(g,p),g})(),...s?[l]:[]]:[!1,null]},Ah=e=>Th(zs().parser,e,dr()[0]),j1=({children:e,...r})=>{var g,m,b;const i=zs(),s=r.hook?_b:i;let c=s;const[u,f=r.ssrSearch??""]=((g=r.ssrPath)==null?void 0:g.split("?"))??[];u&&(r.ssrSearch=f,r.ssrPath=u),r.hrefs=r.hrefs??((m=r.hook)==null?void 0:m.hrefs),r.searchHook=r.searchHook??((b=r.hook)==null?void 0:b.searchHook);let l=H.useRef({}),d=l.current,p=d;for(let _ in s){const k=_==="base"?s[_]+(r[_]??""):r[_]??s[_];d===p&&k!==p[_]&&(l.current=p={...p}),p[_]=k,(k!==s[_]||k!==c[_])&&(c=p)}return H.createElement(Sb.Provider,{value:c,children:e})},Rx=({children:e,component:r},i)=>r?H.createElement(r,{params:i}):typeof e=="function"?e(i):e,N1=e=>{let r=H.useRef(wb);const i=r.current;return r.current=Object.keys(e).length!==Object.keys(i).length||Object.entries(e).some(([s,c])=>c!==i[s])?e:i},Oa=({path:e,nest:r,match:i,...s})=>{const c=zs(),[u]=Ql(c),[f,l,d]=i??Th(c.parser,e,u,r),p=N1({...E1(),...l});if(!f)return null;const g=d?H.createElement(j1,{base:d},Rx(s,p)):Rx(s,p);return H.createElement(Cb.Provider,{value:p,children:g})},Mn=H.forwardRef((e,r)=>{const i=zs(),[s,c]=Ql(i),{to:u="",href:f=u,onClick:l,asChild:d,children:p,className:g,replace:m,state:b,transition:_,...k}=e,C=vb(x=>{x.ctrlKey||x.metaKey||x.altKey||x.shiftKey||x.button!==0||(l==null||l(x),x.defaultPrevented||(x.preventDefault(),c(f,e)))}),y=i.hrefs(f[0]==="~"?f.slice(1):i.base+f,i);return d&&H.isValidElement(p)?H.cloneElement(p,{onClick:C,href:y}):H.createElement("a",{...k,onClick:C,href:y,className:g!=null&&g.call?g(s===f):g,children:p,ref:r})}),kb=e=>Array.isArray(e)?e.flatMap(r=>kb(r&&r.type===H.Fragment?r.props.children:r)):[e],T1=({children:e,location:r})=>{const i=zs(),[s]=Ql(i);for(const c of kb(e)){let u=0;if(H.isValidElement(c)&&(u=Th(i.parser,c.props.path,r||s,c.props.nest))[0])return H.cloneElement(c,{match:u})}return null},Lx=e=>{let r;const i=new Set,s=(p,g)=>{const m=typeof p=="function"?p(r):p;if(!Object.is(m,r)){const b=r;r=g??(typeof m!="object"||m===null)?m:Object.assign({},r,m),i.forEach(_=>_(r,b))}},c=()=>r,l={setState:s,getState:c,getInitialState:()=>d,subscribe:p=>(i.add(p),()=>i.delete(p))},d=r=e(s,c,l);return l},A1=(e=>e?Lx(e):Lx),D1=e=>e;function R1(e,r=D1){const i=dn.useSyncExternalStore(e.subscribe,dn.useCallback(()=>r(e.getState()),[e,r]),dn.useCallback(()=>r(e.getInitialState()),[e,r]));return dn.useDebugValue(i),i}const Ox=e=>{const r=A1(e),i=s=>R1(r,s);return Object.assign(i,r),i},Yn=(e=>e?Ox(e):Ox);async function ke(e,r={}){const i=localStorage.getItem("openfox_token"),s={...r.headers instanceof Headers?Object.fromEntries(r.headers.entries()):r.headers,...i?{"x-session-token":i}:{}};return fetch(e,{...r,headers:s})}function L1(e){return typeof e=="object"&&e!==null&&"type"in e&&"payload"in e}function Eb(){if(typeof crypto<"u"&&crypto.randomUUID)try{return crypto.randomUUID()}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const r=Math.random()*16|0;return(e==="x"?r:r&3|8).toString(16)})}class O1{constructor(r){ar(this,"ws",null);ar(this,"handlers",new Set);ar(this,"statusHandler",null);ar(this,"baseUrl");ar(this,"isReconnecting",!1);ar(this,"connectingPromise",null);ar(this,"lastCloseCode",0);ar(this,"reconnectAttempts",0);ar(this,"manualReconnectScheduled",!1);this.baseUrl=r}getUrl(){const r=localStorage.getItem("openfox_token");if(r){const i=this.baseUrl.includes("?")?"&":"?";return`${this.baseUrl}${i}token=${encodeURIComponent(r)}`}return this.baseUrl}setToken(r){localStorage.setItem("openfox_token",r)}clearToken(){localStorage.removeItem("openfox_token")}hasToken(){return!!localStorage.getItem("openfox_token")}getLastCloseCode(){return this.lastCloseCode}onStatusChange(r){this.statusHandler=r}connect(){var r,i;return((r=this.ws)==null?void 0:r.readyState)===WebSocket.OPEN?Promise.resolve():(this.lastCloseCode=0,this.isReconnecting=!1,this.connectingPromise&&((i=this.ws)==null?void 0:i.readyState)===WebSocket.CONNECTING?this.connectingPromise:(this.connectingPromise=new Promise((s,c)=>{try{const u=this.getUrl();this.ws=new WebSocket(u);const f=setTimeout(()=>{var l;((l=this.ws)==null?void 0:l.readyState)===WebSocket.CONNECTING&&(this.ws.close(),c(new Error("Connection timeout")))},5e3);this.ws.onopen=()=>{var l;clearTimeout(f),this.isReconnecting=!1,this.connectingPromise=null,(l=this.statusHandler)==null||l.call(this,"connected"),s()},this.ws.onclose=l=>{var d,p,g;clearTimeout(f),this.lastCloseCode=l.code,((d=this.ws)==null?void 0:d.readyState)===WebSocket.CONNECTING?(this.connectingPromise=null,(p=this.statusHandler)==null||p.call(this,"disconnected"),c(new Error(`Connection closed: ${l.code}`))):(this.connectingPromise=null,(g=this.statusHandler)==null||g.call(this,"disconnected"),this.attemptReconnect())},this.ws.onerror=l=>{clearTimeout(f),console.error("WebSocket error:",l),this.connectingPromise=null,c(l)},this.ws.onmessage=l=>{try{const d=JSON.parse(l.data);L1(d)&&this.handlers.forEach(p=>p(d))}catch(d){console.error("Failed to parse WebSocket message:",d)}}}catch(u){this.connectingPromise=null,c(u)}}),this.connectingPromise))}attemptReconnect(){var c;if(([1e3,1005,1006,4e3].includes(this.lastCloseCode)||this.lastCloseCode===0)&&this.hasToken()){console.log("[WS] Auth failure or initial failure with token - not auto-reconnecting, awaiting user action");return}if(this.isReconnecting||this.manualReconnectScheduled)return;this.isReconnecting=!0,(c=this.statusHandler)==null||c.call(this,"reconnecting");const s=Math.min(1e3*Math.pow(2,this.reconnectAttempts||0),3e4);this.reconnectAttempts=(this.reconnectAttempts||0)+1,setTimeout(()=>{this.isReconnecting=!1,this.manualReconnectScheduled=!1,this.connect().catch(()=>{})},s)}reconnect(){this.manualReconnectScheduled=!0,this.isReconnecting=!1,this.lastCloseCode=0,this.connectingPromise=null,this.connect().catch(()=>{})}disconnect(){this.isReconnecting=!1,this.reconnectAttempts=0,this.ws&&(this.ws.close(),this.ws=null)}resetReconnectAttempts(){this.reconnectAttempts=0}send(r,i){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");const s=Eb(),c={id:s,type:r,payload:i};return this.ws.send(JSON.stringify(c)),s}subscribe(r){return this.handlers.add(r),()=>this.handlers.delete(r)}get isConnected(){var r;return((r=this.ws)==null?void 0:r.readyState)===WebSocket.OPEN}}const M1=`ws://${window.location.hostname}:${window.location.port||"10469"}/ws`,qt=new O1(M1),di=async(e,r,i)=>{try{const s=await ke(r,{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return s.ok?{success:!0}:{success:!1,error:(await s.json()).error}}catch{return{success:!1,error:"Network error"}}};function jb(e){let r=null;function i(){r===null&&(r=requestAnimationFrame(()=>{r=null,e()}))}return i}let El=[];const cr=Yn()((e,r)=>{function i(){if(El.length===0)return;const c=El;El=[],e(u=>({logs:[...u.logs,...c]}))}const s=jb(i);return{workdir:null,status:null,logs:[],config:null,loading:!1,setWorkdir:c=>{r().workdir!==c&&(e({workdir:c,status:null,logs:[],config:null,loading:!0}),c&&(r().fetchStatus(),r().fetchConfig()))},fetchStatus:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server?workdir=${encodeURIComponent(c)}`)).json();e({status:f,loading:!1})}catch{e({loading:!1})}},fetchConfig:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server/config?workdir=${encodeURIComponent(c)}`)).json();e({config:f.config??null})}catch{}},fetchLogs:async()=>{const c=r().workdir;if(c)try{const l=(await(await ke(`/api/dev-server/logs?workdir=${encodeURIComponent(c)}`)).json()).logs.map(d=>({stream:d.stream,content:d.content}));e({logs:l})}catch{}},start:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server/start?workdir=${encodeURIComponent(c)}`,{method:"POST"})).json();e({status:f,logs:[]})}catch{}},stop:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server/stop?workdir=${encodeURIComponent(c)}`,{method:"POST"})).json();e({status:f})}catch{}},restart:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server/restart?workdir=${encodeURIComponent(c)}`,{method:"POST"})).json();e({status:f,logs:[]})}catch{}},saveConfig:async c=>{const u=r().workdir;if(u)try{const l=await(await ke(`/api/dev-server/config?workdir=${encodeURIComponent(u)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})).json();e({config:l.config??c}),r().fetchStatus()}catch{}},handleMessage:c=>{const u=r().workdir;if(u)switch(c.type){case"devServer.output":{const f=c.payload;if(f.workdir!==u)return;El.push({stream:f.stream,content:f.content}),s();break}case"devServer.state":{const f=c.payload;if(f.workdir!==u)return;e(l=>({status:l.status?{...l.status,state:f.state,errorMessage:f.errorMessage}:l.status}));break}}}}});function I1(e){return{...e.temperature!=null&&{temperature:e.temperature},...e.topP!=null&&{topP:e.topP},...e.topK!=null&&{topK:e.topK},...e.maxTokens!=null&&{maxTokens:e.maxTokens}}}async function Mx(e,r,i){const s=await ke(`/api/providers/${e}/models/${encodeURIComponent(r)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!s.ok){const c=await s.json();throw new Error(c.error??"Failed to update model")}return s.json()}function Ix(e,r,i,s){return e.map(c=>c.id===r?{...c,models:c.models.map(u=>u.id===i?{...u,...s,source:"user"}:u)}:c)}const B1=3e4;function z1(e){switch(e){case"vllm":return"vLLM";case"sglang":return"SGLang";case"ollama":return"Ollama";case"llamacpp":return"llama.cpp";case"openai":return"OpenAI";case"anthropic":return"Anthropic";case"opencode-go":return"OpenCode Go";case"auto":return"Auto";case"unknown":return""}}const At=Yn((e,r)=>({version:null,model:null,maxContext:2e5,llmUrl:null,llmStatus:"unknown",backend:"unknown",providers:[],activeProviderId:null,defaultModelSelection:null,loading:!1,activating:!1,error:null,autoRefreshInterval:null,fetchConfig:async()=>{e({loading:!0,error:null});try{const i=await ke("/api/config");if(!i.ok)throw new Error("Failed to fetch config");const s=await i.json();e({version:s.version,model:s.model,maxContext:s.maxContext,llmUrl:s.llmUrl,llmStatus:s.llmStatus,backend:s.backend,providers:s.providers??[],activeProviderId:s.activeProviderId??null,defaultModelSelection:s.defaultModelSelection??null,loading:!1})}catch(i){e({error:i instanceof Error?i.message:"Unknown error",loading:!1})}},refreshModel:async()=>{try{const i=await ke("/api/model/refresh",{method:"POST"});if(!i.ok)throw new Error("Failed to refresh model");const s=await i.json(),u=Ce.getState().currentSession;if(u!=null&&u.providerId&&u.providerModel){e({llmStatus:s.llmStatus,backend:s.backend});return}e({model:s.model,llmStatus:s.llmStatus,backend:s.backend})}catch(i){console.error("Failed to refresh model:",i)}},activateProvider:async i=>{const{activeProviderId:s,providers:c}=r();if(i===s)return!0;e({activating:!0,error:null});try{const u=await ke(`/api/providers/${i}/activate`,{method:"POST"});if(!u.ok){const l=await u.json();throw new Error(l.error??"Failed to activate provider")}const f=await u.json();return e({activeProviderId:f.activeProviderId,model:f.model,backend:f.backend,providers:c.map(l=>({...l,isActive:l.id===f.activeProviderId})),activating:!1}),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to switch provider",activating:!1}),!1}},syncFromSession:(i,s)=>{const{providers:c}=r();e({activeProviderId:i,model:s,defaultModelSelection:`${i}/${s}`,providers:c.map(u=>({...u,isActive:u.id===i}))})},updateModelContext:async(i,s,c)=>{e({activating:!0,error:null});try{const u=await Mx(i,s,{contextWindow:c}),{providers:f}=r();return e({providers:Ix(f,i,s,{contextWindow:c}),activating:!1}),u.contextState&&Ce.getState().updateContextState(u.contextState),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to update model context",activating:!1}),!1}},updateModelSettings:async(i,s,c)=>{e({activating:!0,error:null});try{const u=await Mx(i,s,c),{providers:f}=r(),l={...c.contextWindow!==void 0&&{contextWindow:c.contextWindow},...I1({temperature:c.temperature??void 0,topP:c.topP??void 0,topK:c.topK??void 0,maxTokens:c.maxTokens??void 0})};return e({providers:Ix(f,i,s,l),activating:!1}),u.contextState&&Ce.getState().updateContextState(u.contextState),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to update model settings",activating:!1}),!1}},refreshProviderModels:async i=>{e({activating:!0,error:null});try{const s=await ke(`/api/providers/${i}/refresh`,{method:"POST"});if(!s.ok){const f=await s.json();throw new Error(f.error??"Failed to refresh models")}const c=await s.json(),{providers:u}=r();return e({providers:u.map(f=>f.id===i?{...f,models:c.models}:f),activating:!1}),!0}catch(s){return e({error:s instanceof Error?s.message:"Failed to refresh models",activating:!1}),!1}},startAutoRefresh:()=>{const{autoRefreshInterval:i,refreshModel:s}=r();if(i)return;const c=setInterval(()=>{s()},B1);e({autoRefreshInterval:c})},stopAutoRefresh:()=>{const{autoRefreshInterval:i}=r();i&&(clearInterval(i),e({autoRefreshInterval:null}))},getActiveProvider:()=>{const{providers:i,activeProviderId:s}=r();return i.find(c=>c.id===s)},getModelContext:i=>{const{providers:s,activeProviderId:c}=r(),u=s.find(l=>l.id===c);if(!u)return 2e5;const f=u.models.find(l=>l.id===i);return(f==null?void 0:f.contextWindow)??2e5}})),Vt=Yn((e,r)=>({projects:[],currentProject:null,loading:!1,listProjects:async()=>{e({loading:!0});try{const s=await(await ke("/api/projects")).json();e({projects:s.projects??[],loading:!1})}catch{e({loading:!1})}},createProject:async(i,s)=>{try{const c=await ke("/api/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:i,workdir:s})});if(!c.ok)return null;const u=await c.json();return await r().listProjects(),u.project}catch{return null}},loadProject:async i=>{try{const s=await ke(`/api/projects/${i}`);if(!s.ok)return null;const c=await s.json();return e({currentProject:c.project}),r().projects.length===0&&await r().listProjects(),c.project}catch{return null}},updateProject:async(i,s)=>{var c;try{const u=await ke(`/api/projects/${i}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!u.ok)return null;const f=await u.json();return((c=r().currentProject)==null?void 0:c.id)===i&&e({currentProject:f.project}),await r().listProjects(),f.project}catch{return null}},deleteProject:async i=>{var s;try{return(await ke(`/api/projects/${i}`,{method:"DELETE"})).ok?(await r().listProjects(),((s=r().currentProject)==null?void 0:s.id)===i&&e({currentProject:null}),!0):!1}catch{return!1}},clearProject:()=>{e({currentProject:null})}}));let jl=[];const Va=Yn()((e,r)=>{function i(){if(jl.length===0)return;const c=jl;jl=[],e(u=>{const f={...u.logs};for(const l of c){const d=f[l.processId]??[];f[l.processId]=[...d,{offset:d.length,content:l.content,timestamp:Date.now(),stream:l.stream}]}return{logs:f}})}const s=jb(i);return{processes:[],logs:{},loading:!1,setProcesses:c=>e({processes:c}),addProcess:c=>e(u=>({processes:[...u.processes,c]})),updateProcess:(c,u)=>e(f=>({processes:f.processes.map(l=>l.id===c?{...l,...u}:l)})),removeProcess:c=>e(u=>({processes:u.processes.filter(f=>f.id!==c),logs:Object.fromEntries(Object.entries(u.logs).filter(([f])=>f!==c))})),stopProcess:async(c,u)=>{try{(await ke(`/api/sessions/${u}/background-process/${c}/stop`,{method:"POST"})).ok&&r().removeProcess(c)}catch{}},appendLog:(c,u,f)=>{jl.push({processId:c,stream:u,content:f}),s()},setLogs:(c,u)=>e(f=>({logs:{...f.logs,[c]:u}})),clearLogs:c=>e(u=>({logs:{...u.logs,[c]:[]}})),handleMessage:(c,u)=>{switch(c){case"backgroundProcess.started":{const{processId:f,name:l,pid:d,status:p}=u;e(g=>({processes:[...g.processes,{id:f,sessionId:"",name:l,command:"",cwd:"",pid:d,status:p,exitCode:null,createdAt:Date.now(),startedAt:Date.now(),endedAt:null}]}));break}case"backgroundProcess.output":{const f=u.processId,l=u.stream,d=u.content;r().appendLog(f,l,d);break}case"backgroundProcess.exited":{const f=u.processId,l=u.exitCode;e(d=>({processes:d.processes.map(p=>p.id===f?{...p,status:"exited",exitCode:l}:p)}));break}case"backgroundProcess.removed":{const f=u.processId;r().removeProcess(f);break}}}}}),Et={GLOBAL_INSTRUCTIONS:"global_instructions",NOTIFICATION_SETTINGS:"notification_settings",DISPLAY_SHOW_THINKING:"display.showThinking",DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT:"display.showVerboseToolOutput",DISPLAY_SHOW_STATS:"display.showStats",DISPLAY_SHOW_AGENT_DEFINITIONS:"display.showAgentDefinitions",DISPLAY_SHOW_WORKFLOW_BARS:"display.showWorkflowBars"};function Nl(e,r){return i=>({loading:{...i.loading,[e]:r}})}function Bx(e,r){return i=>({settings:{...i.settings,[e]:r},loading:{...i.loading,[e]:!1}})}const H1=[Et.DISPLAY_SHOW_THINKING,Et.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT,Et.DISPLAY_SHOW_STATS,Et.DISPLAY_SHOW_AGENT_DEFINITIONS,Et.DISPLAY_SHOW_WORKFLOW_BARS];function Nb(){return{showThinking:en(e=>e.settings[Et.DISPLAY_SHOW_THINKING]??"true")==="true",showVerboseToolOutput:en(e=>e.settings[Et.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT]??"true")==="true",showStats:en(e=>e.settings[Et.DISPLAY_SHOW_STATS]??"true")==="true",showAgentDefinitions:en(e=>e.settings[Et.DISPLAY_SHOW_AGENT_DEFINITIONS]??"true")==="true",showWorkflowBars:en(e=>e.settings[Et.DISPLAY_SHOW_WORKFLOW_BARS]??"true")==="true"}}const en=Yn(e=>({settings:{},loading:{},getSetting:async r=>{e(Nl(r,!0));try{const s=await(await ke(`/api/settings/${r}`)).json();return e(Bx(r,s.value??"")),s.value}catch{return e(Nl(r,!1)),null}},setSetting:async(r,i)=>{e(Nl(r,!0));try{const c=await(await ke(`/api/settings/${r}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:i})})).json();e(Bx(r,c.value??""))}catch{e(Nl(r,!1))}}})),P1=[{key:"complete",label:"Task Complete",description:"When an agent finishes its work"},{key:"waiting_for_user",label:"Waiting for Input",description:"When the agent needs your input"},{key:"phase_done",label:"Phase Done",description:"When a build phase completes successfully"},{key:"phase_blocked",label:"Phase Blocked",description:"When a build phase is blocked and needs intervention"},{key:"new_message",label:"New Message",description:"When a new assistant message starts arriving"}],F1=[{url:"/sounds/notification.mp3",label:"Notification"},{url:"/sounds/waiting-for-user.mp3",label:"Waiting for User"},{url:"/sounds/achievement.mp3",label:"Achievement"},{url:"/sounds/intervention.mp3",label:"Intervention"},{url:"/sounds/typing.mp3",label:"Typing"}],Tb={complete:"/sounds/notification.mp3",waiting_for_user:"/sounds/waiting-for-user.mp3",phase_done:"/sounds/achievement.mp3",phase_blocked:"/sounds/intervention.mp3",new_message:"/sounds/typing.mp3"},ci={soundEnabled:!0,browserNotification:!1,customSoundUrl:null},Ab={soundEnabled:!1,browserNotification:!1,customSoundUrl:null},ch={soundEnabled:!0,browserNotificationEnabled:!1,events:{complete:{...ci},waiting_for_user:{...ci},phase_done:{...ci},phase_blocked:{...ci},new_message:{...Ab}},agentOverrides:{}};function Db(e,r,i){var u;const s=e.events[r];if(!i)return s;const c=(u=e.agentOverrides[i])==null?void 0:u[r];return c?{soundEnabled:c.soundEnabled??s.soundEnabled,browserNotification:c.browserNotification??s.browserNotification,customSoundUrl:c.customSoundUrl!==void 0?c.customSoundUrl:s.customSoundUrl}:s}const Oi=Yn((e,r)=>({settings:ch,loaded:!1,load:()=>{en.getState().getSetting(Et.NOTIFICATION_SETTINGS);const s=en.subscribe(u=>{const f=u.settings[Et.NOTIFICATION_SETTINGS];if(f!==void 0)try{const l=JSON.parse(f);e({settings:zx(l),loaded:!0})}catch{e({loaded:!0})}}),c=en.getState().settings[Et.NOTIFICATION_SETTINGS];if(c)try{const u=JSON.parse(c);e({settings:zx(u),loaded:!0})}catch{e({loaded:!0})}return s},update:i=>{e({settings:i}),Id(i)},updateEvent:(i,s)=>{const c=r().settings,u={...c,events:{...c.events,[i]:{...c.events[i],...s}}};e({settings:u}),Id(u)},updateAgentOverride:(i,s,c)=>{var d;const u=r().settings,f={...u.agentOverrides};if(c===null){if(f[i]){const p={...f[i]};delete p[s],Object.keys(p).length===0?delete f[i]:f[i]=p}}else f[i]={...f[i],[s]:{...((d=f[i])==null?void 0:d[s])??{},...c}};const l={...u,agentOverrides:f};e({settings:l}),Id(l)}}));function Id(e){en.getState().setSetting(Et.NOTIFICATION_SETTINGS,JSON.stringify(e))}function zx(e){var r,i,s,c,u;return{soundEnabled:e.soundEnabled??ch.soundEnabled,browserNotificationEnabled:e.browserNotificationEnabled??ch.browserNotificationEnabled,events:{complete:{...ci,...(r=e.events)==null?void 0:r.complete},waiting_for_user:{...ci,...(i=e.events)==null?void 0:i.waiting_for_user},phase_done:{...ci,...(s=e.events)==null?void 0:s.phase_done},phase_blocked:{...ci,...(c=e.events)==null?void 0:c.phase_blocked},new_message:{...Ab,...(u=e.events)==null?void 0:u.new_message}},agentOverrides:e.agentOverrides??{}}}const Hx=new Map;function U1(e){let r=Hx.get(e);return r||(r=new Audio(e),r.volume=.5,Hx.set(e,r)),r}let Rb=typeof Notification<"u"?Notification.permission:"denied";function $1(){return typeof Notification>"u"?Promise.resolve("denied"):Notification.requestPermission().then(e=>(Rb=e,e))}const q1={complete:"Task Complete",waiting_for_user:"Waiting for Input",phase_done:"Phase Complete",phase_blocked:"Phase Blocked",new_message:"New Message"},W1={complete:"The agent has finished its work.",waiting_for_user:"The agent needs your input to continue.",phase_done:"The build phase completed successfully.",phase_blocked:"The build phase is blocked and needs intervention.",new_message:"A new assistant message is arriving."};function G1(e){typeof Notification>"u"||Rb==="granted"&&(document.hasFocus()||new Notification(q1[e],{body:W1[e],icon:"/fox.svg",tag:`openfox-${e}`}))}function oo(e,r){const{settings:i}=Oi.getState(),s=Db(i,e,r);if(i.soundEnabled&&s.soundEnabled){const c=s.customSoundUrl??Tb[e],u=U1(c);u.currentTime=0,u.play().catch(()=>{})}i.browserNotificationEnabled&&s.browserNotification&&G1(e)}const V1=e=>oo("complete",e),K1=e=>oo("phase_done",e),Y1=e=>oo("phase_blocked",e),Px=e=>oo("waiting_for_user",e),X1=e=>oo("new_message",e);let Ma=!1,or=null;const Bd=new Set,$t={messageId:null,deltaContent:"",thinkingContent:"",toolOutput:[]};let Ms=null,un=null;function zd(){Ms===null&&(Ms=requestAnimationFrame(()=>{Ms=null,un==null||un()}))}function Ai(){Ms!==null&&(cancelAnimationFrame(Ms),Ms=null)}function zt(e,r){return r!==null&&e.sessionId===r}function Z1(e,r,i){return e.id!==void 0||zt(e,r)||i===!0&&e.sessionId!==void 0}function Q1(e,r){return e.includes(r)?e:[...e,r]}function Ia(e,r){return e.filter(i=>i!==r)}function J1(e,r){const i=e.find(c=>c.id===r.id),s=i?{...i,projectId:r.projectId,workdir:r.workdir,mode:r.mode,phase:r.phase,isRunning:r.isRunning,messageCount:r.messages.length,criteriaCount:r.criteria.length,criteriaCompleted:r.criteria.filter(c=>c.status.type==="passed").length}:{id:r.id,projectId:r.projectId,workdir:r.workdir,mode:r.mode,phase:r.phase,isRunning:r.isRunning,createdAt:"",updatedAt:"",criteriaCount:r.criteria.length,criteriaCompleted:r.criteria.filter(c=>c.status.type==="passed").length,messageCount:r.messages.length};return i?e.map(c=>c.id===r.id?s:c):[s,...e]}function ew(e,r,i){return e.map(s=>{const c=(i==null?void 0:i.id)===s.id?i:null,u=r.find(f=>f.id===s.id);return{...s,title:s.title??(u==null?void 0:u.title),mode:(c==null?void 0:c.mode)??(u==null?void 0:u.mode)??s.mode,phase:(c==null?void 0:c.phase)??(u==null?void 0:u.phase)??s.phase,isRunning:(c==null?void 0:c.isRunning)??(u==null?void 0:u.isRunning)??s.isRunning,messageCount:s.messageCount,recentUserPrompts:s.recentUserPrompts}})}const Fx=new Map;function Wa(e,r){var u;const i=r===((u=e.currentSession)==null?void 0:u.id)?e.currentSession:null,s=e.sessions.find(f=>f.id===r),c=(i==null?void 0:i.mode)??(s==null?void 0:s.mode);return c==="planner"?"planner":c==="builder"?"build":"planner"}function tw(e,r){if(e.type==="chat.done"){const i=e.payload,s=Wa(r,e.sessionId),c=i.agentType??s;i.reason==="complete"&&V1(c),i.reason==="waiting_for_user"&&Px(c);return}if(e.type==="chat.path_confirmation"){const i=Wa(r,e.sessionId);Px(i);return}if(e.type==="task.completed"){const i=Wa(r,e.sessionId);K1(i);return}if(e.type==="phase.changed"&&e.sessionId){const i=e.payload,s=Fx.get(e.sessionId)??null;if(Fx.set(e.sessionId,i.phase),s===i.phase)return;const c=Wa(r,e.sessionId);i.phase==="blocked"&&Y1(c)}}const Ce=Yn((e,r)=>(un=()=>{const i=$t;if(!i.messageId)return;const s=i.deltaContent.length>0,c=i.thinkingContent.length>0,u=i.toolOutput.length>0;if(!s&&!c&&!u)return;const f=i.deltaContent,l=i.thinkingContent,d=i.toolOutput;i.deltaContent="",i.thinkingContent="",i.toolOutput=[],e(p=>{var m;const g=p.streamingMessage;if(g&&g.id===i.messageId){let b={...g};if(s&&(b.content=b.content+f),c&&(b.thinkingContent=(b.thinkingContent??"")+l),u){const _=new Set;b.toolCalls=(m=b.toolCalls)==null?void 0:m.map(C=>{const y=d.filter(x=>x.callId===C.id);return y.length===0?C:(_.add(C.id),{...C,streamingOutput:[...C.streamingOutput??[],...y.map(x=>({stream:x.stream,content:x.content}))]})});const k=d.filter(C=>!_.has(C.callId));k.length>0&&$t.toolOutput.push(...k)}return{streamingMessage:b}}if(u){const b=new Set,_=p.messages.map(C=>{var x;if(C.id!==i.messageId)return C;const y=(x=C.toolCalls)==null?void 0:x.map(v=>{const S=d.filter(j=>j.callId===v.id);return S.length===0?v:(b.add(v.id),{...v,streamingOutput:[...v.streamingOutput??[],...S.map(j=>({stream:j.stream,content:j.content}))]})});return{...C,toolCalls:y}}),k=d.filter(C=>!b.has(C.callId));return k.length>0&&$t.toolOutput.push(...k),{messages:_}}return p})},{connectionStatus:"disconnected",showPasswordModal:!1,passwordModalRetry:!1,sessions:[],currentSession:null,unreadSessionIds:[],messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,subAgentContextStates:{},pendingPathConfirmation:null,pendingQuestion:null,visionFallbackByMessage:{},queuedMessages:[],abortInProgress:!1,error:null,sessionsHasMore:!0,sessionsPaginationLoading:!1,pendingSessionCreate:!1,connect:async()=>{const i=r().connectionStatus;if(i==="connected"||i==="reconnecting")return;e({connectionStatus:"reconnecting"});let s=!1;try{s=(await(await ke("/api/auth")).json()).requiresAuth}catch{}if(s&&!qt.hasToken()){e({showPasswordModal:!0,passwordModalRetry:!1,connectionStatus:"reconnecting"});return}qt.onStatusChange(c=>{e({connectionStatus:c}),c==="connected"&&r().listSessions(void 0)});try{if(await qt.connect(),!Ma){Ma=!0;const c=r().handleServerMessage;or=qt.subscribe(c)}}catch(c){console.error("Failed to connect:",c);const u=qt.getLastCloseCode();if(!qt.hasToken()&&(u===1006||u===4e3)){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}or&&(or(),or=null),Ma=!1,e({connectionStatus:"disconnected"})}},reconnect:()=>{qt.disconnect(),or&&(or(),or=null),Ma=!1,e({connectionStatus:"reconnecting"}),r().connect()},disconnect:()=>{qt.disconnect(),or&&(or(),or=null),Ma=!1,e({connectionStatus:"disconnected",showPasswordModal:!1})},submitPassword:async i=>{try{const s=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})});if(!s.ok){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}const{token:c}=await s.json();qt.setToken(c),e({showPasswordModal:!1}),r().connect();const{listProjects:u}=Vt.getState(),{fetchConfig:f}=At.getState();u(),f(),r().connect()}catch{e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"})}},cancelPassword:()=>{qt.clearToken(),e({showPasswordModal:!1,connectionStatus:"disconnected"})},createSession:async(i,s)=>{try{e({pendingSessionCreate:!0});const c=await ke("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectId:i,title:s})});if(!c.ok)return e({pendingSessionCreate:!1}),null;const u=await c.json();return qt.send("session.load",{sessionId:u.session.id}),u.session}catch{return e({pendingSessionCreate:!1}),null}},loadSession:async i=>{try{const s=r().currentSession;!s||s.id!==i?(Ai(),e({currentSession:null,unreadSessionIds:Ia(r().unreadSessionIds,i),subAgentContextStates:{},messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,pendingPathConfirmation:null,queuedMessages:[],abortInProgress:!1,error:null})):e({unreadSessionIds:Ia(r().unreadSessionIds,i)});const c=await ke(`/api/sessions/${i}`);if(!c.ok)return;const u=await c.json();e({currentSession:u.session,messages:u.messages??[],contextState:u.contextState,queuedMessages:u.queueState??[]}),qt.send("session.load",{sessionId:i});try{const f=await ke(`/api/sessions/${i}/background-processes`);if(f.ok){const l=await f.json();Va.getState().setProcesses(l.processes??[])}}catch{}}catch{}},listSessions:async(i,s=20)=>{try{const c=new URLSearchParams;c.set("limit",String(s)),i&&c.set("projectId",i);const f=await(await ke(`/api/sessions?${c.toString()}`)).json();e({sessions:f.sessions??[],sessionsHasMore:i?f.hasMore??!1:!0})}catch{}},loadMoreSessions:async i=>{const s=r();if(!(s.sessionsPaginationLoading||!s.sessionsHasMore)){e({sessionsPaginationLoading:!0});try{const c=new URLSearchParams;c.set("limit","20"),c.set("offset",String(s.sessions.length)),c.set("projectId",i);const f=await(await ke(`/api/sessions?${c.toString()}`)).json();e(l=>({sessions:[...l.sessions,...f.sessions??[]],sessionsHasMore:f.hasMore??!1,sessionsPaginationLoading:!1}))}catch{e({sessionsPaginationLoading:!1})}}},deleteSession:async i=>{var s;try{return(await ke(`/api/sessions/${i}`,{method:"DELETE"})).ok?(await r().listSessions(),((s=r().currentSession)==null?void 0:s.id)===i&&r().clearSession(),!0):!1}catch{return!1}},deleteAllSessions:async i=>{try{return(await ke(`/api/projects/${i}/sessions`,{method:"DELETE"})).ok?(await r().listSessions(),!0):!1}catch{return!1}},clearSession:()=>{Ai(),e(i=>({currentSession:null,messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,unreadSessionIds:i.currentSession?Ia(i.unreadSessionIds,i.currentSession.id):i.unreadSessionIds}))},sendMessage:async(i,s,c)=>{var f;const u=(f=r().currentSession)==null?void 0:f.id;if(u){e({streamingMessageId:null});try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:i,attachments:s,messageKind:c==null?void 0:c.messageKind})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(l){console.error("Error sending message:",l)}}},stopGeneration:async()=>{var s;const i=(s=r().currentSession)==null?void 0:s.id;if(i&&!r().abortInProgress){Ai(),un==null||un(),e({abortInProgress:!0});try{await ke(`/api/sessions/${i}/stop`,{method:"POST"})}catch(c){console.error("Error stopping generation:",c)}}},continueGeneration:async()=>{var s;const i=(s=r().currentSession)==null?void 0:s.id;if(i){e({streamingMessageId:null});try{await ke(`/api/sessions/${i}/continue`,{method:"POST"})}catch(c){console.error("Error continuing generation:",c)}}},launchRunner:(i,s,c)=>{e({streamingMessageId:null});const u={};i!=null&&i.trim()&&(u.content=i),s&&s.length>0&&(u.attachments=s),c&&(u.workflowId=c),qt.send("runner.launch",u)},switchMode:async i=>{var c;const s=(c=r().currentSession)==null?void 0:c.id;if(s)try{const u=await ke(`/api/sessions/${s}/mode`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:i})});if(!u.ok){console.error("Failed to switch mode:",await u.json());return}const f=await u.json();f.session&&e({currentSession:f.session})}catch(u){console.error("Error switching mode:",u)}},switchDangerLevel:async i=>{var c;const s=(c=r().currentSession)==null?void 0:c.id;if(s)try{const u=await ke(`/api/sessions/${s}/danger-level`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({dangerLevel:i})});if(!u.ok){console.error("Failed to switch danger level:",await u.json());return}const f=await u.json();f.session&&e({currentSession:f.session})}catch(u){console.error("Error switching danger level:",u)}},acceptAndBuild:(i,s,c)=>{e({streamingMessageId:null});const u={};i&&(u.workflowId=i),s!=null&&s.trim()&&(u.content=s),c&&c.length>0&&(u.attachments=c),qt.send("mode.accept",u)},editCriteria:async i=>{var c;const s=(c=r().currentSession)==null?void 0:c.id;if(s)try{const u=await ke(`/api/sessions/${s}/criteria`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({criteria:i})});u.ok||console.error("Failed to update criteria:",await u.json())}catch(u){console.error("Error updating criteria:",u)}},compactContext:()=>{qt.send("context.compact",{})},setSessionProvider:async(i,s)=>{var c;try{const u=(c=r().currentSession)==null?void 0:c.id;if(!u)return null;const f=await ke(`/api/sessions/${u}/provider`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerId:i,...s?{model:s}:{}})});if(!f.ok)return null;const l=await f.json();return e({currentSession:l.session,messages:l.messages??[],contextState:l.contextState}),l.session}catch{return null}},updateContextState:i=>{e({contextState:i})},updateSubAgentContextState:(i,s)=>{e(c=>({subAgentContextStates:{...c.subAgentContextStates,[i]:s}}))},clearSubAgentContextState:i=>{e(s=>{const c={...s.subAgentContextStates};return delete c[i],{subAgentContextStates:c}})},confirmPath:async(i,s,c=!1)=>{var f;const u=(f=r().currentSession)==null?void 0:f.id;if(u)try{await ke(`/api/sessions/${u}/confirm-path`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:i,approved:s,alwaysAllow:c})})}catch(l){console.error("Error confirming path:",l)}},answerQuestion:async(i,s)=>{var u;const c=(u=r().currentSession)==null?void 0:u.id;if(c){try{await ke(`/api/sessions/${c}/answer`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:i,answer:s})})}catch(f){console.error("Error answering question:",f)}e({pendingQuestion:null})}},queueAsap:async(i,s,c)=>{var f;const u=(f=r().currentSession)==null?void 0:f.id;if(u)try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:i,attachments:s,messageKind:c})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(l){console.error("Error queueing ASAP message:",l)}},queueCompletion:async(i,s,c)=>{var f;const u=(f=r().currentSession)==null?void 0:f.id;if(u)try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:i,attachments:s,messageKind:c})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(l){console.error("Error queueing completion message:",l)}},cancelQueued:async i=>{var c;const s=(c=r().currentSession)==null?void 0:c.id;if(s)try{const f=await(await ke(`/api/sessions/${s}/queue/${i}`,{method:"DELETE"})).json();f.queueState&&e({queuedMessages:f.queueState})}catch(u){console.error("Error canceling queued message:",u)}},clearError:()=>{e({error:null})},resetPendingSessionCreate:()=>{e({pendingSessionCreate:!1})},handleServerMessage:i=>{var f,l,d,p,g,m,b,_,k,C,y,x,v,S,j,T,N,D,A,M,B,$,V,W;const s=r();tw(i,s);const c=((f=s.currentSession)==null?void 0:f.id)??null,u=()=>{const O=i.sessionId;!O||O===c||e(F=>({unreadSessionIds:Q1(F.unreadSessionIds,O)}))};switch(i.type){case"session.state":{const O=i.payload;if(!Z1(i,c,s.pendingSessionCreate))break;Ai();const F=O.messages.find(R=>R.isStreaming)??null,P=r().pendingSessionCreate===!0,Z=O.pendingConfirmations??[],I=s.pendingPathConfirmation??(Z.length>0?Z[0]??null:null);if(e({currentSession:O.session,sessions:J1(r().sessions,O.session),unreadSessionIds:Ia(r().unreadSessionIds,O.session.id),messages:O.messages,streamingMessageId:(F==null?void 0:F.id)??null,streamingMessage:F,currentTodos:[],pendingPathConfirmation:I,error:null,...P?{pendingSessionCreate:O.session.id}:{}}),O.session.providerId&&O.session.providerModel){const R=At.getState();R.providers.find(Y=>Y.id===O.session.providerId)&&R.syncFromSession(O.session.providerId,O.session.providerModel)}break}case"session.list":{const O=i.payload;e(F=>({sessions:ew(O.sessions,F.sessions,F.currentSession)}));break}case"session.deleted":{const O=i.payload;e(F=>({unreadSessionIds:Ia(F.unreadSessionIds,O.sessionId)})),r().listSessions();break}case"session.deletedAll":{r().listSessions();break}case"session.running":{const O=i.payload,F=i.sessionId,P=(l=r().currentSession)==null?void 0:l.id,Z=F&&F!==P;e(G=>({sessions:G.sessions.map(I=>I.id===F?{...I,isRunning:O.isRunning}:I)})),Z||e(G=>({currentSession:G.currentSession?{...G.currentSession,isRunning:O.isRunning}:null,...O.isRunning?{}:{abortInProgress:!1,queuedMessages:[]}}));break}case"chat.message":{if(!zt(i,((d=r().currentSession)==null?void 0:d.id)??null)){u();break}const O=i.payload;e(F=>F.messages.some(P=>P.id===O.message.id)?F:{messages:[...F.messages,O.message],streamingMessageId:O.message.isStreaming?O.message.id:F.streamingMessageId,streamingMessage:O.message.isStreaming?O.message:F.streamingMessage});break}case"chat.message_updated":{if(!zt(i,((p=r().currentSession)==null?void 0:p.id)??null)){u();break}const O=i.payload,F=O.updates.isStreaming===!1&&r().streamingMessageId===O.messageId;F&&(Ai(),un==null||un()),e(P=>{const Z=P.streamingMessage,G=F;if(Z&&Z.id===O.messageId){const I={...Z,...O.updates};return{messages:P.messages.map(R=>R.id===O.messageId?I:R),streamingMessageId:G?null:P.streamingMessageId,streamingMessage:G?null:{...Z,...O.updates}}}return{messages:P.messages.map(I=>I.id===O.messageId?{...I,...O.updates}:I),streamingMessageId:G?null:P.streamingMessageId}});break}case"chat.delta":{if(!zt(i,((g=r().currentSession)==null?void 0:g.id)??null)){u();break}const O=i.payload;if(!Bd.has(O.messageId)){Bd.add(O.messageId);const F=Wa(r(),i.sessionId);X1(F)}$t.messageId=O.messageId,$t.deltaContent+=O.content,zd();break}case"chat.thinking":{if(!zt(i,((m=r().currentSession)==null?void 0:m.id)??null)){u();break}const O=i.payload;$t.messageId=O.messageId,$t.thinkingContent+=O.content,zd();break}case"chat.tool_preparing":{if(!zt(i,((b=r().currentSession)==null?void 0:b.id)??null)){u();break}const O=i.payload;e(F=>{const P=F.streamingMessage;return P&&P.id===O.messageId?{streamingMessage:{...P,preparingToolCalls:[...P.preparingToolCalls??[],{index:O.index,name:O.name}]}}:{messages:F.messages.map(Z=>Z.id===O.messageId?{...Z,preparingToolCalls:[...Z.preparingToolCalls??[],{index:O.index,name:O.name}]}:Z)}});break}case"chat.tool_call":{if(!zt(i,((_=r().currentSession)==null?void 0:_.id)??null)){u();break}const O=i.payload,F=P=>{var I;const Z=(I=P.preparingToolCalls)==null?void 0:I.filter((R,z)=>{var Y;return R.name===O.tool?(Y=P.preparingToolCalls)==null?void 0:Y.slice(0,z).some(ie=>ie.name===O.tool):!0}),G=$t.toolOutput.filter(R=>R.callId===O.callId);return G.length>0&&($t.toolOutput=$t.toolOutput.filter(R=>R.callId!==O.callId)),{...P,toolCalls:[...P.toolCalls??[],{id:O.callId,name:O.tool,arguments:O.args,startedAt:Date.now(),...G.length>0?{streamingOutput:G.map(R=>({stream:R.stream,content:R.content}))}:{}}],...Z&&Z.length>0?{preparingToolCalls:Z}:{preparingToolCalls:void 0}}};e(P=>{const Z=P.streamingMessage;return Z&&Z.id===O.messageId?{streamingMessage:F(Z)}:{messages:P.messages.map(G=>G.id===O.messageId?F(G):G)}});break}case"chat.tool_output":{if(!zt(i,((k=r().currentSession)==null?void 0:k.id)??null)){u();break}const O=i.payload;$t.messageId=O.messageId,$t.toolOutput.push({messageId:O.messageId,callId:O.callId,stream:O.stream,content:O.output}),zd();break}case"chat.tool_result":{if(!zt(i,((C=r().currentSession)==null?void 0:C.id)??null)){u();break}const O=i.payload,F=P=>{var G;const Z=(G=P.toolCalls)==null?void 0:G.map(I=>I.id===O.callId?{...I,result:O.result}:I);return{...P,toolCalls:Z}};e(P=>{const Z=P.streamingMessage;return Z&&Z.id===O.messageId?{streamingMessage:F(Z)}:{messages:P.messages.map(G=>G.id===O.messageId?F(G):G)}});break}case"chat.vision_fallback":{if(!zt(i,((y=r().currentSession)==null?void 0:y.id)??null)){u();break}const O=i.payload;e(F=>{const P=`${O.messageId}-${O.attachmentId}`,Z={...F.visionFallbackByMessage};return Z[P]={type:O.type,attachmentId:O.attachmentId,filename:O.filename,description:O.description},{visionFallbackByMessage:Z}});break}case"chat.todo":{if(!zt(i,((x=r().currentSession)==null?void 0:x.id)??null)){u();break}const O=i.payload;e({currentTodos:O.todos});break}case"chat.summary":{if(!zt(i,((v=r().currentSession)==null?void 0:v.id)??null)){u();break}const O=i.payload;e(F=>({currentSession:F.currentSession?{...F.currentSession,summary:O.summary}:null}));break}case"chat.progress":{if(!zt(i,((S=r().currentSession)==null?void 0:S.id)??null)){u();break}const O=i.payload;console.log("Progress:",O.message,O.phase);break}case"chat.format_retry":{if(!zt(i,((j=r().currentSession)==null?void 0:j.id)??null)){u();break}const O=i.payload;console.log("Format retry:",O.attempt,"/",O.maxAttempts);break}case"chat.done":{if(!zt(i,((T=r().currentSession)==null?void 0:T.id)??null)){u();break}Ai(),un==null||un();const O=i.payload,F=O.stats;$t.messageId=null,$t.deltaContent="",$t.thinkingContent="",$t.toolOutput=[],Bd.delete(O.messageId),e(P=>{const Z=P.streamingMessage,G=Z&&Z.id===O.messageId?{...Z,isStreaming:!1,stats:F??Z.stats}:null;return{messages:P.messages.map(I=>I.id===O.messageId?G??{...I,isStreaming:!1,stats:F??I.stats}:I),streamingMessageId:null,streamingMessage:null,visionFallbackByMessage:{}}});break}case"chat.error":{if(!zt(i,((N=r().currentSession)==null?void 0:N.id)??null)){u();break}Ai(),un==null||un();const O=i.payload;console.error("Chat error:",O.error,"recoverable:",O.recoverable),O.recoverable||($t.messageId=null,$t.deltaContent="",$t.thinkingContent="",$t.toolOutput=[]),e(F=>({error:{code:"CHAT_ERROR",message:O.error},streamingMessageId:O.recoverable?F.streamingMessageId:null,...O.recoverable?{}:{messages:F.streamingMessage?F.messages.map(P=>P.id===F.streamingMessage.id?F.streamingMessage:P):F.messages,streamingMessage:null}}));break}case"chat.path_confirmation":{if(!zt(i,((D=r().currentSession)==null?void 0:D.id)??null)){u();break}const O=i.payload;e({pendingPathConfirmation:{callId:O.callId,tool:O.tool,paths:O.paths,workdir:O.workdir,reason:O.reason}});break}case"chat.ask_user":{if(!zt(i,((A=r().currentSession)==null?void 0:A.id)??null)){u();return}const O=i.payload;e({pendingQuestion:{callId:O.callId,question:O.question}});break}case"mode.changed":{if(!zt(i,((M=r().currentSession)==null?void 0:M.id)??null)){u();break}const O=i.payload;e(F=>({currentSession:F.currentSession?{...F.currentSession,mode:O.mode}:null}));break}case"phase.changed":{const O=i.payload,F=i.sessionId,P=(B=r().currentSession)==null?void 0:B.id,Z=F&&F!==P;e(G=>({sessions:G.sessions.map(I=>I.id===F?{...I,phase:O.phase}:I)})),Z||e(G=>({currentSession:G.currentSession?{...G.currentSession,phase:O.phase}:null}));break}case"criteria.updated":{if(!zt(i,(($=r().currentSession)==null?void 0:$.id)??null)){u();break}const O=i.payload;e(F=>({currentSession:F.currentSession?{...F.currentSession,criteria:O.criteria}:null}));break}case"context.state":{const O=i.payload,F=zt(i,((V=r().currentSession)==null?void 0:V.id)??null);O.subAgentId?F&&r().updateSubAgentContextState(O.subAgentId,O.context):F?e({contextState:O.context}):u();break}case"session.name_generated":{const O=i.payload,F=i.sessionId,P=(W=r().currentSession)==null?void 0:W.id;e(Z=>{const G=Z.sessions.map(R=>R.id===F?{...R,title:O.name,updatedAt:new Date().toISOString()}:R),I=P===F?Z.currentSession?{...Z.currentSession,title:O.name,updatedAt:new Date().toISOString()}:null:Z.currentSession;return{sessions:G,currentSession:I}});break}case"queue.state":{const O=i.payload;e({queuedMessages:O.messages});break}case"devServer.output":case"devServer.state":{cr.getState().handleMessage(i);break}case"backgroundProcess.started":case"backgroundProcess.output":case"backgroundProcess.exited":case"backgroundProcess.removed":{Va.getState().handleMessage(i.type,i.payload);break}case"error":{const O=i.payload;console.error("Server error:",O),e({error:{code:O.code,message:O.message},streamingMessageId:null});break}}}}));function Lb(){return Ce(e=>{var r;return((r=e.currentSession)==null?void 0:r.isRunning)??!1})}function nw(){return Ce(e=>e.queuedMessages)}function rw(){return Ce(e=>e.abortInProgress)}function iw(){const e=Ce(s=>s.connect),r=Ce(s=>s.connectionStatus),i=Oi(s=>s.load);return H.useEffect(()=>{e()},[e]),H.useEffect(()=>{r==="connected"&&i()},[r,i]),{connectionStatus:r}}function sw({className:e="w-5 h-5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}function Ob({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M14 5l7 7m0 0l-7 7m7-7H3"})})}function aw({className:e="w-5 h-5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"})})}function ow({className:e="w-3 h-3 text-text-muted"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"})})}function lw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M9.5 3.25a2.25 2.25 0 1 1 3 2.122V6A2.5 2.5 0 0 1 10 8.5H6a1 1 0 0 0-1 1v1.128a2.251 2.251 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.5 0v1.836A2.493 2.493 0 0 1 6 7h4a1 1 0 0 0 1-1v-.628A2.25 2.25 0 0 1 9.5 3.25Zm-6 0a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Zm8.25-.75a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM4.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z"})})}function Mr({className:e="w-3.5 h-3.5 text-text-muted"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})}function ur({className:e="w-3 h-3 text-text-muted",rotate:r}){return o.jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:r!==void 0?{transform:`rotate(${r}deg)`}:void 0,children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"})})}function cw({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",strokeWidth:"2"}),o.jsx("path",{d:"M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1",strokeWidth:"2"})]})}function Jl({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})}function uw({className:e="w-3 h-3"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})})}function Dh({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,fill:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("circle",{cx:"12",cy:"5",r:"2"}),o.jsx("circle",{cx:"12",cy:"12",r:"2"}),o.jsx("circle",{cx:"12",cy:"19",r:"2"})]})}function ec({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})})}function Fl({className:e="w-5 h-5 text-accent-primary"}){return o.jsx("svg",{className:e,fill:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{d:"M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"})})}function dw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 9V4.5M9 9H4.5M9 9L3.75 3.75M9 15v4.5M9 15H4.5M9 15l-5.25 5.25M15 9h4.5M15 9V4.5M15 9l5.25-5.25M15 15h4.5M15 15v4.5m0-4.5l5.25 5.25"})})}function hw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"})})}function fw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M8 0a8.2 8.2 0 0 1 .701.031C9.444.095 9.99.645 10.16 1.29l.288 1.107c.018.066.079.158.212.224.231.114.454.243.668.386.123.082.233.09.299.071l1.1-.303c.652-.18 1.37.008 1.755.653a8.043 8.043 0 0 1 .683 1.18c.227.568.096 1.26-.378 1.726l-.812.804a.312.312 0 0 0-.081.283c.024.166.04.335.04.507s-.016.341-.04.507a.312.312 0 0 0 .08.283l.813.804c.474.466.605 1.158.378 1.726a8.07 8.07 0 0 1-.683 1.18c-.385.645-1.103.833-1.755.653l-1.1-.303c-.066-.019-.176-.011-.299.071a5.1 5.1 0 0 1-.668.386c-.133.066-.194.158-.211.224l-.29 1.107c-.168.645-.714 1.196-1.458 1.26a8.094 8.094 0 0 1-1.402 0c-.744-.064-1.29-.615-1.458-1.26l-.29-1.107a.426.426 0 0 0-.211-.224 5.11 5.11 0 0 1-.668-.386c-.123-.082-.233-.09-.299-.071l-1.1.303c-.652.18-1.37-.008-1.755-.653a8.044 8.044 0 0 1-.683-1.18c-.227-.568-.096-1.26.378-1.726l.812-.804a.312.312 0 0 0 .081-.283A5.18 5.18 0 0 1 2.3 8c0-.172.016-.341.04-.507a.312.312 0 0 0-.08-.283l-.813-.804C.973 5.94.842 5.248 1.069 4.68c.181-.452.395-.882.683-1.18.385-.645 1.103-.833 1.755-.653l1.1.303c.066.019.176.011.299-.071.214-.143.437-.272.668-.386a.426.426 0 0 0 .211-.224l.29-1.107C6.009.645 6.556.095 7.299.03 7.53.01 7.764 0 8 0Zm0 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5Z"})})}function pw({className:e="w-3 h-3"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}function mw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"})})}function Ux({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})})}function gw({className:e="w-[18px] h-[18px]"}){return o.jsxs("svg",{className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[o.jsx("circle",{cx:"12",cy:"5",r:"1.5",fill:"currentColor",stroke:"none"}),o.jsx("circle",{cx:"12",cy:"12",r:"1.5",fill:"currentColor",stroke:"none"}),o.jsx("circle",{cx:"12",cy:"19",r:"1.5",fill:"currentColor",stroke:"none"})]})}function xw({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("path",{d:"M6.5 3.5H3a1 1 0 0 0-1 1V13a1 1 0 0 0 1 1h8.5a1 1 0 0 0 1-1V9.5"}),o.jsx("path",{d:"M9.5 2h4.5v4.5"}),o.jsx("path",{d:"M14 2L7.5 8.5"})]})}function vw({className:e="w-3 h-3",color:r}){return o.jsx("svg",{className:e,fill:r??"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{d:"M8 5v14l11-7z"})})}function Mb({className:e="w-3 h-3 text-accent-primary"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}function Ib({className:e="",size:r="md"}){const i=r==="sm"?"w-4 h-4":"w-6 h-6";return o.jsxs("svg",{className:`animate-spin ${i} ${e}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),o.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]})}const Bb=Ib,zb=Ib;function bw({className:e="w-5 h-5"}){return o.jsx("svg",{className:e,viewBox:"0 0 20 20",fill:"currentColor",children:o.jsx("path",{fillRule:"evenodd",d:"M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z",clipRule:"evenodd"})})}function yw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}function _w({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]})}function Sw({className:e="w-3 h-3 text-blue-400 animate-spin flex-shrink-0"}){return o.jsxs("svg",{"aria-label":"Session running",className:e,viewBox:"0 0 24 24",fill:"none",children:[o.jsx("title",{children:"Running"}),o.jsx("circle",{className:"opacity-30",cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"3"}),o.jsx("path",{d:"M21 12a9 9 0 00-9-9",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round"})]})}function ww({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("rect",{x:"3",y:"3",width:"10",height:"10",rx:"1"})})}function Cw({className:e="w-3.5 h-3.5 shrink-0",color:r}){return o.jsx("svg",{className:e,fill:"none",stroke:r,viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})})}function kw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 20 20",fill:"currentColor",children:o.jsx("path",{fillRule:"evenodd",d:"M2 5a2 2 0 012-2h12a2 2 0 012 2v10a2 2 0 01-2 2H4a2 2 0 01-2-2V5zm3 1h10v1H5V6zm10 7H5v1h10v-1zm-10 2H5v1h10v-1z",clipRule:"evenodd"})})}function Hb({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})})}function Ew({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}function Pb({className:e="w-2.5 h-2.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}function jw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 20 20",fill:"currentColor",children:o.jsx("path",{fillRule:"evenodd",d:"M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z",clipRule:"evenodd"})})}function Nw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.55.55 0 0 1 0-.708z"})})}function uh(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const r=Math.random()*16|0;return(e==="x"?r:r&3|8).toString(16)})}function $x(e,r){const i=qt.ws;!i||i.readyState!==WebSocket.OPEN||i.send(JSON.stringify({id:uh(),type:e,payload:r}))}const Jn=Yn((e,r)=>({isOpen:!1,sessions:[],workdir:null,setOpen:i=>e({isOpen:i}),toggleOpen:()=>e(i=>({isOpen:!i.isOpen})),setWorkdir:i=>e({workdir:i}),fetchSessions:async()=>{try{const i=await ke("/api/terminals");if(i.ok){const s=await i.json();e({sessions:s});const c=qt.ws;if(c&&c.readyState===WebSocket.OPEN)for(const u of s)c.send(JSON.stringify({id:uh(),type:"terminal.subscribe",payload:{sessionId:u.id}}))}}catch(i){console.error("Failed to fetch terminals:",i)}},createSession:async i=>{try{const s=await ke("/api/terminals",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workdir:i??r().workdir??void 0})});if(s.ok){const c=await s.json();e(f=>({sessions:[...f.sessions,c]}));const u=qt.ws;u&&u.readyState===WebSocket.OPEN&&u.send(JSON.stringify({id:uh(),type:"terminal.subscribe",payload:{sessionId:c.id}}))}}catch(s){console.error("Failed to create terminal:",s)}},writeSession:(i,s)=>{$x("terminal.write",{sessionId:i,data:s})},resizeSession:(i,s,c)=>{$x("terminal.resize",{sessionId:i,cols:s,rows:c})},killSession:async i=>{try{(await ke(`/api/terminals/${i}`,{method:"DELETE"})).ok&&e(c=>({sessions:c.sessions.filter(u=>u.id!==i)}))}catch(s){console.error("Failed to kill terminal:",s)}},handleMessage:i=>{switch(i.type){case"terminal.exit":{const{sessionId:s}=i.payload||{};s&&e(c=>{const u=c.sessions.filter(f=>f.id!==s);return u.length===0&&c.isOpen?{sessions:[],isOpen:!1}:{sessions:u}});break}}}}));qt.subscribe(e=>{var r;(r=e.type)!=null&&r.startsWith("terminal.")&&Jn.getState().handleMessage(e)});var tc=xb();const nc=H.forwardRef(({icon:e,iconSize:r="w-3.5 h-3.5",className:i="",...s},c)=>o.jsx("button",{ref:c,type:"button",className:`p-1 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors ${i}`,...s,children:o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:e})})}));nc.displayName="IconButton";const Tw="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z",Hs=H.forwardRef((e,r)=>o.jsx(nc,{ref:r,icon:Tw,title:"Edit",...e}));Hs.displayName="EditButton";const Aw="M6 18L18 6M6 6l12 12",Rh=H.forwardRef((e,r)=>o.jsx(nc,{ref:r,icon:Aw,...e}));Rh.displayName="CloseButton";const Dw={sm:"max-w-sm",md:"max-w-md",lg:"max-w-2xl",xl:"max-w-4xl",full:"max-w-[95vw] h-[90vh] flex-1"};function jt({label:e,title:r,size:i="md",minHeight:s,children:c,footer:u,className:f,onClose:l,isOpen:d,closeOnBackdropClick:p=!0,closeOnEscape:g=!0,showCloseButton:m=!0}){const[b,_]=H.useState(!1),k=d!==void 0,C=k?d:b,y=H.useCallback(()=>{k||_(!0)},[k]),x=H.useCallback(()=>{k||_(!1),l==null||l()},[k,l]);H.useEffect(()=>{if(!C||!g)return;const S=j=>{j.key==="Escape"&&x()};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[C,x,g]);const v=e&&(typeof e=="string"?o.jsx("button",{type:"button",onClick:y,className:f,children:e}):o.jsx("span",{onClick:y,className:f,style:{cursor:"pointer"},children:e}));return o.jsxs(o.Fragment,{children:[v,C&&(typeof document<"u"?tc.createPortal(o.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[o.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:p?x:void 0}),o.jsxs("div",{className:`relative w-full ${Dw[i]} max-h-[90vh] bg-bg-secondary border border-border rounded shadow-xl flex flex-col`,children:[(r||m)&&o.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border",children:[r&&o.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:r}),m&&o.jsx(Rh,{onClick:x,className:"ml-auto","aria-label":"Close"})]}),o.jsx("div",{className:"p-4 overflow-y-auto flex-1 min-h-0",style:s?{minHeight:s}:void 0,children:c}),u&&o.jsx("div",{className:"px-4 py-3 border-t border-border",children:u})]})]}),document.body):null)]})}const it=H.forwardRef(({variant:e="secondary",size:r="md",className:i="",children:s,...c},u)=>{const f="rounded font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed",l={primary:"bg-accent-primary/25 text-white hover:bg-accent-primary/40",secondary:"bg-bg-tertiary text-text-primary hover:bg-border",danger:"bg-accent-error text-white hover:bg-accent-error/80"},d={sm:"px-1.5 py-1 text-xs",md:"px-3 py-1.5 text-sm",lg:"px-4 py-2 text-base"};return o.jsx("button",{ref:u,className:`${f} ${l[e]} ${d[r]} ${i}`,...c,children:s})});it.displayName="Button";function Rw({value:e,defaultUrl:r,disabled:i,onChange:s}){const c=e??r;return o.jsxs("div",{className:"relative",children:[o.jsx("select",{value:c,disabled:i,onChange:u=>{const f=u.target.value;s(f===r?null:f)},className:"appearance-none bg-bg-tertiary border border-border rounded px-1.5 pr-5 text-xs focus:outline-none focus:ring-1 focus:ring-accent-primary disabled:opacity-40 cursor-pointer",style:{width:"60px"},children:F1.map(({url:u,label:f})=>o.jsx("option",{value:u,title:f,children:f.split(" ")[0]},u))}),o.jsx(ur,{className:"absolute right-0.5 top-1/2 -translate-y-1/2 w-3 h-3 pointer-events-none text-text-muted"})]})}const qx=[{key:"general",label:"General"},{key:"build",label:"Agent"},{key:"sub-agent",label:"Sub-agent"}];function Lw(){const e=Oi(d=>d.settings),r=Oi(d=>d.update),i=Oi(d=>d.updateEvent),s=Oi(d=>d.updateAgentOverride),c=Oi(d=>d.load);H.useEffect(()=>{c()},[c]);const u=async()=>{await $1()==="granted"&&r({...e,browserNotificationEnabled:!0})},f=(d,p,g,m)=>{d==="general"?i(p,{[g]:m}):s(d,p,{[g]:m})},l=(d,p,g)=>{d==="general"?i(p,{customSoundUrl:g}):s(d,p,{customSoundUrl:g})};return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-3",children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Master Controls"}),o.jsx(Wx,{label:"Sound notifications",description:"Play sounds when events occur",checked:e.soundEnabled,onChange:d=>r({...e,soundEnabled:d})}),o.jsx(Wx,{label:"Browser notifications",description:"Show desktop notifications when the window is not focused",checked:e.browserNotificationEnabled,onChange:d=>{d&&typeof Notification<"u"&&Notification.permission!=="granted"?u():r({...e,browserNotificationEnabled:d})}}),typeof Notification<"u"&&Notification.permission==="denied"&&e.browserNotificationEnabled&&o.jsx("p",{className:"text-xs text-accent-error ml-6",children:"Browser notifications are blocked. Please enable them in your browser settings."})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Notification Settings"}),o.jsx("div",{className:"border border-border rounded overflow-hidden",children:o.jsxs("table",{className:"w-full text-sm",children:[o.jsx("thead",{className:"sticky top-0 bg-bg-tertiary",children:o.jsxs("tr",{className:"border-b border-border",children:[o.jsx("th",{className:"text-left px-3 py-2 text-text-primary font-medium w-40",children:"Event"}),qx.map(d=>o.jsx("th",{className:"text-center px-2 py-2 text-text-primary font-medium",children:d.label},d.key))]})}),o.jsx("tbody",{children:P1.map(d=>o.jsxs("tr",{className:"border-b border-border last:border-b-0 hover:bg-bg-secondary/50",children:[o.jsx("td",{className:"px-3 py-2",children:o.jsx("div",{className:"text-text-primary text-xs",children:d.label})}),qx.map(p=>{const g=Db(e,d.key,p.key==="general"?void 0:p.key),m=Tb[d.key];return o.jsx("td",{className:"px-2 py-2 align-top",children:o.jsxs("div",{className:"flex flex-col items-center gap-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("label",{className:"flex items-center gap-1 text-text-secondary",children:o.jsx("input",{type:"checkbox",checked:g.soundEnabled,onChange:b=>f(p.key,d.key,"soundEnabled",b.target.checked),disabled:!e.soundEnabled,className:"rounded border-border",title:"Sound"})}),o.jsx("label",{className:"flex items-center gap-1 text-text-secondary",children:o.jsx("input",{type:"checkbox",checked:g.browserNotification,onChange:b=>f(p.key,d.key,"browserNotification",b.target.checked),disabled:!e.browserNotificationEnabled,className:"rounded border-border",title:"Browser"})})]}),g.soundEnabled&&e.soundEnabled&&o.jsx(Rw,{value:g.customSoundUrl,defaultUrl:m,disabled:!e.soundEnabled,onChange:b=>l(p.key,d.key,b)})]})},p.key)})]},d.key))})]})})]})]})}function Wx({label:e,description:r,checked:i,onChange:s}){return o.jsxs("label",{className:"flex items-start gap-3 cursor-pointer group",children:[o.jsx("div",{className:"pt-0.5",children:o.jsx("div",{className:`relative w-9 h-5 rounded-full transition-colors ${i?"bg-accent-primary":"bg-bg-tertiary border border-border"}`,onClick:c=>{c.preventDefault(),s(!i)},children:o.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white shadow transition-transform ${i?"translate-x-4":"translate-x-0.5"}`})})}),o.jsxs("div",{children:[o.jsx("div",{className:"text-sm text-text-primary group-hover:text-accent-primary transition-colors",children:e}),o.jsx("div",{className:"text-xs text-text-muted",children:r})]})]})}async function Lh(e,r){r({loading:!0});try{const s=await(await ke(e)).json();r({defaults:s.defaults??[],userItems:s.userItems??[],loading:!1})}catch{r({loading:!1})}}const Rr=Yn((e,r)=>({defaults:[],userItems:[],loading:!1,fetchSkills:async()=>{await Lh("/api/skills",e)},toggleSkill:async i=>{try{const c=await(await ke(`/api/skills/${i}/toggle`,{method:"POST"})).json();e(u=>({defaults:u.defaults.map(f=>f.id===i?{...f,enabled:c.enabled}:f),userItems:u.userItems.map(f=>f.id===i?{...f,enabled:c.enabled}:f)}))}catch{}},fetchSkill:async i=>{try{const s=await ke(`/api/skills/${i}`);return s.ok?await s.json():null}catch{return null}},fetchDefaultContent:async i=>{try{const s=await ke(`/api/skills/defaults/${i}`);return s.ok?await s.json():null}catch{return null}},createSkill:async i=>{const s=await di("POST","/api/skills",i);return s.success&&await r().fetchSkills(),s},updateSkill:async(i,s)=>{const c=await di("PUT",`/api/skills/${i}`,s);return c.success&&await r().fetchSkills(),c},deleteSkill:async i=>{try{const s=await ke(`/api/skills/${i}`,{method:"DELETE"}),c=await s.json();return s.ok?(e(u=>({userItems:u.userItems.filter(f=>f.id!==i)})),{success:!0}):{success:!1,error:c.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateSkill:async i=>{try{const s=await ke(`/api/skills/${i}/duplicate`,{method:"POST"}),c=await s.json();return s.ok?(await r().fetchSkills(),{success:!0}):{success:!1,error:c.error??"Failed to duplicate"}}catch{return{success:!1,error:"Network error"}}}}));function Oh(){const[e,r]=H.useState({id:null,type:null}),i=H.useCallback(u=>r({id:u,type:"delete"}),[]),s=H.useCallback(()=>r({id:null,type:null}),[]),c=H.useCallback((u,f)=>e.id===u&&e.type===f,[e.id,e.type]);return{requestDelete:i,clearConfirm:s,isConfirming:c}}function Mh({onConfirm:e,onCancel:r}){return o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("button",{onClick:e,className:"px-1.5 py-0.5 rounded text-xs hover:opacity-90 transition-colors bg-accent-error/20 text-accent-error hover:bg-accent-error/30",children:"Delete"}),o.jsx("button",{onClick:r,className:"px-1.5 py-0.5 rounded text-text-muted text-xs hover:bg-bg-primary transition-colors",children:"Cancel"})]})}function Ih({onClick:e}){return o.jsx("button",{onClick:e,className:"p-1.5 rounded hover:bg-bg-primary text-text-muted hover:text-accent-error transition-colors",title:"Delete",children:o.jsx(Hb,{})})}function Qa({onClick:e}){return o.jsx("button",{onClick:e,className:"p-1.5 rounded hover:bg-bg-primary text-text-muted hover:text-text-primary transition-colors",title:"Duplicate",children:o.jsx(Jl,{})})}function Mi({label:e,value:r,onChange:i,placeholder:s,readOnly:c,hint:u,mono:f}){return o.jsxs("div",{children:[o.jsxs("label",{className:"block text-xs text-text-secondary mb-1",children:[e,u&&o.jsx("span",{className:"text-text-muted ml-1",children:u})]}),o.jsx("input",{value:r,onChange:l=>i(l.target.value),readOnly:c,placeholder:s,className:`w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary ${f?"font-mono":""} ${c?"opacity-60":""}`})]})}function Ow({onCancel:e,onSave:r,saving:i,saveDisabled:s}){return o.jsxs("div",{className:"flex justify-end gap-2 pt-2 border-t border-border",children:[o.jsx(it,{variant:"secondary",onClick:e,children:"Cancel"}),o.jsx(it,{variant:"primary",onClick:r,disabled:i||s,children:i?"Saving...":"Save"})]})}function Bh({message:e}){return o.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded",children:e})}function Fb({description:e,onNew:r,newLabel:i="+ New"}){return o.jsxs("div",{className:"flex items-center justify-between mb-4",children:[o.jsx("p",{className:"text-text-secondary text-sm",children:e}),o.jsx("div",{className:"flex items-center gap-2 flex-shrink-0 ml-3",children:o.jsx(it,{variant:"primary",size:"sm",onClick:r,children:i})})]})}function Ub({isBuiltIn:e,isConfirmingDelete:r,onView:i,onEdit:s,onDuplicate:c,onDelete:u,children:f}){return o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsx("div",{className:"min-w-0 flex-1 mr-3",children:f}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[e&&i&&o.jsx("button",{onClick:i,className:"p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",title:"View",children:o.jsx(ec,{})}),o.jsx(Qa,{onClick:c}),!e&&s&&o.jsx(Hs,{onClick:s}),!e&&(r?o.jsx(Mh,{onConfirm:()=>{u==null||u()},onCancel:()=>{}}):o.jsx(Ih,{onClick:()=>u==null?void 0:u()}))]})]})}function Mw({id:e,name:r,description:i,isBuiltIn:s,isConfirmingDelete:c,onView:u,onEdit:f,onDuplicate:l,onDelete:d}){return o.jsxs(Ub,{isBuiltIn:s,isConfirmingDelete:c,onView:u,onEdit:f,onDuplicate:l,onDelete:d,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-text-primary text-sm font-medium",children:r}),o.jsx("span",{className:"text-text-muted text-xs font-mono",children:e})]}),i&&o.jsx("p",{className:"text-text-muted text-xs truncate",children:i})]})}function $b({loading:e,hasItems:r,loadingLabel:i,emptyLabel:s,children:c}){return e&&!r?o.jsx("div",{className:"text-text-muted text-sm",children:i}):r?o.jsx("div",{className:"space-y-4",children:c}):s?o.jsx("div",{className:"text-text-muted text-sm",children:s}):null}function qb({name:e,id:r,nameLabel:i="Name",idLabel:s="ID",namePlaceholder:c="My Item",idPlaceholder:u="my-item",nameHint:f,readOnlyId:l=!1,readOnlyHint:d="(read-only)",onNameChange:p,onIdChange:g}){return o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Mi,{label:i,value:e,onChange:p,placeholder:c,hint:f}),o.jsx(Mi,{label:s,value:r,onChange:g,readOnly:l,placeholder:u,hint:l?d:void 0,mono:!0})]})}function Wb(e={}){const{initialData:r={}}=e,[i,s]=H.useState("list"),[c,u]=H.useState(null),[f,l]=H.useState(""),[d,p]=H.useState(!1),[g,m]=H.useState(r),b=H.useCallback(()=>{m(r),l(""),u(null)},[r]),_=H.useCallback(x=>{s(x),x==="list"&&b()},[b]),k=H.useCallback(x=>{m(v=>typeof x=="function"?x(v):x)},[]),C=H.useCallback((x,v={})=>{u(x),s("edit"),m({...v}),l("")},[]),y=H.useCallback(()=>{u(null),s("edit"),m(r),l("")},[r]);return{view:i,editingId:c,formError:f,saving:d,formData:g,setView:_,setEditingId:u,setFormError:l,setFormData:k,setSaving:p,resetForm:b,startEditing:C,startNew:y}}function zh(){return o.jsxs("div",{className:"flex items-start gap-2 px-3 py-2 mt-3 bg-accent-warning/10 border border-accent-warning/30 rounded text-xs",children:[o.jsx("span",{children:"⚠️"}),o.jsx("p",{className:"text-text-secondary",children:"Editing this value now will have the side-effect of invalidating KV-cache, causing your next message in current sessions to take a long time to process. Consider doing this between sessions."})]})}function Gx({skill:e,isBuiltIn:r,isConfirmingDelete:i,onView:s,onEdit:c,onDuplicate:u,onDelete:f}){return o.jsx(Mw,{id:e.id,name:e.name,description:e.description,isBuiltIn:r,isConfirmingDelete:i,onView:s,onEdit:c,onDuplicate:u,onDelete:f})}function Iw({isOpen:e}){const r=Rr(O=>O.defaults),i=Rr(O=>O.userItems),s=Rr(O=>O.loading),c=Rr(O=>O.fetchSkills),u=Rr(O=>O.fetchSkill),f=Rr(O=>O.fetchDefaultContent),l=Rr(O=>O.createSkill),d=Rr(O=>O.updateSkill),p=Rr(O=>O.deleteSkill),{view:g,editingId:m,formError:b,saving:_,formData:k,setView:C,setEditingId:y,setFormError:x,setFormData:v,setSaving:S}=Wb(),{clearConfirm:j}=Oh();H.useEffect(()=>{e&&(c(),C("list"),y(null),j())},[e,c,j]);const T=(O,F,P,Z)=>{v({name:Z??O.metadata.name,id:P??O.metadata.id,description:O.metadata.description??"",version:O.metadata.version??"1.0.0",prompt:O.prompt,isReadOnly:F})},N=async O=>{if(r.some(P=>P.id===O)){const P=await f(O);if(!P)return;T(P,!0),y(O),x(""),C("edit")}else{const P=await u(O);if(!P)return;T(P,!0),y(O),x(""),C("edit")}},D=async O=>{const P=r.some(G=>G.id===O)?await f(O):await u(O);if(!P)return;const Z=`${O}-copy-${Date.now()}`;T(P,!1,Z,`${P.metadata.name} (copy)`),y(null),x(""),C("edit")},A=()=>{v({name:"",id:"",description:"",version:"1.0.0",prompt:"",isReadOnly:!1}),C("edit")},M=async O=>{const F=await u(O);F&&(T(F,!1),y(O),x(""),C("edit"))},B=async O=>{await p(O),j()},$=async()=>{const O=m??k.id;if(!O||!k.name||!k.prompt){x("Name, ID, and prompt are required.");return}S(!0),x("");const F={metadata:{id:O,name:k.name,description:k.description,version:k.version},prompt:k.prompt},P=m?await d(m,F):await l(F);if(S(!1),!P.success){x(P.error??"Failed to save skill.");return}C("list")},V=O=>{v(F=>({...F,name:O})),m||v(F=>({...F,id:O.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}))},W=k.isReadOnly;return g==="edit"?o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"flex justify-between items-center mb-3",children:[o.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:W?k.name:m?"Edit Skill":"New Skill"}),o.jsx("button",{onClick:()=>C("list"),className:"text-text-muted hover:text-text-primary",children:"Cancel"})]}),b&&o.jsx(Bh,{message:b}),o.jsxs("div",{className:"space-y-3 mb-3",children:[o.jsx(qb,{name:k.name,id:k.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Skill",idPlaceholder:"my-skill",readOnlyId:!0,onNameChange:V,onIdChange:()=>{}}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Mi,{label:"Description",value:k.description,onChange:O=>v(F=>({...F,description:O})),placeholder:"What this skill does...",readOnly:W}),o.jsx(Mi,{label:"Version",value:k.version,onChange:O=>v(F=>({...F,version:O})),placeholder:"1.0.0",readOnly:W})]})]}),o.jsxs("div",{className:"flex-1 min-h-[120px] border-t border-border pt-3 flex flex-col",children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Prompt"}),o.jsx("textarea",{value:k.prompt,onChange:O=>v(F=>({...F,prompt:O.target.value})),readOnly:W,placeholder:"The system prompt for this skill...",className:"flex-1 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-none focus:outline-none focus:ring-1 focus:ring-accent-primary"})]}),o.jsx(zh,{}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 border-t border-border flex-shrink-0",children:[o.jsx(it,{variant:"secondary",onClick:()=>C("list"),children:"Cancel"}),W?o.jsx(it,{variant:"primary",onClick:()=>{v(O=>({...O,name:O.name+" (copy)",id:`${m}-copy-${Date.now()}`,isReadOnly:!1})),y(null)},children:"Duplicate & Customize"}):o.jsx(it,{variant:"primary",onClick:$,disabled:_||!k.name||!k.id||!k.prompt,children:_?"Saving...":"Save"})]})]}):o.jsxs("div",{children:[o.jsx(Fb,{description:"Skills provide domain-specific knowledge that agents can load on demand.",onNew:A}),o.jsxs($b,{loading:s,hasItems:r.length>0||i.length>0,loadingLabel:"Loading skills...",emptyLabel:"No skills created yet.",children:[r.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Built-in"}),o.jsx("div",{className:"space-y-2",children:r.map(O=>o.jsx(Gx,{skill:O,isBuiltIn:!0,isConfirmingDelete:!1,onView:()=>N(O.id),onDuplicate:()=>D(O.id)},O.id))})]}),i.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Custom"}),o.jsx("div",{className:"space-y-2",children:i.map(O=>o.jsx(Gx,{skill:O,isBuiltIn:!1,isConfirmingDelete:!1,onView:()=>N(O.id),onEdit:()=>M(O.id),onDuplicate:()=>D(O.id),onDelete:()=>B(O.id)},O.id))})]})]})]})}function Bw({isOpen:e,onClose:r}){const[i,s]=H.useState("instructions");return o.jsx(jt,{isOpen:e,onClose:r,title:"Settings",size:"xl",minHeight:"500px",children:o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"flex border-b border-border mb-4 -mt-1",children:[o.jsx(Ba,{label:"Instructions",active:i==="instructions",onClick:()=>s("instructions")}),o.jsx(Ba,{label:"Skills",active:i==="skills",onClick:()=>s("skills")}),o.jsx(Ba,{label:"Notifications",active:i==="notifications",onClick:()=>s("notifications")}),o.jsx(Ba,{label:"Display",active:i==="display",onClick:()=>s("display")}),o.jsx(Ba,{label:"Advanced",active:i==="advanced",onClick:()=>s("advanced")})]}),i==="instructions"&&o.jsx(Pw,{isOpen:e}),i==="skills"&&o.jsx(Iw,{isOpen:e}),i==="notifications"&&o.jsx("div",{className:"max-h-[60vh] overflow-y-auto",children:o.jsx(Lw,{})}),i==="display"&&o.jsx(Hw,{}),i==="advanced"&&o.jsx(zw,{onClose:r})]})})}function zw({onClose:e}){const[,r]=dr();function i(){e(),r("/onboarding")}return o.jsx("div",{className:"space-y-6",children:o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary mb-1",children:"Onboarding"}),o.jsx("p",{className:"text-sm text-text-muted mb-4",children:"Reset your OpenFox setup and go through the initial configuration again."}),o.jsx(it,{variant:"secondary",onClick:i,children:"Launch Onboarding"})]})})}function Hw(){const e=en(g=>g.settings),r=en(g=>g.loading),i=en(g=>g.getSetting),s=en(g=>g.setSetting),c=r[Et.DISPLAY_SHOW_THINKING]??!1,u=[{key:Et.DISPLAY_SHOW_THINKING,label:"Show thinking blocks",description:"Display AI reasoning content in the feed"},{key:Et.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT,label:"Show expanded tool output",description:"Always show full tool call details instead of compact view"},{key:Et.DISPLAY_SHOW_STATS,label:"Show stats bar",description:"Display model, tokens, and timing information"},{key:Et.DISPLAY_SHOW_AGENT_DEFINITIONS,label:"Show agent definitions",description:"Display agent definition injections in the feed"},{key:Et.DISPLAY_SHOW_WORKFLOW_BARS,label:"Show workflow bars",description:"Display workflow start and end markers"}],f=Object.fromEntries(u.map(g=>[g.key,e[g.key]??"true"])),[l,d]=H.useState(()=>Object.fromEntries(u.map(g=>[g.key,f[g.key]==="true"])));H.useEffect(()=>{u.forEach(g=>i(g.key))},[i]),H.useEffect(()=>{d(Object.fromEntries(u.map(g=>[g.key,f[g.key]==="true"])))},[JSON.stringify(f)]);const p=async g=>{const m=String(!l[g]);d(b=>({...b,[g]:!b[g]})),await s(g,m)};return c?o.jsx("div",{className:"text-sm text-text-muted",children:"Loading..."}):o.jsx("div",{className:"space-y-6",children:o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary mb-4",children:"Feed Display"}),o.jsx("div",{className:"space-y-4",children:u.map(({key:g,label:m,description:b})=>o.jsxs("label",{className:"flex items-center justify-between cursor-pointer",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-sm text-text-primary",children:m}),o.jsx("div",{className:"text-xs text-text-muted",children:b})]}),o.jsx("button",{type:"button",onClick:()=>p(g),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${l[g]?"bg-accent-primary":"bg-bg-tertiary"}`,children:o.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${l[g]?"translate-x-6":"translate-x-1"}`})})]},g))})]})})}function Ba({label:e,active:r,onClick:i}){return o.jsx("button",{onClick:i,className:`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${r?"border-accent-primary text-accent-primary":"border-transparent text-text-muted hover:text-text-secondary hover:border-border"}`,children:e})}function Pw({isOpen:e}){const r=en(y=>y.settings),i=en(y=>y.loading),s=en(y=>y.getSetting),c=en(y=>y.setSetting),u=r[Et.GLOBAL_INSTRUCTIONS]??"",f=i[Et.GLOBAL_INSTRUCTIONS]??!1,[l,d]=H.useState(u),[p,g]=H.useState(!1),[m,b]=H.useState(!1);H.useEffect(()=>{e&&s(Et.GLOBAL_INSTRUCTIONS)},[e,s]),H.useEffect(()=>{d(u),g(!1)},[u]);const _=async()=>{b(!0),c(Et.GLOBAL_INSTRUCTIONS,l),b(!1),g(!1)},k=()=>{d(u),g(!1)},C=f||m;return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-text-primary mb-2",children:"Global Instructions"}),o.jsx("p",{className:"text-sm text-text-muted mb-2",children:"These instructions are injected into every prompt, regardless of project."}),o.jsx("textarea",{value:l,onChange:y=>{d(y.target.value),g(!0)},placeholder:"Enter global instructions that apply to all projects...",className:"w-full h-64 px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-none focus:outline-none focus:ring-1 focus:ring-accent-primary",disabled:C})]}),p&&o.jsx(zh,{}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(it,{variant:"secondary",onClick:k,disabled:!p,children:"Discard"}),o.jsx(it,{variant:"primary",onClick:_,disabled:!p||C,children:m?"Saving...":"Save"})]})]})}var Hd={exports:{}},Vx;function Fw(){return Vx||(Vx=1,(function(e,r){(function(i,s){e.exports=s()})(globalThis,(()=>(()=>{var i={4567:function(f,l,d){var p=this&&this.__decorate||function(v,S,j,T){var N,D=arguments.length,A=D<3?S:T===null?T=Object.getOwnPropertyDescriptor(S,j):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(v,S,j,T);else for(var M=v.length-1;M>=0;M--)(N=v[M])&&(A=(D<3?N(A):D>3?N(S,j,A):N(S,j))||A);return D>3&&A&&Object.defineProperty(S,j,A),A},g=this&&this.__param||function(v,S){return function(j,T){S(j,T,v)}};Object.defineProperty(l,"__esModule",{value:!0}),l.AccessibilityManager=void 0;const m=d(9042),b=d(9924),_=d(844),k=d(4725),C=d(2585),y=d(3656);let x=l.AccessibilityManager=class extends _.Disposable{constructor(v,S,j,T){super(),this._terminal=v,this._coreBrowserService=j,this._renderService=T,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let N=0;N<this._terminal.rows;N++)this._rowElements[N]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[N]);if(this._topBoundaryFocusListener=N=>this._handleBoundaryFocus(N,0),this._bottomBoundaryFocusListener=N=>this._handleBoundaryFocus(N,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new b.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((N=>this._handleResize(N.rows)))),this.register(this._terminal.onRender((N=>this._refreshRows(N.start,N.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((N=>this._handleChar(N)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
57
|
+
*/var kx;function c1(){if(kx)return Md;kx=1;var e=Zl();function r(m,b){return m===b&&(m!==0||1/m===1/b)||m!==m&&b!==b}var i=typeof Object.is=="function"?Object.is:r,s=e.useState,c=e.useEffect,u=e.useLayoutEffect,f=e.useDebugValue;function l(m,b){var _=b(),k=s({inst:{value:_,getSnapshot:b}}),C=k[0].inst,y=k[1];return u(function(){C.value=_,C.getSnapshot=b,d(C)&&y({inst:C})},[m,_,b]),c(function(){return d(C)&&y({inst:C}),m(function(){d(C)&&y({inst:C})})},[m]),f(_),_}function d(m){var b=m.getSnapshot;m=m.value;try{var _=b();return!i(m,_)}catch{return!0}}function p(m,b){return b()}var g=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?p:l;return Md.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:g,Md}var Ex;function u1(){return Ex||(Ex=1,Od.exports=c1()),Od.exports}var d1=u1();const h1=JS.useInsertionEffect,f1=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",p1=f1?H.useLayoutEffect:H.useEffect,m1=h1||p1,vb=e=>{const r=H.useRef([e,(...i)=>r[0](...i)]).current;return m1(()=>{r[0]=e}),r[1]},g1="popstate",jh="pushState",Nh="replaceState",x1="hashchange",jx=[g1,jh,Nh,x1],v1=e=>{for(const r of jx)addEventListener(r,e);return()=>{for(const r of jx)removeEventListener(r,e)}},bb=(e,r)=>d1.useSyncExternalStore(v1,e,r),Nx=()=>location.search,b1=({ssrSearch:e}={})=>bb(Nx,e!=null?()=>e:Nx),Tx=()=>location.pathname,y1=({ssrPath:e}={})=>bb(Tx,e!=null?()=>e:Tx),_1=(e,{replace:r=!1,state:i=null}={})=>history[r?Nh:jh](i,"",e),S1=(e={})=>[y1(e),_1],Ax=Symbol.for("wouter_v3");if(typeof history<"u"&&typeof window[Ax]>"u"){for(const e of[jh,Nh]){const r=history[e];history[e]=function(){const i=r.apply(this,arguments),s=new Event(e);return s.arguments=arguments,dispatchEvent(s),i}}Object.defineProperty(window,Ax,{value:!0})}const w1=(e,r)=>r.toLowerCase().indexOf(e.toLowerCase())?"~"+r:r.slice(e.length)||"/",yb=(e="")=>e==="/"?"":e,C1=(e,r)=>e[0]==="~"?e.slice(1):yb(r)+e,k1=(e="",r)=>w1(Dx(yb(e)),Dx(r)),Dx=e=>{try{return decodeURI(e)}catch{return e}},_b={hook:S1,searchHook:b1,parser:l1,base:"",ssrPath:void 0,ssrSearch:void 0,ssrContext:void 0,hrefs:e=>e,aroundNav:(e,r,i)=>e(r,i)},Sb=H.createContext(_b),zs=()=>H.useContext(Sb),wb={},Cb=H.createContext(wb),E1=()=>H.useContext(Cb),Ql=e=>{const[r,i]=e.hook(e);return[k1(e.base,r),vb((s,c)=>e.aroundNav(i,C1(s,e.base),c))]},dr=()=>Ql(zs()),Th=(e,r,i,s)=>{const{pattern:c,keys:u}=r instanceof RegExp?{keys:!1,pattern:r}:e(r||"*",s),f=c.exec(i)||[],[l,...d]=f;return l!==void 0?[!0,(()=>{const p=u!==!1?Object.fromEntries(u.map((m,b)=>[m,d[b]])):f.groups;let g={...d};return p&&Object.assign(g,p),g})(),...s?[l]:[]]:[!1,null]},Ah=e=>Th(zs().parser,e,dr()[0]),j1=({children:e,...r})=>{var g,m,b;const i=zs(),s=r.hook?_b:i;let c=s;const[u,f=r.ssrSearch??""]=((g=r.ssrPath)==null?void 0:g.split("?"))??[];u&&(r.ssrSearch=f,r.ssrPath=u),r.hrefs=r.hrefs??((m=r.hook)==null?void 0:m.hrefs),r.searchHook=r.searchHook??((b=r.hook)==null?void 0:b.searchHook);let l=H.useRef({}),d=l.current,p=d;for(let _ in s){const k=_==="base"?s[_]+(r[_]??""):r[_]??s[_];d===p&&k!==p[_]&&(l.current=p={...p}),p[_]=k,(k!==s[_]||k!==c[_])&&(c=p)}return H.createElement(Sb.Provider,{value:c,children:e})},Rx=({children:e,component:r},i)=>r?H.createElement(r,{params:i}):typeof e=="function"?e(i):e,N1=e=>{let r=H.useRef(wb);const i=r.current;return r.current=Object.keys(e).length!==Object.keys(i).length||Object.entries(e).some(([s,c])=>c!==i[s])?e:i},Oa=({path:e,nest:r,match:i,...s})=>{const c=zs(),[u]=Ql(c),[f,l,d]=i??Th(c.parser,e,u,r),p=N1({...E1(),...l});if(!f)return null;const g=d?H.createElement(j1,{base:d},Rx(s,p)):Rx(s,p);return H.createElement(Cb.Provider,{value:p,children:g})},Mn=H.forwardRef((e,r)=>{const i=zs(),[s,c]=Ql(i),{to:u="",href:f=u,onClick:l,asChild:d,children:p,className:g,replace:m,state:b,transition:_,...k}=e,C=vb(x=>{x.ctrlKey||x.metaKey||x.altKey||x.shiftKey||x.button!==0||(l==null||l(x),x.defaultPrevented||(x.preventDefault(),c(f,e)))}),y=i.hrefs(f[0]==="~"?f.slice(1):i.base+f,i);return d&&H.isValidElement(p)?H.cloneElement(p,{onClick:C,href:y}):H.createElement("a",{...k,onClick:C,href:y,className:g!=null&&g.call?g(s===f):g,children:p,ref:r})}),kb=e=>Array.isArray(e)?e.flatMap(r=>kb(r&&r.type===H.Fragment?r.props.children:r)):[e],T1=({children:e,location:r})=>{const i=zs(),[s]=Ql(i);for(const c of kb(e)){let u=0;if(H.isValidElement(c)&&(u=Th(i.parser,c.props.path,r||s,c.props.nest))[0])return H.cloneElement(c,{match:u})}return null},Lx=e=>{let r;const i=new Set,s=(p,g)=>{const m=typeof p=="function"?p(r):p;if(!Object.is(m,r)){const b=r;r=g??(typeof m!="object"||m===null)?m:Object.assign({},r,m),i.forEach(_=>_(r,b))}},c=()=>r,l={setState:s,getState:c,getInitialState:()=>d,subscribe:p=>(i.add(p),()=>i.delete(p))},d=r=e(s,c,l);return l},A1=(e=>e?Lx(e):Lx),D1=e=>e;function R1(e,r=D1){const i=dn.useSyncExternalStore(e.subscribe,dn.useCallback(()=>r(e.getState()),[e,r]),dn.useCallback(()=>r(e.getInitialState()),[e,r]));return dn.useDebugValue(i),i}const Ox=e=>{const r=A1(e),i=s=>R1(r,s);return Object.assign(i,r),i},Yn=(e=>e?Ox(e):Ox);async function ke(e,r={}){const i=localStorage.getItem("openfox_token"),s={...r.headers instanceof Headers?Object.fromEntries(r.headers.entries()):r.headers,...i?{"x-session-token":i}:{}};return fetch(e,{...r,headers:s})}function L1(e){return typeof e=="object"&&e!==null&&"type"in e&&"payload"in e}function Eb(){if(typeof crypto<"u"&&crypto.randomUUID)try{return crypto.randomUUID()}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const r=Math.random()*16|0;return(e==="x"?r:r&3|8).toString(16)})}class O1{constructor(r){ar(this,"ws",null);ar(this,"handlers",new Set);ar(this,"statusHandler",null);ar(this,"baseUrl");ar(this,"isReconnecting",!1);ar(this,"connectingPromise",null);ar(this,"lastCloseCode",0);ar(this,"reconnectAttempts",0);ar(this,"manualReconnectScheduled",!1);this.baseUrl=r}getUrl(){const r=localStorage.getItem("openfox_token");if(r){const i=this.baseUrl.includes("?")?"&":"?";return`${this.baseUrl}${i}token=${encodeURIComponent(r)}`}return this.baseUrl}setToken(r){localStorage.setItem("openfox_token",r)}clearToken(){localStorage.removeItem("openfox_token")}hasToken(){return!!localStorage.getItem("openfox_token")}getLastCloseCode(){return this.lastCloseCode}onStatusChange(r){this.statusHandler=r}connect(){var r,i;return((r=this.ws)==null?void 0:r.readyState)===WebSocket.OPEN?Promise.resolve():(this.lastCloseCode=0,this.isReconnecting=!1,this.connectingPromise&&((i=this.ws)==null?void 0:i.readyState)===WebSocket.CONNECTING?this.connectingPromise:(this.connectingPromise=new Promise((s,c)=>{try{const u=this.getUrl();this.ws=new WebSocket(u);const f=setTimeout(()=>{var l;((l=this.ws)==null?void 0:l.readyState)===WebSocket.CONNECTING&&(this.ws.close(),c(new Error("Connection timeout")))},5e3);this.ws.onopen=()=>{var l;clearTimeout(f),this.isReconnecting=!1,this.connectingPromise=null,(l=this.statusHandler)==null||l.call(this,"connected"),s()},this.ws.onclose=l=>{var d,p,g;clearTimeout(f),this.lastCloseCode=l.code,((d=this.ws)==null?void 0:d.readyState)===WebSocket.CONNECTING?(this.connectingPromise=null,(p=this.statusHandler)==null||p.call(this,"disconnected"),c(new Error(`Connection closed: ${l.code}`))):(this.connectingPromise=null,(g=this.statusHandler)==null||g.call(this,"disconnected"),this.attemptReconnect())},this.ws.onerror=l=>{clearTimeout(f),console.error("WebSocket error:",l),this.connectingPromise=null,c(l)},this.ws.onmessage=l=>{try{const d=JSON.parse(l.data);L1(d)&&this.handlers.forEach(p=>p(d))}catch(d){console.error("Failed to parse WebSocket message:",d)}}}catch(u){this.connectingPromise=null,c(u)}}),this.connectingPromise))}attemptReconnect(){var c;if(([1e3,1005,1006,4e3].includes(this.lastCloseCode)||this.lastCloseCode===0)&&this.hasToken()){console.log("[WS] Auth failure or initial failure with token - not auto-reconnecting, awaiting user action");return}if(this.isReconnecting||this.manualReconnectScheduled)return;this.isReconnecting=!0,(c=this.statusHandler)==null||c.call(this,"reconnecting");const s=Math.min(1e3*Math.pow(2,this.reconnectAttempts||0),3e4);this.reconnectAttempts=(this.reconnectAttempts||0)+1,setTimeout(()=>{this.isReconnecting=!1,this.manualReconnectScheduled=!1,this.connect().catch(()=>{})},s)}reconnect(){this.manualReconnectScheduled=!0,this.isReconnecting=!1,this.lastCloseCode=0,this.connectingPromise=null,this.connect().catch(()=>{})}disconnect(){this.isReconnecting=!1,this.reconnectAttempts=0,this.ws&&(this.ws.close(),this.ws=null)}resetReconnectAttempts(){this.reconnectAttempts=0}send(r,i){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");const s=Eb(),c={id:s,type:r,payload:i};return this.ws.send(JSON.stringify(c)),s}subscribe(r){return this.handlers.add(r),()=>this.handlers.delete(r)}get isConnected(){var r;return((r=this.ws)==null?void 0:r.readyState)===WebSocket.OPEN}}const M1=`ws://${window.location.hostname}:${window.location.port||"10469"}/ws`,qt=new O1(M1),di=async(e,r,i)=>{try{const s=await ke(r,{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return s.ok?{success:!0}:{success:!1,error:(await s.json()).error}}catch{return{success:!1,error:"Network error"}}};function jb(e){let r=null;function i(){r===null&&(r=requestAnimationFrame(()=>{r=null,e()}))}return i}let El=[];const cr=Yn()((e,r)=>{function i(){if(El.length===0)return;const c=El;El=[],e(u=>({logs:[...u.logs,...c]}))}const s=jb(i);return{workdir:null,status:null,logs:[],config:null,loading:!1,setWorkdir:c=>{r().workdir!==c&&(e({workdir:c,status:null,logs:[],config:null,loading:!0}),c&&(r().fetchStatus(),r().fetchConfig()))},fetchStatus:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server?workdir=${encodeURIComponent(c)}`)).json();e({status:f,loading:!1})}catch{e({loading:!1})}},fetchConfig:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server/config?workdir=${encodeURIComponent(c)}`)).json();e({config:f.config??null})}catch{}},fetchLogs:async()=>{const c=r().workdir;if(c)try{const l=(await(await ke(`/api/dev-server/logs?workdir=${encodeURIComponent(c)}`)).json()).logs.map(d=>({stream:d.stream,content:d.content}));e({logs:l})}catch{}},start:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server/start?workdir=${encodeURIComponent(c)}`,{method:"POST"})).json();e({status:f,logs:[]})}catch{}},stop:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server/stop?workdir=${encodeURIComponent(c)}`,{method:"POST"})).json();e({status:f})}catch{}},restart:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server/restart?workdir=${encodeURIComponent(c)}`,{method:"POST"})).json();e({status:f,logs:[]})}catch{}},saveConfig:async c=>{const u=r().workdir;if(u)try{const l=await(await ke(`/api/dev-server/config?workdir=${encodeURIComponent(u)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})).json();e({config:l.config??c}),r().fetchStatus()}catch{}},handleMessage:c=>{const u=r().workdir;if(u)switch(c.type){case"devServer.output":{const f=c.payload;if(f.workdir!==u)return;El.push({stream:f.stream,content:f.content}),s();break}case"devServer.state":{const f=c.payload;if(f.workdir!==u)return;e(l=>({status:l.status?{...l.status,state:f.state,errorMessage:f.errorMessage}:l.status}));break}}}}});function I1(e){return{...e.temperature!=null&&{temperature:e.temperature},...e.topP!=null&&{topP:e.topP},...e.topK!=null&&{topK:e.topK},...e.maxTokens!=null&&{maxTokens:e.maxTokens}}}async function Mx(e,r,i){const s=await ke(`/api/providers/${e}/models/${encodeURIComponent(r)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!s.ok){const c=await s.json();throw new Error(c.error??"Failed to update model")}return s.json()}function Ix(e,r,i,s){return e.map(c=>c.id===r?{...c,models:c.models.map(u=>u.id===i?{...u,...s,source:"user"}:u)}:c)}const B1=3e4;function z1(e){switch(e){case"vllm":return"vLLM";case"sglang":return"SGLang";case"ollama":return"Ollama";case"llamacpp":return"llama.cpp";case"openai":return"OpenAI";case"anthropic":return"Anthropic";case"opencode-go":return"OpenCode Go";case"auto":return"Auto";case"unknown":return""}}const At=Yn((e,r)=>({version:null,model:null,maxContext:2e5,llmUrl:null,llmStatus:"unknown",backend:"unknown",providers:[],activeProviderId:null,defaultModelSelection:null,loading:!1,activating:!1,error:null,autoRefreshInterval:null,fetchConfig:async()=>{e({loading:!0,error:null});try{const i=await ke("/api/config");if(!i.ok)throw new Error("Failed to fetch config");const s=await i.json();e({version:s.version,model:s.model,maxContext:s.maxContext,llmUrl:s.llmUrl,llmStatus:s.llmStatus,backend:s.backend,providers:s.providers??[],activeProviderId:s.activeProviderId??null,defaultModelSelection:s.defaultModelSelection??null,loading:!1})}catch(i){e({error:i instanceof Error?i.message:"Unknown error",loading:!1})}},refreshModel:async()=>{try{const i=await ke("/api/model/refresh",{method:"POST"});if(!i.ok)throw new Error("Failed to refresh model");const s=await i.json(),u=Ce.getState().currentSession;if(u!=null&&u.providerId&&u.providerModel){e({llmStatus:s.llmStatus,backend:s.backend});return}e({model:s.model,llmStatus:s.llmStatus,backend:s.backend})}catch(i){console.error("Failed to refresh model:",i)}},activateProvider:async i=>{const{activeProviderId:s,providers:c}=r();if(i===s)return!0;e({activating:!0,error:null});try{const u=await ke(`/api/providers/${i}/activate`,{method:"POST"});if(!u.ok){const l=await u.json();throw new Error(l.error??"Failed to activate provider")}const f=await u.json();return e({activeProviderId:f.activeProviderId,model:f.model,backend:f.backend,providers:c.map(l=>({...l,isActive:l.id===f.activeProviderId})),activating:!1}),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to switch provider",activating:!1}),!1}},syncFromSession:(i,s)=>{const{providers:c}=r();e({activeProviderId:i,model:s,defaultModelSelection:`${i}/${s}`,providers:c.map(u=>({...u,isActive:u.id===i}))})},updateModelContext:async(i,s,c)=>{e({activating:!0,error:null});try{const u=await Mx(i,s,{contextWindow:c}),{providers:f}=r();return e({providers:Ix(f,i,s,{contextWindow:c}),activating:!1}),u.contextState&&Ce.getState().updateContextState(u.contextState),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to update model context",activating:!1}),!1}},updateModelSettings:async(i,s,c)=>{e({activating:!0,error:null});try{const u=await Mx(i,s,c),{providers:f}=r(),l={...c.contextWindow!==void 0&&{contextWindow:c.contextWindow},...I1({temperature:c.temperature??void 0,topP:c.topP??void 0,topK:c.topK??void 0,maxTokens:c.maxTokens??void 0})};return e({providers:Ix(f,i,s,l),activating:!1}),u.contextState&&Ce.getState().updateContextState(u.contextState),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to update model settings",activating:!1}),!1}},refreshProviderModels:async i=>{e({activating:!0,error:null});try{const s=await ke(`/api/providers/${i}/refresh`,{method:"POST"});if(!s.ok){const f=await s.json();throw new Error(f.error??"Failed to refresh models")}const c=await s.json(),{providers:u}=r();return e({providers:u.map(f=>f.id===i?{...f,models:c.models}:f),activating:!1}),!0}catch(s){return e({error:s instanceof Error?s.message:"Failed to refresh models",activating:!1}),!1}},startAutoRefresh:()=>{const{autoRefreshInterval:i,refreshModel:s}=r();if(i)return;const c=setInterval(()=>{s()},B1);e({autoRefreshInterval:c})},stopAutoRefresh:()=>{const{autoRefreshInterval:i}=r();i&&(clearInterval(i),e({autoRefreshInterval:null}))},getActiveProvider:()=>{const{providers:i,activeProviderId:s}=r();return i.find(c=>c.id===s)},getModelContext:i=>{const{providers:s,activeProviderId:c}=r(),u=s.find(l=>l.id===c);if(!u)return 2e5;const f=u.models.find(l=>l.id===i);return(f==null?void 0:f.contextWindow)??2e5}})),Vt=Yn((e,r)=>({projects:[],currentProject:null,loading:!1,listProjects:async()=>{e({loading:!0});try{const s=await(await ke("/api/projects")).json();e({projects:s.projects??[],loading:!1})}catch{e({loading:!1})}},createProject:async(i,s)=>{try{const c=await ke("/api/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:i,workdir:s})});if(!c.ok)return null;const u=await c.json();return await r().listProjects(),u.project}catch{return null}},loadProject:async i=>{try{const s=await ke(`/api/projects/${i}`);if(!s.ok)return null;const c=await s.json();return e({currentProject:c.project}),r().projects.length===0&&await r().listProjects(),c.project}catch{return null}},updateProject:async(i,s)=>{var c;try{const u=await ke(`/api/projects/${i}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!u.ok)return null;const f=await u.json();return((c=r().currentProject)==null?void 0:c.id)===i&&e({currentProject:f.project}),await r().listProjects(),f.project}catch{return null}},deleteProject:async i=>{var s;try{return(await ke(`/api/projects/${i}`,{method:"DELETE"})).ok?(await r().listProjects(),((s=r().currentProject)==null?void 0:s.id)===i&&e({currentProject:null}),!0):!1}catch{return!1}},clearProject:()=>{e({currentProject:null})}}));let jl=[];const Va=Yn()((e,r)=>{function i(){if(jl.length===0)return;const c=jl;jl=[],e(u=>{const f={...u.logs};for(const l of c){const d=f[l.processId]??[];f[l.processId]=[...d,{offset:d.length,content:l.content,timestamp:Date.now(),stream:l.stream}]}return{logs:f}})}const s=jb(i);return{processes:[],logs:{},loading:!1,setProcesses:c=>e({processes:c}),addProcess:c=>e(u=>({processes:[...u.processes,c]})),updateProcess:(c,u)=>e(f=>({processes:f.processes.map(l=>l.id===c?{...l,...u}:l)})),removeProcess:c=>e(u=>({processes:u.processes.filter(f=>f.id!==c),logs:Object.fromEntries(Object.entries(u.logs).filter(([f])=>f!==c))})),stopProcess:async(c,u)=>{try{(await ke(`/api/sessions/${u}/background-process/${c}/stop`,{method:"POST"})).ok&&r().removeProcess(c)}catch{}},appendLog:(c,u,f)=>{jl.push({processId:c,stream:u,content:f}),s()},setLogs:(c,u)=>e(f=>({logs:{...f.logs,[c]:u}})),clearLogs:c=>e(u=>({logs:{...u.logs,[c]:[]}})),handleMessage:(c,u)=>{switch(c){case"backgroundProcess.started":{const{processId:f,name:l,pid:d,status:p}=u;e(g=>({processes:[...g.processes,{id:f,sessionId:"",name:l,command:"",cwd:"",pid:d,status:p,exitCode:null,createdAt:Date.now(),startedAt:Date.now(),endedAt:null}]}));break}case"backgroundProcess.output":{const f=u.processId,l=u.stream,d=u.content;r().appendLog(f,l,d);break}case"backgroundProcess.exited":{const f=u.processId,l=u.exitCode;e(d=>({processes:d.processes.map(p=>p.id===f?{...p,status:"exited",exitCode:l}:p)}));break}case"backgroundProcess.removed":{const f=u.processId;r().removeProcess(f);break}}}}}),Et={GLOBAL_INSTRUCTIONS:"global_instructions",NOTIFICATION_SETTINGS:"notification_settings",DISPLAY_SHOW_THINKING:"display.showThinking",DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT:"display.showVerboseToolOutput",DISPLAY_SHOW_STATS:"display.showStats",DISPLAY_SHOW_AGENT_DEFINITIONS:"display.showAgentDefinitions",DISPLAY_SHOW_WORKFLOW_BARS:"display.showWorkflowBars"};function Nl(e,r){return i=>({loading:{...i.loading,[e]:r}})}function Bx(e,r){return i=>({settings:{...i.settings,[e]:r},loading:{...i.loading,[e]:!1}})}const H1=[Et.DISPLAY_SHOW_THINKING,Et.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT,Et.DISPLAY_SHOW_STATS,Et.DISPLAY_SHOW_AGENT_DEFINITIONS,Et.DISPLAY_SHOW_WORKFLOW_BARS];function Nb(){return{showThinking:en(e=>e.settings[Et.DISPLAY_SHOW_THINKING]??"true")==="true",showVerboseToolOutput:en(e=>e.settings[Et.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT]??"true")==="true",showStats:en(e=>e.settings[Et.DISPLAY_SHOW_STATS]??"true")==="true",showAgentDefinitions:en(e=>e.settings[Et.DISPLAY_SHOW_AGENT_DEFINITIONS]??"true")==="true",showWorkflowBars:en(e=>e.settings[Et.DISPLAY_SHOW_WORKFLOW_BARS]??"true")==="true"}}const en=Yn(e=>({settings:{},loading:{},getSetting:async r=>{e(Nl(r,!0));try{const s=await(await ke(`/api/settings/${r}`)).json();return e(Bx(r,s.value??"")),s.value}catch{return e(Nl(r,!1)),null}},setSetting:async(r,i)=>{e(Nl(r,!0));try{const c=await(await ke(`/api/settings/${r}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:i})})).json();e(Bx(r,c.value??""))}catch{e(Nl(r,!1))}}})),P1=[{key:"complete",label:"Task Complete",description:"When an agent finishes its work"},{key:"waiting_for_user",label:"Waiting for Input",description:"When the agent needs your input"},{key:"phase_done",label:"Phase Done",description:"When a build phase completes successfully"},{key:"phase_blocked",label:"Phase Blocked",description:"When a build phase is blocked and needs intervention"},{key:"new_message",label:"New Message",description:"When a new assistant message starts arriving"}],F1=[{url:"/sounds/notification.mp3",label:"Notification"},{url:"/sounds/waiting-for-user.mp3",label:"Waiting for User"},{url:"/sounds/achievement.mp3",label:"Achievement"},{url:"/sounds/intervention.mp3",label:"Intervention"},{url:"/sounds/typing.mp3",label:"Typing"}],Tb={complete:"/sounds/notification.mp3",waiting_for_user:"/sounds/waiting-for-user.mp3",phase_done:"/sounds/achievement.mp3",phase_blocked:"/sounds/intervention.mp3",new_message:"/sounds/typing.mp3"},ci={soundEnabled:!0,browserNotification:!1,customSoundUrl:null},Ab={soundEnabled:!1,browserNotification:!1,customSoundUrl:null},ch={soundEnabled:!0,browserNotificationEnabled:!1,events:{complete:{...ci},waiting_for_user:{...ci},phase_done:{...ci},phase_blocked:{...ci},new_message:{...Ab}},agentOverrides:{}};function Db(e,r,i){var u;const s=e.events[r];if(!i)return s;const c=(u=e.agentOverrides[i])==null?void 0:u[r];return c?{soundEnabled:c.soundEnabled??s.soundEnabled,browserNotification:c.browserNotification??s.browserNotification,customSoundUrl:c.customSoundUrl!==void 0?c.customSoundUrl:s.customSoundUrl}:s}const Oi=Yn((e,r)=>({settings:ch,loaded:!1,load:()=>{en.getState().getSetting(Et.NOTIFICATION_SETTINGS);const s=en.subscribe(u=>{const f=u.settings[Et.NOTIFICATION_SETTINGS];if(f!==void 0)try{const l=JSON.parse(f);e({settings:zx(l),loaded:!0})}catch{e({loaded:!0})}}),c=en.getState().settings[Et.NOTIFICATION_SETTINGS];if(c)try{const u=JSON.parse(c);e({settings:zx(u),loaded:!0})}catch{e({loaded:!0})}return s},update:i=>{e({settings:i}),Id(i)},updateEvent:(i,s)=>{const c=r().settings,u={...c,events:{...c.events,[i]:{...c.events[i],...s}}};e({settings:u}),Id(u)},updateAgentOverride:(i,s,c)=>{var d;const u=r().settings,f={...u.agentOverrides};if(c===null){if(f[i]){const p={...f[i]};delete p[s],Object.keys(p).length===0?delete f[i]:f[i]=p}}else f[i]={...f[i],[s]:{...((d=f[i])==null?void 0:d[s])??{},...c}};const l={...u,agentOverrides:f};e({settings:l}),Id(l)}}));function Id(e){en.getState().setSetting(Et.NOTIFICATION_SETTINGS,JSON.stringify(e))}function zx(e){var r,i,s,c,u;return{soundEnabled:e.soundEnabled??ch.soundEnabled,browserNotificationEnabled:e.browserNotificationEnabled??ch.browserNotificationEnabled,events:{complete:{...ci,...(r=e.events)==null?void 0:r.complete},waiting_for_user:{...ci,...(i=e.events)==null?void 0:i.waiting_for_user},phase_done:{...ci,...(s=e.events)==null?void 0:s.phase_done},phase_blocked:{...ci,...(c=e.events)==null?void 0:c.phase_blocked},new_message:{...Ab,...(u=e.events)==null?void 0:u.new_message}},agentOverrides:e.agentOverrides??{}}}const Hx=new Map;function U1(e){let r=Hx.get(e);return r||(r=new Audio(e),r.volume=.5,Hx.set(e,r)),r}let Rb=typeof Notification<"u"?Notification.permission:"denied";function $1(){return typeof Notification>"u"?Promise.resolve("denied"):Notification.requestPermission().then(e=>(Rb=e,e))}const q1={complete:"Task Complete",waiting_for_user:"Waiting for Input",phase_done:"Phase Complete",phase_blocked:"Phase Blocked",new_message:"New Message"},W1={complete:"The agent has finished its work.",waiting_for_user:"The agent needs your input to continue.",phase_done:"The build phase completed successfully.",phase_blocked:"The build phase is blocked and needs intervention.",new_message:"A new assistant message is arriving."};function G1(e){typeof Notification>"u"||Rb==="granted"&&(document.hasFocus()||new Notification(q1[e],{body:W1[e],icon:"/fox.svg",tag:`openfox-${e}`}))}function oo(e,r){const{settings:i}=Oi.getState(),s=Db(i,e,r);if(i.soundEnabled&&s.soundEnabled){const c=s.customSoundUrl??Tb[e],u=U1(c);u.currentTime=0,u.play().catch(()=>{})}i.browserNotificationEnabled&&s.browserNotification&&G1(e)}const V1=e=>oo("complete",e),K1=e=>oo("phase_done",e),Y1=e=>oo("phase_blocked",e),Px=e=>oo("waiting_for_user",e),X1=e=>oo("new_message",e);let Ma=!1,or=null;const Bd=new Set,$t={messageId:null,deltaContent:"",thinkingContent:"",toolOutput:[]};let Ms=null,un=null;function zd(){Ms===null&&(Ms=requestAnimationFrame(()=>{Ms=null,un==null||un()}))}function Ai(){Ms!==null&&(cancelAnimationFrame(Ms),Ms=null)}function zt(e,r){return r!==null&&e.sessionId===r}function Z1(e,r,i){return e.id!==void 0||zt(e,r)||i===!0&&e.sessionId!==void 0}function Q1(e,r){return e.includes(r)?e:[...e,r]}function Ia(e,r){return e.filter(i=>i!==r)}function J1(e,r){const i=e.find(c=>c.id===r.id),s=i?{...i,projectId:r.projectId,workdir:r.workdir,mode:r.mode,phase:r.phase,isRunning:r.isRunning,messageCount:r.messages.length,criteriaCount:r.criteria.length,criteriaCompleted:r.criteria.filter(c=>c.status.type==="passed").length}:{id:r.id,projectId:r.projectId,workdir:r.workdir,mode:r.mode,phase:r.phase,isRunning:r.isRunning,createdAt:"",updatedAt:"",criteriaCount:r.criteria.length,criteriaCompleted:r.criteria.filter(c=>c.status.type==="passed").length,messageCount:r.messages.length};return i?e.map(c=>c.id===r.id?s:c):[s,...e]}function ew(e,r,i){return e.map(s=>{const c=(i==null?void 0:i.id)===s.id?i:null,u=r.find(f=>f.id===s.id);return{...s,title:s.title??(u==null?void 0:u.title),mode:(c==null?void 0:c.mode)??(u==null?void 0:u.mode)??s.mode,phase:(c==null?void 0:c.phase)??(u==null?void 0:u.phase)??s.phase,isRunning:(c==null?void 0:c.isRunning)??(u==null?void 0:u.isRunning)??s.isRunning,messageCount:s.messageCount,recentUserPrompts:s.recentUserPrompts}})}const Fx=new Map;function Wa(e,r){var u;const i=r===((u=e.currentSession)==null?void 0:u.id)?e.currentSession:null,s=e.sessions.find(f=>f.id===r),c=(i==null?void 0:i.mode)??(s==null?void 0:s.mode);return c==="planner"?"planner":c==="builder"?"build":"planner"}function tw(e,r){if(e.type==="chat.done"){const i=e.payload,s=Wa(r,e.sessionId),c=i.agentType??s;i.reason==="complete"&&V1(c),i.reason==="waiting_for_user"&&Px(c);return}if(e.type==="chat.path_confirmation"){const i=Wa(r,e.sessionId);Px(i);return}if(e.type==="task.completed"){const i=Wa(r,e.sessionId);K1(i);return}if(e.type==="phase.changed"&&e.sessionId){const i=e.payload,s=Fx.get(e.sessionId)??null;if(Fx.set(e.sessionId,i.phase),s===i.phase)return;const c=Wa(r,e.sessionId);i.phase==="blocked"&&Y1(c)}}const Ce=Yn((e,r)=>(un=()=>{const i=$t;if(!i.messageId)return;const s=i.deltaContent.length>0,c=i.thinkingContent.length>0,u=i.toolOutput.length>0;if(!s&&!c&&!u)return;const f=i.deltaContent,l=i.thinkingContent,d=i.toolOutput;i.deltaContent="",i.thinkingContent="",i.toolOutput=[],e(p=>{var m;const g=p.streamingMessage;if(g&&g.id===i.messageId){let b={...g};if(s&&(b.content=b.content+f),c&&(b.thinkingContent=(b.thinkingContent??"")+l),u){const _=new Set;b.toolCalls=(m=b.toolCalls)==null?void 0:m.map(C=>{const y=d.filter(x=>x.callId===C.id);return y.length===0?C:(_.add(C.id),{...C,streamingOutput:[...C.streamingOutput??[],...y.map(x=>({stream:x.stream,content:x.content}))]})});const k=d.filter(C=>!_.has(C.callId));k.length>0&&$t.toolOutput.push(...k)}return{streamingMessage:b}}if(u){const b=new Set,_=p.messages.map(C=>{var x;if(C.id!==i.messageId)return C;const y=(x=C.toolCalls)==null?void 0:x.map(v=>{const S=d.filter(j=>j.callId===v.id);return S.length===0?v:(b.add(v.id),{...v,streamingOutput:[...v.streamingOutput??[],...S.map(j=>({stream:j.stream,content:j.content}))]})});return{...C,toolCalls:y}}),k=d.filter(C=>!b.has(C.callId));return k.length>0&&$t.toolOutput.push(...k),{messages:_}}return p})},{connectionStatus:"disconnected",showPasswordModal:!1,passwordModalRetry:!1,sessions:[],currentSession:null,unreadSessionIds:[],messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,subAgentContextStates:{},pendingPathConfirmation:null,pendingQuestion:null,visionFallbackByMessage:{},queuedMessages:[],abortInProgress:!1,error:null,sessionsHasMore:!0,sessionsPaginationLoading:!1,pendingSessionCreate:!1,connect:async()=>{const i=r().connectionStatus;if(i==="connected"||i==="reconnecting")return;e({connectionStatus:"reconnecting"});let s=!1;try{s=(await(await ke("/api/auth")).json()).requiresAuth}catch{}if(s&&!qt.hasToken()){e({showPasswordModal:!0,passwordModalRetry:!1,connectionStatus:"reconnecting"});return}qt.onStatusChange(c=>{e({connectionStatus:c}),c==="connected"&&r().listSessions(void 0)});try{if(await qt.connect(),!Ma){Ma=!0;const c=r().handleServerMessage;or=qt.subscribe(c)}}catch(c){console.error("Failed to connect:",c);const u=qt.getLastCloseCode();if(!qt.hasToken()&&(u===1006||u===4e3)){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}or&&(or(),or=null),Ma=!1,e({connectionStatus:"disconnected"})}},reconnect:()=>{qt.disconnect(),or&&(or(),or=null),Ma=!1,e({connectionStatus:"reconnecting"}),r().connect()},disconnect:()=>{qt.disconnect(),or&&(or(),or=null),Ma=!1,e({connectionStatus:"disconnected",showPasswordModal:!1})},submitPassword:async i=>{try{const s=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})});if(!s.ok){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}const{token:c}=await s.json();qt.setToken(c),e({showPasswordModal:!1}),r().connect();const{listProjects:u}=Vt.getState(),{fetchConfig:f}=At.getState();u(),f(),r().connect()}catch{e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"})}},cancelPassword:()=>{qt.clearToken(),e({showPasswordModal:!1,connectionStatus:"disconnected"})},createSession:async(i,s)=>{try{e({pendingSessionCreate:!0});const c=await ke("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectId:i,title:s})});if(!c.ok)return e({pendingSessionCreate:!1}),null;const u=await c.json();return qt.send("session.load",{sessionId:u.session.id}),u.session}catch{return e({pendingSessionCreate:!1}),null}},loadSession:async i=>{try{const s=r().currentSession;!s||s.id!==i?(Ai(),e({currentSession:null,unreadSessionIds:Ia(r().unreadSessionIds,i),subAgentContextStates:{},messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,pendingPathConfirmation:null,queuedMessages:[],abortInProgress:!1,error:null})):e({unreadSessionIds:Ia(r().unreadSessionIds,i)});const c=await ke(`/api/sessions/${i}`);if(!c.ok)return;const u=await c.json();e({currentSession:u.session,messages:u.messages??[],contextState:u.contextState,queuedMessages:u.queueState??[]}),qt.send("session.load",{sessionId:i});try{const f=await ke(`/api/sessions/${i}/background-processes`);if(f.ok){const l=await f.json();Va.getState().setProcesses(l.processes??[])}}catch{}}catch{}},listSessions:async(i,s=20)=>{try{const c=new URLSearchParams;c.set("limit",String(s)),i&&c.set("projectId",i);const f=await(await ke(`/api/sessions?${c.toString()}`)).json();e({sessions:f.sessions??[],sessionsHasMore:i?f.hasMore??!1:!0})}catch{}},loadMoreSessions:async i=>{const s=r();if(!(s.sessionsPaginationLoading||!s.sessionsHasMore)){e({sessionsPaginationLoading:!0});try{const c=new URLSearchParams;c.set("limit","20"),c.set("offset",String(s.sessions.length)),c.set("projectId",i);const f=await(await ke(`/api/sessions?${c.toString()}`)).json();e(l=>({sessions:[...l.sessions,...f.sessions??[]],sessionsHasMore:f.hasMore??!1,sessionsPaginationLoading:!1}))}catch{e({sessionsPaginationLoading:!1})}}},deleteSession:async i=>{var s;try{return(await ke(`/api/sessions/${i}`,{method:"DELETE"})).ok?(await r().listSessions(),((s=r().currentSession)==null?void 0:s.id)===i&&r().clearSession(),!0):!1}catch{return!1}},deleteAllSessions:async i=>{try{return(await ke(`/api/projects/${i}/sessions`,{method:"DELETE"})).ok?(await r().listSessions(),!0):!1}catch{return!1}},clearSession:()=>{Ai(),e(i=>({currentSession:null,messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,unreadSessionIds:i.currentSession?Ia(i.unreadSessionIds,i.currentSession.id):i.unreadSessionIds}))},sendMessage:async(i,s,c)=>{var f;const u=(f=r().currentSession)==null?void 0:f.id;if(u){e({streamingMessageId:null});try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:i,attachments:s,messageKind:c==null?void 0:c.messageKind})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(l){console.error("Error sending message:",l)}}},stopGeneration:async()=>{var s;const i=(s=r().currentSession)==null?void 0:s.id;if(i&&!r().abortInProgress){Ai(),un==null||un(),e({abortInProgress:!0});try{await ke(`/api/sessions/${i}/stop`,{method:"POST"})}catch(c){console.error("Error stopping generation:",c)}}},continueGeneration:async()=>{var s;const i=(s=r().currentSession)==null?void 0:s.id;if(i){e({streamingMessageId:null});try{await ke(`/api/sessions/${i}/continue`,{method:"POST"})}catch(c){console.error("Error continuing generation:",c)}}},launchRunner:(i,s,c)=>{e({streamingMessageId:null});const u={};i!=null&&i.trim()&&(u.content=i),s&&s.length>0&&(u.attachments=s),c&&(u.workflowId=c),qt.send("runner.launch",u)},switchMode:async i=>{var c;const s=(c=r().currentSession)==null?void 0:c.id;if(s)try{const u=await ke(`/api/sessions/${s}/mode`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:i})});if(!u.ok){console.error("Failed to switch mode:",await u.json());return}const f=await u.json();f.session&&e({currentSession:f.session})}catch(u){console.error("Error switching mode:",u)}},switchDangerLevel:async i=>{var c;const s=(c=r().currentSession)==null?void 0:c.id;if(s)try{const u=await ke(`/api/sessions/${s}/danger-level`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({dangerLevel:i})});if(!u.ok){console.error("Failed to switch danger level:",await u.json());return}const f=await u.json();f.session&&e({currentSession:f.session})}catch(u){console.error("Error switching danger level:",u)}},acceptAndBuild:(i,s,c)=>{e({streamingMessageId:null});const u={};i&&(u.workflowId=i),s!=null&&s.trim()&&(u.content=s),c&&c.length>0&&(u.attachments=c),qt.send("mode.accept",u)},editCriteria:async i=>{var c;const s=(c=r().currentSession)==null?void 0:c.id;if(s)try{const u=await ke(`/api/sessions/${s}/criteria`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({criteria:i})});u.ok||console.error("Failed to update criteria:",await u.json())}catch(u){console.error("Error updating criteria:",u)}},compactContext:()=>{qt.send("context.compact",{})},setSessionProvider:async(i,s)=>{var c;try{const u=(c=r().currentSession)==null?void 0:c.id;if(!u)return null;const f=await ke(`/api/sessions/${u}/provider`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerId:i,...s?{model:s}:{}})});if(!f.ok)return null;const l=await f.json();return e({currentSession:l.session,messages:l.messages??[],contextState:l.contextState}),l.session}catch{return null}},updateContextState:i=>{e({contextState:i})},updateSubAgentContextState:(i,s)=>{e(c=>({subAgentContextStates:{...c.subAgentContextStates,[i]:s}}))},clearSubAgentContextState:i=>{e(s=>{const c={...s.subAgentContextStates};return delete c[i],{subAgentContextStates:c}})},confirmPath:async(i,s,c=!1)=>{var f;const u=(f=r().currentSession)==null?void 0:f.id;if(u)try{await ke(`/api/sessions/${u}/confirm-path`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:i,approved:s,alwaysAllow:c})})}catch(l){console.error("Error confirming path:",l)}},answerQuestion:async(i,s)=>{var u;const c=(u=r().currentSession)==null?void 0:u.id;if(c){try{await ke(`/api/sessions/${c}/answer`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:i,answer:s})})}catch(f){console.error("Error answering question:",f)}e({pendingQuestion:null})}},queueAsap:async(i,s,c)=>{var f;const u=(f=r().currentSession)==null?void 0:f.id;if(u)try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:i,attachments:s,messageKind:c})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(l){console.error("Error queueing ASAP message:",l)}},queueCompletion:async(i,s,c)=>{var f;const u=(f=r().currentSession)==null?void 0:f.id;if(u)try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:i,attachments:s,messageKind:c})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(l){console.error("Error queueing completion message:",l)}},cancelQueued:async i=>{var c;const s=(c=r().currentSession)==null?void 0:c.id;if(s)try{const f=await(await ke(`/api/sessions/${s}/queue/${i}`,{method:"DELETE"})).json();f.queueState&&e({queuedMessages:f.queueState})}catch(u){console.error("Error canceling queued message:",u)}},clearError:()=>{e({error:null})},resetPendingSessionCreate:()=>{e({pendingSessionCreate:!1})},handleServerMessage:i=>{var f,l,d,p,g,m,b,_,k,C,y,x,v,S,j,T,N,D,A,M,B,$,V,W;const s=r();tw(i,s);const c=((f=s.currentSession)==null?void 0:f.id)??null,u=()=>{const O=i.sessionId;!O||O===c||e(F=>({unreadSessionIds:Q1(F.unreadSessionIds,O)}))};switch(i.type){case"session.state":{const O=i.payload;if(!Z1(i,c,s.pendingSessionCreate))break;Ai();const F=O.messages.find(R=>R.isStreaming)??null,P=r().pendingSessionCreate===!0,Z=O.pendingConfirmations??[],I=s.pendingPathConfirmation??(Z.length>0?Z[0]??null:null);if(e({currentSession:O.session,sessions:J1(r().sessions,O.session),unreadSessionIds:Ia(r().unreadSessionIds,O.session.id),messages:O.messages,streamingMessageId:(F==null?void 0:F.id)??null,streamingMessage:F,currentTodos:[],pendingPathConfirmation:I,error:null,...P?{pendingSessionCreate:O.session.id}:{}}),O.session.providerId&&O.session.providerModel){const R=At.getState();R.providers.find(Y=>Y.id===O.session.providerId)&&R.syncFromSession(O.session.providerId,O.session.providerModel)}break}case"session.list":{const O=i.payload;e(F=>({sessions:ew(O.sessions,F.sessions,F.currentSession)}));break}case"session.deleted":{const O=i.payload;e(F=>({unreadSessionIds:Ia(F.unreadSessionIds,O.sessionId)})),r().listSessions();break}case"session.deletedAll":{r().listSessions();break}case"session.running":{const O=i.payload,F=i.sessionId,P=(l=r().currentSession)==null?void 0:l.id,Z=F&&F!==P;e(G=>({sessions:G.sessions.map(I=>I.id===F?{...I,isRunning:O.isRunning}:I)})),Z||e(G=>({currentSession:G.currentSession?{...G.currentSession,isRunning:O.isRunning}:null,...O.isRunning?{}:{abortInProgress:!1,queuedMessages:[]}}));break}case"chat.message":{if(!zt(i,((d=r().currentSession)==null?void 0:d.id)??null)){u();break}const O=i.payload;e(F=>F.messages.some(P=>P.id===O.message.id)?F:{messages:[...F.messages,O.message],streamingMessageId:O.message.isStreaming?O.message.id:F.streamingMessageId,streamingMessage:O.message.isStreaming?O.message:F.streamingMessage});break}case"chat.message_updated":{if(!zt(i,((p=r().currentSession)==null?void 0:p.id)??null)){u();break}const O=i.payload,F=O.updates.isStreaming===!1&&r().streamingMessageId===O.messageId;F&&(Ai(),un==null||un()),e(P=>{const Z=P.streamingMessage,G=F;if(Z&&Z.id===O.messageId){const I={...Z,...O.updates};return{messages:P.messages.map(R=>R.id===O.messageId?I:R),streamingMessageId:G?null:P.streamingMessageId,streamingMessage:G?null:{...Z,...O.updates}}}return{messages:P.messages.map(I=>I.id===O.messageId?{...I,...O.updates}:I),streamingMessageId:G?null:P.streamingMessageId}});break}case"chat.delta":{if(!zt(i,((g=r().currentSession)==null?void 0:g.id)??null)){u();break}const O=i.payload;if(!Bd.has(O.messageId)){Bd.add(O.messageId);const F=Wa(r(),i.sessionId);X1(F)}$t.messageId=O.messageId,$t.deltaContent+=O.content,zd();break}case"chat.thinking":{if(!zt(i,((m=r().currentSession)==null?void 0:m.id)??null)){u();break}const O=i.payload;$t.messageId=O.messageId,$t.thinkingContent+=O.content,zd();break}case"chat.tool_preparing":{if(!zt(i,((b=r().currentSession)==null?void 0:b.id)??null)){u();break}const O=i.payload;e(F=>{const P=F.streamingMessage;return P&&P.id===O.messageId?{streamingMessage:{...P,preparingToolCalls:[...P.preparingToolCalls??[],{index:O.index,name:O.name}]}}:{messages:F.messages.map(Z=>Z.id===O.messageId?{...Z,preparingToolCalls:[...Z.preparingToolCalls??[],{index:O.index,name:O.name}]}:Z)}});break}case"chat.tool_call":{if(!zt(i,((_=r().currentSession)==null?void 0:_.id)??null)){u();break}const O=i.payload,F=P=>{var I;const Z=(I=P.preparingToolCalls)==null?void 0:I.filter((R,z)=>{var Y;return R.name===O.tool?(Y=P.preparingToolCalls)==null?void 0:Y.slice(0,z).some(ie=>ie.name===O.tool):!0}),G=$t.toolOutput.filter(R=>R.callId===O.callId);return G.length>0&&($t.toolOutput=$t.toolOutput.filter(R=>R.callId!==O.callId)),{...P,toolCalls:[...P.toolCalls??[],{id:O.callId,name:O.tool,arguments:O.args,startedAt:Date.now(),...G.length>0?{streamingOutput:G.map(R=>({stream:R.stream,content:R.content}))}:{}}],...Z&&Z.length>0?{preparingToolCalls:Z}:{preparingToolCalls:void 0}}};e(P=>{const Z=P.streamingMessage;return Z&&Z.id===O.messageId?{streamingMessage:F(Z)}:{messages:P.messages.map(G=>G.id===O.messageId?F(G):G)}});break}case"chat.tool_output":{if(!zt(i,((k=r().currentSession)==null?void 0:k.id)??null)){u();break}const O=i.payload;$t.messageId=O.messageId,$t.toolOutput.push({messageId:O.messageId,callId:O.callId,stream:O.stream,content:O.output}),zd();break}case"chat.tool_result":{if(!zt(i,((C=r().currentSession)==null?void 0:C.id)??null)){u();break}const O=i.payload,F=P=>{var G;const Z=(G=P.toolCalls)==null?void 0:G.map(I=>I.id===O.callId?{...I,result:O.result}:I);return{...P,toolCalls:Z}};e(P=>{const Z=P.streamingMessage;return Z&&Z.id===O.messageId?{streamingMessage:F(Z)}:{messages:P.messages.map(G=>G.id===O.messageId?F(G):G)}});break}case"chat.vision_fallback":{if(!zt(i,((y=r().currentSession)==null?void 0:y.id)??null)){u();break}const O=i.payload;e(F=>{const P=`${O.messageId}-${O.attachmentId}`,Z={...F.visionFallbackByMessage};return Z[P]={type:O.type,attachmentId:O.attachmentId,filename:O.filename,description:O.description},{visionFallbackByMessage:Z}});break}case"chat.todo":{if(!zt(i,((x=r().currentSession)==null?void 0:x.id)??null)){u();break}const O=i.payload;e({currentTodos:O.todos});break}case"chat.summary":{if(!zt(i,((v=r().currentSession)==null?void 0:v.id)??null)){u();break}const O=i.payload;e(F=>({currentSession:F.currentSession?{...F.currentSession,summary:O.summary}:null}));break}case"chat.progress":{if(!zt(i,((S=r().currentSession)==null?void 0:S.id)??null)){u();break}const O=i.payload;console.log("Progress:",O.message,O.phase);break}case"chat.format_retry":{if(!zt(i,((j=r().currentSession)==null?void 0:j.id)??null)){u();break}const O=i.payload;console.log("Format retry:",O.attempt,"/",O.maxAttempts);break}case"chat.done":{if(!zt(i,((T=r().currentSession)==null?void 0:T.id)??null)){u();break}Ai(),un==null||un();const O=i.payload,F=O.stats;$t.messageId=null,$t.deltaContent="",$t.thinkingContent="",$t.toolOutput=[],Bd.delete(O.messageId),e(P=>{const Z=P.streamingMessage,G=Z&&Z.id===O.messageId?{...Z,isStreaming:!1,stats:F??Z.stats}:null;return{messages:P.messages.map(I=>I.id===O.messageId?G??{...I,isStreaming:!1,stats:F??I.stats}:I),streamingMessageId:null,streamingMessage:null,visionFallbackByMessage:{}}});break}case"chat.error":{if(!zt(i,((N=r().currentSession)==null?void 0:N.id)??null)){u();break}Ai(),un==null||un();const O=i.payload;console.error("Chat error:",O.error,"recoverable:",O.recoverable),O.recoverable||($t.messageId=null,$t.deltaContent="",$t.thinkingContent="",$t.toolOutput=[]),e(F=>({error:{code:"CHAT_ERROR",message:O.error},streamingMessageId:O.recoverable?F.streamingMessageId:null,...O.recoverable?{}:{messages:F.streamingMessage?F.messages.map(P=>P.id===F.streamingMessage.id?F.streamingMessage:P):F.messages,streamingMessage:null}}));break}case"chat.path_confirmation":{if(!zt(i,((D=r().currentSession)==null?void 0:D.id)??null)){u();break}const O=i.payload;e({pendingPathConfirmation:{callId:O.callId,tool:O.tool,paths:O.paths,workdir:O.workdir,reason:O.reason}});break}case"chat.ask_user":{if(!zt(i,((A=r().currentSession)==null?void 0:A.id)??null)){u();return}const O=i.payload;e({pendingQuestion:{callId:O.callId,question:O.question}});break}case"mode.changed":{if(!zt(i,((M=r().currentSession)==null?void 0:M.id)??null)){u();break}const O=i.payload;e(F=>({currentSession:F.currentSession?{...F.currentSession,mode:O.mode}:null}));break}case"phase.changed":{const O=i.payload,F=i.sessionId,P=(B=r().currentSession)==null?void 0:B.id,Z=F&&F!==P;e(G=>({sessions:G.sessions.map(I=>I.id===F?{...I,phase:O.phase}:I)})),Z||e(G=>({currentSession:G.currentSession?{...G.currentSession,phase:O.phase}:null}));break}case"criteria.updated":{if(!zt(i,(($=r().currentSession)==null?void 0:$.id)??null)){u();break}const O=i.payload;e(F=>({currentSession:F.currentSession?{...F.currentSession,criteria:O.criteria}:null}));break}case"context.state":{const O=i.payload,F=zt(i,((V=r().currentSession)==null?void 0:V.id)??null);O.subAgentId?F&&r().updateSubAgentContextState(O.subAgentId,O.context):F?e({contextState:O.context}):u();break}case"session.name_generated":{const O=i.payload,F=i.sessionId,P=(W=r().currentSession)==null?void 0:W.id;e(Z=>{const G=Z.sessions.map(R=>R.id===F?{...R,title:O.name,updatedAt:new Date().toISOString()}:R),I=P===F?Z.currentSession?{...Z.currentSession,title:O.name,updatedAt:new Date().toISOString()}:null:Z.currentSession;return{sessions:G,currentSession:I}});break}case"queue.state":{const O=i.payload;e({queuedMessages:O.messages});break}case"devServer.output":case"devServer.state":{cr.getState().handleMessage(i);break}case"backgroundProcess.started":case"backgroundProcess.output":case"backgroundProcess.exited":case"backgroundProcess.removed":{Va.getState().handleMessage(i.type,i.payload);break}case"error":{const O=i.payload;console.error("Server error:",O),e({error:{code:O.code,message:O.message},streamingMessageId:null});break}}}}));function Lb(){return Ce(e=>{var r;return((r=e.currentSession)==null?void 0:r.isRunning)??!1})}function nw(){return Ce(e=>e.queuedMessages)}function rw(){return Ce(e=>e.abortInProgress)}function iw(){const e=Ce(s=>s.connect),r=Ce(s=>s.connectionStatus),i=Oi(s=>s.load);return H.useEffect(()=>{e()},[e]),H.useEffect(()=>{r==="connected"&&i()},[r,i]),{connectionStatus:r}}function sw({className:e="w-5 h-5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}function Ob({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M14 5l7 7m0 0l-7 7m7-7H3"})})}function aw({className:e="w-5 h-5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"})})}function ow({className:e="w-3 h-3 text-text-muted"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"})})}function lw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M9.5 3.25a2.25 2.25 0 1 1 3 2.122V6A2.5 2.5 0 0 1 10 8.5H6a1 1 0 0 0-1 1v1.128a2.251 2.251 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.5 0v1.836A2.493 2.493 0 0 1 6 7h4a1 1 0 0 0 1-1v-.628A2.25 2.25 0 0 1 9.5 3.25Zm-6 0a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Zm8.25-.75a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM4.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z"})})}function Mr({className:e="w-3.5 h-3.5 text-text-muted"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})}function ur({className:e="w-3 h-3 text-text-muted",rotate:r}){return o.jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:r!==void 0?{transform:`rotate(${r}deg)`}:void 0,children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"})})}function cw({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",strokeWidth:"2"}),o.jsx("path",{d:"M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1",strokeWidth:"2"})]})}function Jl({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})}function uw({className:e="w-3 h-3"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})})}function Dh({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,fill:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("circle",{cx:"12",cy:"5",r:"2"}),o.jsx("circle",{cx:"12",cy:"12",r:"2"}),o.jsx("circle",{cx:"12",cy:"19",r:"2"})]})}function ec({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})})}function Fl({className:e="w-5 h-5 text-accent-primary"}){return o.jsx("svg",{className:e,fill:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{d:"M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"})})}function dw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 9V4.5M9 9H4.5M9 9L3.75 3.75M9 15v4.5M9 15H4.5M9 15l-5.25 5.25M15 9h4.5M15 9V4.5M15 9l5.25-5.25M15 15h4.5M15 15v4.5m0-4.5l5.25 5.25"})})}function hw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"})})}function fw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M8 0a8.2 8.2 0 0 1 .701.031C9.444.095 9.99.645 10.16 1.29l.288 1.107c.018.066.079.158.212.224.231.114.454.243.668.386.123.082.233.09.299.071l1.1-.303c.652-.18 1.37.008 1.755.653a8.043 8.043 0 0 1 .683 1.18c.227.568.096 1.26-.378 1.726l-.812.804a.312.312 0 0 0-.081.283c.024.166.04.335.04.507s-.016.341-.04.507a.312.312 0 0 0 .08.283l.813.804c.474.466.605 1.158.378 1.726a8.07 8.07 0 0 1-.683 1.18c-.385.645-1.103.833-1.755.653l-1.1-.303c-.066-.019-.176-.011-.299.071a5.1 5.1 0 0 1-.668.386c-.133.066-.194.158-.211.224l-.29 1.107c-.168.645-.714 1.196-1.458 1.26a8.094 8.094 0 0 1-1.402 0c-.744-.064-1.29-.615-1.458-1.26l-.29-1.107a.426.426 0 0 0-.211-.224 5.11 5.11 0 0 1-.668-.386c-.123-.082-.233-.09-.299-.071l-1.1.303c-.652.18-1.37-.008-1.755-.653a8.044 8.044 0 0 1-.683-1.18c-.227-.568-.096-1.26.378-1.726l.812-.804a.312.312 0 0 0 .081-.283A5.18 5.18 0 0 1 2.3 8c0-.172.016-.341.04-.507a.312.312 0 0 0-.08-.283l-.813-.804C.973 5.94.842 5.248 1.069 4.68c.181-.452.395-.882.683-1.18.385-.645 1.103-.833 1.755-.653l1.1.303c.066.019.176.011.299-.071.214-.143.437-.272.668-.386a.426.426 0 0 0 .211-.224l.29-1.107C6.009.645 6.556.095 7.299.03 7.53.01 7.764 0 8 0Zm0 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5Z"})})}function pw({className:e="w-3 h-3"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}function mw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"})})}function Ux({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})})}function gw({className:e="w-[18px] h-[18px]"}){return o.jsxs("svg",{className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[o.jsx("circle",{cx:"12",cy:"5",r:"1.5",fill:"currentColor",stroke:"none"}),o.jsx("circle",{cx:"12",cy:"12",r:"1.5",fill:"currentColor",stroke:"none"}),o.jsx("circle",{cx:"12",cy:"19",r:"1.5",fill:"currentColor",stroke:"none"})]})}function xw({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("path",{d:"M6.5 3.5H3a1 1 0 0 0-1 1V13a1 1 0 0 0 1 1h8.5a1 1 0 0 0 1-1V9.5"}),o.jsx("path",{d:"M9.5 2h4.5v4.5"}),o.jsx("path",{d:"M14 2L7.5 8.5"})]})}function vw({className:e="w-3 h-3",color:r}){return o.jsx("svg",{className:e,fill:r??"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{d:"M8 5v14l11-7z"})})}function Mb({className:e="w-3 h-3 text-accent-primary"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}function Ib({className:e="",size:r="md"}){const i=r==="sm"?"w-4 h-4":"w-6 h-6";return o.jsxs("svg",{className:`animate-spin ${i} ${e}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),o.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]})}const Bb=Ib,zb=Ib;function bw({className:e="w-5 h-5"}){return o.jsx("svg",{className:e,viewBox:"0 0 20 20",fill:"currentColor",children:o.jsx("path",{fillRule:"evenodd",d:"M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z",clipRule:"evenodd"})})}function yw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}function _w({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]})}function Sw({className:e="w-3 h-3 text-blue-400 animate-spin flex-shrink-0"}){return o.jsxs("svg",{"aria-label":"Session running",className:e,viewBox:"0 0 24 24",fill:"none",children:[o.jsx("title",{children:"Running"}),o.jsx("circle",{className:"opacity-30",cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"3"}),o.jsx("path",{d:"M21 12a9 9 0 00-9-9",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round"})]})}function ww({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("rect",{x:"3",y:"3",width:"10",height:"10",rx:"1"})})}function Cw({className:e="w-3.5 h-3.5 shrink-0",color:r}){return o.jsx("svg",{className:e,fill:"none",stroke:r,viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})})}function kw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 20 20",fill:"currentColor",children:o.jsx("path",{fillRule:"evenodd",d:"M2 5a2 2 0 012-2h12a2 2 0 012 2v10a2 2 0 01-2 2H4a2 2 0 01-2-2V5zm3 1h10v1H5V6zm10 7H5v1h10v-1zm-10 2H5v1h10v-1z",clipRule:"evenodd"})})}function Hb({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})})}function Ew({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}function Pb({className:e="w-2.5 h-2.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}function jw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 20 20",fill:"currentColor",children:o.jsx("path",{fillRule:"evenodd",d:"M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z",clipRule:"evenodd"})})}function Nw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.55.55 0 0 1 0-.708z"})})}function uh(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const r=Math.random()*16|0;return(e==="x"?r:r&3|8).toString(16)})}function $x(e,r){const i=qt.ws;!i||i.readyState!==WebSocket.OPEN||i.send(JSON.stringify({id:uh(),type:e,payload:r}))}const Jn=Yn((e,r)=>({isOpen:!1,sessions:[],workdir:null,setOpen:i=>e({isOpen:i}),toggleOpen:()=>e(i=>({isOpen:!i.isOpen})),setWorkdir:i=>e({workdir:i}),fetchSessions:async()=>{try{const i=await ke("/api/terminals");if(i.ok){const s=await i.json();e({sessions:s});const c=qt.ws;if(c&&c.readyState===WebSocket.OPEN)for(const u of s)c.send(JSON.stringify({id:uh(),type:"terminal.subscribe",payload:{sessionId:u.id}}))}}catch(i){console.error("Failed to fetch terminals:",i)}},createSession:async i=>{try{const s=await ke("/api/terminals",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workdir:i??r().workdir??void 0})});if(s.ok){const c=await s.json();e(f=>({sessions:[...f.sessions,c]}));const u=qt.ws;u&&u.readyState===WebSocket.OPEN&&u.send(JSON.stringify({id:uh(),type:"terminal.subscribe",payload:{sessionId:c.id}}))}}catch(s){console.error("Failed to create terminal:",s)}},writeSession:(i,s)=>{$x("terminal.write",{sessionId:i,data:s})},resizeSession:(i,s,c)=>{$x("terminal.resize",{sessionId:i,cols:s,rows:c})},killSession:async i=>{try{(await ke(`/api/terminals/${i}`,{method:"DELETE"})).ok&&e(c=>({sessions:c.sessions.filter(u=>u.id!==i)}))}catch(s){console.error("Failed to kill terminal:",s)}},handleMessage:i=>{switch(i.type){case"terminal.exit":{const{sessionId:s}=i.payload||{};s&&e(c=>{const u=c.sessions.filter(f=>f.id!==s);return u.length===0&&c.isOpen?{sessions:[],isOpen:!1}:{sessions:u}});break}}}}));qt.subscribe(e=>{var r;(r=e.type)!=null&&r.startsWith("terminal.")&&Jn.getState().handleMessage(e)});var tc=xb();const nc=H.forwardRef(({icon:e,iconSize:r="w-3.5 h-3.5",className:i="",...s},c)=>o.jsx("button",{ref:c,type:"button",className:`p-1 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors ${i}`,...s,children:o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:e})})}));nc.displayName="IconButton";const Tw="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z",Hs=H.forwardRef((e,r)=>o.jsx(nc,{ref:r,icon:Tw,title:"Edit",...e}));Hs.displayName="EditButton";const Aw="M6 18L18 6M6 6l12 12",Rh=H.forwardRef((e,r)=>o.jsx(nc,{ref:r,icon:Aw,...e}));Rh.displayName="CloseButton";const Dw={sm:"max-w-sm",md:"max-w-md",lg:"max-w-2xl",xl:"max-w-4xl",full:"max-w-[95vw] h-[90vh] flex-1"};function jt({label:e,title:r,size:i="md",minHeight:s,children:c,footer:u,className:f,onClose:l,isOpen:d,closeOnBackdropClick:p=!0,closeOnEscape:g=!0,showCloseButton:m=!0}){const[b,_]=H.useState(!1),k=d!==void 0,C=k?d:b,y=H.useCallback(()=>{k||_(!0)},[k]),x=H.useCallback(()=>{k||_(!1),l==null||l()},[k,l]);H.useEffect(()=>{if(!C||!g)return;const S=j=>{j.key==="Escape"&&x()};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[C,x,g]);const v=e&&(typeof e=="string"?o.jsx("button",{type:"button",onClick:y,className:f,children:e}):o.jsx("span",{onClick:y,className:f,style:{cursor:"pointer"},children:e}));return o.jsxs(o.Fragment,{children:[v,C&&(typeof document<"u"?tc.createPortal(o.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[o.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:p?x:void 0}),o.jsxs("div",{className:`relative w-full ${Dw[i]} max-h-[90vh] bg-bg-secondary border border-border rounded shadow-xl flex flex-col`,children:[(r||m)&&o.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border",children:[r&&o.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:r}),m&&o.jsx(Rh,{onClick:x,className:"ml-auto","aria-label":"Close"})]}),o.jsx("div",{className:"p-4 overflow-y-auto flex-1 min-h-0",style:s?{minHeight:s}:void 0,children:c}),u&&o.jsx("div",{className:"px-4 py-3 border-t border-border",children:u})]})]}),document.body):null)]})}const it=H.forwardRef(({variant:e="secondary",size:r="md",className:i="",children:s,...c},u)=>{const f="rounded font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed",l={primary:"bg-accent-primary/25 text-white hover:bg-accent-primary/40",secondary:"bg-bg-tertiary text-text-primary hover:bg-border",danger:"bg-accent-error text-white hover:bg-accent-error/80"},d={sm:"px-1.5 py-1 text-xs",md:"px-3 py-1.5 text-sm",lg:"px-4 py-2 text-base"};return o.jsx("button",{ref:u,className:`${f} ${l[e]} ${d[r]} ${i}`,...c,children:s})});it.displayName="Button";function Rw({value:e,defaultUrl:r,disabled:i,onChange:s}){const c=e??r;return o.jsxs("div",{className:"relative",children:[o.jsx("select",{value:c,disabled:i,onChange:u=>{const f=u.target.value;s(f===r?null:f)},className:"appearance-none bg-bg-tertiary border border-border rounded px-1.5 pr-5 text-xs focus:outline-none focus:ring-1 focus:ring-accent-primary disabled:opacity-40 cursor-pointer",style:{width:"60px"},children:F1.map(({url:u,label:f})=>o.jsx("option",{value:u,title:f,children:f.split(" ")[0]},u))}),o.jsx(ur,{className:"absolute right-0.5 top-1/2 -translate-y-1/2 w-3 h-3 pointer-events-none text-text-muted"})]})}const qx=[{key:"general",label:"General"},{key:"build",label:"Agent"},{key:"sub-agent",label:"Sub-agent"}];function Lw(){const e=Oi(d=>d.settings),r=Oi(d=>d.update),i=Oi(d=>d.updateEvent),s=Oi(d=>d.updateAgentOverride),c=Oi(d=>d.load);H.useEffect(()=>{c()},[c]);const u=async()=>{await $1()==="granted"&&r({...e,browserNotificationEnabled:!0})},f=(d,p,g,m)=>{d==="general"?i(p,{[g]:m}):s(d,p,{[g]:m})},l=(d,p,g)=>{d==="general"?i(p,{customSoundUrl:g}):s(d,p,{customSoundUrl:g})};return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-3",children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Master Controls"}),o.jsx(Wx,{label:"Sound notifications",description:"Play sounds when events occur",checked:e.soundEnabled,onChange:d=>r({...e,soundEnabled:d})}),o.jsx(Wx,{label:"Browser notifications",description:"Show desktop notifications when the window is not focused",checked:e.browserNotificationEnabled,onChange:d=>{d&&typeof Notification<"u"&&Notification.permission!=="granted"?u():r({...e,browserNotificationEnabled:d})}}),typeof Notification<"u"&&Notification.permission==="denied"&&e.browserNotificationEnabled&&o.jsx("p",{className:"text-xs text-accent-error ml-6",children:"Browser notifications are blocked. Please enable them in your browser settings."})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Notification Settings"}),o.jsx("div",{className:"border border-border rounded overflow-hidden",children:o.jsxs("table",{className:"w-full text-sm",children:[o.jsx("thead",{className:"sticky top-0 bg-bg-tertiary",children:o.jsxs("tr",{className:"border-b border-border",children:[o.jsx("th",{className:"text-left px-3 py-2 text-text-primary font-medium w-40",children:"Event"}),qx.map(d=>o.jsx("th",{className:"text-center px-2 py-2 text-text-primary font-medium",children:d.label},d.key))]})}),o.jsx("tbody",{children:P1.map(d=>o.jsxs("tr",{className:"border-b border-border last:border-b-0 hover:bg-bg-secondary/50",children:[o.jsx("td",{className:"px-3 py-2",children:o.jsx("div",{className:"text-text-primary text-xs",children:d.label})}),qx.map(p=>{const g=Db(e,d.key,p.key==="general"?void 0:p.key),m=Tb[d.key];return o.jsx("td",{className:"px-2 py-2 align-top",children:o.jsxs("div",{className:"flex flex-col items-center gap-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("label",{className:"flex items-center gap-1 text-text-secondary",children:o.jsx("input",{type:"checkbox",checked:g.soundEnabled,onChange:b=>f(p.key,d.key,"soundEnabled",b.target.checked),disabled:!e.soundEnabled,className:"rounded border-border",title:"Sound"})}),o.jsx("label",{className:"flex items-center gap-1 text-text-secondary",children:o.jsx("input",{type:"checkbox",checked:g.browserNotification,onChange:b=>f(p.key,d.key,"browserNotification",b.target.checked),disabled:!e.browserNotificationEnabled,className:"rounded border-border",title:"Browser"})})]}),g.soundEnabled&&e.soundEnabled&&o.jsx(Rw,{value:g.customSoundUrl,defaultUrl:m,disabled:!e.soundEnabled,onChange:b=>l(p.key,d.key,b)})]})},p.key)})]},d.key))})]})})]})]})}function Wx({label:e,description:r,checked:i,onChange:s}){return o.jsxs("label",{className:"flex items-start gap-3 cursor-pointer group",children:[o.jsx("div",{className:"pt-0.5",children:o.jsx("div",{className:`relative w-9 h-5 rounded-full transition-colors ${i?"bg-accent-primary":"bg-bg-tertiary border border-border"}`,onClick:c=>{c.preventDefault(),s(!i)},children:o.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white shadow transition-transform ${i?"translate-x-4":"translate-x-0.5"}`})})}),o.jsxs("div",{children:[o.jsx("div",{className:"text-sm text-text-primary group-hover:text-accent-primary transition-colors",children:e}),o.jsx("div",{className:"text-xs text-text-muted",children:r})]})]})}async function Lh(e,r){r({loading:!0});try{const s=await(await ke(e)).json();r({defaults:s.defaults??[],userItems:s.userItems??[],loading:!1})}catch{r({loading:!1})}}const Rr=Yn((e,r)=>({defaults:[],userItems:[],loading:!1,fetchSkills:async()=>{await Lh("/api/skills",e)},toggleSkill:async i=>{try{const c=await(await ke(`/api/skills/${i}/toggle`,{method:"POST"})).json();e(u=>({defaults:u.defaults.map(f=>f.id===i?{...f,enabled:c.enabled}:f),userItems:u.userItems.map(f=>f.id===i?{...f,enabled:c.enabled}:f)}))}catch{}},fetchSkill:async i=>{try{const s=await ke(`/api/skills/${i}`);return s.ok?await s.json():null}catch{return null}},fetchDefaultContent:async i=>{try{const s=await ke(`/api/skills/defaults/${i}`);return s.ok?await s.json():null}catch{return null}},createSkill:async i=>{const s=await di("POST","/api/skills",i);return s.success&&await r().fetchSkills(),s},updateSkill:async(i,s)=>{const c=await di("PUT",`/api/skills/${i}`,s);return c.success&&await r().fetchSkills(),c},deleteSkill:async i=>{try{const s=await ke(`/api/skills/${i}`,{method:"DELETE"}),c=await s.json();return s.ok?(e(u=>({userItems:u.userItems.filter(f=>f.id!==i)})),{success:!0}):{success:!1,error:c.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateSkill:async i=>{try{const s=await ke(`/api/skills/${i}/duplicate`,{method:"POST"}),c=await s.json();return s.ok?(await r().fetchSkills(),{success:!0}):{success:!1,error:c.error??"Failed to duplicate"}}catch{return{success:!1,error:"Network error"}}}}));function Oh(){const[e,r]=H.useState({id:null,type:null}),i=H.useCallback(u=>r({id:u,type:"delete"}),[]),s=H.useCallback(()=>r({id:null,type:null}),[]),c=H.useCallback((u,f)=>e.id===u&&e.type===f,[e.id,e.type]);return{requestDelete:i,clearConfirm:s,isConfirming:c}}function Mh({onConfirm:e,onCancel:r}){return o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("button",{onClick:e,className:"px-1.5 py-0.5 rounded text-xs hover:opacity-90 transition-colors bg-accent-error/20 text-accent-error hover:bg-accent-error/30",children:"Delete"}),o.jsx("button",{onClick:r,className:"px-1.5 py-0.5 rounded text-text-muted text-xs hover:bg-bg-primary transition-colors",children:"Cancel"})]})}function Ih({onClick:e}){return o.jsx("button",{onClick:e,className:"p-1.5 rounded hover:bg-bg-primary text-text-muted hover:text-accent-error transition-colors",title:"Delete",children:o.jsx(Hb,{})})}function Qa({onClick:e}){return o.jsx("button",{onClick:e,className:"p-1.5 rounded hover:bg-bg-primary text-text-muted hover:text-text-primary transition-colors",title:"Duplicate",children:o.jsx(Jl,{})})}function Mi({label:e,value:r,onChange:i,placeholder:s,readOnly:c,hint:u,mono:f}){return o.jsxs("div",{children:[o.jsxs("label",{className:"block text-xs text-text-secondary mb-1",children:[e,u&&o.jsx("span",{className:"text-text-muted ml-1",children:u})]}),o.jsx("input",{value:r,onChange:l=>i(l.target.value),readOnly:c,placeholder:s,className:`w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary ${f?"font-mono":""} ${c?"opacity-60":""}`})]})}function Ow({onCancel:e,onSave:r,saving:i,saveDisabled:s}){return o.jsxs("div",{className:"flex justify-end gap-2 pt-2 border-t border-border",children:[o.jsx(it,{variant:"secondary",onClick:e,children:"Cancel"}),o.jsx(it,{variant:"primary",onClick:r,disabled:i||s,children:i?"Saving...":"Save"})]})}function Bh({message:e}){return o.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded",children:e})}function Fb({description:e,onNew:r,newLabel:i="+ New"}){return o.jsxs("div",{className:"flex items-center justify-between mb-4",children:[o.jsx("p",{className:"text-text-secondary text-sm",children:e}),o.jsx("div",{className:"flex items-center gap-2 flex-shrink-0 ml-3",children:o.jsx(it,{variant:"primary",size:"sm",onClick:r,children:i})})]})}function Ub({isBuiltIn:e,isConfirmingDelete:r,onView:i,onEdit:s,onDuplicate:c,onDelete:u,children:f}){return o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsx("div",{className:"min-w-0 flex-1 mr-3",children:f}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[e&&i&&o.jsx("button",{onClick:i,className:"p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",title:"View",children:o.jsx(ec,{})}),o.jsx(Qa,{onClick:c}),!e&&s&&o.jsx(Hs,{onClick:s}),!e&&(r?o.jsx(Mh,{onConfirm:()=>{u==null||u()},onCancel:()=>{}}):o.jsx(Ih,{onClick:()=>u==null?void 0:u()}))]})]})}function Mw({id:e,name:r,description:i,isBuiltIn:s,isConfirmingDelete:c,onView:u,onEdit:f,onDuplicate:l,onDelete:d}){return o.jsxs(Ub,{isBuiltIn:s,isConfirmingDelete:c,onView:u,onEdit:f,onDuplicate:l,onDelete:d,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-text-primary text-sm font-medium",children:r}),o.jsx("span",{className:"text-text-muted text-xs font-mono",children:e})]}),i&&o.jsx("p",{className:"text-text-muted text-xs truncate",children:i})]})}function $b({loading:e,hasItems:r,loadingLabel:i,emptyLabel:s,children:c}){return e&&!r?o.jsx("div",{className:"text-text-muted text-sm",children:i}):r?o.jsx("div",{className:"space-y-4",children:c}):s?o.jsx("div",{className:"text-text-muted text-sm",children:s}):null}function qb({name:e,id:r,nameLabel:i="Name",idLabel:s="ID",namePlaceholder:c="My Item",idPlaceholder:u="my-item",nameHint:f,readOnlyId:l=!1,readOnlyHint:d="(read-only)",onNameChange:p,onIdChange:g}){return o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Mi,{label:i,value:e,onChange:p,placeholder:c,hint:f}),o.jsx(Mi,{label:s,value:r,onChange:g,readOnly:l,placeholder:u,hint:l?d:void 0,mono:!0})]})}function Wb(e={}){const{initialData:r={}}=e,[i,s]=H.useState("list"),[c,u]=H.useState(null),[f,l]=H.useState(""),[d,p]=H.useState(!1),[g,m]=H.useState(r),b=H.useCallback(()=>{m(r),l(""),u(null)},[r]),_=H.useCallback(x=>{s(x),x==="list"&&b()},[b]),k=H.useCallback(x=>{m(v=>typeof x=="function"?x(v):x)},[]),C=H.useCallback((x,v={})=>{u(x),s("edit"),m({...v}),l("")},[]),y=H.useCallback(()=>{u(null),s("edit"),m(r),l("")},[r]);return{view:i,editingId:c,formError:f,saving:d,formData:g,setView:_,setEditingId:u,setFormError:l,setFormData:k,setSaving:p,resetForm:b,startEditing:C,startNew:y}}function zh(){return o.jsxs("div",{className:"flex items-start gap-2 px-3 py-2 mt-3 bg-accent-warning/10 border border-accent-warning/30 rounded text-xs",children:[o.jsx("span",{children:"⚠️"}),o.jsx("p",{className:"text-text-secondary",children:"Editing this value now will have the side-effect of invalidating KV-cache, causing your next message in current sessions to take a long time to process. Consider doing this between sessions."})]})}function Gx({skill:e,isBuiltIn:r,isConfirmingDelete:i,onView:s,onEdit:c,onDuplicate:u,onDelete:f}){return o.jsx(Mw,{id:e.id,name:e.name,description:e.description,isBuiltIn:r,isConfirmingDelete:i,onView:s,onEdit:c,onDuplicate:u,onDelete:f})}function Iw({isOpen:e}){const r=Rr(O=>O.defaults),i=Rr(O=>O.userItems),s=Rr(O=>O.loading),c=Rr(O=>O.fetchSkills),u=Rr(O=>O.fetchSkill),f=Rr(O=>O.fetchDefaultContent),l=Rr(O=>O.createSkill),d=Rr(O=>O.updateSkill),p=Rr(O=>O.deleteSkill),{view:g,editingId:m,formError:b,saving:_,formData:k,setView:C,setEditingId:y,setFormError:x,setFormData:v,setSaving:S}=Wb(),{clearConfirm:j}=Oh();H.useEffect(()=>{e&&(c(),C("list"),y(null),j())},[e,c,j]);const T=(O,F,P,Z)=>{v({name:Z??O.metadata.name,id:P??O.metadata.id,description:O.metadata.description??"",version:O.metadata.version??"1.0.0",prompt:O.prompt,isReadOnly:F})},N=async O=>{if(r.some(P=>P.id===O)){const P=await f(O);if(!P)return;T(P,!0),y(O),x(""),C("edit")}else{const P=await u(O);if(!P)return;T(P,!0),y(O),x(""),C("edit")}},D=async O=>{const P=r.some(G=>G.id===O)?await f(O):await u(O);if(!P)return;const Z=`${O}-copy-${Date.now()}`;T(P,!1,Z,`${P.metadata.name} (copy)`),y(null),x(""),C("edit")},A=()=>{v({name:"",id:"",description:"",version:"1.0.0",prompt:"",isReadOnly:!1}),C("edit")},M=async O=>{const F=await u(O);F&&(T(F,!1),y(O),x(""),C("edit"))},B=async O=>{await p(O),j()},$=async()=>{const O=m??k.id;if(!O||!k.name||!k.prompt){x("Name, ID, and prompt are required.");return}S(!0),x("");const F={metadata:{id:O,name:k.name,description:k.description,version:k.version},prompt:k.prompt},P=m?await d(m,F):await l(F);if(S(!1),!P.success){x(P.error??"Failed to save skill.");return}C("list")},V=O=>{v(F=>({...F,name:O})),m||v(F=>({...F,id:O.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}))},W=k.isReadOnly;return g==="edit"?o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"flex justify-between items-center mb-3",children:[o.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:W?k.name:m?"Edit Skill":"New Skill"}),o.jsx("button",{onClick:()=>C("list"),className:"text-text-muted hover:text-text-primary",children:"Cancel"})]}),b&&o.jsx(Bh,{message:b}),o.jsxs("div",{className:"space-y-3 mb-3",children:[o.jsx(qb,{name:k.name,id:k.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Skill",idPlaceholder:"my-skill",readOnlyId:!0,onNameChange:V,onIdChange:()=>{}}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Mi,{label:"Description",value:k.description,onChange:O=>v(F=>({...F,description:O})),placeholder:"What this skill does...",readOnly:W}),o.jsx(Mi,{label:"Version",value:k.version,onChange:O=>v(F=>({...F,version:O})),placeholder:"1.0.0",readOnly:W})]})]}),o.jsxs("div",{className:"flex-1 min-h-[120px] border-t border-border pt-3 flex flex-col",children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Prompt"}),o.jsx("textarea",{value:k.prompt,onChange:O=>v(F=>({...F,prompt:O.target.value})),readOnly:W,placeholder:"The system prompt for this skill...",className:"h-80 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary"})]}),o.jsx(zh,{}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 border-t border-border flex-shrink-0",children:[o.jsx(it,{variant:"secondary",onClick:()=>C("list"),children:"Cancel"}),W?o.jsx(it,{variant:"primary",onClick:()=>{v(O=>({...O,name:O.name+" (copy)",id:`${m}-copy-${Date.now()}`,isReadOnly:!1})),y(null)},children:"Duplicate & Customize"}):o.jsx(it,{variant:"primary",onClick:$,disabled:_||!k.name||!k.id||!k.prompt,children:_?"Saving...":"Save"})]})]}):o.jsxs("div",{children:[o.jsx(Fb,{description:"Skills provide domain-specific knowledge that agents can load on demand.",onNew:A}),o.jsxs($b,{loading:s,hasItems:r.length>0||i.length>0,loadingLabel:"Loading skills...",emptyLabel:"No skills created yet.",children:[r.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Built-in"}),o.jsx("div",{className:"space-y-2",children:r.map(O=>o.jsx(Gx,{skill:O,isBuiltIn:!0,isConfirmingDelete:!1,onView:()=>N(O.id),onDuplicate:()=>D(O.id)},O.id))})]}),i.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Custom"}),o.jsx("div",{className:"space-y-2",children:i.map(O=>o.jsx(Gx,{skill:O,isBuiltIn:!1,isConfirmingDelete:!1,onView:()=>N(O.id),onEdit:()=>M(O.id),onDuplicate:()=>D(O.id),onDelete:()=>B(O.id)},O.id))})]})]})]})}function Bw({isOpen:e,onClose:r}){const[i,s]=H.useState("instructions");return o.jsx(jt,{isOpen:e,onClose:r,title:"Settings",size:"xl",minHeight:"500px",children:o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"flex border-b border-border mb-4 -mt-1",children:[o.jsx(Ba,{label:"Instructions",active:i==="instructions",onClick:()=>s("instructions")}),o.jsx(Ba,{label:"Skills",active:i==="skills",onClick:()=>s("skills")}),o.jsx(Ba,{label:"Notifications",active:i==="notifications",onClick:()=>s("notifications")}),o.jsx(Ba,{label:"Display",active:i==="display",onClick:()=>s("display")}),o.jsx(Ba,{label:"Advanced",active:i==="advanced",onClick:()=>s("advanced")})]}),i==="instructions"&&o.jsx(Pw,{isOpen:e}),i==="skills"&&o.jsx(Iw,{isOpen:e}),i==="notifications"&&o.jsx("div",{className:"max-h-[60vh] overflow-y-auto",children:o.jsx(Lw,{})}),i==="display"&&o.jsx(Hw,{}),i==="advanced"&&o.jsx(zw,{onClose:r})]})})}function zw({onClose:e}){const[,r]=dr();function i(){e(),r("/onboarding")}return o.jsx("div",{className:"space-y-6",children:o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary mb-1",children:"Onboarding"}),o.jsx("p",{className:"text-sm text-text-muted mb-4",children:"Reset your OpenFox setup and go through the initial configuration again."}),o.jsx(it,{variant:"secondary",onClick:i,children:"Launch Onboarding"})]})})}function Hw(){const e=en(g=>g.settings),r=en(g=>g.loading),i=en(g=>g.getSetting),s=en(g=>g.setSetting),c=r[Et.DISPLAY_SHOW_THINKING]??!1,u=[{key:Et.DISPLAY_SHOW_THINKING,label:"Show thinking blocks",description:"Display AI reasoning content in the feed"},{key:Et.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT,label:"Show expanded tool output",description:"Always show full tool call details instead of compact view"},{key:Et.DISPLAY_SHOW_STATS,label:"Show stats bar",description:"Display model, tokens, and timing information"},{key:Et.DISPLAY_SHOW_AGENT_DEFINITIONS,label:"Show agent definitions",description:"Display agent definition injections in the feed"},{key:Et.DISPLAY_SHOW_WORKFLOW_BARS,label:"Show workflow bars",description:"Display workflow start and end markers"}],f=Object.fromEntries(u.map(g=>[g.key,e[g.key]??"true"])),[l,d]=H.useState(()=>Object.fromEntries(u.map(g=>[g.key,f[g.key]==="true"])));H.useEffect(()=>{u.forEach(g=>i(g.key))},[i]),H.useEffect(()=>{d(Object.fromEntries(u.map(g=>[g.key,f[g.key]==="true"])))},[JSON.stringify(f)]);const p=async g=>{const m=String(!l[g]);d(b=>({...b,[g]:!b[g]})),await s(g,m)};return c?o.jsx("div",{className:"text-sm text-text-muted",children:"Loading..."}):o.jsx("div",{className:"space-y-6",children:o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary mb-4",children:"Feed Display"}),o.jsx("div",{className:"space-y-4",children:u.map(({key:g,label:m,description:b})=>o.jsxs("label",{className:"flex items-center justify-between cursor-pointer",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-sm text-text-primary",children:m}),o.jsx("div",{className:"text-xs text-text-muted",children:b})]}),o.jsx("button",{type:"button",onClick:()=>p(g),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${l[g]?"bg-accent-primary":"bg-bg-tertiary"}`,children:o.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${l[g]?"translate-x-6":"translate-x-1"}`})})]},g))})]})})}function Ba({label:e,active:r,onClick:i}){return o.jsx("button",{onClick:i,className:`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${r?"border-accent-primary text-accent-primary":"border-transparent text-text-muted hover:text-text-secondary hover:border-border"}`,children:e})}function Pw({isOpen:e}){const r=en(y=>y.settings),i=en(y=>y.loading),s=en(y=>y.getSetting),c=en(y=>y.setSetting),u=r[Et.GLOBAL_INSTRUCTIONS]??"",f=i[Et.GLOBAL_INSTRUCTIONS]??!1,[l,d]=H.useState(u),[p,g]=H.useState(!1),[m,b]=H.useState(!1);H.useEffect(()=>{e&&s(Et.GLOBAL_INSTRUCTIONS)},[e,s]),H.useEffect(()=>{d(u),g(!1)},[u]);const _=async()=>{b(!0),c(Et.GLOBAL_INSTRUCTIONS,l),b(!1),g(!1)},k=()=>{d(u),g(!1)},C=f||m;return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-text-primary mb-2",children:"Global Instructions"}),o.jsx("p",{className:"text-sm text-text-muted mb-2",children:"These instructions are injected into every prompt, regardless of project."}),o.jsx("textarea",{value:l,onChange:y=>{d(y.target.value),g(!0)},placeholder:"Enter global instructions that apply to all projects...",className:"w-full min-h-80 px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary",disabled:C})]}),p&&o.jsx(zh,{}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(it,{variant:"secondary",onClick:k,disabled:!p,children:"Discard"}),o.jsx(it,{variant:"primary",onClick:_,disabled:!p||C,children:m?"Saving...":"Save"})]})]})}var Hd={exports:{}},Vx;function Fw(){return Vx||(Vx=1,(function(e,r){(function(i,s){e.exports=s()})(globalThis,(()=>(()=>{var i={4567:function(f,l,d){var p=this&&this.__decorate||function(v,S,j,T){var N,D=arguments.length,A=D<3?S:T===null?T=Object.getOwnPropertyDescriptor(S,j):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(v,S,j,T);else for(var M=v.length-1;M>=0;M--)(N=v[M])&&(A=(D<3?N(A):D>3?N(S,j,A):N(S,j))||A);return D>3&&A&&Object.defineProperty(S,j,A),A},g=this&&this.__param||function(v,S){return function(j,T){S(j,T,v)}};Object.defineProperty(l,"__esModule",{value:!0}),l.AccessibilityManager=void 0;const m=d(9042),b=d(9924),_=d(844),k=d(4725),C=d(2585),y=d(3656);let x=l.AccessibilityManager=class extends _.Disposable{constructor(v,S,j,T){super(),this._terminal=v,this._coreBrowserService=j,this._renderService=T,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let N=0;N<this._terminal.rows;N++)this._rowElements[N]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[N]);if(this._topBoundaryFocusListener=N=>this._handleBoundaryFocus(N,0),this._bottomBoundaryFocusListener=N=>this._handleBoundaryFocus(N,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new b.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((N=>this._handleResize(N.rows)))),this.register(this._terminal.onRender((N=>this._refreshRows(N.start,N.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((N=>this._handleChar(N)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
58
58
|
`)))),this.register(this._terminal.onA11yTab((N=>this._handleTab(N)))),this.register(this._terminal.onKey((N=>this._handleKey(N.key)))),this.register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this.register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this.register((0,y.addDisposableDomListener)(document,"selectionchange",(()=>this._handleSelectionChange()))),this.register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRows(),this.register((0,_.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(v){for(let S=0;S<v;S++)this._handleChar(" ")}_handleChar(v){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==v&&(this._charsToAnnounce+=v):this._charsToAnnounce+=v,v===`
|
|
59
59
|
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=m.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(v){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(v)||this._charsToConsume.push(v)}_refreshRows(v,S){this._liveRegionDebouncer.refresh(v,S,this._terminal.rows)}_renderRows(v,S){const j=this._terminal.buffer,T=j.lines.length.toString();for(let N=v;N<=S;N++){const D=j.lines.get(j.ydisp+N),A=[],M=(D==null?void 0:D.translateToString(!0,void 0,void 0,A))||"",B=(j.ydisp+N+1).toString(),$=this._rowElements[N];$&&(M.length===0?($.innerText=" ",this._rowColumns.set($,[0,1])):($.textContent=M,this._rowColumns.set($,A)),$.setAttribute("aria-posinset",B),$.setAttribute("aria-setsize",T))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(v,S){const j=v.target,T=this._rowElements[S===0?1:this._rowElements.length-2];if(j.getAttribute("aria-posinset")===(S===0?"1":`${this._terminal.buffer.lines.length}`)||v.relatedTarget!==T)return;let N,D;if(S===0?(N=j,D=this._rowElements.pop(),this._rowContainer.removeChild(D)):(N=this._rowElements.shift(),D=j,this._rowContainer.removeChild(N)),N.removeEventListener("focus",this._topBoundaryFocusListener),D.removeEventListener("focus",this._bottomBoundaryFocusListener),S===0){const A=this._createAccessibilityTreeNode();this._rowElements.unshift(A),this._rowContainer.insertAdjacentElement("afterbegin",A)}else{const A=this._createAccessibilityTreeNode();this._rowElements.push(A),this._rowContainer.appendChild(A)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(S===0?-1:1),this._rowElements[S===0?1:this._rowElements.length-2].focus(),v.preventDefault(),v.stopImmediatePropagation()}_handleSelectionChange(){var M;if(this._rowElements.length===0)return;const v=document.getSelection();if(!v)return;if(v.isCollapsed)return void(this._rowContainer.contains(v.anchorNode)&&this._terminal.clearSelection());if(!v.anchorNode||!v.focusNode)return void console.error("anchorNode and/or focusNode are null");let S={node:v.anchorNode,offset:v.anchorOffset},j={node:v.focusNode,offset:v.focusOffset};if((S.node.compareDocumentPosition(j.node)&Node.DOCUMENT_POSITION_PRECEDING||S.node===j.node&&S.offset>j.offset)&&([S,j]=[j,S]),S.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(S={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(S.node))return;const T=this._rowElements.slice(-1)[0];if(j.node.compareDocumentPosition(T)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(j={node:T,offset:((M=T.textContent)==null?void 0:M.length)??0}),!this._rowContainer.contains(j.node))return;const N=({node:B,offset:$})=>{const V=B instanceof Text?B.parentNode:B;let W=parseInt(V==null?void 0:V.getAttribute("aria-posinset"),10)-1;if(isNaN(W))return console.warn("row is invalid. Race condition?"),null;const O=this._rowColumns.get(V);if(!O)return console.warn("columns is null. Race condition?"),null;let F=$<O.length?O[$]:O.slice(-1)[0]+1;return F>=this._terminal.cols&&(++W,F=0),{row:W,column:F}},D=N(S),A=N(j);if(D&&A){if(D.row>A.row||D.row===A.row&&D.column>=A.column)throw new Error("invalid range");this._terminal.select(D.column,D.row,(A.row-D.row)*this._terminal.cols-D.column+A.column)}}_handleResize(v){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let S=this._rowContainer.children.length;S<this._terminal.rows;S++)this._rowElements[S]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[S]);for(;this._rowElements.length>v;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const v=this._coreBrowserService.mainDocument.createElement("div");return v.setAttribute("role","listitem"),v.tabIndex=-1,this._refreshRowDimensions(v),v}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let v=0;v<this._terminal.rows;v++)this._refreshRowDimensions(this._rowElements[v])}}_refreshRowDimensions(v){v.style.height=`${this._renderService.dimensions.css.cell.height}px`}};l.AccessibilityManager=x=p([g(1,C.IInstantiationService),g(2,k.ICoreBrowserService),g(3,k.IRenderService)],x)},3614:(f,l)=>{function d(b){return b.replace(/\r?\n/g,"\r")}function p(b,_){return _?"\x1B[200~"+b+"\x1B[201~":b}function g(b,_,k,C){b=p(b=d(b),k.decPrivateModes.bracketedPasteMode&&C.rawOptions.ignoreBracketedPasteMode!==!0),k.triggerDataEvent(b,!0),_.value=""}function m(b,_,k){const C=k.getBoundingClientRect(),y=b.clientX-C.left-10,x=b.clientY-C.top-10;_.style.width="20px",_.style.height="20px",_.style.left=`${y}px`,_.style.top=`${x}px`,_.style.zIndex="1000",_.focus()}Object.defineProperty(l,"__esModule",{value:!0}),l.rightClickHandler=l.moveTextAreaUnderMouseCursor=l.paste=l.handlePasteEvent=l.copyHandler=l.bracketTextForPaste=l.prepareTextForTerminal=void 0,l.prepareTextForTerminal=d,l.bracketTextForPaste=p,l.copyHandler=function(b,_){b.clipboardData&&b.clipboardData.setData("text/plain",_.selectionText),b.preventDefault()},l.handlePasteEvent=function(b,_,k,C){b.stopPropagation(),b.clipboardData&&g(b.clipboardData.getData("text/plain"),_,k,C)},l.paste=g,l.moveTextAreaUnderMouseCursor=m,l.rightClickHandler=function(b,_,k,C,y){m(b,_,k),y&&C.rightClickSelect(b),_.value=C.selectionText,_.select()}},7239:(f,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.ColorContrastCache=void 0;const p=d(1505);l.ColorContrastCache=class{constructor(){this._color=new p.TwoKeyMap,this._css=new p.TwoKeyMap}setCss(g,m,b){this._css.set(g,m,b)}getCss(g,m){return this._css.get(g,m)}setColor(g,m,b){this._color.set(g,m,b)}getColor(g,m){return this._color.get(g,m)}clear(){this._color.clear(),this._css.clear()}}},3656:(f,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.addDisposableDomListener=void 0,l.addDisposableDomListener=function(d,p,g,m){d.addEventListener(p,g,m);let b=!1;return{dispose:()=>{b||(b=!0,d.removeEventListener(p,g,m))}}}},3551:function(f,l,d){var p=this&&this.__decorate||function(x,v,S,j){var T,N=arguments.length,D=N<3?v:j===null?j=Object.getOwnPropertyDescriptor(v,S):j;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")D=Reflect.decorate(x,v,S,j);else for(var A=x.length-1;A>=0;A--)(T=x[A])&&(D=(N<3?T(D):N>3?T(v,S,D):T(v,S))||D);return N>3&&D&&Object.defineProperty(v,S,D),D},g=this&&this.__param||function(x,v){return function(S,j){v(S,j,x)}};Object.defineProperty(l,"__esModule",{value:!0}),l.Linkifier=void 0;const m=d(3656),b=d(8460),_=d(844),k=d(2585),C=d(4725);let y=l.Linkifier=class extends _.Disposable{get currentLink(){return this._currentLink}constructor(x,v,S,j,T){super(),this._element=x,this._mouseService=v,this._renderService=S,this._bufferService=j,this._linkProviderService=T,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new b.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new b.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,_.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,_.toDisposable)((()=>{var N;this._lastMouseEvent=void 0,(N=this._activeProviderReplies)==null||N.clear()}))),this.register(this._bufferService.onResize((()=>{this._clearCurrentLink(),this._wasResized=!0}))),this.register((0,m.addDisposableDomListener)(this._element,"mouseleave",(()=>{this._isMouseOut=!0,this._clearCurrentLink()}))),this.register((0,m.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,m.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,m.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(x){this._lastMouseEvent=x;const v=this._positionFromMouseEvent(x,this._element,this._mouseService);if(!v)return;this._isMouseOut=!1;const S=x.composedPath();for(let j=0;j<S.length;j++){const T=S[j];if(T.classList.contains("xterm"))break;if(T.classList.contains("xterm-hover"))return}this._lastBufferCell&&v.x===this._lastBufferCell.x&&v.y===this._lastBufferCell.y||(this._handleHover(v),this._lastBufferCell=v)}_handleHover(x){if(this._activeLine!==x.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(x,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,x)||(this._clearCurrentLink(),this._askForLink(x,!0))}_askForLink(x,v){var j,T;this._activeProviderReplies&&v||((j=this._activeProviderReplies)==null||j.forEach((N=>{N==null||N.forEach((D=>{D.link.dispose&&D.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=x.y);let S=!1;for(const[N,D]of this._linkProviderService.linkProviders.entries())v?(T=this._activeProviderReplies)!=null&&T.get(N)&&(S=this._checkLinkProviderResult(N,x,S)):D.provideLinks(x.y,(A=>{var B,$;if(this._isMouseOut)return;const M=A==null?void 0:A.map((V=>({link:V})));(B=this._activeProviderReplies)==null||B.set(N,M),S=this._checkLinkProviderResult(N,x,S),(($=this._activeProviderReplies)==null?void 0:$.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(x.y,this._activeProviderReplies)}))}_removeIntersectingLinks(x,v){const S=new Set;for(let j=0;j<v.size;j++){const T=v.get(j);if(T)for(let N=0;N<T.length;N++){const D=T[N],A=D.link.range.start.y<x?0:D.link.range.start.x,M=D.link.range.end.y>x?this._bufferService.cols:D.link.range.end.x;for(let B=A;B<=M;B++){if(S.has(B)){T.splice(N--,1);break}S.add(B)}}}}_checkLinkProviderResult(x,v,S){var N;if(!this._activeProviderReplies)return S;const j=this._activeProviderReplies.get(x);let T=!1;for(let D=0;D<x;D++)this._activeProviderReplies.has(D)&&!this._activeProviderReplies.get(D)||(T=!0);if(!T&&j){const D=j.find((A=>this._linkAtPosition(A.link,v)));D&&(S=!0,this._handleNewLink(D))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!S)for(let D=0;D<this._activeProviderReplies.size;D++){const A=(N=this._activeProviderReplies.get(D))==null?void 0:N.find((M=>this._linkAtPosition(M.link,v)));if(A){S=!0,this._handleNewLink(A);break}}return S}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(x){if(!this._currentLink)return;const v=this._positionFromMouseEvent(x,this._element,this._mouseService);v&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,v)&&this._currentLink.link.activate(x,this._currentLink.link.text)}_clearCurrentLink(x,v){this._currentLink&&this._lastMouseEvent&&(!x||!v||this._currentLink.link.range.start.y>=x&&this._currentLink.link.range.end.y<=v)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,_.disposeArray)(this._linkCacheDisposables))}_handleNewLink(x){if(!this._lastMouseEvent)return;const v=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);v&&this._linkAtPosition(x.link,v)&&(this._currentLink=x,this._currentLink.state={decorations:{underline:x.link.decorations===void 0||x.link.decorations.underline,pointerCursor:x.link.decorations===void 0||x.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,x.link,this._lastMouseEvent),x.link.decorations={},Object.defineProperties(x.link.decorations,{pointerCursor:{get:()=>{var S,j;return(j=(S=this._currentLink)==null?void 0:S.state)==null?void 0:j.decorations.pointerCursor},set:S=>{var j;(j=this._currentLink)!=null&&j.state&&this._currentLink.state.decorations.pointerCursor!==S&&(this._currentLink.state.decorations.pointerCursor=S,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",S))}},underline:{get:()=>{var S,j;return(j=(S=this._currentLink)==null?void 0:S.state)==null?void 0:j.decorations.underline},set:S=>{var j,T,N;(j=this._currentLink)!=null&&j.state&&((N=(T=this._currentLink)==null?void 0:T.state)==null?void 0:N.decorations.underline)!==S&&(this._currentLink.state.decorations.underline=S,this._currentLink.state.isHovered&&this._fireUnderlineEvent(x.link,S))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((S=>{if(!this._currentLink)return;const j=S.start===0?0:S.start+1+this._bufferService.buffer.ydisp,T=this._bufferService.buffer.ydisp+1+S.end;if(this._currentLink.link.range.start.y>=j&&this._currentLink.link.range.end.y<=T&&(this._clearCurrentLink(j,T),this._lastMouseEvent)){const N=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);N&&this._askForLink(N,!1)}}))))}_linkHover(x,v,S){var j;(j=this._currentLink)!=null&&j.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(v,!0),this._currentLink.state.decorations.pointerCursor&&x.classList.add("xterm-cursor-pointer")),v.hover&&v.hover(S,v.text)}_fireUnderlineEvent(x,v){const S=x.range,j=this._bufferService.buffer.ydisp,T=this._createLinkUnderlineEvent(S.start.x-1,S.start.y-j-1,S.end.x,S.end.y-j-1,void 0);(v?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(T)}_linkLeave(x,v,S){var j;(j=this._currentLink)!=null&&j.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(v,!1),this._currentLink.state.decorations.pointerCursor&&x.classList.remove("xterm-cursor-pointer")),v.leave&&v.leave(S,v.text)}_linkAtPosition(x,v){const S=x.range.start.y*this._bufferService.cols+x.range.start.x,j=x.range.end.y*this._bufferService.cols+x.range.end.x,T=v.y*this._bufferService.cols+v.x;return S<=T&&T<=j}_positionFromMouseEvent(x,v,S){const j=S.getCoords(x,v,this._bufferService.cols,this._bufferService.rows);if(j)return{x:j[0],y:j[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(x,v,S,j,T){return{x1:x,y1:v,x2:S,y2:j,cols:this._bufferService.cols,fg:T}}};l.Linkifier=y=p([g(1,C.IMouseService),g(2,C.IRenderService),g(3,k.IBufferService),g(4,C.ILinkProviderService)],y)},9042:(f,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.tooMuchOutput=l.promptLabel=void 0,l.promptLabel="Terminal input",l.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(f,l,d){var p=this&&this.__decorate||function(C,y,x,v){var S,j=arguments.length,T=j<3?y:v===null?v=Object.getOwnPropertyDescriptor(y,x):v;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")T=Reflect.decorate(C,y,x,v);else for(var N=C.length-1;N>=0;N--)(S=C[N])&&(T=(j<3?S(T):j>3?S(y,x,T):S(y,x))||T);return j>3&&T&&Object.defineProperty(y,x,T),T},g=this&&this.__param||function(C,y){return function(x,v){y(x,v,C)}};Object.defineProperty(l,"__esModule",{value:!0}),l.OscLinkProvider=void 0;const m=d(511),b=d(2585);let _=l.OscLinkProvider=class{constructor(C,y,x){this._bufferService=C,this._optionsService=y,this._oscLinkService=x}provideLinks(C,y){var M;const x=this._bufferService.buffer.lines.get(C-1);if(!x)return void y(void 0);const v=[],S=this._optionsService.rawOptions.linkHandler,j=new m.CellData,T=x.getTrimmedLength();let N=-1,D=-1,A=!1;for(let B=0;B<T;B++)if(D!==-1||x.hasContent(B)){if(x.loadCell(B,j),j.hasExtendedAttrs()&&j.extended.urlId){if(D===-1){D=B,N=j.extended.urlId;continue}A=j.extended.urlId!==N}else D!==-1&&(A=!0);if(A||D!==-1&&B===T-1){const $=(M=this._oscLinkService.getLinkData(N))==null?void 0:M.uri;if($){const V={start:{x:D+1,y:C},end:{x:B+(A||B!==T-1?0:1),y:C}};let W=!1;if(!(S!=null&&S.allowNonHttpProtocols))try{const O=new URL($);["http:","https:"].includes(O.protocol)||(W=!0)}catch{W=!0}W||v.push({text:$,range:V,activate:(O,F)=>S?S.activate(O,F,V):k(0,F),hover:(O,F)=>{var P;return(P=S==null?void 0:S.hover)==null?void 0:P.call(S,O,F,V)},leave:(O,F)=>{var P;return(P=S==null?void 0:S.leave)==null?void 0:P.call(S,O,F,V)}})}A=!1,j.hasExtendedAttrs()&&j.extended.urlId?(D=B,N=j.extended.urlId):(D=-1,N=-1)}}y(v)}};function k(C,y){if(confirm(`Do you want to navigate to ${y}?
|
|
60
60
|
|
|
@@ -135,7 +135,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
135
135
|
[`)&&!b.startsWith("[")).map(b=>b.replace(/^\d+: /,"")).join(`
|
|
136
136
|
`);return o.jsx("div",{className:`rounded overflow-hidden border border-border ${c?"":"max-h-[45vh]"} overflow-y-auto`,children:o.jsxs("div",{className:"grid grid-cols-[2.5rem_1fr]",children:[o.jsx("div",{className:"bg-bg-tertiary text-text-muted text-xs font-mono text-right pr-2 select-none py-0.5",children:g.filter(b=>!b.startsWith(`
|
|
137
137
|
[`)&&!b.startsWith("[")).map((b,_)=>{const k=b.match(/^(\d+): /);return o.jsx("div",{className:"leading-[1.5rem]",children:k?k[1]:_+1},_)})}),o.jsx("div",{className:"min-w-0 overflow-x-hidden py-0.5",children:o.jsx(ao,{code:m,language:l,variant:"block"})})]})})}),RA={error:{icon:"✗",color:"text-accent-error",bg:"bg-red-500/10",border:"border-red-500/30"},warning:{icon:"⚠",color:"text-accent-warning",bg:"bg-yellow-500/10",border:"border-yellow-500/30"},info:{icon:"ℹ",color:"text-accent-info",bg:"bg-blue-500/10",border:"border-blue-500/30"},hint:{icon:"💡",color:"text-text-muted",bg:"bg-gray-500/10",border:"border-gray-500/30"}},ib=H.memo(function({diagnostics:r}){if(r.length===0)return null;const i=r.filter(u=>u.severity==="error"),s=r.filter(u=>u.severity==="warning"),c=r.filter(u=>u.severity==="info"||u.severity==="hint");return o.jsxs("div",{className:"rounded border border-border overflow-hidden mt-2",children:[o.jsxs("div",{className:"flex items-center gap-3 px-2 py-1.5 bg-bg-tertiary border-b border-border",children:[o.jsx("span",{className:"text-xs font-medium text-text-secondary",children:"LSP Diagnostics"}),i.length>0&&o.jsxs("span",{className:"text-xs text-accent-error font-medium",children:[i.length," error",i.length!==1?"s":""]}),s.length>0&&o.jsxs("span",{className:"text-xs text-accent-warning font-medium",children:[s.length," warning",s.length!==1?"s":""]}),c.length>0&&o.jsxs("span",{className:"text-xs text-text-muted",children:[c.length," info"]})]}),o.jsx("div",{className:"max-h-48 overflow-y-auto",children:r.map((u,f)=>{const l=RA[u.severity];return o.jsxs("div",{className:`flex items-start gap-2 px-2 py-1.5 ${l.bg} border-b border-border last:border-b-0`,children:[o.jsx("span",{className:`${l.color} text-xs flex-shrink-0 w-4 text-center`,children:l.icon}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("span",{className:"text-[10px] text-text-muted font-mono",children:["Ln ",u.range.start.line+1,":",u.range.start.character+1]}),u.code&&o.jsxs("span",{className:"text-[10px] text-text-muted font-mono",children:["[",u.code,"]"]})]}),o.jsx("div",{className:"text-xs text-text-primary break-words",children:u.message})]})]},f)})})]})}),LA=H.memo(function({command:r,timeout:i,startedAt:s,streamingOutput:c,status:u,result:f,error:l,durationMs:d}){const p=H.useRef(null),[g,m]=H.useState(0);H.useEffect(()=>{p.current&&u==="pending"&&(p.current.scrollTop=p.current.scrollHeight)},[c,u]),H.useEffect(()=>{if(u!=="pending"||!s)return;const C=setInterval(()=>{m(Date.now()-s)},100);return()=>clearInterval(C)},[u,s]);const b=i/1e3,_=u==="pending"?g/1e3:(d??0)/1e3,k=u==="pending"?(c==null?void 0:c.map(C=>C.content).join(""))??"":f??"";return o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between gap-4",children:[o.jsxs("div",{className:"flex items-center gap-2 text-xs flex-1 min-w-0",children:[o.jsx("span",{className:"text-text-muted flex-shrink-0",children:"$"}),o.jsx("code",{className:"text-text-primary break-all",children:r})]}),o.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-muted flex-shrink-0",children:[u==="pending"&&o.jsx("span",{className:"animate-pulse text-accent-warning",children:"running"}),u==="interrupted"&&o.jsx("span",{className:"text-red-400",children:"interrupted"}),o.jsxs("span",{className:u==="pending"?"text-text-secondary":"text-text-muted",children:[_.toFixed(1),"s / ",b,"s"]})]})]}),u==="pending"&&o.jsx("div",{className:"h-1 bg-bg-tertiary rounded overflow-hidden",children:o.jsx("div",{className:"h-full bg-accent-warning transition-all duration-100",style:{width:`${Math.min(100,g/i*100)}%`}})}),(k||u==="pending")&&o.jsx("pre",{ref:p,className:`text-xs bg-bg-primary p-2 rounded max-h-64 overflow-y-auto ${u==="pending"?"border border-accent-warning/30":""}`,style:{overflowX:"hidden",whiteSpace:"normal"},children:u==="pending"&&c?c.map((C,y)=>o.jsx("span",{className:C.stream==="stderr"?"text-accent-warning":"",children:eo(C.content)},y)):eo(k)}),u==="error"&&l&&o.jsx("div",{className:"text-xs text-accent-error bg-accent-error/10 p-2 rounded",children:l}),u!=="pending"&&d!==void 0&&o.jsxs("div",{className:"text-[10px] text-text-muted",children:["Completed in ",(d/1e3).toFixed(2),"s"]})]})});function OA(e){switch(e){case"sensitive_file":return{title:"Sensitive File Access",description:"Accessing files that may contain secrets"};case"both":return{title:"Sensitive File Access",description:"Accessing sensitive files outside project"};case"dangerous_command":return{title:"Dangerous Command",description:"Running potentially dangerous command"};case"outside_workdir":default:return{title:"Path Access Request",description:"Accessing paths outside project directory"}}}function MA({confirmation:e}){const r=Ce(g=>g.confirmPath),i=Ce(g=>g.currentSession),s=Ce(g=>g.switchDangerLevel),{title:c,description:u}=OA(e.reason),f=e.reason==="sensitive_file"||e.reason==="both",l=f?"border-red-500/50":"border-amber-500/50",d=f?"bg-red-500/10":"bg-amber-500/10",p=()=>{i!=null&&i.id&&s("dangerous"),r(e.callId,!0,!1)};return o.jsxs("div",{className:`border ${l} ${d} rounded p-3 my-2`,children:[o.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[o.jsx(Pb,{}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("div",{className:`text-sm font-medium ${f?"text-red-400":"text-amber-400"}`,children:c}),o.jsx("div",{className:"text-xs text-text-muted",children:u})]})]}),o.jsxs("div",{className:"text-xs text-text-muted mb-2",children:[o.jsx("span",{className:"font-medium",children:e.tool})," ","wants to access:"]}),o.jsx("div",{className:"bg-bg-primary rounded p-2 mb-3 max-h-24 overflow-y-auto",children:o.jsx("ul",{className:"space-y-0.5",children:e.paths.map((g,m)=>o.jsx("li",{className:`text-xs font-mono ${f?"text-red-300":"text-amber-300"} break-all`,children:g},m))})}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx("button",{onClick:()=>r(e.callId,!1),className:"flex-1 px-3 py-1.5 text-xs font-medium rounded bg-bg-tertiary hover:bg-bg-tertiary/80 text-text-secondary border border-border transition-colors",children:"Deny"}),o.jsx("button",{onClick:()=>r(e.callId,!0,!1),className:"flex-1 px-3 py-1.5 text-xs font-medium rounded bg-accent-primary hover:bg-accent-primary/80 text-white transition-colors",children:"Allow"}),o.jsx("button",{onClick:p,className:"flex-1 px-3 py-1.5 text-xs font-medium rounded bg-red-600 hover:bg-red-700 text-white transition-colors",title:"Enable dangerous mode and allow this request",children:"Allow Everything"})]})]})}function IA(e,r){if(e==="read_file"){const s=String(r.path??""),c=r.offset,u=r.limit,f=[];return c!==void 0&&c!==1&&f.push(`offset=${c}`),u!==void 0&&f.push(`limit=${u}`),f.length>0?`${s} [${f.join(", ")}]`:s}if(e==="write_file"||e==="edit_file")return String(r.path??"");if(e==="run_command"||e==="bash")return String(r.command??"");if(e==="return_value"){const s=String(r.content??"");return s.length>60?s.slice(0,60)+"...":s}const i=JSON.stringify(r);return i.length>50?i.slice(0,50)+"...":i}function sb(e,r,i){return IA(e,r)}function BA(e){return JSON.stringify(e,null,2)}const zA={pending:{icon:"●",color:"text-accent-warning",animate:!0},success:{icon:"✓",color:"text-accent-success",animate:!1},error:{icon:"✗",color:"text-accent-error",animate:!1},interrupted:{icon:"✗",color:"text-red-400",animate:!1}},HA=H.memo(function({tool:r,args:i,status:s,variant:c="compact",forceCompact:u,result:f,error:l,durationMs:d,diagnostics:p,editContext:g,startedAt:m,streamingOutput:b,metadata:_,callId:k}){const C=r==="edit_file"||r==="write_file",y=r==="run_command"&&s==="pending",x=r==="read_file",S=u?!1:C||y||r==="return_value",[j,T]=H.useState(S),N=zA[s],D=Ce(M=>M.pendingPathConfirmation),A=s==="pending"&&D&&k&&D.callId===k?D:null;return c==="compact"?o.jsxs("div",{className:"flex items-center gap-1.5 text-xs bg-bg-tertiary rounded px-2 py-1.5",children:[o.jsx(v0,{tool:r}),o.jsx("span",{className:"text-accent-primary font-medium",children:r}),o.jsx("span",{className:"text-text-muted truncate flex-1",children:sb(r,i)}),o.jsx("span",{className:`${N.color} ${N.animate?"animate-pulse":""}`,children:s==="pending"?"...":"done"})]}):o.jsxs("div",{className:"border border-border rounded overflow-hidden my-1 min-w-0",children:[o.jsxs("button",{className:"w-full flex items-center gap-1.5 p-2 bg-bg-tertiary hover:bg-bg-tertiary/80 text-left",onClick:()=>T(!j),children:[o.jsx("span",{className:`${N.color} ${N.animate?"animate-pulse":""}`,children:N.icon}),o.jsx("span",{className:"font-mono text-accent-primary text-sm",children:r}),o.jsx("span",{className:"text-text-muted text-xs flex-1 truncate",children:sb(r,i)}),o.jsx("span",{className:"text-text-muted text-xs",children:j?"▼":"▶"})]}),A&&o.jsx(MA,{confirmation:A}),(j||x)&&o.jsxs("div",{className:"p-2 bg-bg-secondary border-t border-border space-y-2 min-w-0",children:[r==="run_command"&&o.jsx(LA,{command:String(i.command??""),timeout:i.timeout??12e4,startedAt:m,streamingOutput:b,status:s,result:f,error:l,durationMs:d}),r==="edit_file"&&s==="success"&&o.jsxs(o.Fragment,{children:[g&&g.regions.length>0?o.jsx(jA,{regions:g.regions,filePath:String(i.path??"")}):o.jsx(kA,{oldString:String(i.old_string??""),newString:String(i.new_string??""),filePath:String(i.path??"")}),p&&p.length>0&&o.jsx(ib,{diagnostics:p})]}),r==="write_file"&&s==="success"&&o.jsxs(o.Fragment,{children:[o.jsx(EA,{content:String(i.content??""),filePath:String(i.path??"")}),p&&p.length>0&&o.jsx(ib,{diagnostics:p})]}),r==="read_file"&&s==="success"&&o.jsx(DA,{result:f,metadata:_,filePath:String(i.path??""),heightExpanded:j}),r==="return_value"&&(()=>{const M=(b==null?void 0:b.map($=>$.content).join(""))??"",B=s==="pending"&&M?M:String(i.content??"");return o.jsxs("div",{children:[o.jsx("div",{className:"text-[10px] text-accent-primary font-medium mb-1 uppercase tracking-wide",children:"Sub-Agent Summary"}),o.jsx("div",{className:"text-xs prose prose-invert prose-sm max-w-none",children:o.jsx(Ui,{content:B})})]})})(),r!=="edit_file"&&r!=="write_file"&&r!=="run_command"&&r!=="read_file"&&r!=="return_value"&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-[10px] text-text-muted mb-0.5",children:"Arguments:"}),o.jsx("pre",{className:"text-xs bg-bg-primary p-1.5 rounded overflow-x-auto",children:BA(i)})]}),s==="success"&&f!==void 0&&o.jsxs("div",{children:[o.jsxs("div",{className:"text-[10px] text-text-muted mb-0.5",children:["Result",d!==void 0&&` (${d}ms)`,":"]}),o.jsx("pre",{className:"text-xs bg-bg-primary p-1.5 rounded overflow-x-auto max-h-32",children:f||"No output"})]})]}),s==="success"&&(r==="edit_file"||r==="write_file"||r==="read_file")&&d!==void 0&&o.jsxs("div",{className:"text-[10px] text-text-muted",children:["Completed in ",d,"ms"]}),s==="error"&&l&&r!=="run_command"&&o.jsxs("div",{children:[o.jsx("div",{className:"text-[10px] text-accent-error mb-0.5",children:"Error:"}),o.jsx("pre",{className:"text-xs bg-bg-primary p-1.5 rounded text-accent-error",children:l})]})]})]})}),PA={read_file:"Reading file",write_file:"Writing file",edit_file:"Editing file",run_command:"Running command",glob:"Searching files",grep:"Searching content",ask_user:"Asking user",criterion:"Managing criterion",todo_write:"Updating tasks"};function FA(e){return PA[e]??`Preparing ${e}`}const UA=H.memo(function({name:r}){const i=FA(r);return o.jsx("div",{className:"border border-border rounded overflow-hidden my-1 min-w-0 animate-pulse",children:o.jsxs("div",{className:"flex items-center gap-1.5 p-2 bg-bg-tertiary",children:[o.jsx("span",{className:"text-accent-warning animate-pulse",children:"..."}),o.jsx(v0,{tool:r}),o.jsx("span",{className:"font-mono text-accent-primary text-sm",children:r}),o.jsxs("span",{className:"text-text-muted text-xs flex-1",children:[i,"..."]})]})})}),$A={pending:{icon:"○",color:"text-text-muted"},in_progress:{icon:"●",color:"text-accent-warning",animate:!0},completed:{icon:"✓",color:"text-accent-success"}},qA=H.memo(function({todos:r}){return Array.isArray(r)?r.length===0?o.jsx("div",{className:"text-xs text-text-muted italic my-1",children:"No tasks"}):o.jsxs("div",{className:"my-1 rounded border border-border bg-bg-tertiary overflow-hidden",children:[o.jsx("div",{className:"px-2 py-1.5 border-b border-border bg-bg-secondary",children:o.jsx("span",{className:"text-xs font-medium text-text-muted",children:"Tasks"})}),o.jsx("div",{children:r.map((i,s)=>{const c=$A[i.status];return o.jsxs("div",{className:`flex items-start gap-2 px-2 py-1.5 ${s>0?"border-t border-border":""}`,children:[o.jsx("span",{className:`${(c==null?void 0:c.color)??"text-text-muted"} ${c!=null&&c.animate?"animate-pulse":""} text-sm leading-tight`,children:(c==null?void 0:c.icon)??"○"}),o.jsx("span",{className:`text-sm leading-tight ${i.status==="completed"?"text-text-muted":"text-text-primary"}`,children:i.content})]},s)})})]}):o.jsx("div",{className:"text-xs text-accent-warning italic my-1",children:"⚠️ Invalid todos data"})}),ab={add:{icon:"○",color:"text-text-muted"},update:{icon:"○",color:"text-text-muted"},remove:{icon:"○",color:"text-text-muted"},complete:{icon:"◉",color:"text-purple-400"},pass:{icon:"✓",color:"text-accent-success"},fail:{icon:"✗",color:"text-accent-error"},get:{icon:"○",color:"text-text-muted"}},_0=H.memo(function({toolCalls:r,criteria:i}){if(r.length===0)return null;const s=new Map((i==null?void 0:i.map(u=>[u.id,u]))??[]),c=r.find(u=>{var f,l;return u.arguments.action==="get"&&((f=u.result)==null?void 0:f.success)&&((l=u.result)==null?void 0:l.output)});return o.jsxs("div",{className:"my-1 rounded border border-border bg-bg-tertiary overflow-hidden",children:[o.jsx("div",{className:"px-2 py-1.5 border-b border-border bg-bg-secondary",children:o.jsx("span",{className:"text-xs font-medium text-text-muted",children:"Acceptance Criteria"})}),o.jsx("div",{children:c?(()=>{const u=c.result.output;if(u==="No criteria defined yet.")return o.jsxs("div",{className:"flex items-start gap-2 px-2 py-1.5",children:[o.jsx("span",{className:"text-text-muted text-sm leading-tight flex-shrink-0",children:"○"}),o.jsx("div",{className:"flex-1 min-w-0 text-text-muted text-sm",children:"No criteria defined yet."})]});try{return JSON.parse(u).map((l,d)=>o.jsxs("div",{className:`flex items-start gap-2 px-2 py-1.5 ${d>0?"border-t border-border":""}`,children:[o.jsx("span",{className:"text-text-muted text-sm leading-tight flex-shrink-0",children:"○"}),o.jsx("div",{className:"flex-1 min-w-0",children:o.jsx(Ui,{content:`[${l.id}] ${l.description}`})})]},l.id??d))}catch{return r.map((f,l)=>o.jsx(ob,{tc:f,index:l,criteriaMap:s},f.id??l))}})():r.map((u,f)=>o.jsx(ob,{tc:u,index:f,criteriaMap:s},u.id??f))})]})});function ob({tc:e,index:r,criteriaMap:i}){const s=e.arguments.action,c=s&&ab[s]?ab[s]:{icon:"○",color:"text-text-muted"},u=e.arguments,f=s==="remove",l=u.id,d=u.description,p=l?i.get(l):void 0,g=d??(p==null?void 0:p.description)??(f&&l?`[${l}]`:"Criterion updated"),m=u.reason,b=s==="fail";return o.jsxs("div",{className:`flex items-start gap-2 px-2 py-1.5 ${r>0?"border-t border-border":""}`,children:[o.jsx("span",{className:`${c.color} text-sm leading-tight flex-shrink-0`,children:c.icon}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("div",{className:f?"line-through text-text-muted":"",children:o.jsx(Ui,{content:g})}),m&&o.jsxs("div",{className:`mt-1 text-sm ${b?"text-accent-error":"text-text-muted"}`,children:[o.jsx("span",{className:"text-text-muted",children:"└ "}),'"',m,'"']})]})]})}function WA(e){return e==="criterion"}const GA="#6b7280";function Kl(e,r){var i;return((i=e.find(s=>s.id===r))==null?void 0:i.color)??GA}const kt=Yn(e=>{const r=async()=>{await Lh("/api/agents",e)};return{defaults:[],userItems:[],loading:!1,fetchAgents:r,fetchAgent:async i=>{try{const s=await ke(`/api/agents/${i}`);return s.ok?await s.json():null}catch{return null}},fetchDefaultContent:async i=>{try{const s=await ke(`/api/agents/defaults/${i}`);return s.ok?await s.json():null}catch{return null}},createAgent:async i=>{const s=await di("POST","/api/agents",i);return s.success&&await r(),s},updateAgent:async(i,s)=>{const c=await di("PUT",`/api/agents/${i}`,s);return c.success&&await r(),c},deleteAgent:async i=>{try{const s=await ke(`/api/agents/${i}`,{method:"DELETE"}),c=await s.json();return s.ok?(e(u=>({userItems:u.userItems.filter(f=>f.id!==i)})),{success:!0}):{success:!1,error:c.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateAgent:async i=>{try{const s=await ke(`/api/agents/${i}/duplicate`,{method:"POST"}),c=await s.json();return s.ok?(await r(),{success:!0}):{success:!1,error:c.error??"Failed to duplicate"}}catch{return{success:!1,error:"Network error"}}}}});function VA(e){const r=[];let i=[];const s=()=>{i.length>0&&(r.push({type:"criteria_group",toolCalls:i}),i=[])};for(const c of e)c.type==="tool_call"&&WA(c.toolCall.name)?i.push(c.toolCall):(s(),r.push(c));return s(),r}function KA(e,r){if(e.segments&&e.segments.length>0)return YA(e.segments,e.toolCalls??[],e.preparingToolCalls??[],e.stats,r);const i=[];if(e.thinkingContent&&i.push({type:"thinking",content:e.thinkingContent}),e.content&&i.push({type:"text",content:e.content}),e.toolCalls)for(const s of e.toolCalls)i.push({type:"tool_call",toolCall:s});if(e.preparingToolCalls)for(const s of e.preparingToolCalls)i.push({type:"preparing_tool_call",preparing:s});return r&&e.stats&&i.push({type:"stats",stats:e.stats}),i}function YA(e,r,i,s,c){const u=[],f=new Map(r.map(l=>[l.id,l]));for(const l of e)switch(l.type){case"text":u.push({type:"text",content:l.content});break;case"thinking":l.content&&l.content.trim().length>0&&u.push({type:"thinking",content:l.content});break;case"tool_call":{const d=f.get(l.toolCallId);d&&u.push({type:"tool_call",toolCall:d});break}}for(const l of i)u.push({type:"preparing_tool_call",preparing:l});return c&&s&&u.push({type:"stats",stats:s}),u}const bf=H.memo(function({message:r,showStats:i=!0,showThinking:s=!0,showVerboseToolOutput:c=!0}){const u=Ce(b=>{var _;return(_=b.currentSession)==null?void 0:_.criteria}),f=kt(b=>b.defaults),l=kt(b=>b.userItems),d=[...f,...l],p=KA(r,i),g=s?p:p.filter(b=>b.type!=="thinking"),m=VA(g);return m.length===0?null:o.jsx("div",{className:"feed-item",children:o.jsxs("div",{className:"min-w-0",children:[m.map((b,_)=>{var k,C;switch(b.type){case"thinking":return o.jsx(yA,{content:b.content},_);case"text":return o.jsx("div",{className:"prose prose-sm prose-invert max-w-none",children:o.jsx(Ui,{content:b.content})},_);case"preparing_tool_call":return o.jsx(UA,{name:b.preparing.name},`preparing-${b.preparing.index}`);case"tool_call":{const y=b.toolCall,x=y.result;if(y.name==="todo_write"){const j=y.arguments.todos,T=Array.isArray(j)?j:[];return o.jsx(qA,{todos:T},_)}const v=(k=x==null?void 0:x.output)==null?void 0:k.includes("[interrupted by user]"),S=x?v?"interrupted":x.success?"success":"error":"pending";return o.jsx(HA,{tool:y.name,args:y.arguments,status:S,variant:"expandable",forceCompact:!c,result:x==null?void 0:x.output,error:x==null?void 0:x.error,durationMs:x==null?void 0:x.durationMs,diagnostics:x==null?void 0:x.diagnostics,editContext:x==null?void 0:x.editContext,startedAt:y.startedAt,streamingOutput:y.streamingOutput,metadata:x==null?void 0:x.metadata,callId:y.id},_)}case"criteria_group":return o.jsx(_0,{toolCalls:b.toolCalls,criteria:u},_);case"stats":{const y=b.stats,x=((C=y.model.split("/").pop())==null?void 0:C.split("-").slice(0,2).join("-"))??y.model,v=Kl(d,y.mode),S=T=>T>=1e3?`${(T/1e3).toFixed(1)}k`:T.toString(),j=T=>T>=1e3?`${(T/1e3).toFixed(1)}k`:T.toFixed(1);return o.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-[10px] text-text-muted mt-3",children:[o.jsx("span",{className:"flex-1 h-px bg-border"}),o.jsx("span",{className:"text-text-secondary",children:x}),o.jsx("span",{className:"text-text-muted",children:"·"}),o.jsx("span",{style:{color:v},children:y.mode}),o.jsx("span",{className:"text-text-muted",children:"·"}),o.jsxs("span",{children:[y.totalTime.toFixed(1),"s"]}),y.toolTime>0&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-text-muted",children:"·"}),o.jsxs("span",{children:[y.toolTime.toFixed(1),"s tools"]})]}),o.jsx("span",{className:"text-text-muted",children:"·"}),o.jsxs("span",{children:[S(y.prefillTokens)," @ ",j(y.prefillSpeed)," pp"]}),o.jsx("span",{className:"text-text-muted",children:"·"}),o.jsxs("span",{children:[S(y.generationTokens)," @ ",j(y.generationSpeed)," tg"]}),o.jsx("span",{className:"text-text-muted",children:"·"}),o.jsx("button",{type:"button",className:"text-text-muted hover:text-text-secondary transition-colors",title:"View detailed stats",onClick:()=>{const T=new CustomEvent("open-turn-stats",{detail:{stats:y}});window.dispatchEvent(T)},children:o.jsx(pw,{className:"w-3 h-3"})}),o.jsx("span",{className:"flex-1 h-px bg-border"})]},_)}}}),r.partial&&o.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] text-accent-warning mt-1",children:[o.jsx(Pb,{}),o.jsx("span",{children:"Aborted"})]})]})})}),Ct=Yn((e,r)=>({defaults:[],userItems:[],activeWorkflowId:"default",loading:!1,templateVariables:[],fetchTemplateVariables:async()=>{try{const s=await(await ke("/api/workflows/template-variables")).json();e({templateVariables:s.variables??[]})}catch{}},fetchWorkflows:async()=>{e({loading:!0});try{const s=await(await ke("/api/workflows")).json();e({defaults:s.defaults??[],userItems:s.userItems??[],activeWorkflowId:s.activeWorkflowId??"default",loading:!1})}catch{e({loading:!1})}},fetchWorkflow:async i=>{try{const s=await ke(`/api/workflows/${i}`);return s.ok?await s.json():null}catch{return null}},fetchDefaultContent:async i=>{try{const s=await ke(`/api/workflows/defaults/${i}`);return s.ok?await s.json():null}catch{return null}},createWorkflow:async i=>{const s=await di("POST","/api/workflows",i);return s.success&&await r().fetchWorkflows(),s},updateWorkflow:async(i,s)=>{const c=await di("PUT",`/api/workflows/${i}`,s);return c.success&&await r().fetchWorkflows(),c},deleteWorkflow:async i=>{try{const s=await ke(`/api/workflows/${i}`,{method:"DELETE"}),c=await s.json();return s.ok?(e(u=>({userItems:u.userItems.filter(f=>f.id!==i)})),{success:!0}):{success:!1,error:c.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateWorkflow:async i=>{try{const s=await ke(`/api/workflows/${i}/duplicate`,{method:"POST"}),c=await s.json();return s.ok?(await r().fetchWorkflows(),{success:!0}):{success:!1,error:c.error??"Failed to duplicate"}}catch{return{success:!1,error:"Network error"}}}}));function Yl(e,r){const i=parseInt(e.slice(1,3),16),s=parseInt(e.slice(3,5),16),c=parseInt(e.slice(5,7),16);return`rgba(${i},${s},${c},${r})`}function XA(e){if(e<60)return`${e}s`;const r=Math.floor(e/60),i=Math.round(e%60);return i>0?`${r}m ${i}s`:`${r}m`}function ZA(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}const QA=H.memo(function({data:r}){var f;const i=Ct(l=>l.defaults),s=Ct(l=>l.userItems),u=((f=[...i,...s].find(l=>l.id===r.workflowId))==null?void 0:f.color)??r.workflowColor??"#8b949e";return o.jsxs("div",{className:"feed-item rounded p-3 border",style:{borderColor:Yl(u,.3),backgroundColor:Yl(u,.08)},children:[o.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[o.jsx(Cw,{color:u}),o.jsx("span",{className:"text-sm font-medium",style:{color:u},children:r.workflowName??"Task Completed"})]}),o.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-5 gap-2",children:[o.jsx($a,{label:"Iterations",value:String(r.iterations)}),o.jsx($a,{label:"Total time",value:XA(r.totalTimeSeconds)}),o.jsx($a,{label:"Tool calls",value:String(r.totalToolCalls)}),o.jsx($a,{label:"Tokens",value:ZA(r.totalTokensGenerated)}),o.jsx($a,{label:"Speed",value:r.avgGenerationSpeed>0?`${r.avgGenerationSpeed} tok/s`:"-"})]})]})});function $a({label:e,value:r}){return o.jsxs("div",{className:"bg-bg-primary/50 rounded px-2 py-1",children:[o.jsx("div",{className:"text-sm text-text-muted",children:e}),o.jsx("div",{className:"text-sm text-text-primary font-medium",children:r})]})}const JA=H.memo(function({data:r}){var f;const i=Ct(l=>l.defaults),s=Ct(l=>l.userItems),u=((f=[...i,...s].find(l=>l.id===r.workflowId))==null?void 0:f.color)??r.workflowColor??"#6b7280";return o.jsxs("div",{className:"feed-item flex items-center gap-2 px-3 py-2 rounded border",style:{borderColor:Yl(u,.3),backgroundColor:Yl(u,.08)},children:[o.jsx(vw,{className:"w-3 h-3 shrink-0",color:u}),o.jsx("span",{className:"text-sm font-medium",style:{color:u},children:r.workflowName}),o.jsx("span",{className:"text-text-muted text-sm",children:"started"})]})});function e5({attachments:e,messageId:r}){const[i,s]=H.useState(null),c=Ce(g=>g.visionFallbackByMessage),u=Ce(g=>g.messages),f=H.useMemo(()=>{const g=u.findIndex(m=>m.id===r);if(g===-1)return null;for(let m=g+1;m<u.length;m++){const b=u[m];if(b&&b.role==="assistant")return b.id}return null},[u,r]),l=g=>{s(g)},d=()=>{s(null)},p=g=>{const m=`${r}-${g}`;if(c[m])return c[m];if(f){const b=`${f}-${g}`;return c[b]}return null};return e.length===0?null:o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"mt-3 flex flex-wrap gap-3",children:e.map(g=>{const m=p(g.id);return o.jsxs("div",{className:"relative inline-block",children:[o.jsxs("button",{onClick:()=>l(g.data),className:"group relative inline-block",title:g.filename,disabled:(m==null?void 0:m.type)==="start",children:[o.jsx("img",{src:g.data,alt:g.filename,className:"max-w-[256px] max-h-[256px] object-contain rounded-lg border border-border hover:border-accent-primary transition-colors cursor-pointer"}),(m==null?void 0:m.type)==="start"&&o.jsx("div",{className:"absolute inset-0 bg-black/60 flex items-center justify-center rounded-lg",children:o.jsx("span",{className:"text-xs text-text-primary animate-pulse",children:"Describing image..."})})]}),(m==null?void 0:m.type)==="done"&&m.description&&o.jsxs("div",{className:"mt-2 p-2 bg-bg-tertiary rounded text-xs text-text-secondary max-w-[256px]",children:[m.description.slice(0,200),m.description.length>200?"...":""]})]},g.id)})}),i&&o.jsx(y0,{src:i,alt:"Attached image",isOpen:!0,onClose:d})]})}function t5({isOpen:e,onClose:r,promptContext:i}){const[s,c]=H.useState({systemPrompt:!1,messages:!0,tools:!0,requestOptions:!0,injectedFiles:!0,userMessage:!0}),u=f=>{c(l=>({...l,[f]:!l[f]}))};return o.jsx(jt,{isOpen:e,onClose:r,title:"Prompt Inspector",size:"lg",children:o.jsxs("div",{className:"space-y-4",children:[o.jsx(As,{title:"User Message",expanded:s.userMessage??!0,onToggle:()=>u("userMessage"),children:o.jsx("pre",{className:"text-sm text-text-secondary whitespace-pre-wrap bg-bg-tertiary rounded p-3 max-h-48 overflow-auto",children:i.userMessage||"(empty)"})}),i.messages.length>0&&o.jsx(As,{title:`Prompt Messages (${i.messages.length})`,expanded:s.messages??!0,onToggle:()=>u("messages"),children:o.jsx("div",{className:"space-y-2",children:i.messages.map((f,l)=>o.jsxs("div",{className:"border border-border rounded overflow-hidden",children:[o.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-bg-tertiary/50 text-xs text-text-muted",children:[o.jsx("span",{className:"font-mono text-text-primary",children:f.role}),o.jsx("span",{className:"rounded bg-bg-tertiary px-1.5 py-0.5",children:f.source}),f.toolCallId&&o.jsx("span",{className:"font-mono",children:f.toolCallId}),f.attachments&&f.attachments.length>0&&o.jsxs("span",{className:"rounded bg-bg-tertiary px-1.5 py-0.5",children:[f.attachments.length," attachment",f.attachments.length===1?"":"s"]})]}),f.attachments&&f.attachments.length>0&&o.jsx("div",{className:"border-b border-border px-3 py-2 text-xs text-text-muted",children:f.attachments.map(d=>d.filename).join(", ")}),o.jsx("pre",{className:"text-xs text-text-secondary whitespace-pre-wrap bg-bg-tertiary rounded-b p-3 max-h-64 overflow-auto font-mono",children:f.content||"(empty)"})]},`${f.role}-${l}`))})}),o.jsx(As,{title:`Tools (${i.tools.length})`,expanded:s.tools??!0,onToggle:()=>u("tools"),children:o.jsxs("div",{className:"space-y-2",children:[i.tools.length===0&&o.jsx("div",{className:"text-sm text-text-muted",children:"No tools sent with this request."}),i.tools.map((f,l)=>o.jsxs("div",{className:"bg-bg-tertiary rounded p-3 space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsx("span",{className:"font-mono text-sm text-text-primary",children:f.name}),o.jsx("span",{className:"text-xs text-text-muted",children:"parameters"})]}),o.jsx("div",{className:"text-sm text-text-secondary",children:f.description}),o.jsx("pre",{className:"text-xs text-text-secondary whitespace-pre-wrap max-h-48 overflow-auto font-mono",children:JSON.stringify(f.parameters,null,2)})]},`${f.name}-${l}`))]})}),o.jsx(As,{title:"Request Options",expanded:s.requestOptions??!0,onToggle:()=>u("requestOptions"),children:o.jsx("pre",{className:"text-xs text-text-secondary whitespace-pre-wrap bg-bg-tertiary rounded p-3 max-h-48 overflow-auto font-mono lowercase",children:JSON.stringify(i.requestOptions,null,2)})}),i.injectedFiles.length>0&&o.jsx(As,{title:`Injected Files (${i.injectedFiles.length})`,expanded:s.injectedFiles??!0,onToggle:()=>u("injectedFiles"),children:o.jsx("div",{className:"space-y-2",children:i.injectedFiles.map((f,l)=>o.jsx(n5,{file:f,expanded:s[`file-${l}`]??!1,onToggle:()=>u(`file-${l}`)},l))})}),o.jsx(As,{title:"System Prompt",expanded:s.systemPrompt??!1,onToggle:()=>u("systemPrompt"),badge:`${Math.round(i.systemPrompt.length/1e3)}K chars`,children:o.jsx("pre",{className:"text-xs text-text-secondary whitespace-pre-wrap bg-bg-tertiary rounded p-3 max-h-96 overflow-auto font-mono",children:i.systemPrompt})})]})})}function n5({file:e,expanded:r,onToggle:i}){return o.jsxs("div",{className:"bg-bg-tertiary rounded overflow-hidden",children:[o.jsxs("button",{onClick:i,className:"w-full flex items-center gap-2 p-2 hover:bg-bg-primary/30 transition-colors",children:[o.jsx(ur,{className:`w-3 h-3 text-text-muted transition-transform ${r?"rotate-90":""}`}),o.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded ${e.source==="global"?"bg-purple-500/20 text-purple-400":e.source==="project"?"bg-blue-500/20 text-blue-400":"bg-green-500/20 text-green-400"}`,children:e.source}),o.jsx("span",{className:"text-sm text-text-primary font-mono truncate flex-1 text-left",children:e.path}),e.content&&o.jsxs("span",{className:"text-xs text-text-muted",children:[Math.round(e.content.length/1e3),"K chars"]})]}),r&&e.content&&o.jsx("div",{className:"border-t border-border/50 p-2",children:o.jsx("pre",{className:"text-xs text-text-secondary whitespace-pre-wrap max-h-64 overflow-auto font-mono",children:e.content})})]})}function As({title:e,expanded:r,onToggle:i,badge:s,children:c}){return o.jsxs("div",{className:"border border-border rounded overflow-hidden",children:[o.jsx("button",{onClick:i,className:"w-full flex items-center justify-between p-3 bg-bg-tertiary/50 hover:bg-bg-tertiary transition-colors",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ur,{className:`w-4 h-4 text-text-muted transition-transform ${r?"rotate-90":""}`}),o.jsx("span",{className:"font-medium text-text-primary",children:e}),s&&o.jsx("span",{className:"text-xs text-text-muted bg-bg-tertiary px-1.5 py-0.5 rounded",children:s})]})}),r&&o.jsx("div",{className:"p-3 border-t border-border",children:c})]})}function r5({content:e,promptContext:r,align:i="right"}){const[s,c]=H.useState(!1),[u,f]=H.useState(!1),[l,d]=H.useState(!1),p=H.useRef(null);H.useEffect(()=>{const b=_=>{p.current&&!p.current.contains(_.target)&&c(!1)};return s&&document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[s]);const g=async()=>{try{if(navigator.clipboard)await navigator.clipboard.writeText(e);else{const b=document.createElement("textarea");b.value=e,b.style.position="fixed",b.style.left="-999999px",document.body.appendChild(b),b.select(),document.execCommand("copy"),document.body.removeChild(b)}d(!0),c(!1),window.setTimeout(()=>d(!1),1500)}catch(b){console.error("Failed to copy:",b)}},m=i==="right";return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:`flex items-start gap-1.5 ${m?"":"order-first"}`,children:[l&&o.jsx(Mr,{className:"w-4 h-4 text-accent-success"}),o.jsxs("div",{ref:p,className:"relative",children:[o.jsx("button",{onClick:()=>c(!s),className:"p-1 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary",title:"Message options",children:o.jsx(Dh,{})}),s&&o.jsxs("div",{className:`absolute top-full mt-1 bg-bg-secondary border border-border rounded shadow-xl z-50 py-1 min-w-36 ${m?"right-0":"left-0"}`,children:[o.jsxs("button",{onClick:g,className:"w-full px-3 py-1.5 text-left text-sm text-text-primary hover:bg-bg-tertiary flex items-center gap-2",children:[o.jsx(Jl,{className:"w-4 h-4"}),"Copy"]}),r&&o.jsxs("button",{onClick:()=>{f(!0),c(!1)},className:"w-full px-3 py-1.5 text-left text-sm text-text-primary hover:bg-bg-tertiary flex items-center gap-2",children:[o.jsx(ec,{className:"w-4 h-4"}),"Inspect"]})]})]})]}),r&&o.jsx(t5,{isOpen:u,onClose:()=>f(!1),promptContext:r})]})}function i5({message:e}){const[r,i]=H.useState(!1);if(e.messageKind!=="auto-prompt")return null;const s=e.metadata,c=(s==null?void 0:s.color)??"#6b7280",u=(s==null?void 0:s.name)??"Agent",f=(s==null?void 0:s.type)??"agent",d={agent:"definition injected",workflow:"instructions",compaction:"prompt injected",subagent:"instructions"}[f]??"injected",p=f==="workflow"||f==="subagent";return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-[10px] text-text-muted font-mono mt-3 mb-4",children:[o.jsx("span",{className:"flex-1 h-px bg-border"}),o.jsx("span",{className:`w-1.5 h-1.5 rounded-full flex-shrink-0 ${p?"":"cursor-pointer"}`,style:{backgroundColor:c},onClick:()=>!p&&i(!0)}),o.jsx("span",{className:p?"":"cursor-pointer hover:text-text-secondary transition-colors",style:{color:c},onClick:()=>!p&&i(!0),children:u}),o.jsx("span",{children:"·"}),o.jsx("span",{className:p?"":"cursor-pointer hover:text-text-secondary transition-colors",onClick:()=>!p&&i(!0),children:d}),o.jsx("span",{className:"flex-1 h-px bg-border"})]}),p&&o.jsx("div",{className:"flex justify-center feed-item mb-4",children:o.jsx("div",{className:"max-w-[75%] rounded p-3 bg-bg-tertiary/50 text-text-secondary text-sm",style:{borderLeft:`3px solid ${c}`},children:o.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs",children:e.content})})}),o.jsx(jt,{isOpen:r,onClose:()=>i(!1),title:`${u} Prompt`,size:"lg",children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"w-3 h-3 rounded-full",style:{backgroundColor:c}}),o.jsx("span",{className:"text-sm text-text-primary font-medium",children:u}),o.jsxs("span",{className:"text-xs text-text-muted",children:["(",f,")"]})]}),o.jsx("div",{className:"h-full min-h-96",children:o.jsx("pre",{className:"text-sm text-text-secondary whitespace-pre-wrap bg-bg-tertiary rounded p-4 h-full min-h-96 overflow-auto font-mono",children:e.content})})]})})]})}function s5({message:e,promptContext:r}){const i=e.messageKind==="auto-prompt",s=e.messageKind==="command",c=e.isSystemGenerated;return o.jsxs("div",{className:"flex justify-end items-start gap-1.5 feed-item",children:[!c&&o.jsx(r5,{content:e.content,promptContext:r,align:"right"}),o.jsxs("div",{className:`max-w-[75%] rounded p-2 ${c?s?"bg-teal-500/10 border border-teal-500/30":i?"bg-slate-500/10 border border-slate-500/30":"bg-amber-500/10 border border-amber-500/30":"bg-accent-primary/15 text-white"}`,children:[c&&o.jsx("span",{className:`text-[10px] block mb-0.5 ${s?"text-teal-400":i?"text-slate-400":"text-amber-400"}`,children:s?"Command":i?"Auto":"System"}),o.jsx("div",{className:`whitespace-pre-wrap text-sm ${c?`${s?"text-teal-200":i?"text-slate-200":"text-amber-200 italic"}`:""}`,children:e.content}),e.attachments&&e.attachments.length>0&&o.jsx(e5,{attachments:e.attachments,messageId:e.id})]})]})}const S0=H.memo(function({message:r,isLastAssistantMessage:i=!1,promptContext:s}){const c=r.role==="user",u=r.role==="assistant",f=r.role==="system",l=r.role==="tool";if(u)return o.jsx(bf,{message:r,showStats:i});if(f&&r.isCompacted)return o.jsxs("div",{className:"feed-item bg-bg-tertiary/50 border border-border rounded p-2",children:[o.jsx("div",{className:"text-text-muted text-xs mb-0.5",children:"[Compacted]"}),o.jsx("div",{className:"text-text-secondary text-xs whitespace-pre-wrap",children:r.content.replace(`[COMPACTED HISTORY]
|
|
138
|
-
`,"")})]});if(l)return o.jsxs("div",{className:"feed-item bg-bg-tertiary/30 border-l-2 border-accent-primary rounded-r p-2",children:[o.jsxs("div",{className:"text-accent-primary text-xs mb-0.5",children:["Tool: ",r.toolName]}),o.jsxs("pre",{className:"text-text-secondary text-xs whitespace-pre-wrap overflow-x-auto max-h-32",children:[r.content.slice(0,500),r.content.length>500&&"..."]})]});if(r.messageKind==="workflow-started")try{const d=JSON.parse(r.content);return o.jsx(JA,{data:d})}catch{}if(r.messageKind==="task-completed")try{const d=JSON.parse(r.content);return o.jsx(QA,{data:d})}catch{}return r.messageKind==="context-reset"?o.jsxs("div",{className:"flex items-center gap-4 mb-6 text-text-muted text-xs uppercase tracking-wide",children:[o.jsx("div",{className:"flex-1 border-t border-border"}),o.jsx("span",{children:r.content}),o.jsx("div",{className:"flex-1 border-t border-border"})]}):r.messageKind==="auto-prompt"&&r.isSystemGenerated?o.jsx(i5,{message:r}):c?o.jsx(s5,{message:r,promptContext:s}):o.jsx("div",{className:"flex justify-start feed-item",children:o.jsx("div",{className:"max-w-[75%] rounded p-2 bg-bg-tertiary text-text-primary",children:o.jsx(Ui,{content:r.content})})})});function a5({stats:e,onClose:r}){var i;return o.jsx(jt,{isOpen:!0,onClose:r,title:"Turn Stats",size:"md",children:o.jsxs("div",{className:"space-y-4",children:[o.jsx("div",{className:"flex items-center gap-3",children:o.jsxs("p",{className:"text-xs text-text-muted",children:[e.model," · ",e.mode]})}),o.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[o.jsx(Ol,{label:"Total Time",value:`${e.totalTime.toFixed(1)}s`}),o.jsx(Ol,{label:"Prefill",value:e.prefillTokens>=1e3?`${(e.prefillTokens/1e3).toFixed(1)}k`:String(e.prefillTokens)}),o.jsx(Ol,{label:"Generated",value:e.generationTokens>=1e3?`${(e.generationTokens/1e3).toFixed(1)}k`:String(e.generationTokens)}),o.jsx(Ol,{label:"LLM Calls",value:String(((i=e.llmCalls)==null?void 0:i.length)??1)})]}),e.llmCalls&&e.llmCalls.length>0&&o.jsxs("div",{children:[o.jsx("h4",{className:"text-sm font-medium text-text-secondary mb-2",children:"LLM Calls"}),e.llmCalls.map((s,c)=>o.jsxs("div",{className:"bg-bg-tertiary/30 rounded p-3 mb-2",children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsxs("span",{className:"text-xs text-text-muted",children:["Call ",c+1]}),o.jsxs("span",{className:"text-xs text-text-muted",children:[s.ttft.toFixed(2),"s TTFT · ",s.completionTime.toFixed(2),"s gen"]})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[o.jsxs("div",{children:[o.jsx("span",{className:"text-text-muted",children:"Tokens:"})," ",o.jsxs("span",{className:"text-text-primary",children:[s.promptTokens," → ",s.completionTokens]})]}),o.jsxs("div",{className:"flex flex-wrap gap-x-2 gap-y-1",children:[s.temperature!==void 0&&o.jsx(Ml,{label:"temp",value:s.temperature.toFixed(2)}),s.topP!==void 0&&o.jsx(Ml,{label:"topP",value:s.topP.toFixed(2)}),s.topK!==void 0&&o.jsx(Ml,{label:"topK",value:String(s.topK)}),s.maxTokens!==void 0&&o.jsx(Ml,{label:"maxTok",value:String(s.maxTokens)})]})]})]},c))]})]})})}function Ol({label:e,value:r}){return o.jsxs("div",{className:"bg-bg-tertiary/50 rounded p-3",children:[o.jsx("div",{className:"text-xs text-text-muted",children:e}),o.jsx("div",{className:"text-lg font-semibold text-text-primary",children:r})]})}function Ml({label:e,value:r}){return o.jsxs("span",{className:"bg-bg-tertiary px-1.5 py-0.5 rounded text-text-primary",children:[o.jsxs("span",{className:"text-text-muted",children:[e,":"]})," ",r]})}const w0=(e,r)=>{const i=H.useRef(!0),s=H.useRef(null),[c,u]=H.useState(!0),f=()=>{const l=e.current;l&&(l.scrollTop=l.scrollHeight)};return H.useEffect(()=>{const l=e.current;if(!l)return;const d=_=>{if(_.deltaY>0){requestAnimationFrame(()=>requestAnimationFrame(()=>{l.scrollHeight-l.scrollTop-l.offsetHeight<100&&(i.current=!0,u(!0))}));return}i.current=!1,u(!1)},p=_=>{_.touches[0]&&(s.current=_.touches[0].clientY)},g=_=>{if(s.current===null)return;const k=_.touches[0];if(!k)return;if(k.clientY-s.current>0){i.current=!1,u(!1);return}requestAnimationFrame(()=>requestAnimationFrame(()=>{l.scrollHeight-l.scrollTop-l.offsetHeight<100&&(i.current=!0,u(!0))}))},m=new MutationObserver(()=>{i.current&&requestAnimationFrame(f)}),b=setInterval(()=>{i.current&&f()},1e3);return l.addEventListener("wheel",d,{passive:!0}),l.addEventListener("touchstart",p,{passive:!0}),l.addEventListener("touchmove",g,{passive:!0}),m.observe(l,{childList:!0,subtree:!0,characterData:!0}),()=>{l.removeEventListener("wheel",d),l.removeEventListener("touchstart",p),l.removeEventListener("touchmove",g),m.disconnect(),clearInterval(b)}},[r==null?void 0:r.id]),{force_scroll_to_bottom:()=>{i.current=!0,u(!0),f()},isAutoScrollActive:c,setAutoScroll:l=>{i.current=l,u(l),l&&f()}}},o5={verifier:"Verification",code_reviewer:"Code Review",test_generator:"Test Generation",debugger:"Debug"};function l5(e){return{backgroundColor:`${e}20`,color:e,borderColor:`${e}4d`}}function lb(e,r){return r||e>85?"text-accent-error":e>60?"text-accent-warning":"text-text-muted"}function c5({contextState:e}){const{currentTokens:r,maxTokens:i,compactionCount:s,dangerZone:c}=e,u=Math.round(r/i*100);return o.jsxs("div",{className:"flex items-center gap-1.5 text-[10px]",children:[o.jsxs("span",{className:lb(u,c),children:[Ul(r),"/",Ul(i)]}),o.jsxs("span",{className:lb(u,c),children:["(",u,"%)"]}),o.jsx(Jb,{percent:u,dangerZone:c,size:"sm"}),c&&o.jsx("span",{className:"text-accent-error animate-pulse",children:"Low!"}),s>0&&o.jsxs("span",{className:"text-text-muted bg-bg-tertiary px-1 rounded",children:[s,"x"]})]})}const u5=H.memo(function({messages:r,subAgentType:i,subAgentId:s,isStreaming:c}){const u=H.useRef(null),f=H.useRef(null),[l,d]=H.useState(!1),p=kt(D=>D.defaults),g=kt(D=>D.userItems),m=[...p,...g],b=Ce(D=>D.subAgentContextStates[s]),{showThinking:_,showVerboseToolOutput:k}=Nb(),{isAutoScrollActive:C,setAutoScroll:y}=w0(f,null);H.useEffect(()=>{c||y(!0)},[c]);const x=H.useCallback(()=>{const D=!l;d(D),D&&setTimeout(()=>{var A;(A=u.current)==null||A.scrollIntoView({block:"start",behavior:"smooth"})},220)},[l]),v=m.find(D=>D.id===i),S=(v==null?void 0:v.name)??o5[i]??i,j=Kl(m,i),T=l5(j),N=r.filter(D=>D.role!=="tool");return o.jsxs("div",{ref:u,className:"feed-item border border-border rounded overflow-hidden bg-bg-secondary",children:[o.jsxs("div",{className:"w-full flex items-center justify-between px-2 py-1 border-b relative",style:T,children:[o.jsx("span",{className:"text-xs font-medium",children:S}),o.jsx("div",{className:"absolute left-1/2 -translate-x-1/2",children:b&&o.jsx(c5,{contextState:b})}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("button",{type:"button",className:"text-sm text-text-muted hover:text-text-primary flex items-center gap-1.5",onClick:()=>y(!C),children:[o.jsx("span",{className:`w-1 h-1 rounded-full ${C?"bg-accent-success":"border border-text-muted"}`}),"live"]}),o.jsxs("button",{type:"button",className:"text-[10px] px-1.5 py-0.5 rounded bg-bg-tertiary",onClick:x,children:[l?"▼":"▶"," Expand"]})]})]}),o.jsx("div",{ref:f,className:`${l?"max-h-[calc(100vh-10rem)]":"max-h-80"} overflow-y-auto p-2 transition-[max-height] duration-200`,children:N.map(D=>D.role==="assistant"?o.jsx(bf,{message:D,showStats:!0,showThinking:_,showVerboseToolOutput:k},D.id):o.jsx(S0,{message:D,isLastAssistantMessage:!1},D.id))})]})});function d5(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"")}function h5({agent:e,isBuiltIn:r,isConfirmingDelete:i,onView:s,onEdit:c,onDuplicate:u,onDelete:f}){return o.jsxs(Ub,{isBuiltIn:r,isConfirmingDelete:i,onView:s,onEdit:c,onDuplicate:u,onDelete:f,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0",style:{backgroundColor:e.color??"#6b7280"}}),o.jsx("span",{className:"text-text-primary text-sm font-medium",children:e.name}),o.jsx("span",{className:"text-text-muted text-xs font-mono",children:e.id}),r&&o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-medium bg-bg-primary text-text-muted",children:"Built-in"})]}),e.description&&o.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:e.description}),o.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[e.allowedTools.slice(0,5).map(l=>o.jsx("span",{className:"text-[10px] font-mono text-text-muted bg-bg-primary px-1 py-0.5 rounded",children:l},l)),e.allowedTools.length>5&&o.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",e.allowedTools.length-5," more"]})]})]})}function cb({title:e,agents:r,subagents:i,isBuiltIn:s,onView:c,onDuplicate:u,onEdit:f,onDelete:l}){if(r.length===0&&i.length===0)return null;const d=p=>o.jsx(h5,{agent:p,isBuiltIn:s,isConfirmingDelete:!1,onView:()=>c(p.id),onEdit:s?void 0:()=>f==null?void 0:f(p.id),onDuplicate:()=>u(p.id),onDelete:s?void 0:()=>l==null?void 0:l(p.id)},p.id);return o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:e}),o.jsxs("div",{className:"space-y-2",children:[r.map(d),i.length>0&&o.jsxs("div",{className:"mt-3",children:[o.jsx("div",{className:"text-xs text-text-muted uppercase tracking-wider mb-1.5",children:"Sub-agents"}),o.jsx("div",{className:"space-y-2",children:i.map(d)})]})]})]})}function f5({isOpen:e,onClose:r,initialEditId:i}){const s=kt(fe=>fe.defaults),c=kt(fe=>fe.userItems),u=kt(fe=>fe.loading),f=kt(fe=>fe.fetchAgents),l=kt(fe=>fe.fetchAgent),d=kt(fe=>fe.fetchDefaultContent),p=kt(fe=>fe.createAgent),g=kt(fe=>fe.updateAgent),m=kt(fe=>fe.deleteAgent),[b,_]=H.useState("list"),[k,C]=H.useState(null),[y,x]=H.useState(!1),[v,S]=H.useState(""),[j,T]=H.useState(""),[N,D]=H.useState(""),[A,M]=H.useState(!0),[B,$]=H.useState([]),[V,W]=H.useState("#6b7280"),[O,F]=H.useState(""),[P,Z]=H.useState(""),[G,I]=H.useState(!1),[R,z]=H.useState([]);function Y(fe){const Ae=new Map;for(const Be of fe){const ot=Be.indexOf(":");if(ot===-1)Ae.set(Be,new Set);else{const ue=Be.slice(0,ot),Ne=Be.slice(ot+1).split(",").filter(Boolean);Ae.set(ue,new Set(Ne))}}return Ae}function U(fe){const Ae=[];for(const[Be,ot]of fe)ot.size===0?Ae.push(Be):Ae.push(`${Be}:${[...ot].join(",")}`);return Ae}const ie=Y(B),Q=(fe,Ae)=>{const Be=new Map(ie),ot=Be.get(fe)||new Set,ue=new Set(ot);ue.has(Ae)?ue.delete(Ae):ue.add(Ae),ue.size===0?Be.set(fe,new Set):Be.set(fe,ue),$(U(Be))},ee=fe=>{const Ae=new Map(ie);Ae.has(fe)?Ae.delete(fe):Ae.set(fe,new Set),$(U(Ae))},X=fe=>{S(fe.metadata.name),T(fe.metadata.id),D(fe.metadata.description),M(fe.metadata.subagent),$(fe.metadata.allowedTools),W(fe.metadata.color??"#6b7280"),F(fe.prompt),Z("")},q=(fe,Ae,Be)=>{S(fe.metadata.name+" (copy)"),T(`${Ae}-copy-${Date.now()}`),D(fe.metadata.description),M(fe.metadata.subagent),$(fe.metadata.allowedTools),W(fe.metadata.color??"#6b7280"),F(fe.prompt),Z(""),C(null),x(!1),_("edit")},oe=(fe,Ae)=>{X(fe),C(Ae),x(!0),_("edit")};H.useEffect(()=>{e&&(f(),ke("/api/tools").then(fe=>fe.json()).then(fe=>z(fe.tools||[])).catch(()=>z([])),i?s.some(Ae=>Ae.id===i)?d(i).then(Ae=>{Ae&&q(Ae,i)}):l(i).then(Ae=>{Ae&&(X(Ae),C(i),x(!1),_("edit"))}):(_("list"),C(null),x(!1)))},[e,f,l,d,i]);const re=async fe=>{if(s.some(Be=>Be.id===fe)){const Be=await d(fe);if(!Be)return;oe(Be,fe)}else{const Be=await l(fe);if(!Be)return;oe(Be,fe)}},ve=async fe=>{const Ae=await d(fe);Ae&&q(Ae,fe)},be=()=>{C(null),S(""),T(""),D(""),M(!0),$(["read_file"]),W("#6b7280"),F(""),Z(""),x(!1),_("edit")},Re=async fe=>{const Ae=await l(fe);Ae&&(X(Ae),C(fe),x(!1),_("edit"))},Ie=async fe=>{await m(fe)},He=async()=>{const fe=k??j;if(!fe||!v||!O){Z("Name and prompt are required.");return}I(!0),Z("");const Ae={metadata:{id:fe,name:v,description:N,subagent:A,allowedTools:B,color:V},prompt:O},Be=k?await g(k,Ae):await p(Ae);if(I(!1),!Be.success){Z(Be.error??"Failed to save agent.");return}i?r():_("list")},Ue=()=>{i?r():(_("list"),x(!1))},je=fe=>{S(fe),k||T(d5(fe))},me=s.filter(fe=>fe.subagent),Te=s.filter(fe=>!fe.subagent),$e=c.filter(fe=>fe.subagent),Lt=c.filter(fe=>!fe.subagent);return b==="edit"?o.jsx(jt,{isOpen:e,onClose:Ue,title:y?`${v}`:k?"Edit Agent":"New Agent",size:"xl",children:o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"space-y-3",children:[P&&o.jsx(Bh,{message:P}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Mi,{label:"Name",value:v,onChange:je,placeholder:"My Agent",readOnly:y}),o.jsx(Mi,{label:"ID",value:j,onChange:T,readOnly:!0,placeholder:"my_agent",hint:"(read-only)",mono:!0})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Mi,{label:"Description",value:N,onChange:D,placeholder:"What this agent does",readOnly:y}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Type"}),o.jsxs("div",{className:"flex items-center gap-3 h-[34px]",children:[o.jsx("button",{onClick:()=>!y&&M(!0),className:`px-2.5 py-1 rounded text-xs font-medium transition-colors ${A?"bg-accent-primary/25 text-accent-primary":"bg-bg-tertiary text-text-muted hover:text-text-secondary"} ${y?"pointer-events-none opacity-60":""}`,children:"Sub-agent"}),o.jsx("button",{onClick:()=>!y&&M(!1),className:`px-2.5 py-1 rounded text-xs font-medium transition-colors ${A?"bg-bg-tertiary text-text-muted hover:text-text-secondary":"bg-accent-primary/25 text-accent-primary"} ${y?"pointer-events-none opacity-60":""}`,children:"Top-level"}),o.jsxs("div",{className:"flex items-center gap-1.5 ml-auto",children:[o.jsx("label",{className:"text-xs text-text-secondary",children:"Color"}),o.jsx("input",{type:"color",value:V,onChange:fe=>!y&&W(fe.target.value),disabled:y,className:"w-6 h-6 rounded cursor-pointer border border-border bg-transparent"})]})]})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Tools"}),o.jsx("div",{className:"flex flex-wrap gap-1.5 p-2 bg-bg-tertiary border border-border rounded max-h-32 overflow-y-auto",children:R.map(fe=>{const Ae=ie.has(fe.name),Be=fe.actions.length>0,ot=ie.get(fe.name)||new Set,ue=o.jsxs("button",{className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${Ae?"bg-accent-primary/25 text-accent-primary":"bg-bg-primary text-text-muted"}`,children:[o.jsx("span",{children:fe.name}),Be&&o.jsx("span",{className:`text-[10px] ${Ae&&ot.size>0?"text-accent-primary":"text-text-muted"}`,children:"*"})]},fe.name);return Be?y?o.jsxs("button",{className:"px-1.5 py-0.5 rounded text-xs font-mono flex items-center gap-1 bg-bg-primary text-text-muted pointer-events-none opacity-60",children:[o.jsx("span",{children:fe.name}),o.jsx("span",{className:"text-[10px]",children:"*"})]},fe.name):o.jsx(lo,{trigger:ue,minWidth:"160px",items:[...fe.actions.map(_e=>({label:o.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",htmlFor:`${fe.name}-${_e}`,children:[o.jsx("input",{type:"checkbox",id:`${fe.name}-${_e}`,checked:ot.has(_e),onChange:()=>Q(fe.name,_e),disabled:y,className:"w-3 h-3 rounded accent-accent-primary"}),o.jsx("span",{children:_e})]}),closeOnClick:!1})),{label:Ae?"Deselect all":"Select all",closeOnClick:!1,onClick:()=>{if(Ae)ee(fe.name);else{const _e=new Map(ie);_e.set(fe.name,new Set(fe.actions)),$(U(_e))}}}]},fe.name):o.jsx("button",{onClick:()=>!y&&ee(fe.name),className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${Ae?"bg-accent-primary/25 text-accent-primary":"bg-bg-primary text-text-muted hover:text-text-secondary"} ${y?"pointer-events-none":"cursor-pointer"}`,children:o.jsx("span",{children:fe.name})},fe.name)})})]})]}),o.jsxs("div",{className:"flex-1 min-h-[150px] border-t border-border pt-3 flex flex-col",children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Prompt"}),o.jsx("textarea",{value:O,onChange:fe=>!y&&F(fe.target.value),readOnly:y,placeholder:"Instructions for this agent...",className:`flex-1 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-none focus:outline-none focus:ring-1 focus:ring-accent-primary ${y?"opacity-60":""}`})]}),o.jsx(Ow,{onCancel:Ue,onSave:He,saving:G,saveDisabled:!v||!O||y}),y&&o.jsx("div",{className:"flex justify-end mt-2",children:o.jsx(it,{variant:"primary",onClick:()=>{S(v+" (copy)"),T(`${k}-copy-${Date.now()}`),C(null),x(!1)},children:"Duplicate & Customize"})})]})}):o.jsxs(jt,{isOpen:e,onClose:r,title:"Agents",size:"lg",children:[o.jsxs("div",{className:"flex items-center justify-between mb-4",children:[o.jsx("p",{className:"text-text-secondary text-sm",children:"Agents define behavior, tools, and prompts for top-level modes and sub-agents."}),o.jsx("div",{className:"flex items-center gap-2 flex-shrink-0 ml-3",children:o.jsx(it,{variant:"primary",size:"sm",onClick:be,children:"+ New"})})]}),u&&s.length===0&&c.length===0?o.jsx("div",{className:"text-text-muted text-sm",children:"Loading agents..."}):s.length===0&&c.length===0?o.jsx("div",{className:"text-text-muted text-sm",children:"No agents defined."}):o.jsxs("div",{className:"space-y-4",children:[s.length>0&&o.jsx(cb,{title:"Built-in",agents:Te,subagents:me,isBuiltIn:!0,onView:re,onDuplicate:ve}),c.length>0&&o.jsx(cb,{title:"Custom",agents:Lt,subagents:$e,isBuiltIn:!1,onView:re,onDuplicate:ve,onEdit:Re,onDelete:Ie})]})]})}function p5(){const e=Ce(x=>{var v;return(v=x.currentSession)==null?void 0:v.mode}),r=Ce(x=>x.switchMode),i=kt(x=>x.defaults),s=kt(x=>x.userItems),c=kt(x=>x.fetchAgents),u=[...i,...s],[f,l]=H.useState(!1),[d,p]=H.useState(!1),[g,m]=H.useState(null),b=H.useRef(null);if(H.useEffect(()=>{c()},[c]),H.useEffect(()=>{function x(v){b.current&&!b.current.contains(v.target)&&l(!1)}return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[]),!e)return null;const _=u.filter(x=>!x.subagent),k=_.find(x=>x.id===e),C=(k==null?void 0:k.name)??e,y=Kl(u,e);return o.jsxs("div",{className:"relative",ref:b,children:[o.jsxs("button",{type:"button",onClick:()=>l(!f),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors",title:"Switch agent",children:[o.jsx("span",{className:"text-sm font-medium",style:{color:y},children:C}),o.jsx(ur,{className:`w-3 h-3 text-text-muted transition-transform ${f?"rotate-180":""}`})]}),f&&_.length>0&&o.jsxs("div",{className:"absolute bottom-full left-0 mb-1 w-56 bg-bg-secondary border border-border rounded-lg shadow-lg overflow-hidden z-50",children:[_.map((x,v)=>{const S=x.id===e,j=Kl(u,x.id),T=v<4?`Ctrl+${v+1}`:null;return o.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 text-sm transition-colors group ${S?"bg-bg-tertiary":"hover:bg-bg-tertiary cursor-pointer"}`,children:[o.jsxs("button",{type:"button",onClick:()=>{S||r(x.id),l(!1)},className:"flex-1 text-left flex items-center gap-2 min-w-0",children:[o.jsx("span",{className:"font-medium truncate",style:{color:j},children:x.name}),S&&o.jsx(Mr,{className:"w-3.5 h-3.5 text-text-muted shrink-0"})]}),T&&o.jsxs("span",{className:"shrink-0 px-1.5 py-0.5 text-[10px] bg-bg-tertiary text-text-muted rounded",children:["Ctrl+",v+1]})]},x.id)}),o.jsx("div",{className:"border-t border-border p-1",children:o.jsx("button",{type:"button",onClick:()=>{l(!1),p(!0)},className:"w-full text-left px-3 py-1.5 rounded text-sm text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors",children:"Manage Agents..."})})]}),o.jsx(f5,{isOpen:d,onClose:()=>{p(!1),m(null)},initialEditId:g})]})}function m5(){const e=Ce(s=>s.currentSession),r=Ce(s=>s.switchDangerLevel);if(!e)return null;const i=e.dangerLevel??"normal";return o.jsxs("div",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-bg-tertiary/50",children:[o.jsx("button",{type:"button",onClick:()=>r("normal"),className:`px-2 py-0.5 text-xs font-medium rounded transition-colors ${i==="normal"?"bg-accent-success/20 text-accent-success":"text-text-muted hover:text-text-primary hover:bg-bg-tertiary"}`,title:"Normal mode - requires path confirmation",children:"Normal"}),o.jsx("button",{type:"button",onClick:()=>r("dangerous"),className:`px-2 py-0.5 text-xs font-medium rounded transition-colors ${i==="dangerous"?"bg-red-500/20 text-red-400":"text-text-muted hover:text-text-primary hover:bg-bg-tertiary"}`,title:"Dangerous mode - bypasses all confirmations",children:"Dangerous"})]})}function g5({question:e}){const r=Ce(f=>f.answerQuestion),[i,s]=H.useState(""),c=()=>{r(e.callId,i)},u=f=>{f.key==="Enter"&&!f.shiftKey&&(f.preventDefault(),c())};return o.jsx(jt,{isOpen:!0,onClose:()=>{},size:"sm",closeOnBackdropClick:!1,closeOnEscape:!1,showCloseButton:!1,children:o.jsxs("div",{className:"space-y-4",children:[o.jsx("p",{className:"text-sm text-text-primary",children:e.question}),o.jsx("textarea",{value:i,onChange:f=>s(f.target.value),onKeyDown:u,placeholder:"Type your answer here...",className:"w-full min-h-[120px] px-3 py-2 bg-bg-tertiary border border-border rounded text-sm text-text-primary placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-accent-primary/50 resize-y",autoFocus:!0}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(it,{variant:"secondary",size:"sm",onClick:()=>r(e.callId,""),children:"Skip"}),o.jsx(it,{variant:"primary",size:"sm",onClick:c,children:"Send Answer"})]})]})})}function x5(){const e=Ce(s=>s.connectionStatus),r=Ce(s=>s.reconnect);if(e==="connected")return null;const i=e==="reconnecting";return o.jsxs("div",{className:`
|
|
138
|
+
`,"")})]});if(l)return o.jsxs("div",{className:"feed-item bg-bg-tertiary/30 border-l-2 border-accent-primary rounded-r p-2",children:[o.jsxs("div",{className:"text-accent-primary text-xs mb-0.5",children:["Tool: ",r.toolName]}),o.jsxs("pre",{className:"text-text-secondary text-xs whitespace-pre-wrap overflow-x-auto max-h-32",children:[r.content.slice(0,500),r.content.length>500&&"..."]})]});if(r.messageKind==="workflow-started")try{const d=JSON.parse(r.content);return o.jsx(JA,{data:d})}catch{}if(r.messageKind==="task-completed")try{const d=JSON.parse(r.content);return o.jsx(QA,{data:d})}catch{}return r.messageKind==="context-reset"?o.jsxs("div",{className:"flex items-center gap-4 mb-6 text-text-muted text-xs uppercase tracking-wide",children:[o.jsx("div",{className:"flex-1 border-t border-border"}),o.jsx("span",{children:r.content}),o.jsx("div",{className:"flex-1 border-t border-border"})]}):r.messageKind==="auto-prompt"&&r.isSystemGenerated?o.jsx(i5,{message:r}):c?o.jsx(s5,{message:r,promptContext:s}):o.jsx("div",{className:"flex justify-start feed-item",children:o.jsx("div",{className:"max-w-[75%] rounded p-2 bg-bg-tertiary text-text-primary",children:o.jsx(Ui,{content:r.content})})})});function a5({stats:e,onClose:r}){var i;return o.jsx(jt,{isOpen:!0,onClose:r,title:"Turn Stats",size:"md",children:o.jsxs("div",{className:"space-y-4",children:[o.jsx("div",{className:"flex items-center gap-3",children:o.jsxs("p",{className:"text-xs text-text-muted",children:[e.model," · ",e.mode]})}),o.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[o.jsx(Ol,{label:"Total Time",value:`${e.totalTime.toFixed(1)}s`}),o.jsx(Ol,{label:"Prefill",value:e.prefillTokens>=1e3?`${(e.prefillTokens/1e3).toFixed(1)}k`:String(e.prefillTokens)}),o.jsx(Ol,{label:"Generated",value:e.generationTokens>=1e3?`${(e.generationTokens/1e3).toFixed(1)}k`:String(e.generationTokens)}),o.jsx(Ol,{label:"LLM Calls",value:String(((i=e.llmCalls)==null?void 0:i.length)??1)})]}),e.llmCalls&&e.llmCalls.length>0&&o.jsxs("div",{children:[o.jsx("h4",{className:"text-sm font-medium text-text-secondary mb-2",children:"LLM Calls"}),e.llmCalls.map((s,c)=>o.jsxs("div",{className:"bg-bg-tertiary/30 rounded p-3 mb-2",children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsxs("span",{className:"text-xs text-text-muted",children:["Call ",c+1]}),o.jsxs("span",{className:"text-xs text-text-muted",children:[s.ttft.toFixed(2),"s TTFT · ",s.completionTime.toFixed(2),"s gen"]})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[o.jsxs("div",{children:[o.jsx("span",{className:"text-text-muted",children:"Tokens:"})," ",o.jsxs("span",{className:"text-text-primary",children:[s.promptTokens," → ",s.completionTokens]})]}),o.jsxs("div",{className:"flex flex-wrap gap-x-2 gap-y-1",children:[s.temperature!==void 0&&o.jsx(Ml,{label:"temp",value:s.temperature.toFixed(2)}),s.topP!==void 0&&o.jsx(Ml,{label:"topP",value:s.topP.toFixed(2)}),s.topK!==void 0&&o.jsx(Ml,{label:"topK",value:String(s.topK)}),s.maxTokens!==void 0&&o.jsx(Ml,{label:"maxTok",value:String(s.maxTokens)})]})]})]},c))]})]})})}function Ol({label:e,value:r}){return o.jsxs("div",{className:"bg-bg-tertiary/50 rounded p-3",children:[o.jsx("div",{className:"text-xs text-text-muted",children:e}),o.jsx("div",{className:"text-lg font-semibold text-text-primary",children:r})]})}function Ml({label:e,value:r}){return o.jsxs("span",{className:"bg-bg-tertiary px-1.5 py-0.5 rounded text-text-primary",children:[o.jsxs("span",{className:"text-text-muted",children:[e,":"]})," ",r]})}const w0=(e,r)=>{const i=H.useRef(!0),s=H.useRef(null),[c,u]=H.useState(!0),f=()=>{const l=e.current;l&&(l.scrollTop=l.scrollHeight)};return H.useEffect(()=>{const l=e.current;if(!l)return;const d=_=>{if(_.deltaY>0){requestAnimationFrame(()=>requestAnimationFrame(()=>{l.scrollHeight-l.scrollTop-l.offsetHeight<100&&(i.current=!0,u(!0))}));return}i.current=!1,u(!1)},p=_=>{_.touches[0]&&(s.current=_.touches[0].clientY)},g=_=>{if(s.current===null)return;const k=_.touches[0];if(!k)return;if(k.clientY-s.current>0){i.current=!1,u(!1);return}requestAnimationFrame(()=>requestAnimationFrame(()=>{l.scrollHeight-l.scrollTop-l.offsetHeight<100&&(i.current=!0,u(!0))}))},m=new MutationObserver(()=>{i.current&&requestAnimationFrame(f)}),b=setInterval(()=>{i.current&&f()},1e3);return l.addEventListener("wheel",d,{passive:!0}),l.addEventListener("touchstart",p,{passive:!0}),l.addEventListener("touchmove",g,{passive:!0}),m.observe(l,{childList:!0,subtree:!0,characterData:!0}),()=>{l.removeEventListener("wheel",d),l.removeEventListener("touchstart",p),l.removeEventListener("touchmove",g),m.disconnect(),clearInterval(b)}},[r==null?void 0:r.id]),{force_scroll_to_bottom:()=>{i.current=!0,u(!0),f()},isAutoScrollActive:c,setAutoScroll:l=>{i.current=l,u(l),l&&f()}}},o5={verifier:"Verification",code_reviewer:"Code Review",test_generator:"Test Generation",debugger:"Debug"};function l5(e){return{backgroundColor:`${e}20`,color:e,borderColor:`${e}4d`}}function lb(e,r){return r||e>85?"text-accent-error":e>60?"text-accent-warning":"text-text-muted"}function c5({contextState:e}){const{currentTokens:r,maxTokens:i,compactionCount:s,dangerZone:c}=e,u=Math.round(r/i*100);return o.jsxs("div",{className:"flex items-center gap-1.5 text-[10px]",children:[o.jsxs("span",{className:lb(u,c),children:[Ul(r),"/",Ul(i)]}),o.jsxs("span",{className:lb(u,c),children:["(",u,"%)"]}),o.jsx(Jb,{percent:u,dangerZone:c,size:"sm"}),c&&o.jsx("span",{className:"text-accent-error animate-pulse",children:"Low!"}),s>0&&o.jsxs("span",{className:"text-text-muted bg-bg-tertiary px-1 rounded",children:[s,"x"]})]})}const u5=H.memo(function({messages:r,subAgentType:i,subAgentId:s,isStreaming:c}){const u=H.useRef(null),f=H.useRef(null),[l,d]=H.useState(!1),p=kt(D=>D.defaults),g=kt(D=>D.userItems),m=[...p,...g],b=Ce(D=>D.subAgentContextStates[s]),{showThinking:_,showVerboseToolOutput:k}=Nb(),{isAutoScrollActive:C,setAutoScroll:y}=w0(f,null);H.useEffect(()=>{c||y(!0)},[c]);const x=H.useCallback(()=>{const D=!l;d(D),D&&setTimeout(()=>{var A;(A=u.current)==null||A.scrollIntoView({block:"start",behavior:"smooth"})},220)},[l]),v=m.find(D=>D.id===i),S=(v==null?void 0:v.name)??o5[i]??i,j=Kl(m,i),T=l5(j),N=r.filter(D=>D.role!=="tool");return o.jsxs("div",{ref:u,className:"feed-item border border-border rounded overflow-hidden bg-bg-secondary",children:[o.jsxs("div",{className:"w-full flex items-center justify-between px-2 py-1 border-b relative",style:T,children:[o.jsx("span",{className:"text-xs font-medium",children:S}),o.jsx("div",{className:"absolute left-1/2 -translate-x-1/2",children:b&&o.jsx(c5,{contextState:b})}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("button",{type:"button",className:"text-sm text-text-muted hover:text-text-primary flex items-center gap-1.5",onClick:()=>y(!C),children:[o.jsx("span",{className:`w-1 h-1 rounded-full ${C?"bg-accent-success":"border border-text-muted"}`}),"live"]}),o.jsxs("button",{type:"button",className:"text-[10px] px-1.5 py-0.5 rounded bg-bg-tertiary",onClick:x,children:[l?"▼":"▶"," Expand"]})]})]}),o.jsx("div",{ref:f,className:`${l?"max-h-[calc(100vh-10rem)]":"max-h-80"} overflow-y-auto p-2 transition-[max-height] duration-200`,children:N.map(D=>D.role==="assistant"?o.jsx(bf,{message:D,showStats:!0,showThinking:_,showVerboseToolOutput:k},D.id):o.jsx(S0,{message:D,isLastAssistantMessage:!1},D.id))})]})});function d5(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"")}function h5({agent:e,isBuiltIn:r,isConfirmingDelete:i,onView:s,onEdit:c,onDuplicate:u,onDelete:f}){return o.jsxs(Ub,{isBuiltIn:r,isConfirmingDelete:i,onView:s,onEdit:c,onDuplicate:u,onDelete:f,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0",style:{backgroundColor:e.color??"#6b7280"}}),o.jsx("span",{className:"text-text-primary text-sm font-medium",children:e.name}),o.jsx("span",{className:"text-text-muted text-xs font-mono",children:e.id}),r&&o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-medium bg-bg-primary text-text-muted",children:"Built-in"})]}),e.description&&o.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:e.description}),o.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[e.allowedTools.slice(0,5).map(l=>o.jsx("span",{className:"text-[10px] font-mono text-text-muted bg-bg-primary px-1 py-0.5 rounded",children:l},l)),e.allowedTools.length>5&&o.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",e.allowedTools.length-5," more"]})]})]})}function cb({title:e,agents:r,subagents:i,isBuiltIn:s,onView:c,onDuplicate:u,onEdit:f,onDelete:l}){if(r.length===0&&i.length===0)return null;const d=p=>o.jsx(h5,{agent:p,isBuiltIn:s,isConfirmingDelete:!1,onView:()=>c(p.id),onEdit:s?void 0:()=>f==null?void 0:f(p.id),onDuplicate:()=>u(p.id),onDelete:s?void 0:()=>l==null?void 0:l(p.id)},p.id);return o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:e}),o.jsxs("div",{className:"space-y-2",children:[r.map(d),i.length>0&&o.jsxs("div",{className:"mt-3",children:[o.jsx("div",{className:"text-xs text-text-muted uppercase tracking-wider mb-1.5",children:"Sub-agents"}),o.jsx("div",{className:"space-y-2",children:i.map(d)})]})]})]})}function f5({isOpen:e,onClose:r,initialEditId:i}){const s=kt(fe=>fe.defaults),c=kt(fe=>fe.userItems),u=kt(fe=>fe.loading),f=kt(fe=>fe.fetchAgents),l=kt(fe=>fe.fetchAgent),d=kt(fe=>fe.fetchDefaultContent),p=kt(fe=>fe.createAgent),g=kt(fe=>fe.updateAgent),m=kt(fe=>fe.deleteAgent),[b,_]=H.useState("list"),[k,C]=H.useState(null),[y,x]=H.useState(!1),[v,S]=H.useState(""),[j,T]=H.useState(""),[N,D]=H.useState(""),[A,M]=H.useState(!0),[B,$]=H.useState([]),[V,W]=H.useState("#6b7280"),[O,F]=H.useState(""),[P,Z]=H.useState(""),[G,I]=H.useState(!1),[R,z]=H.useState([]);function Y(fe){const Ae=new Map;for(const Be of fe){const ot=Be.indexOf(":");if(ot===-1)Ae.set(Be,new Set);else{const ue=Be.slice(0,ot),Ne=Be.slice(ot+1).split(",").filter(Boolean);Ae.set(ue,new Set(Ne))}}return Ae}function U(fe){const Ae=[];for(const[Be,ot]of fe)ot.size===0?Ae.push(Be):Ae.push(`${Be}:${[...ot].join(",")}`);return Ae}const ie=Y(B),Q=(fe,Ae)=>{const Be=new Map(ie),ot=Be.get(fe)||new Set,ue=new Set(ot);ue.has(Ae)?ue.delete(Ae):ue.add(Ae),ue.size===0?Be.set(fe,new Set):Be.set(fe,ue),$(U(Be))},ee=fe=>{const Ae=new Map(ie);Ae.has(fe)?Ae.delete(fe):Ae.set(fe,new Set),$(U(Ae))},X=fe=>{S(fe.metadata.name),T(fe.metadata.id),D(fe.metadata.description),M(fe.metadata.subagent),$(fe.metadata.allowedTools),W(fe.metadata.color??"#6b7280"),F(fe.prompt),Z("")},q=(fe,Ae,Be)=>{S(fe.metadata.name+" (copy)"),T(`${Ae}-copy-${Date.now()}`),D(fe.metadata.description),M(fe.metadata.subagent),$(fe.metadata.allowedTools),W(fe.metadata.color??"#6b7280"),F(fe.prompt),Z(""),C(null),x(!1),_("edit")},oe=(fe,Ae)=>{X(fe),C(Ae),x(!0),_("edit")};H.useEffect(()=>{e&&(f(),ke("/api/tools").then(fe=>fe.json()).then(fe=>z(fe.tools||[])).catch(()=>z([])),i?s.some(Ae=>Ae.id===i)?d(i).then(Ae=>{Ae&&q(Ae,i)}):l(i).then(Ae=>{Ae&&(X(Ae),C(i),x(!1),_("edit"))}):(_("list"),C(null),x(!1)))},[e,f,l,d,i]);const re=async fe=>{if(s.some(Be=>Be.id===fe)){const Be=await d(fe);if(!Be)return;oe(Be,fe)}else{const Be=await l(fe);if(!Be)return;oe(Be,fe)}},ve=async fe=>{const Ae=await d(fe);Ae&&q(Ae,fe)},be=()=>{C(null),S(""),T(""),D(""),M(!0),$(["read_file"]),W("#6b7280"),F(""),Z(""),x(!1),_("edit")},Re=async fe=>{const Ae=await l(fe);Ae&&(X(Ae),C(fe),x(!1),_("edit"))},Ie=async fe=>{await m(fe)},He=async()=>{const fe=k??j;if(!fe||!v||!O){Z("Name and prompt are required.");return}I(!0),Z("");const Ae={metadata:{id:fe,name:v,description:N,subagent:A,allowedTools:B,color:V},prompt:O},Be=k?await g(k,Ae):await p(Ae);if(I(!1),!Be.success){Z(Be.error??"Failed to save agent.");return}i?r():_("list")},Ue=()=>{i?r():(_("list"),x(!1))},je=fe=>{S(fe),k||T(d5(fe))},me=s.filter(fe=>fe.subagent),Te=s.filter(fe=>!fe.subagent),$e=c.filter(fe=>fe.subagent),Lt=c.filter(fe=>!fe.subagent);return b==="edit"?o.jsx(jt,{isOpen:e,onClose:Ue,title:y?`${v}`:k?"Edit Agent":"New Agent",size:"xl",children:o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"space-y-3",children:[P&&o.jsx(Bh,{message:P}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Mi,{label:"Name",value:v,onChange:je,placeholder:"My Agent",readOnly:y}),o.jsx(Mi,{label:"ID",value:j,onChange:T,readOnly:!0,placeholder:"my_agent",hint:"(read-only)",mono:!0})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Mi,{label:"Description",value:N,onChange:D,placeholder:"What this agent does",readOnly:y}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Type"}),o.jsxs("div",{className:"flex items-center gap-3 h-[34px]",children:[o.jsx("button",{onClick:()=>!y&&M(!0),className:`px-2.5 py-1 rounded text-xs font-medium transition-colors ${A?"bg-accent-primary/25 text-accent-primary":"bg-bg-tertiary text-text-muted hover:text-text-secondary"} ${y?"pointer-events-none opacity-60":""}`,children:"Sub-agent"}),o.jsx("button",{onClick:()=>!y&&M(!1),className:`px-2.5 py-1 rounded text-xs font-medium transition-colors ${A?"bg-bg-tertiary text-text-muted hover:text-text-secondary":"bg-accent-primary/25 text-accent-primary"} ${y?"pointer-events-none opacity-60":""}`,children:"Top-level"}),o.jsxs("div",{className:"flex items-center gap-1.5 ml-auto",children:[o.jsx("label",{className:"text-xs text-text-secondary",children:"Color"}),o.jsx("input",{type:"color",value:V,onChange:fe=>!y&&W(fe.target.value),disabled:y,className:"w-6 h-6 rounded cursor-pointer border border-border bg-transparent"})]})]})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Tools"}),o.jsx("div",{className:"flex flex-wrap gap-1.5 p-2 bg-bg-tertiary border border-border rounded max-h-32 overflow-y-auto",children:R.map(fe=>{const Ae=ie.has(fe.name),Be=fe.actions.length>0,ot=ie.get(fe.name)||new Set,ue=o.jsxs("button",{className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${Ae?"bg-accent-primary/25 text-accent-primary":"bg-bg-primary text-text-muted"}`,children:[o.jsx("span",{children:fe.name}),Be&&o.jsx("span",{className:`text-[10px] ${Ae&&ot.size>0?"text-accent-primary":"text-text-muted"}`,children:"*"})]},fe.name);return Be?y?o.jsxs("button",{className:"px-1.5 py-0.5 rounded text-xs font-mono flex items-center gap-1 bg-bg-primary text-text-muted pointer-events-none opacity-60",children:[o.jsx("span",{children:fe.name}),o.jsx("span",{className:"text-[10px]",children:"*"})]},fe.name):o.jsx(lo,{trigger:ue,minWidth:"160px",items:[...fe.actions.map(_e=>({label:o.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",htmlFor:`${fe.name}-${_e}`,children:[o.jsx("input",{type:"checkbox",id:`${fe.name}-${_e}`,checked:ot.has(_e),onChange:()=>Q(fe.name,_e),disabled:y,className:"w-3 h-3 rounded accent-accent-primary"}),o.jsx("span",{children:_e})]}),closeOnClick:!1})),{label:Ae?"Deselect all":"Select all",closeOnClick:!1,onClick:()=>{if(Ae)ee(fe.name);else{const _e=new Map(ie);_e.set(fe.name,new Set(fe.actions)),$(U(_e))}}}]},fe.name):o.jsx("button",{onClick:()=>!y&&ee(fe.name),className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${Ae?"bg-accent-primary/25 text-accent-primary":"bg-bg-primary text-text-muted hover:text-text-secondary"} ${y?"pointer-events-none":"cursor-pointer"}`,children:o.jsx("span",{children:fe.name})},fe.name)})})]})]}),o.jsxs("div",{className:"flex-1 min-h-[150px] border-t border-border pt-3 flex flex-col",children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Prompt"}),o.jsx("textarea",{value:O,onChange:fe=>!y&&F(fe.target.value),readOnly:y,placeholder:"Instructions for this agent...",className:`h-80 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary ${y?"opacity-60":""}`})]}),o.jsx(Ow,{onCancel:Ue,onSave:He,saving:G,saveDisabled:!v||!O||y}),y&&o.jsx("div",{className:"flex justify-end mt-2",children:o.jsx(it,{variant:"primary",onClick:()=>{S(v+" (copy)"),T(`${k}-copy-${Date.now()}`),C(null),x(!1)},children:"Duplicate & Customize"})})]})}):o.jsxs(jt,{isOpen:e,onClose:r,title:"Agents",size:"lg",children:[o.jsxs("div",{className:"flex items-center justify-between mb-4",children:[o.jsx("p",{className:"text-text-secondary text-sm",children:"Agents define behavior, tools, and prompts for top-level modes and sub-agents."}),o.jsx("div",{className:"flex items-center gap-2 flex-shrink-0 ml-3",children:o.jsx(it,{variant:"primary",size:"sm",onClick:be,children:"+ New"})})]}),u&&s.length===0&&c.length===0?o.jsx("div",{className:"text-text-muted text-sm",children:"Loading agents..."}):s.length===0&&c.length===0?o.jsx("div",{className:"text-text-muted text-sm",children:"No agents defined."}):o.jsxs("div",{className:"space-y-4",children:[s.length>0&&o.jsx(cb,{title:"Built-in",agents:Te,subagents:me,isBuiltIn:!0,onView:re,onDuplicate:ve}),c.length>0&&o.jsx(cb,{title:"Custom",agents:Lt,subagents:$e,isBuiltIn:!1,onView:re,onDuplicate:ve,onEdit:Re,onDelete:Ie})]})]})}function p5(){const e=Ce(x=>{var v;return(v=x.currentSession)==null?void 0:v.mode}),r=Ce(x=>x.switchMode),i=kt(x=>x.defaults),s=kt(x=>x.userItems),c=kt(x=>x.fetchAgents),u=[...i,...s],[f,l]=H.useState(!1),[d,p]=H.useState(!1),[g,m]=H.useState(null),b=H.useRef(null);if(H.useEffect(()=>{c()},[c]),H.useEffect(()=>{function x(v){b.current&&!b.current.contains(v.target)&&l(!1)}return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[]),!e)return null;const _=u.filter(x=>!x.subagent),k=_.find(x=>x.id===e),C=(k==null?void 0:k.name)??e,y=Kl(u,e);return o.jsxs("div",{className:"relative",ref:b,children:[o.jsxs("button",{type:"button",onClick:()=>l(!f),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors",title:"Switch agent",children:[o.jsx("span",{className:"text-sm font-medium",style:{color:y},children:C}),o.jsx(ur,{className:`w-3 h-3 text-text-muted transition-transform ${f?"rotate-180":""}`})]}),f&&_.length>0&&o.jsxs("div",{className:"absolute bottom-full left-0 mb-1 w-56 bg-bg-secondary border border-border rounded-lg shadow-lg overflow-hidden z-50",children:[_.map((x,v)=>{const S=x.id===e,j=Kl(u,x.id),T=v<4?`Ctrl+${v+1}`:null;return o.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 text-sm transition-colors group ${S?"bg-bg-tertiary":"hover:bg-bg-tertiary cursor-pointer"}`,children:[o.jsxs("button",{type:"button",onClick:()=>{S||r(x.id),l(!1)},className:"flex-1 text-left flex items-center gap-2 min-w-0",children:[o.jsx("span",{className:"font-medium truncate",style:{color:j},children:x.name}),S&&o.jsx(Mr,{className:"w-3.5 h-3.5 text-text-muted shrink-0"})]}),T&&o.jsxs("span",{className:"shrink-0 px-1.5 py-0.5 text-[10px] bg-bg-tertiary text-text-muted rounded",children:["Ctrl+",v+1]})]},x.id)}),o.jsx("div",{className:"border-t border-border p-1",children:o.jsx("button",{type:"button",onClick:()=>{l(!1),p(!0)},className:"w-full text-left px-3 py-1.5 rounded text-sm text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors",children:"Manage Agents..."})})]}),o.jsx(f5,{isOpen:d,onClose:()=>{p(!1),m(null)},initialEditId:g})]})}function m5(){const e=Ce(s=>s.currentSession),r=Ce(s=>s.switchDangerLevel);if(!e)return null;const i=e.dangerLevel??"normal";return o.jsxs("div",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-bg-tertiary/50",children:[o.jsx("button",{type:"button",onClick:()=>r("normal"),className:`px-2 py-0.5 text-xs font-medium rounded transition-colors ${i==="normal"?"bg-accent-success/20 text-accent-success":"text-text-muted hover:text-text-primary hover:bg-bg-tertiary"}`,title:"Normal mode - requires path confirmation",children:"Normal"}),o.jsx("button",{type:"button",onClick:()=>r("dangerous"),className:`px-2 py-0.5 text-xs font-medium rounded transition-colors ${i==="dangerous"?"bg-red-500/20 text-red-400":"text-text-muted hover:text-text-primary hover:bg-bg-tertiary"}`,title:"Dangerous mode - bypasses all confirmations",children:"Dangerous"})]})}function g5({question:e}){const r=Ce(f=>f.answerQuestion),[i,s]=H.useState(""),c=()=>{r(e.callId,i)},u=f=>{f.key==="Enter"&&!f.shiftKey&&(f.preventDefault(),c())};return o.jsx(jt,{isOpen:!0,onClose:()=>{},size:"sm",closeOnBackdropClick:!1,closeOnEscape:!1,showCloseButton:!1,children:o.jsxs("div",{className:"space-y-4",children:[o.jsx("p",{className:"text-sm text-text-primary",children:e.question}),o.jsx("textarea",{value:i,onChange:f=>s(f.target.value),onKeyDown:u,placeholder:"Type your answer here...",className:"w-full min-h-[120px] px-3 py-2 bg-bg-tertiary border border-border rounded text-sm text-text-primary placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-accent-primary/50 resize-y",autoFocus:!0}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(it,{variant:"secondary",size:"sm",onClick:()=>r(e.callId,""),children:"Skip"}),o.jsx(it,{variant:"primary",size:"sm",onClick:c,children:"Send Answer"})]})]})})}function x5(){const e=Ce(s=>s.connectionStatus),r=Ce(s=>s.reconnect);if(e==="connected")return null;const i=e==="reconnecting";return o.jsxs("div",{className:`
|
|
139
139
|
flex items-center justify-between px-4 py-2
|
|
140
140
|
text-sm font-medium
|
|
141
141
|
${i?"bg-amber-500/15 border-b border-amber-500/30 text-amber-300":"bg-red-500/15 border-b border-red-500/30 text-red-300"}
|
|
@@ -146,7 +146,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
146
146
|
`,children:i?"Reconnecting...":"Reconnect"})]})}function v5(){const e=rw(),r=e?"bg-amber-400":"bg-accent-primary";return o.jsxs("div",{className:"flex items-center gap-3 text-xs text-text-muted py-2",children:[o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsxs("span",{className:"flex gap-0.5",children:[o.jsx("span",{className:`w-1 h-1 rounded-full animate-bounce ${r}`,style:{animationDelay:"0ms"}}),o.jsx("span",{className:`w-1 h-1 rounded-full animate-bounce ${r}`,style:{animationDelay:"150ms"}}),o.jsx("span",{className:`w-1 h-1 rounded-full animate-bounce ${r}`,style:{animationDelay:"300ms"}})]}),o.jsx("span",{className:"text-text-secondary",children:e?"Running... (abort in progress)":"Running"})]}),!e&&o.jsx("span",{className:"text-text-muted",children:"esc to interrupt"})]})}function b5({attachment:e,onRemove:r}){const i=s=>s<1024?`${s} B`:s<1048576?`${(s/1024).toFixed(1)} KB`:`${(s/1048576).toFixed(1)} MB`;return o.jsxs("div",{className:"relative inline-flex flex-col items-center p-2 bg-bg-tertiary rounded-lg border border-border",children:[o.jsx(Ja,{onClick:()=>r(e.id),className:"absolute -top-2 -right-2",size:"sm",variant:"overlay","aria-label":`Remove ${e.filename}`}),o.jsx("img",{src:e.data,alt:e.filename,className:"w-16 h-16 object-cover rounded-md bg-bg-secondary"}),o.jsx("div",{className:"mt-1 text-xs text-text-muted text-center max-w-16 truncate",title:e.filename,children:e.filename}),o.jsx("div",{className:"text-[10px] text-text-muted",children:i(e.size)})]})}function y5({history:e,selectedIndex:r,onSelect:i,onEscape:s,onNavigate:c}){const u=H.useRef(null),f=H.useRef(null);H.useEffect(()=>{f.current&&u.current&&f.current.scrollIntoView({block:"nearest",behavior:"smooth"})},[r]);const l=p=>{switch(p.key){case"Enter":p.preventDefault(),e[r]&&i(e[r].content);break;case"Escape":p.preventDefault(),s();break;case"ArrowUp":p.preventDefault(),c("up");break;case"ArrowDown":p.preventDefault(),c("down");break}},d=p=>{i(p)};return o.jsx("div",{ref:u,role:"list",className:"mb-2 p-2 bg-bg-secondary border border-border rounded-lg overflow-y-auto max-h-64",onKeyDown:l,children:e.map((p,g)=>o.jsxs("div",{ref:g===r?f:null,role:"listitem",onClick:()=>d(p.content),className:`
|
|
147
147
|
p-2 rounded cursor-pointer transition-colors
|
|
148
148
|
${g===r?"bg-accent-primary/20 border border-accent-primary":"hover:bg-bg-tertiary"}
|
|
149
|
-
`,children:[o.jsxs("div",{className:"text-xs text-text-muted font-mono",children:[p.formattedTimestamp,p.sessionName&&o.jsxs(o.Fragment,{children:[" | ",o.jsx("span",{className:"text-accent-primary font-medium",children:p.sessionName})]})]}),o.jsx("div",{className:"text-sm text-text-primary mt-1",children:p.trimmedContent})]},p.id))})}const on=Yn((e,r)=>({defaults:[],userItems:[],loading:!1,fetchCommands:async()=>{await Lh("/api/commands",e)},fetchCommand:async i=>{try{const s=await ke(`/api/commands/${i}`);return s.ok?await s.json():null}catch{return null}},fetchDefaultContent:async i=>{try{const s=await ke(`/api/commands/defaults/${i}`);return s.ok?await s.json():null}catch{return null}},createCommand:async i=>{const s=await di("POST","/api/commands",i);return s.success&&await r().fetchCommands(),s},updateCommand:async(i,s)=>{const c=await di("PUT",`/api/commands/${i}`,s);return c.success&&await r().fetchCommands(),c},deleteCommand:async i=>{try{const s=await ke(`/api/commands/${i}`,{method:"DELETE"}),c=await s.json();return s.ok?(e(u=>({userItems:u.userItems.filter(f=>f.id!==i)})),{success:!0}):{success:!1,error:c.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateCommand:async i=>{try{const s=await ke(`/api/commands/${i}/duplicate`,{method:"POST"}),c=await s.json();return s.ok?(await r().fetchCommands(),{success:!0}):{success:!1,error:c.error??"Failed to duplicate"}}catch{return{success:!1,error:"Network error"}}}})),_5={maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576};async function S5(e,r={}){const i={..._5,...r};if(!e.type.startsWith("image/"))throw new Error("File is not an image");if(!["image/png","image/jpeg","image/gif"].includes(e.type))throw new Error(`Unsupported image format: ${e.type}. Only PNG, JPG, and GIF are supported.`);if(e.size<=i.maxSizeBytes){const c=await e.arrayBuffer(),u=T5(c),f=`data:${e.type};base64,${u}`,l=await C0(f);return{dataUrl:f,mimeType:e.type,size:e.size,width:l.width,height:l.height}}return await w5(e,i)}async function w5(e,r){const i=await k5(e),s=await C0(i),{width:c,height:u}=C5(s.width,s.height,r.maxWidth,r.maxHeight),f=E5();f.width=c,f.height=u;const l=f.getContext("2d");if(!l)throw new Error("Failed to get canvas context");l.imageSmoothingEnabled=!0,l.imageSmoothingQuality="high",l.drawImage(s,0,0,c,u);let d=r.quality,p;do{if(p=f.toDataURL(e.type.startsWith("image/gif")?"image/png":e.type,d),ub(p)<=r.maxSizeBytes||d<=.3)break;d-=.1}while(!0);const g=ub(p);return{dataUrl:p,mimeType:e.type.startsWith("image/gif")?"image/png":e.type,size:g,width:c,height:u}}function C5(e,r,i,s){const c=e/r;return e>r&&e>i?{width:i,height:Math.round(i/c)}:r>e&&r>s?{width:Math.round(s*c),height:s}:{width:e,height:r}}function k5(e){return new Promise((r,i)=>{const s=N5(),c=new s;c.onload=()=>r(c.result),c.onerror=()=>i(new Error("Failed to read file")),c.readAsDataURL(e)})}function C0(e){return new Promise((r,i)=>{const s=j5(),c=new s;c.onload=()=>r(c),c.onerror=()=>i(new Error("Failed to load image")),c.src=e})}function E5(){var r;const e=yf();if(!((r=e.document)!=null&&r.createElement))throw new Error("Image compression requires browser canvas APIs");return e.document.createElement("canvas")}function j5(){const e=yf();if(!e.Image)throw new Error("Image compression requires browser image APIs");return e.Image}function N5(){const e=yf();if(!e.FileReader)throw new Error("Image compression requires browser file APIs");return e.FileReader}function yf(){return globalThis}function T5(e){const r=new Uint8Array(e);let i="";for(let s=0;s<r.byteLength;s++){const c=r[s];c!==void 0&&(i+=String.fromCharCode(c))}return btoa(i)}function ub(e){const i=e.split(",")[1];return i?Math.round(i.length*3/4):0}function A5(e){return["image/png","image/jpeg","image/gif"].includes(e.type)}function D5(e,r=50*1024*1024){return e.size>r?{valid:!1,error:`Image file is too large (${db(e.size)}). Maximum size is ${db(r)}.`}:{valid:!0}}function db(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}async function ah(e,r,i,s={}){const{maxSizeBytes:c=50*1024*1024,filename:u}=s;if(!A5(e)){i(`Unsupported file type: ${e.type}. Only PNG, JPG, and GIF are supported.`);return}const f=D5(e,c);if(!f.valid){i(f.error??"Image file is too large");return}try{const l=await S5(e,{maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576}),d={id:Eb(),filename:u??e.name,mimeType:l.mimeType,size:l.size,data:l.dataUrl};r(d)}catch(l){const d=l instanceof Error?l.message??"Failed to process image":"Failed to process image";i(d)}}function R5(e){const r={};let i=null;for(const s of e){if(s.role==="user"&&!s.isSystemGenerated){i=s.id;continue}s.role==="assistant"&&s.promptContext&&i&&r[i]===void 0&&(r[i]=s.promptContext)}return r}function oh(e){return{contextWindow:e.contextWindow,temperature:e.temperature??null,topP:e.topP??null,topK:e.topK??null,maxTokens:e.maxTokens??null}}function L5({label:e,children:r}){return o.jsxs("div",{className:"space-y-3",children:[o.jsx("h4",{className:"text-sm font-medium text-text-secondary border-b border-border/50 pb-1",children:e}),r]})}function qa({label:e,value:r,onChange:i,min:s,max:c,step:u=1,helpText:f,defaultValue:l}){const[d,p]=H.useState((r==null?void 0:r.toString())??""),[g,m]=H.useState(r===null);H.useEffect(()=>{p((r==null?void 0:r.toString())??""),m(r===null)},[r]);const b=k=>{if(p(k),k==="")i(null);else{const C=parseFloat(k);isNaN(C)||i(C)}},_=()=>{g?(m(!1),l!==void 0&&(p(l.toString()),i(l))):(m(!0),i(null))};return o.jsxs("div",{children:[o.jsxs("label",{className:"flex items-center gap-2 text-sm font-medium text-text-secondary mb-1",children:[e,o.jsx("button",{type:"button",onClick:_,className:`text-xs px-1.5 py-0.5 rounded border ${g?"border-accent-primary/50 bg-accent-primary/10 text-accent-primary":"border-border text-text-muted hover:text-text-secondary"}`,title:g?"Click to set a custom value":"Click to use default",children:g?"default":"custom"})]}),o.jsx("input",{type:"number",min:s,max:c,step:u,value:d,readOnly:g,onChange:k=>b(k.target.value),onClick:()=>g&&_(),placeholder:g?"Using profile default (click to edit)":"",className:`w-full bg-bg-tertiary border border-border rounded px-3 py-2 text-text-primary focus:outline-none focus:border-accent-primary ${g?"opacity-50 cursor-pointer":""}`}),f&&o.jsx("p",{className:"text-xs text-text-muted mt-1",children:f})]})}function O5({isOpen:e,onClose:r,providerId:i,model:s}){const[c,u]=H.useState(()=>oh(s)),[f,l]=H.useState(!1),d=At(m=>m.updateModelSettings);H.useEffect(()=>{u(oh(s))},[s]);const p=async()=>{if(c.contextWindow<1024||c.contextWindow>1e7)return;l(!0);const m=c.temperature!==(s.temperature??null)||c.topP!==(s.topP??null)||c.topK!==(s.topK??null)||c.maxTokens!==(s.maxTokens??null);await d(i,s.id,{contextWindow:c.contextWindow,...m&&{temperature:c.temperature,topP:c.topP,topK:c.topK,maxTokens:c.maxTokens}}),l(!1),r()},g=()=>{u(oh(s)),r()};return e?o.jsx(jt,{isOpen:e,onClose:r,title:"Model Properties",size:"sm",footer:o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(it,{variant:"secondary",onClick:g,disabled:f,children:"Cancel"}),o.jsx(it,{variant:"primary",onClick:p,disabled:f||c.contextWindow<1024||c.contextWindow>1e7,children:f?"Saving...":"Save"})]}),children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-text-secondary mb-1",children:"Model Name"}),o.jsx("p",{className:"text-text-primary bg-bg-tertiary px-3 py-2 rounded font-mono text-sm break-all",children:s.id})]}),o.jsx(qa,{label:"Context Window",value:c.contextWindow,onChange:m=>m!==null&&u(b=>({...b,contextWindow:m})),min:1024,max:1e7,helpText:"Range: 1,024 - 10,000,000 tokens"}),o.jsxs(L5,{label:"Sampling Parameters",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(qa,{label:"Temperature",value:c.temperature,onChange:m=>u(b=>({...b,temperature:m})),min:0,max:2,step:.1,helpText:"0.0 - 2.0",defaultValue:1}),o.jsx(qa,{label:"Top P",value:c.topP,onChange:m=>u(b=>({...b,topP:m})),min:0,max:1,step:.05,helpText:"0.0 - 1.0",defaultValue:1})]}),o.jsx(qa,{label:"Top K",value:c.topK,onChange:m=>u(b=>({...b,topK:m})),min:1,max:200,helpText:"1 - 200 (leave as default if not supported)"})]}),o.jsx(qa,{label:"Max Tokens",value:c.maxTokens,onChange:m=>u(b=>({...b,maxTokens:m})),min:256,max:32e3,helpText:"Maximum tokens to generate per response"}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-text-secondary mb-1",children:"Source"}),o.jsxs("p",{className:"text-text-primary bg-bg-tertiary px-3 py-2 rounded text-sm",children:[s.source==="backend"&&"Auto-detected from backend",s.source==="user"&&"Manually set",s.source==="default"&&"Default value"]})]})]})}):null}function M5(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function I5(){var F;const[,e]=dr(),r=Ce(P=>P.currentSession),i=Ce(P=>P.setSessionProvider),[s,c]=H.useState(!1),[u,f]=H.useState([]),[l,d]=H.useState(null),p=H.useRef(null),[g,m]=H.useState(null),b=H.useRef(new Set),_=At(P=>P.providers),k=At(P=>P.activeProviderId),C=At(P=>P.model);At(P=>P.backend);const y=At(P=>P.llmStatus),x=At(P=>P.activating),v=At(P=>P.activateProvider),S=At(P=>P.refreshModel),j=At(P=>P.refreshProviderModels);H.useEffect(()=>{function P(Z){p.current&&!p.current.contains(Z.target)&&(c(!1),f([]),b.current=new Set)}return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[]),H.useEffect(()=>{if(s){const P=_.map(Z=>Z.id);f(P),P.forEach(Z=>{b.current.has(Z)||(b.current.add(Z),D(Z))})}},[s,_]),_.find(P=>P.id===k);const T=y==="disconnected",N=C?((F=C.split("/").pop())==null?void 0:F.replace(/-/g," "))??C:"detecting...",D=async P=>{d(P);try{await j(P)}catch{}finally{d(null)}},A=P=>{u.includes(P.id)?f(u.filter(Z=>Z!==P.id)):(f([...u,P.id]),D(P.id))},M=async P=>{if(P.id===k){A(P);return}r?(i(P.id,void 0),At.getState().syncFromSession(P.id,""),c(!1),f([])):await v(P.id)&&(c(!1),f([]))},B=P=>{A(P)},$=async(P,Z)=>{P.stopPropagation(),b.current.delete(Z),await j(Z),await D(Z)},V=(P,Z)=>{m({providerId:P,model:Z})},W=()=>{m(null)},O=async(P,Z)=>{if(console.log("[ProviderSelector.handleModelClick] providerId:",P,"model:",Z),r){console.log("[ProviderSelector.handleModelClick] Calling setSessionProvider"),i(P,Z),At.getState().syncFromSession(P,Z),f([]),c(!1);return}d("activating");try{(await ke(`/api/providers/${P}/activate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:Z})})).ok&&(await At.getState().fetchConfig(),f([]),c(!1))}catch{}finally{d(null)}};return _.length===0?o.jsxs("button",{type:"button",onClick:()=>S(),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors group",title:T?"LLM server is offline. Click to retry.":C??"Click to refresh model",children:[T?o.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"LLM offline"}):o.jsx("span",{className:"text-sm text-accent-primary",children:N}),o.jsx("span",{className:"text-text-muted opacity-0 group-hover:opacity-100 transition-opacity",children:"↻"})]}):o.jsxs("div",{className:"relative",ref:p,children:[o.jsxs("button",{type:"button",onClick:()=>c(!s),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors group",title:"Click to switch provider or model",children:[T?o.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"offline"}):o.jsx("span",{className:"text-sm text-accent-primary",children:N}),o.jsx(ur,{className:"w-3 h-3 text-text-muted transition-transform",rotate:s?180:0})]}),s&&o.jsxs("div",{className:"absolute bottom-full right-0 mb-1 w-72 bg-bg-secondary border border-border rounded-lg shadow-lg z-50 overflow-hidden",children:[o.jsx("div",{className:"py-1",children:_.map(P=>{var Z;return o.jsxs("div",{children:[o.jsxs("div",{className:`px-3 py-2 flex items-center justify-between ${P.id===k?"bg-bg-tertiary":"hover:bg-bg-tertiary"} ${x?"opacity-50 cursor-wait":"cursor-pointer"}`,children:[o.jsxs("div",{onClick:()=>!x&&M(P),className:"flex flex-col min-w-0 flex-1 cursor-pointer",children:[o.jsx("span",{className:`text-sm font-medium truncate ${P.id===k?"text-accent-primary":"text-text-primary"}`,children:P.name}),o.jsx("span",{className:"text-xs text-text-muted truncate",children:P.backend!=="auto"&&z1(P.backend)})]}),o.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[P.id===k?o.jsx("span",{className:"text-accent-success",title:"Active",children:o.jsx(Mr,{className:"w-4 h-4"})}):o.jsx("span",{className:"w-4"}),o.jsx("button",{type:"button",onClick:G=>{G.stopPropagation(),$(G,P.id)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Refresh models",children:o.jsx(yw,{className:`w-4 h-4 ${l===P.id?"animate-spin":""} ${P.id===k?"text-accent-primary":"text-text-muted"}`})}),o.jsx("button",{type:"button",onClick:G=>{G.stopPropagation(),B(P)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Show models",children:o.jsx(ur,{className:`w-4 h-4 transition-transform ${u.includes(P.id)?"rotate-180":""} ${P.id===k?"text-accent-primary":"text-text-muted"}`})})]})]}),u.includes(P.id)&&o.jsx("div",{className:"bg-bg-primary border-t border-border",children:l===P.id?o.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"Loading models..."}):(Z=P.models)!=null&&Z.length?P.models.map(G=>{var I;return o.jsxs("button",{type:"button",onClick:()=>O(P.id,G.id),disabled:l==="activating",className:`w-full px-4 py-1.5 text-left hover:bg-bg-tertiary transition-colors text-sm flex items-center justify-between group ${l==="activating"?"opacity-50 cursor-wait":""} ${C===G.id?"text-accent-primary":"text-text-secondary"}`,children:[o.jsx("span",{className:"truncate flex-1",children:((I=G.id.split("/").pop())==null?void 0:I.replace(/-/g," "))??G.id}),o.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[o.jsx("span",{className:"text-xs text-text-muted",children:M5(G.contextWindow)}),o.jsx("button",{type:"button",onClick:R=>{R.stopPropagation(),V(P.id,G)},className:"opacity-0 group-hover:opacity-100 p-0.5 hover:bg-bg-tertiary rounded transition-opacity",title:"Edit model context",children:o.jsx(uw,{className:"w-3 h-3 text-text-muted"})})]}),C===G.id&&o.jsx("span",{className:"text-accent-success flex-shrink-0 ml-1",children:o.jsx(Mr,{className:"w-3.5 h-3.5"})})]},G.id)}):o.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"No models available"})})]},P.id)})}),o.jsx("div",{className:"border-t border-border px-3 py-2",children:o.jsx("button",{onClick:()=>e("/onboarding"),className:"text-xs text-accent-primary hover:underline",children:"Manage providers"})})]}),g&&o.jsx(O5,{isOpen:!0,onClose:W,providerId:g.providerId,model:g.model})]})}function B5(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function z5({onClick:e}){return o.jsx("button",{type:"button",onClick:e,className:"p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",title:"View",children:o.jsx(ec,{})})}function k0({isOpen:e,onClose:r,initialEditId:i}){const s=on(me=>me.defaults),c=on(me=>me.userItems),u=on(me=>me.loading),f=on(me=>me.fetchCommands),l=on(me=>me.fetchCommand),d=on(me=>me.fetchDefaultContent),p=on(me=>me.createCommand),g=on(me=>me.updateCommand),m=on(me=>me.deleteCommand),[b,_]=H.useState(null),[k,C]=H.useState(null),{view:y,editingId:x,formError:v,saving:S,formData:j,setView:T,setEditingId:N,setFormError:D,setFormData:A,setSaving:M}=Wb(),{requestDelete:B,clearConfirm:$,isConfirming:V}=Oh(),W=H.useRef(!1),O=kt(me=>me.defaults),F=kt(me=>me.userItems),P=kt(me=>me.fetchAgents),G=[...O,...F].filter(me=>!me.subagent),I=H.useRef(f),R=H.useRef(P),z=H.useRef(l),Y=H.useRef(d),U=H.useRef(i),ie=H.useRef(T),Q=H.useRef(N),ee=H.useRef(D),X=H.useRef($);H.useEffect(()=>{I.current=f,R.current=P,z.current=l,Y.current=d,U.current=i,ie.current=T,Q.current=N,ee.current=D,X.current=$}),H.useEffect(()=>{if(e)if(I.current(),R.current(),W.current||(X.current(),W.current=!0),U.current){const me=s.some(Te=>Te.id===U.current);ie.current("edit"),Q.current(U.current),ee.current(""),me?Y.current(U.current).then(Te=>{Te&&A({name:Te.metadata.name+" (copy)",id:`${U.current}-copy-${Date.now()}`,prompt:Te.prompt,agentMode:Te.metadata.agentMode??"",isDefault:!0})}):z.current(U.current).then(Te=>{Te&&A({name:Te.metadata.name,id:Te.metadata.id,prompt:Te.prompt,agentMode:Te.metadata.agentMode??"",isDefault:!1})})}else ie.current("list"),Q.current(null);else W.current=!1},[e]);const q=async me=>{_(me);const Te=await d(me);C((Te==null?void 0:Te.prompt)??null)},oe=async me=>{if(s.some($e=>$e.id===me)){const $e=await d(me);$e&&(N(null),A({name:`${$e.metadata.name} (copy)`,id:`${me}-copy-${Date.now()}`,prompt:$e.prompt,agentMode:$e.metadata.agentMode??"",isDefault:!0}),D(""),T("edit"))}else{const $e=await l(me);$e&&(N(null),A({name:`${$e.metadata.name} (copy)`,id:`${me}-copy-${Date.now()}`,prompt:$e.prompt,agentMode:$e.metadata.agentMode??"",isDefault:!1}),D(""),T("edit"))}},re=()=>{A({name:"",id:"",prompt:"",agentMode:"",isDefault:!1}),N(null),T("edit")},ve=async me=>{const Te=await l(me);Te&&(N(me),A({name:Te.metadata.name,id:Te.metadata.id,prompt:Te.prompt,agentMode:Te.metadata.agentMode??"",isDefault:!1}),D(""),T("edit"))},be=async me=>{await m(me),$()},Re=async()=>{const me=x??j.id;if(!me||!j.name||!j.prompt){D("Name and message are required.");return}M(!0),D("");const Te={metadata:{id:me,name:j.name,...j.agentMode?{agentMode:j.agentMode}:{}},prompt:j.prompt},$e=x?await g(x,Te):await p(Te);if(M(!1),!$e.success){D($e.error??"Failed to save command.");return}i?r():T("list")},Ie=()=>{i?r():(T("list"),_(null),C(null))},He=me=>{A(Te=>({...Te,name:me})),(!x||j.isDefault)&&A(Te=>({...Te,id:B5(me)}))},Ue=()=>{_(null),C(null),T("list")},je=()=>{b&&(_(null),T("edit"),N(b),d(b).then(me=>{me&&A({name:`${me.metadata.name} (copy)`,id:`${b}-copy-${Date.now()}`,prompt:me.prompt,agentMode:me.metadata.agentMode??"",isDefault:!0})}))};if(b){const me=s.find(Te=>Te.id===b);return o.jsx(jt,{isOpen:e,onClose:Ue,title:`Default: ${(me==null?void 0:me.name)??b}`,size:"xl",children:o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"space-y-3 mb-3",children:[o.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-muted",children:[o.jsx("span",{className:"px-1.5 py-0.5 rounded bg-bg-tertiary text-text-secondary",children:"Built-in"}),o.jsx("span",{className:"font-mono",children:b})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Name"}),o.jsx("div",{className:"px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm",children:me==null?void 0:me.name})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Agent Mode"}),o.jsx("div",{className:"px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm text-text-muted",children:(me==null?void 0:me.agentMode)||"None"})]})]}),o.jsxs("div",{className:"flex-1 min-h-[120px] border-t border-border pt-3 flex flex-col",children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Message"}),o.jsx("textarea",{value:k??"",readOnly:!0,placeholder:"...",className:"flex-1 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-none opacity-60"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 mt-3 border-t border-border flex-shrink-0",children:[o.jsx(it,{variant:"secondary",onClick:Ue,children:"Close"}),o.jsx(it,{variant:"primary",onClick:je,children:"Duplicate & Customize"})]})]})})}return y==="edit"?o.jsx(jt,{isOpen:e,onClose:Ie,title:x?"Edit Command":"New Command",size:"xl",children:o.jsxs("div",{className:"flex flex-col h-full",children:[v&&o.jsx(Bh,{message:v}),o.jsxs("div",{className:"space-y-3 mb-3",children:[o.jsx(qb,{name:j.name,id:j.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Command",idPlaceholder:"my-command",readOnlyId:!!x&&!j.isDefault,onNameChange:He,onIdChange:me=>A(Te=>({...Te,id:me}))}),o.jsxs("div",{children:[o.jsxs("label",{className:"block text-xs text-text-secondary mb-1",children:["Agent Mode ",o.jsx("span",{className:"text-text-muted",children:"(optional)"})]}),o.jsxs("select",{value:j.agentMode,onChange:me=>A(Te=>({...Te,agentMode:me.target.value})),className:"w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",children:[o.jsx("option",{value:"",children:"None (keep current mode)"}),G.map(me=>o.jsx("option",{value:me.id,children:me.name},me.id))]})]})]}),o.jsxs("div",{className:"flex-1 min-h-[120px] border-t border-border pt-3 flex flex-col",children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Message"}),o.jsx("textarea",{value:j.prompt,onChange:me=>A(Te=>({...Te,prompt:me.target.value})),placeholder:"The message that will be sent when this command is triggered...",className:"flex-1 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-none focus:outline-none focus:ring-1 focus:ring-accent-primary"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 mt-3 border-t border-border flex-shrink-0",children:[o.jsx(it,{variant:"secondary",onClick:Ie,children:"Cancel"}),o.jsx(it,{variant:"primary",onClick:Re,disabled:S||!j.name||!j.prompt,children:S?"Saving...":"Save"})]})]})}):o.jsxs(jt,{isOpen:e,onClose:r,title:"Commands",size:"lg",children:[o.jsx(Fb,{description:"Commands are pre-defined messages you can send with a single click.",onNew:re}),o.jsxs($b,{loading:u,hasItems:s.length>0||c.length>0,loadingLabel:"Loading commands...",emptyLabel:"No commands created yet.",children:[s.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Built-in"}),o.jsx("div",{className:"space-y-2",children:s.map(me=>o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsx("div",{className:"min-w-0 flex-1 mr-3",children:o.jsx("span",{className:"text-text-primary text-sm font-medium",children:me.name})}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx(z5,{onClick:()=>q(me.id)}),o.jsx(Qa,{onClick:()=>oe(me.id)})]})]},me.id))})]}),c.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Custom"}),o.jsx("div",{className:"space-y-2",children:c.map(me=>o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsx("div",{className:"min-w-0 flex-1 mr-3",children:o.jsx("div",{className:"flex items-center gap-2",children:o.jsx("span",{className:"text-text-primary text-sm font-medium",children:me.name})})}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx(Hs,{onClick:()=>ve(me.id)}),o.jsx(Qa,{onClick:()=>oe(me.id)}),V(me.id,"delete")?o.jsx(Mh,{onConfirm:()=>be(me.id),onCancel:$}):o.jsx(Ih,{onClick:()=>B(me.id)})]})]},me.id))})]})]})]})}function E0({items:e,isOpen:r,onOpen:i,onClose:s,filterFn:c}){const[u,f]=H.useState(""),[l,d]=H.useState(0),p=H.useRef(null),g=H.useRef(null);H.useEffect(()=>{r&&(f(""),d(0),requestAnimationFrame(()=>{var y;return(y=g.current)==null?void 0:y.focus()}))},[r]),H.useEffect(()=>{if(!r)return;const y=x=>{p.current&&!p.current.contains(x.target)&&s()};return document.addEventListener("mousedown",y),()=>document.removeEventListener("mousedown",y)},[r,s]);const m=H.useCallback(()=>{r?s():i()},[r,i,s]),b=H.useCallback(y=>{f(y),d(0)},[]),_=H.useCallback(y=>{const x=e.filter(v=>c(v,u));switch(y.key){case"ArrowDown":y.preventDefault(),d(v=>Math.min(v+1,x.length-1));break;case"ArrowUp":y.preventDefault(),d(v=>Math.max(v-1,0));break;case"Enter":y.preventDefault();break;case"Escape":y.preventDefault(),s();break}},[e,u,c,s]),k=H.useCallback(()=>{d(0)},[]),C=e.filter(y=>c(y,u));return{isOpen:r,search:u,selectedIndex:l,filtered:C,containerRef:p,searchRef:g,handleToggle:m,handleSearchChange:b,handleKeyDown:_,setSelectedIndex:d,resetSelection:k}}function j0({label:e,isOpen:r,onClick:i,className:s=""}){return o.jsxs("button",{type:"button",onClick:i,className:`flex items-center gap-1 text-sm text-text-muted hover:text-text-primary transition-colors ${s}`,children:[e,o.jsx(ur,{className:"w-3 h-3 transition-transform",rotate:r?180:0})]})}function N0({value:e,onChange:r,onKeyDown:i,ref:s,placeholder:c}){return o.jsx("div",{className:"p-2 border-b border-border",children:o.jsx("input",{ref:s,value:e,onChange:u=>r(u.target.value),onKeyDown:i,placeholder:c,className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary"})})}function T0({children:e,maxHeight:r="max-h-64"}){return o.jsx("div",{className:`overflow-y-auto ${r} p-1`,children:e})}function A0({hasItems:e,message:r}){return o.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:e?"No matches":r})}function D0({label:e,onClick:r}){return o.jsx("div",{className:"border-t border-border p-1",children:o.jsx("button",{type:"button",onClick:r,className:"w-full text-left px-3 py-1.5 rounded text-sm text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors",children:e})})}function H5({onSendCommand:e,onOpenManager:r,textareaContent:i,attachments:s}){const[c,u]=H.useState(!1),[f,l]=H.useState(null),d=on(D=>D.defaults),p=on(D=>D.userItems),g=on(D=>D.fetchCommands),m=[...d,...p],{isOpen:b,search:_,selectedIndex:k,filtered:C,containerRef:y,searchRef:x,handleToggle:v,handleSearchChange:S,handleKeyDown:j}=E0({items:m,isOpen:c,onOpen:()=>u(!0),onClose:()=>u(!1),filterFn:(D,A)=>!A||D.name.toLowerCase().includes(A.toLowerCase())});H.useEffect(()=>{c&&g()},[c,g]);const T=async D=>{const A=await on.getState().fetchCommand(D);A&&e(A.prompt,A.metadata.agentMode,i,s),u(!1)},N=()=>{u(!1),r()};return o.jsxs("div",{ref:y,className:"relative",children:[o.jsx(j0,{label:"Commands",isOpen:b,onClick:v}),b&&o.jsxs("div",{className:"absolute bottom-full right-0 mb-1 w-72 bg-bg-secondary border border-border rounded-lg shadow-xl z-50",onKeyDown:j,children:[o.jsx(N0,{value:_,onChange:S,onKeyDown:j,ref:x,placeholder:"Search commands..."}),o.jsx(T0,{children:C.length===0?o.jsx(A0,{hasItems:m.length>0,message:"No commands yet"}):C.map((D,A)=>o.jsxs("div",{className:`flex items-center gap-1 px-3 py-2 rounded transition-colors group ${A===k?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[o.jsx("button",{type:"button",onClick:()=>T(D.id),className:"flex-1 text-left",children:o.jsx("div",{className:"text-sm text-text-primary font-medium",children:D.name})}),o.jsx(Hs,{className:"opacity-0 group-hover:opacity-100",onClick:M=>{M.stopPropagation(),u(!1),l(D.id)}})]},D.id))}),o.jsx(D0,{label:"Manage Commands...",onClick:N})]}),o.jsx(k0,{isOpen:!!f,onClose:()=>l(null),initialEditId:f})]})}function P5(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function F5(e){let r=1;for(;e.some(i=>i.id===`s${r}`);)r++;return`s${r}`}const U5=[{value:"agent",label:"Agent"},{value:"sub_agent",label:"Sub-Agent"},{value:"shell",label:"Shell"}],R0={all_criteria_passed:"All passed",all_criteria_completed_or_passed:"All completed",any_criteria_blocked:"Blocked",has_pending_criteria:"Pending/Failed",step_result:"Result",always:"Always"},L0=[{value:"all_criteria_passed",label:"All criteria passed"},{value:"all_criteria_completed_or_passed",label:"All criteria completed or passed"},{value:"any_criteria_blocked",label:"Any criteria blocked (retry limit)"},{value:"has_pending_criteria",label:"Has pending or failed criteria"},{value:"step_result",label:"Step result is..."},{value:"always",label:"Always (fallback)"}],Ri=150,Or=54,Ds=80,Ln=30,Rs=70,hb=100,Li=50,Il=50,fb=4;function _f(e,r){if(e.type==="agent"){const i=r.find(s=>s.id===e.toolMode);return{name:(i==null?void 0:i.name)??(e.toolMode||"Agent"),color:(i==null?void 0:i.color)||"#3b82f6"}}if(e.type==="sub_agent"){const i=r.find(s=>s.id===e.subAgentType);return{name:(i==null?void 0:i.name)??(e.subAgentType||"Sub-Agent"),color:(i==null?void 0:i.color)||"#a855f7"}}return{name:"Shell",color:"#22c55e"}}function $5(e,r,i,s){const c=Il+Li+Ri+hb+Ri+Li+Il,u=c/2,f=Il+Li+Ri/2,l=Il+Li+Ri+hb+Ri/2,d=[],p=[],g=new Map,m=e.filter(O=>O.type==="agent"||O.type==="shell"),b=e.filter(O=>O.type==="sub_agent"),_=b.length>0,k=_?f:u,C=m.length>0?l:u,y=Li+Ln/2;if(d.push({id:"$start",type:"terminal",label:"Start",cx:k,cy:y,w:Ds,h:Ln}),g.set("$start",{cx:k,cy:y,w:Ds,h:Ln}),e.length===0){const O=y+Ln/2+Rs*2+Ln/2;return d.push({id:"$done",type:"terminal",label:"Done",cx:k,cy:O,w:Ds,h:Ln}),g.set("$done",{cx:k,cy:O,w:Ds,h:Ln}),{nodes:d,edges:p,width:c,height:O+Ln/2+Li,posMap:g}}const x=y+Ln/2+Rs,v=(O,F)=>{O.forEach((P,Z)=>{const G=x+Z*(Or+Rs)+Or/2,{name:I,color:R}=_f(P,s);d.push({id:P.id,type:"step",label:I,color:R,cx:F,cy:G,w:Ri,h:Or}),g.set(P.id,{cx:F,cy:G,w:Ri,h:Or})})};v(m,k),v(b,C);const S=m.length>0?x+(m.length-1)*(Or+Rs)+Or/2:y,j=_?x+(b.length-1)*(Or+Rs)+Or/2:y,T=Math.max(S,j)+Or/2+Rs+Ln/2;d.push({id:"$done",type:"terminal",label:"Done",cx:k,cy:T,w:Ds,h:Ln}),g.set("$done",{cx:k,cy:T,w:Ds,h:Ln});const N=[];r&&g.has(r)&&N.push({from:"$start",to:r,label:i,edgeKey:"start",direction:"down",backEdgeIndex:0});let D=0;for(const O of e)O.transitions.forEach((F,P)=>{if(!F.goto||!g.has(F.goto))return;const Z=g.get(O.id),G=g.get(F.goto),I=F.when.type==="step_result"?`${F.when.result}`:R0[F.when.type]??F.when.type,R=O.id===F.goto;let z;R?z="back":G.cy>Z.cy+1?z="down":G.cy<Z.cy-1?z="back":z="same",N.push({from:O.id,to:F.goto,label:I,edgeKey:`${O.id}:${P}`,direction:z,backEdgeIndex:z==="back"?D++:0})});const A=new Map,M=new Map,B=new Map,$=new Map;for(const O of N)O.direction==="down"&&(A.set(O.from,(A.get(O.from)??0)+1),M.set(O.to,(M.get(O.to)??0)+1));const V=new Map,W=new Map;for(const O of N){if(O.direction!=="same")continue;const F=[O.from,O.to].sort().join("|");V.set(F,(V.get(F)??0)+1)}for(const O of N){if(O.direction==="back"||O.direction==="same"){let z=0;if(O.direction==="same"){const Y=[O.from,O.to].sort().join("|");z=W.get(Y)??0,W.set(Y,z+1)}p.push({...O,fromPort:0,toPort:0,sameEdgeIndex:z});continue}const F=A.get(O.from)??1,P=M.get(O.to)??1,Z=B.get(O.from)??0,G=$.get(O.to)??0;B.set(O.from,Z+1),$.set(O.to,G+1);const I=F===1?0:-.6+1.2*Z/(F-1),R=P===1?0:-.6+1.2*G/(P-1);p.push({...O,fromPort:I,toPort:R,sameEdgeIndex:0})}return{nodes:d,edges:p,width:c,height:T+Ln/2+Li,posMap:g}}function q5({steps:e,entryStep:r,selectedNodeId:i,selectedEdgeKey:s,startConditionLabel:c,agentTypes:u,isReadOnly:f,onSelectNode:l,onSelectEdge:d,onRemoveStep:p,onCreateTransition:g,onReconnectTo:m,onReconnectFrom:b,onDeleteTransition:_}){const k=H.useRef(null),C=H.useRef(!1),[y,x]=H.useState(null),[v,S]=H.useState(null),[j,T]=H.useState(null),{nodes:N,edges:D,width:A,height:M,posMap:B}=H.useMemo(()=>$5(e,r,c,u),[e,r,c,u]),$=H.useCallback(Q=>{var re;const ee=k.current;if(!ee)return{x:0,y:0};const X=ee.createSVGPoint();X.x=Q.clientX,X.y=Q.clientY;const q=(re=ee.getScreenCTM())==null?void 0:re.inverse();if(!q)return{x:0,y:0};const oe=X.matrixTransform(q);return{x:oe.x,y:oe.y}},[]),V=H.useCallback(Q=>!Q||!v||Q==="$start"?!1:v.type==="reconnect-from"?Q!=="$done":!0,[v]),W=H.useCallback((Q,ee)=>{if(f)return;Q.stopPropagation(),Q.preventDefault();const X=$(Q);S({type:"new",fromNodeId:ee,mouseX:X.x,mouseY:X.y})},[$,f]),O=H.useCallback((Q,ee)=>{if(f)return;Q.stopPropagation(),Q.preventDefault();const X=$(Q);S({type:"reconnect-to",fromNodeId:ee.from,edgeKey:ee.edgeKey,mouseX:X.x,mouseY:X.y})},[$,f]),F=H.useCallback((Q,ee)=>{if(f)return;Q.stopPropagation(),Q.preventDefault();const X=$(Q);S({type:"reconnect-from",fromNodeId:ee.from,fixedTargetId:ee.to,edgeKey:ee.edgeKey,mouseX:X.x,mouseY:X.y})},[$,f]),P=H.useCallback(Q=>{if(!v)return;const ee=$(Q);S(X=>X?{...X,mouseX:ee.x,mouseY:ee.y}:null)},[v,$]),Z=H.useCallback(()=>{v&&(C.current=!0,j&&V(j)&&(v.type==="new"?g(v.fromNodeId,j):v.type==="reconnect-to"?m(v.edgeKey,j):v.type==="reconnect-from"&&b(v.edgeKey,j)),S(null),T(null))},[v,j,V,g,m,b]),G=H.useCallback(()=>{if(C.current){C.current=!1;return}l(null),d(null)},[l,d]);H.useEffect(()=>{if(f)return;const Q=ee=>{ee.target instanceof HTMLInputElement||ee.target instanceof HTMLTextAreaElement||ee.target instanceof HTMLSelectElement||(ee.key==="Delete"||ee.key==="Backspace")&&s&&s!=="start"&&(ee.preventDefault(),_(s),d(null))};return document.addEventListener("keydown",Q),()=>document.removeEventListener("keydown",Q)},[f,s,_,d]);const I=Q=>{const ee=B.get(Q.from),X=B.get(Q.to);if(!ee||!X)return null;let q,oe,re,ve="middle",be,Re;if(Q.direction==="down"){const Ie=ee.cx+Q.fromPort*(ee.w/2-10),He=ee.cy+ee.h/2,Ue=X.cx+Q.toPort*(X.w/2-10),je=X.cy-X.h/2,me=je-He,Te=Ue-Ie;q=`M ${Ie} ${He} C ${Ie} ${He+me*.4}, ${Ue-Te*.2} ${je-me*.1}, ${Ue} ${je}`,oe=Ie+(Ue-Ie)*.5,re=He+me*.6,be={x:Ie,y:He},Re={x:Ue,y:je}}else if(Q.direction==="back"){const Ie=Q.from===Q.to,He=ee.cx>=A/2,Ue=Q.backEdgeIndex*16,je=He?A-20-Ue:20+Ue;if(Ie){const me=ee.cx>=A/2,Te=30+Q.backEdgeIndex*14,$e=ee.cy-ee.h/2,Lt=me?ee.cx+ee.w/2:ee.cx-ee.w/2,fe=me?Lt+Te:Lt-Te,Ae=ee.cx+(me?ee.w/4:-ee.w/4),Be=$e-20-Q.backEdgeIndex*10;q=`M ${Lt} ${ee.cy} C ${fe} ${ee.cy}, ${fe} ${Be}, ${Ae} ${$e}`,oe=fe+10,re=Be+4,ve="middle",be={x:Lt,y:ee.cy},Re={x:Ae,y:$e}}else{const me=He?ee.cx+ee.w/2:ee.cx-ee.w/2,Te=X.cx+(He?X.w/4:-X.w/4),$e=Math.min(ee.cy,X.cy)-X.h/2-18-Q.backEdgeIndex*14;q=`M ${me} ${ee.cy} L ${je} ${ee.cy} L ${je} ${$e} L ${Te} ${$e} L ${Te} ${X.cy-X.h/2}`,oe=je,re=(ee.cy+$e)/2,ve=He?"start":"end",be={x:me,y:ee.cy},Re={x:Te,y:X.cy-X.h/2}}}else{const Ie=X.cx>ee.cx,He=Q.sameEdgeIndex===0?-12:12,Ue=Ie?ee.cx+ee.w/2:ee.cx-ee.w/2,je=Ie?X.cx-X.w/2:X.cx+X.w/2,me=ee.cy+He,Te=X.cy+He,$e=(Ue+je)/2;q=`M ${Ue} ${me} C ${$e} ${me}, ${$e} ${Te}, ${je} ${Te}`,oe=$e,re=(me+Te)/2-6,be={x:Ue,y:me},Re={x:je,y:Te}}return{path:q,labelX:oe,labelY:re,labelAnchor:ve,fromPt:be,toPt:Re}},R=(Q,ee)=>{const X=I(Q);if(!X)return null;const{path:q,labelX:oe,labelY:re,labelAnchor:ve}=X,be=s===Q.edgeKey,Re=Q.label&&!(Q.from==="$start"&&Q.label==="Always");return o.jsxs("g",{children:[o.jsx("path",{d:q,fill:"none",stroke:"transparent",strokeWidth:14,className:"cursor-pointer",onClick:Ie=>{Ie.stopPropagation(),d(be?null:Q.edgeKey)}}),o.jsx("path",{d:q,fill:"none",stroke:be?"#58a6ff":"#484f58",strokeWidth:be?2.2:1.2,markerEnd:be?"url(#arrow-selected)":"url(#arrow)",pointerEvents:"none"}),Re&&o.jsx("text",{x:oe+(ve==="start"?5:ve==="end"?-5:0),y:re+3,textAnchor:ve,className:"text-[8px]",fill:be?"#79c0ff":"#8b949e",style:{paintOrder:"stroke",stroke:"#0d1117",strokeWidth:3,strokeLinejoin:"round"},pointerEvents:"none",children:Q.label})]},ee)},z=()=>{if(!s||v)return null;const Q=D.find(re=>re.edgeKey===s);if(!Q)return null;const ee=I(Q);if(!ee)return null;const{fromPt:X,toPt:q}=ee,oe=6;return o.jsxs(o.Fragment,{children:[Q.edgeKey!=="start"&&o.jsx("circle",{cx:X.x,cy:X.y,r:oe,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:re=>F(re,Q)}),o.jsx("circle",{cx:q.x,cy:q.y,r:oe,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:re=>O(re,Q)})]})},Y=()=>{if(!v)return null;let Q,ee,X,q;if(v.type==="reconnect-from"){const ve=B.get(v.fixedTargetId);if(!ve)return null;Q=v.mouseX,ee=v.mouseY,X=ve.cx,q=ve.cy-ve.h/2}else{const ve=B.get(v.fromNodeId);if(!ve)return null;Q=ve.cx,ee=ve.cy+ve.h/2,X=v.mouseX,q=v.mouseY}const oe=q-ee,re=Math.abs(oe)>10?`M ${Q} ${ee} C ${Q} ${ee+oe*.4}, ${X} ${q-oe*.4}, ${X} ${q}`:`M ${Q} ${ee} L ${X} ${q}`;return o.jsx("path",{d:re,fill:"none",stroke:"#58a6ff",strokeWidth:2,strokeDasharray:"6 3",strokeOpacity:.7,pointerEvents:"none"})},U=Q=>{const ee=Q.cy+Q.h/2,X=(v==null?void 0:v.fromNodeId)===Q.id;return o.jsx("circle",{cx:Q.cx,cy:ee,r:fb,fill:X?"#58a6ff":"#1c2128",stroke:X?"#58a6ff":"#484f58",strokeWidth:1.5,strokeOpacity:X?1:.5,className:"cursor-crosshair",onMouseDown:q=>W(q,Q.id)})},ie=Q=>{const ee=Q.cy-Q.h/2,X=v&&j===Q.id&&V(Q.id);return o.jsx("circle",{cx:Q.cx,cy:ee,r:fb,fill:X?"#3fb950":"#1c2128",stroke:X?"#3fb950":"#484f58",strokeWidth:1.5,strokeOpacity:X?1:.5})};return o.jsxs("svg",{ref:k,viewBox:`0 0 ${A} ${M}`,className:"block w-full",preserveAspectRatio:"xMidYMin meet",onMouseMove:P,onMouseUp:Z,onClick:G,children:[o.jsxs("defs",{children:[o.jsx("marker",{id:"arrow",viewBox:"0 0 10 7",refX:"10",refY:"3.5",markerWidth:"7",markerHeight:"5",orient:"auto",children:o.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:"#484f58"})}),o.jsx("marker",{id:"arrow-selected",viewBox:"0 0 10 7",refX:"10",refY:"3.5",markerWidth:"7",markerHeight:"5",orient:"auto",children:o.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:"#58a6ff"})})]}),D.map((Q,ee)=>R(Q,ee)),N.map(Q=>{const ee=i===Q.id,X=Q.cx-Q.w/2,q=Q.cy-Q.h/2,oe=y===Q.id,re=v&&j===Q.id&&V(Q.id);if(Q.type==="terminal"){const be=Q.id==="$start",Re=be?"#58a6ff":"#3fb950",Ie=be,He=!be;return o.jsxs("g",{onClick:Ue=>{Ue.stopPropagation(),be&&!f&&d("start")},className:be&&!f?"cursor-pointer":void 0,children:[re&&o.jsx("rect",{x:X-3,y:q-3,width:Q.w+6,height:Q.h+6,rx:Q.h/2+3,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),be&&s==="start"&&o.jsx("rect",{x:X-3,y:q-3,width:Q.w+6,height:Q.h+6,rx:Q.h/2+3,fill:"none",stroke:"#58a6ff",strokeOpacity:.5,strokeWidth:2}),o.jsx("rect",{x:X,y:q,width:Q.w,height:Q.h,rx:Q.h/2,fill:Re,fillOpacity:.08,stroke:Re,strokeOpacity:.4,strokeWidth:1.5}),o.jsx("text",{x:Q.cx,y:Q.cy+4,textAnchor:"middle",fill:Re,className:"text-[10px] font-medium",pointerEvents:"none",children:Q.label}),Ie&&U(Q),He&&ie(Q)]},Q.id)}const ve=Q.color??"#6b7280";return o.jsxs("g",{onClick:be=>{be.stopPropagation(),f||l(ee?null:Q.id)},onMouseEnter:()=>x(Q.id),onMouseLeave:()=>x(null),className:f?void 0:"cursor-pointer",children:[re&&o.jsx("rect",{x:X-3,y:q-3,width:Q.w+6,height:Q.h+6,rx:12,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),ee&&o.jsx("rect",{x:X-3,y:q-3,width:Q.w+6,height:Q.h+6,rx:12,fill:"none",stroke:"#58a6ff",strokeOpacity:.5,strokeWidth:2}),o.jsx("rect",{x:X,y:q,width:Q.w,height:Q.h,rx:10,fill:ve,fillOpacity:.08,stroke:ve,strokeOpacity:.6,strokeWidth:ee?2:1.5}),o.jsx("text",{x:Q.cx,y:Q.cy+4,textAnchor:"middle",fill:"#c9d1d9",className:"text-[11px] font-medium",pointerEvents:"none",children:Q.label}),!f&&U(Q),!f&&ie(Q),oe&&!v&&!f&&o.jsxs("g",{onClick:be=>{be.stopPropagation(),p(Q.id)},className:"cursor-pointer",children:[o.jsx("circle",{cx:X+Q.w-2,cy:q+2,r:8,fill:"#0d1117",fillOpacity:.9,stroke:"#f85149",strokeOpacity:.5,strokeWidth:1}),o.jsx("line",{x1:X+Q.w-5,y1:q-1,x2:X+Q.w+1,y2:q+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"}),o.jsx("line",{x1:X+Q.w+1,y1:q-1,x2:X+Q.w-5,y2:q+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"})]})]},Q.id)}),v&&N.map(Q=>V(Q.id)?o.jsx("rect",{x:Q.cx-Q.w/2-8,y:Q.cy-Q.h/2-8,width:Q.w+16,height:Q.h+16,fill:"transparent",rx:12,onMouseEnter:()=>T(Q.id),onMouseLeave:()=>T(null),onMouseUp:ee=>{ee.stopPropagation(),Z()}},`drop-${Q.id}`):null),Y(),z()]})}const er="w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",Bi="w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",ln="block text-[11px] text-text-secondary mb-0.5";function W5({fromLabel:e,toLabel:r,condition:i,fromStep:s,agentTypes:c,onUpdateCondition:u,onDelete:f}){const l=s&&(s.type==="sub_agent"||s.type==="agent")?c.find(p=>p.id===(s.type==="sub_agent"?s.subAgentType:s.toolMode)):void 0,d=(l==null?void 0:l.results)&&l.results.length>0;return o.jsxs("div",{className:"space-y-3 text-sm",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-blue-500/15 text-blue-300",children:"Transition"}),o.jsx("button",{onClick:f,className:"p-1 rounded text-text-muted hover:text-accent-error text-xs",children:"Delete"})]}),o.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-text-secondary",children:[o.jsx("span",{className:"font-medium text-text-primary",children:e}),o.jsx(Ob,{}),o.jsx("span",{className:"font-medium text-text-primary",children:r})]}),o.jsxs("div",{children:[o.jsx("label",{className:ln,children:"Condition"}),o.jsx("select",{value:i.type,onChange:p=>{u(p.target.value==="step_result"?{type:"step_result",result:"success"}:{type:p.target.value})},className:Bi,children:L0.map(p=>o.jsx("option",{value:p.value,children:p.label},p.value))})]}),i.type==="step_result"&&o.jsxs("div",{children:[o.jsx("label",{className:ln,children:"Result"}),d?o.jsx("select",{value:i.result??l.results[0],onChange:p=>{u({type:"step_result",result:p.target.value})},className:Bi,children:l.results.map(p=>o.jsx("option",{value:p,children:p},p))}):o.jsx("input",{type:"text",value:i.result??"success",onChange:p=>u({type:"step_result",result:p.target.value}),placeholder:"e.g. success, passed, failed",className:er})]}),o.jsx("p",{className:"text-text-muted text-[10px]",children:"Drag handles to reconnect. Press Delete to remove."})]})}function lh({variables:e,onInsert:r}){return e.length===0?null:o.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:e.map(i=>o.jsx("button",{type:"button",onClick:()=>r(i.name),title:i.description,className:"px-1.5 py-0.5 rounded text-[10px] font-mono bg-bg-primary border border-border text-text-secondary hover:text-accent-primary hover:border-accent-primary/40 transition-colors",children:`{{${i.name}}}`},i.name))})}function G5({step:e,isEntry:r,agentTypes:i,transitionCount:s,templateVariables:c,onUpdate:u,onRemove:f,onSetEntry:l}){const{color:d,name:p}=_f(e,i);return o.jsxs("div",{className:"space-y-3 text-sm",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold",style:{backgroundColor:d+"20",color:d},children:p}),r&&o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-accent-primary/15 text-accent-primary",children:"Entry"})]}),o.jsxs("div",{className:"flex items-center gap-1",children:[!r&&o.jsx("button",{onClick:l,className:"p-1 rounded text-text-muted hover:text-accent-primary text-xs",children:"Set entry"}),o.jsx("button",{onClick:f,className:"p-1 rounded text-text-muted hover:text-accent-error text-xs",children:"Delete"})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:ln,children:"Type"}),o.jsx("select",{value:e.type,onChange:g=>{const m=g.target.value,b=m==="sub_agent"?"verification":"build";if(m==="agent"){const _=i.find(k=>!k.subagent);u({...e,type:m,phase:b,toolMode:(_==null?void 0:_.id)??"builder",name:(_==null?void 0:_.name)??"Agent"})}else if(m==="sub_agent"){const _=i.find(k=>k.subagent);u({...e,type:m,phase:b,subAgentType:(_==null?void 0:_.id)??"",name:(_==null?void 0:_.name)??"Sub-Agent"})}else u({...e,type:m,phase:b,name:"Shell"})},className:Bi,children:U5.map(g=>o.jsx("option",{value:g.value,children:g.label},g.value))})]}),e.type==="agent"&&o.jsxs("div",{children:[o.jsx("label",{className:ln,children:"Agent Type"}),o.jsx("select",{value:e.toolMode??"builder",onChange:g=>{const m=i.find(b=>b.id===g.target.value);u({...e,toolMode:g.target.value,name:(m==null?void 0:m.name)??g.target.value})},className:Bi,children:i.filter(g=>!g.subagent).map(g=>o.jsx("option",{value:g.id,children:g.name},g.id))})]}),e.type==="sub_agent"&&o.jsxs("div",{children:[o.jsx("label",{className:ln,children:"Sub-Agent Type"}),o.jsxs("select",{value:e.subAgentType??"",onChange:g=>{const m=i.find(b=>b.id===g.target.value);u({...e,subAgentType:g.target.value,name:(m==null?void 0:m.name)??g.target.value})},className:Bi,children:[o.jsx("option",{value:"",children:"— select —"}),i.filter(g=>g.subagent).map(g=>o.jsx("option",{value:g.id,children:g.name},g.id))]})]}),(e.type==="agent"||e.type==="sub_agent")&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("label",{className:ln,children:"Prompt"}),o.jsx("textarea",{value:e.prompt??"",onChange:g=>u({...e,prompt:g.target.value||void 0}),rows:6,className:`${er} resize-y text-xs`,placeholder:"Injected on first entry..."}),o.jsx(lh,{variables:c,onInsert:g=>u({...e,prompt:(e.prompt??"")+`{{${g}}}`})})]}),o.jsxs("div",{children:[o.jsx("label",{className:ln,children:"Nudge Prompt"}),o.jsx("textarea",{value:e.nudgePrompt??"",onChange:g=>u({...e,nudgePrompt:g.target.value||void 0}),rows:6,className:`${er} resize-y text-xs`,placeholder:"Injected on re-entry..."}),o.jsx(lh,{variables:c,onInsert:g=>u({...e,nudgePrompt:(e.nudgePrompt??"")+`{{${g}}}`})})]})]}),e.type==="shell"&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("label",{className:ln,children:"Command"}),o.jsx("textarea",{value:e.command??"",onChange:g=>u({...e,command:g.target.value}),rows:3,className:`${er} font-mono text-xs resize-y`,placeholder:"cd {{workdir}} && npm run lint"}),o.jsx(lh,{variables:c,onInsert:g=>u({...e,command:(e.command??"")+`{{${g}}}`})})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsx("label",{className:ln,children:"Timeout (ms)"}),o.jsx("input",{type:"number",value:e.timeout??6e4,onChange:g=>u({...e,timeout:Number(g.target.value)}),className:`${er} font-mono text-xs`})]}),o.jsxs("div",{children:[o.jsx("label",{className:ln,children:"Success Codes"}),o.jsx("input",{value:(e.successExitCodes??[0]).join(", "),onChange:g=>u({...e,successExitCodes:g.target.value.split(",").map(m=>Number(m.trim())).filter(m=>!isNaN(m))}),className:`${er} font-mono text-xs`})]})]})]}),o.jsx("div",{className:"pt-1 border-t border-border/50",children:o.jsxs("p",{className:"text-text-muted text-[10px]",children:[s," outgoing transition",s!==1?"s":""," — drag from the bottom port to connect."]})})]})}const pb=[];function O0({isOpen:e,onClose:r,initialEditId:i}){const s=Ct(pe=>pe.defaults),c=Ct(pe=>pe.userItems),u=Ct(pe=>pe.loading),f=Ct(pe=>pe.templateVariables),l=Ct(pe=>pe.fetchWorkflows),d=Ct(pe=>pe.fetchWorkflow),p=Ct(pe=>pe.fetchDefaultContent),g=Ct(pe=>pe.fetchTemplateVariables),m=Ct(pe=>pe.createWorkflow),b=Ct(pe=>pe.updateWorkflow),_=Ct(pe=>pe.deleteWorkflow),{requestDelete:k,clearConfirm:C,isConfirming:y}=Oh(),[x,v]=H.useState("list"),[S,j]=H.useState(null),[T,N]=H.useState(!1),[D,A]=H.useState(null),[M,B]=H.useState(null),[$,V]=H.useState(""),[W,O]=H.useState(""),[F,P]=H.useState(""),[Z,G]=H.useState("1.0.0"),[I,R]=H.useState("#3b82f6"),[z,Y]=H.useState(""),[U,ie]=H.useState(50),[Q,ee]=H.useState(pb),[X,q]=H.useState({type:"always"}),[oe,re]=H.useState(""),[ve,be]=H.useState(!1),[Re,Ie]=H.useState([]),[He]=H.useState(null);H.useEffect(()=>{e&&(l(),g(),ke("/api/agents").then(pe=>pe.json()).then(pe=>Ie(pe.agents??[])).catch(()=>{}),A(null),B(null),i?s.some(ye=>ye.id===i)?p(i).then(ye=>{ye&&(V(ye.metadata.name+" (copy)"),O(`${i}-copy-${Date.now()}`),P(ye.metadata.description),G(ye.metadata.version),R(ye.metadata.color??"#3b82f6"),Y(ye.entryStep),ie(ye.settings.maxIterations),ee(ye.steps),q(ye.startCondition??{type:"always"}),re(""),j(null),N(!1),v("edit"))}):d(i).then(ye=>{ye&&(V(ye.metadata.name),O(ye.metadata.id),P(ye.metadata.description),G(ye.metadata.version),R(ye.metadata.color??"#3b82f6"),Y(ye.entryStep),ie(ye.settings.maxIterations),ee(ye.steps),q(ye.startCondition??{type:"always"}),re(""),j(i),N(!1),v("edit"))}):(v("list"),j(null),N(!1)))},[e,l,d,p,g,i]);const Ue=async pe=>{const ye=await d(pe);ye&&(j(pe),V(ye.metadata.name),O(ye.metadata.id),P(ye.metadata.description),G(ye.metadata.version),R(ye.metadata.color??"#3b82f6"),Y(ye.entryStep),ie(ye.settings.maxIterations),ee(ye.steps),q(ye.startCondition??{type:"always"}),re(""),A(null),B(null),v("edit"))},je=async()=>{var Qe;const pe=S??W;if(!pe||!$)return re("Name is required."),!1;if(Q.length===0)return re("Add at least one step."),!1;let ye=z;if(!ye||!Q.some(te=>te.id===ye)){if(ye=((Qe=Q.find(te=>te.id))==null?void 0:Qe.id)??"",!ye)return re("All steps need an ID."),!1;Y(ye)}be(!0),re("");const we={metadata:{id:pe,name:$,description:F,version:Z||"1.0.0",color:I},entryStep:ye,settings:{maxIterations:U},steps:Q,startCondition:X},We=S?await b(S,we):await m(we);return be(!1),We.success?(S||j(pe),!0):(re(We.error??"Failed to save."),!1)},me=async()=>{await je()},Te=async()=>{await je()&&(i?r():v("list"))},$e=()=>{i?r():v("list")},Lt=pe=>{V(pe),S||O(P5(pe))},fe=async pe=>{if(s.some(we=>we.id===pe)){const we=await p(pe);if(!we)return;V(we.metadata.name),O(we.metadata.id),P(we.metadata.description),G(we.metadata.version),R(we.metadata.color??"#3b82f6"),Y(we.entryStep),ie(we.settings.maxIterations),ee(we.steps),q(we.startCondition??{type:"always"}),re(""),j(pe),N(!0)}else{const we=await d(pe);if(!we)return;V(we.metadata.name),O(we.metadata.id),P(we.metadata.description),G(we.metadata.version),R(we.metadata.color??"#3b82f6"),Y(we.entryStep),ie(we.settings.maxIterations),ee(we.steps),q(we.startCondition??{type:"always"}),re(""),j(pe),N(!0)}v("edit")},Ae=async pe=>{const we=s.some(We=>We.id===pe)?await p(pe):await d(pe);we&&(V(we.metadata.name+" (copy)"),O(`${pe}-copy-${Date.now()}`),P(we.metadata.description),G(we.metadata.version),R(we.metadata.color??"#3b82f6"),Y(we.entryStep),ie(we.settings.maxIterations),ee(we.steps),q(we.startCondition??{type:"always"}),re(""),j(null),N(!1),v("edit"))},Be=()=>{j(null),V(""),O(""),P(""),G("1.0.0"),R("#3b82f6"),Y(""),ie(50),ee(structuredClone(pb)),q({type:"always"}),re(""),A(null),B(null),N(!1),v("edit")},ot=async pe=>{await _(pe),C()},ue=H.useCallback(pe=>{A(pe),B(null)},[]),_e=H.useCallback(pe=>{B(pe),A(null)},[]),Ne=D!==null?Number(D):-1,Oe=Ne>=0?Q[Ne]??null:null,qe=H.useCallback(pe=>{ee(ye=>ye.map((we,We)=>We===Ne?pe:we))},[Ne]),Nt=X.type==="step_result"?`${X.result}`:R0[X.type]??X.type,Ze=()=>{const pe=Q.length,ye=F5(Q),we=Re.find(We=>!We.subagent);ee([...Q,{id:ye,name:(we==null?void 0:we.name)??"Agent",type:"agent",phase:"build",toolMode:(we==null?void 0:we.id)??"builder",transitions:[]}]),z||Y(ye),ue(String(pe))},Ot=H.useCallback((pe,ye)=>{pe==="$start"?(Y(ye),_e("start")):ee(we=>{const We=we.find(te=>te.id===pe),Qe=We?We.transitions.length:0;return _e(`${pe}:${Qe}`),we.map(te=>te.id===pe?{...te,transitions:[...te.transitions,{when:{type:"always"},goto:ye}]}:te)})},[_e]),Tt=H.useCallback((pe,ye)=>{if(pe==="start")Y(ye);else{const we=pe.lastIndexOf(":"),We=pe.slice(0,we),Qe=parseInt(pe.slice(we+1));ee(te=>te.map(Ee=>Ee.id===We?{...Ee,transitions:Ee.transitions.map((Le,Ve)=>Ve===Qe?{...Le,goto:ye}:Le)}:Ee))}},[]),Yt=H.useCallback((pe,ye)=>{const we=pe.lastIndexOf(":"),We=pe.slice(0,we),Qe=parseInt(pe.slice(we+1));ee(te=>{const Ee=te.find(Ve=>Ve.id===We);if(!Ee)return te;const Le=Ee.transitions[Qe];return Le?te.map(Ve=>Ve.id===We?{...Ve,transitions:Ve.transitions.filter((Mt,gn)=>gn!==Qe)}:Ve.id===ye?{...Ve,transitions:[...Ve.transitions,Le]}:Ve):te}),B(null)},[]),lt=H.useCallback(pe=>{if(pe==="start")Y("");else{const ye=pe.lastIndexOf(":"),we=pe.slice(0,ye),We=parseInt(pe.slice(ye+1));ee(Qe=>Qe.map(te=>te.id===we?{...te,transitions:te.transitions.filter((Ee,Le)=>Le!==We)}:te))}B(null)},[]),Bn=H.useCallback((pe,ye)=>{if(pe==="start")q(ye);else{const we=pe.lastIndexOf(":"),We=pe.slice(0,we),Qe=parseInt(pe.slice(we+1));ee(te=>te.map(Ee=>Ee.id===We?{...Ee,transitions:Ee.transitions.map((Le,Ve)=>Ve===Qe?{...Le,when:ye}:Le)}:Ee))}},[]),Xt=pe=>_f(pe,Re).name,Us=()=>{if(!M)return null;if(M==="start"){const Le=Q.find(Ve=>Ve.id===z);return{type:"start",fromLabel:"Start",toLabel:Le?Xt(Le):"(none)",condition:X}}const pe=M.lastIndexOf(":"),ye=M.slice(0,pe),we=parseInt(M.slice(pe+1)),We=Q.find(Le=>Le.id===ye);if(!We)return null;const Qe=We.transitions[we];if(!Qe)return null;const te=Q.find(Le=>Le.id===Qe.goto),Ee=Qe.goto==="$done"?"Done":te?Xt(te):Qe.goto;return{type:"step",fromLabel:Xt(We),toLabel:Ee,condition:Qe.when}};if(x==="edit"){const pe=Us();return o.jsxs(jt,{isOpen:e,onClose:$e,title:T?$:S?"Edit Workflow":"New Workflow",size:"full",children:[oe&&o.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded mb-3",children:oe}),o.jsxs("div",{className:"flex items-end gap-3 mb-3 pb-3 border-b border-border flex-wrap",children:[o.jsxs("div",{className:"min-w-[140px]",children:[o.jsx("label",{className:ln,children:"Name"}),o.jsx("input",{value:$,onChange:ye=>Lt(ye.target.value),placeholder:"Workflow name",className:`${er} ${T?"opacity-50":""}`,readOnly:T})]}),o.jsxs("div",{className:"min-w-[100px]",children:[o.jsx("label",{className:ln,children:"ID"}),o.jsx("input",{value:W,readOnly:!0,className:`${er} font-mono opacity-50`})]}),o.jsxs("div",{className:"flex-1 min-w-[140px]",children:[o.jsx("label",{className:ln,children:"Description"}),o.jsx("input",{value:F,onChange:ye=>!T&&P(ye.target.value),readOnly:T,placeholder:"What does this workflow do?",className:`${er} ${T?"opacity-50":""}`})]}),o.jsxs("div",{className:"w-20",children:[o.jsx("label",{className:ln,children:"Max Iter."}),o.jsx("input",{type:"number",value:U,onChange:ye=>!T&&ie(Number(ye.target.value)),readOnly:T,className:`${er} font-mono ${T?"opacity-50":""}`})]}),o.jsxs("div",{children:[o.jsx("label",{className:ln,children:"Color"}),o.jsx("input",{type:"color",value:I,onChange:ye=>!T&&R(ye.target.value),disabled:T,className:`w-8 h-8 rounded border border-border bg-transparent ${T?"opacity-50":"cursor-pointer"}`})]})]}),o.jsxs("div",{className:"flex gap-3",style:{height:"calc(90vh - 220px)",minHeight:300},children:[o.jsxs("div",{className:"flex-1 min-w-0 bg-bg-primary/50 border border-border rounded-lg flex flex-col overflow-hidden",children:[o.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-border/50 shrink-0",children:[o.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wider font-medium",children:"Flow"}),!T&&o.jsx("button",{onClick:Ze,className:"text-[11px] text-accent-primary hover:text-accent-primary/80",children:"+ Add Step"})]}),o.jsxs("div",{className:"flex-1 min-h-0 p-2 overflow-auto",children:[o.jsx(q5,{steps:Q,entryStep:z,selectedNodeId:(Oe==null?void 0:Oe.id)??null,selectedEdgeKey:M,startConditionLabel:Nt,agentTypes:Re,isReadOnly:T,onSelectNode:ye=>{if(ye===null){ue(null);return}const we=Q.findIndex(We=>We.id===ye);ue(we>=0?String(we):null)},onSelectEdge:_e,onRemoveStep:ye=>{var We;const we=Q.findIndex(Qe=>Qe.id===ye);if(ee(Qe=>Qe.filter(te=>te.id!==ye)),Ne===we&&ue(null),z===ye){const Qe=Q.filter(te=>te.id!==ye);Y(((We=Qe[0])==null?void 0:We.id)??"")}},onCreateTransition:Ot,onReconnectTo:Tt,onReconnectFrom:Yt,onDeleteTransition:lt}),Q.length===0&&o.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-text-muted",children:[o.jsx("p",{className:"text-xs mb-2",children:"No steps yet"}),o.jsx("button",{onClick:Ze,className:"px-3 py-1.5 rounded bg-accent-primary/10 text-accent-primary text-xs hover:bg-accent-primary/20",children:"+ Add your first step"})]})]})]}),o.jsxs("div",{className:"w-[300px] shrink-0 border border-border rounded-lg bg-bg-secondary flex flex-col overflow-hidden",children:[o.jsx("div",{className:"px-3 py-1.5 border-b border-border shrink-0",children:o.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wider font-medium",children:"Properties"})}),o.jsx("div",{className:"p-3 overflow-y-auto flex-1 min-h-0",children:T&&(pe||Oe)?o.jsx("p",{className:"text-text-muted text-xs text-center py-8",children:'View only — click "Duplicate & Customize" to edit.'}):pe?pe.type==="start"?o.jsxs("div",{className:"space-y-3 text-sm",children:[o.jsx("div",{className:"flex items-center gap-2",children:o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-blue-500/20 text-blue-300",children:"Start"})}),z&&o.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-text-secondary",children:[o.jsx("span",{className:"text-text-primary font-medium",children:"Start"}),o.jsx(Ob,{}),o.jsx("span",{className:"text-text-primary font-medium",children:pe.toLabel})]}),o.jsxs("div",{children:[o.jsx("label",{className:ln,children:"Activation Condition"}),o.jsx("select",{value:X.type,onChange:ye=>q(ye.target.value==="step_result"?{type:"step_result",result:"success"}:{type:ye.target.value}),className:Bi,children:L0.map(ye=>o.jsx("option",{value:ye.value,children:ye.label},ye.value))})]}),X.type==="step_result"&&o.jsxs("div",{children:[o.jsx("label",{className:ln,children:"Result"}),z&&(()=>{const ye=Q.find(te=>te.id===z),we=ye&&(ye.type==="sub_agent"||ye.type==="agent")?Re.find(te=>te.id===(ye.type==="sub_agent"?ye.subAgentType:ye.toolMode)):void 0,We=(we==null?void 0:we.results)&&we.results.length>0,Qe=(we==null?void 0:we.results)??[];return We?o.jsx("select",{value:X.result??Qe[0],onChange:te=>q({type:"step_result",result:te.target.value}),className:Bi,children:Qe.map(te=>o.jsx("option",{value:te,children:te},te))}):o.jsx("input",{type:"text",value:X.result??"success",onChange:te=>q({type:"step_result",result:te.target.value}),placeholder:"e.g. success, passed, failed",className:er})})()]}),o.jsx("p",{className:"text-text-muted text-[10px]",children:"Workflow only proceeds when this condition is met. Drag the target handle to change entry step."})]}):o.jsx(W5,{fromLabel:pe.fromLabel,toLabel:pe.toLabel,condition:pe.condition,fromStep:pe.type==="step"?Q.find(ye=>ye.id===pe.fromLabel):void 0,agentTypes:Re,onUpdateCondition:ye=>Bn(M,ye),onDelete:()=>lt(M)}):Oe?o.jsx(G5,{step:Oe,isEntry:Oe.id===z,agentTypes:Re,transitionCount:Oe.transitions.length,templateVariables:f,onUpdate:qe,onRemove:()=>{var ye;if(Oe&&(ee(Q.filter((we,We)=>We!==Ne)),ue(null),z===Oe.id)){const we=Q.filter((We,Qe)=>Qe!==Ne);Y(((ye=we[0])==null?void 0:ye.id)??"")}},onSetEntry:()=>Y(Oe.id)}):o.jsxs("p",{className:"text-text-muted text-xs text-center py-8",children:["Click a node or edge to edit.",o.jsx("br",{}),"Drag from a port to connect."]})})]})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 mt-3 border-t border-border",children:[o.jsx(it,{variant:"secondary",onClick:$e,children:"Close"}),T?o.jsx(it,{variant:"primary",onClick:()=>{V($+" (copy)"),O(`${S}-copy-${Date.now()}`),j(null),N(!1)},children:"Duplicate & Customize"}):o.jsxs(o.Fragment,{children:[o.jsx(it,{variant:"secondary",onClick:me,disabled:ve||!$,children:ve?"Saving...":"Save"}),o.jsx(it,{variant:"primary",onClick:Te,disabled:ve||!$,children:"Save & Close"})]})]})]})}return o.jsxs(jt,{isOpen:e,onClose:r,title:"Workflows",size:"lg",children:[o.jsxs("div",{className:"flex items-center justify-between mb-4",children:[o.jsx("p",{className:"text-text-secondary text-sm",children:"Workflows define the orchestrator's step sequence when running tasks."}),o.jsx("div",{className:"flex items-center gap-2 flex-shrink-0 ml-3",children:o.jsx(it,{variant:"primary",size:"sm",onClick:Be,children:"+ New"})})]}),u&&s.length===0&&c.length===0?o.jsx("div",{className:"text-text-muted text-sm",children:"Loading workflows..."}):s.length===0&&c.length===0?o.jsx("div",{className:"text-text-muted text-sm",children:"No workflows installed."}):o.jsxs("div",{className:"space-y-4",children:[s.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Built-in"}),o.jsx("div",{className:"space-y-2",children:s.map(pe=>o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsxs("div",{className:"min-w-0 flex-1 mr-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-text-primary text-sm font-medium",children:pe.name}),o.jsxs("span",{className:"text-text-muted text-xs",children:["v",pe.version]})]}),o.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:pe.description})]}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx("button",{onClick:()=>fe(pe.id),className:"p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",title:"View",children:o.jsx(ec,{})}),o.jsx(Qa,{onClick:()=>Ae(pe.id)})]})]},pe.id))})]}),c.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Custom"}),o.jsx("div",{className:"space-y-2",children:c.map(pe=>o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsxs("div",{className:"min-w-0 flex-1 mr-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-text-primary text-sm font-medium",children:pe.name}),o.jsxs("span",{className:"text-text-muted text-xs",children:["v",pe.version]})]}),o.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:pe.description})]}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx(Qa,{onClick:()=>Ae(pe.id)}),o.jsx(Hs,{onClick:()=>Ue(pe.id)}),y(pe.id,"delete")?o.jsx(Mh,{onConfirm:()=>ot(pe.id),onCancel:()=>{}}):o.jsx(Ih,{onClick:()=>k(pe.id)})]})]},pe.id))})]})]})]})}function V5(e,r){const i=e.startCondition;if(!i||i.type==="always")return!0;switch(i.type){case"has_pending_criteria":return r.some(s=>s.status.type!=="passed");case"all_criteria_passed":return r.length===0||r.every(s=>s.status.type==="passed");case"all_criteria_completed_or_passed":return r.every(s=>s.status.type==="completed"||s.status.type==="passed");case"any_criteria_blocked":return r.some(s=>s.status.type==="failed"&&s.attempts.filter(c=>c.status==="failed").length>=4);case"step_result":return null;default:return null}}function K5({onSelectWorkflow:e,onOpenManager:r,criteria:i}){const[s,c]=H.useState(!1),[u,f]=H.useState(null),l=Ct(N=>N.defaults),d=Ct(N=>N.userItems),p=Ct(N=>N.fetchWorkflows),g=[...l,...d],{isOpen:m,search:b,selectedIndex:_,filtered:k,containerRef:C,searchRef:y,handleToggle:x,handleSearchChange:v,handleKeyDown:S}=E0({items:g,isOpen:s,onOpen:()=>c(!0),onClose:()=>c(!1),filterFn:(N,D)=>!D||N.name.toLowerCase().includes(D.toLowerCase())});H.useEffect(()=>{s&&p()},[s,p]);const j=N=>{e(N),c(!1)},T=()=>{c(!1),r()};return o.jsxs("div",{ref:C,className:"relative",children:[o.jsx(j0,{label:"Workflows",isOpen:m,onClick:x}),m&&o.jsxs("div",{className:"absolute bottom-full right-0 mb-1 w-72 bg-bg-secondary border border-border rounded-lg shadow-xl z-50",onKeyDown:S,children:[o.jsx(N0,{value:b,onChange:v,onKeyDown:S,ref:y,placeholder:"Search workflows..."}),o.jsx(T0,{children:k.length===0?o.jsx(A0,{hasItems:g.length>0,message:"No workflows yet"}):k.map((N,D)=>{const A=V5(N,i),M=N.color??"#3b82f6";return o.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 rounded transition-colors group ${D===_?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[o.jsxs("button",{type:"button",onClick:()=>j(N.id),className:"flex-1 text-left flex items-center gap-2",children:[o.jsx("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:M}}),o.jsx("span",{className:"text-sm text-text-primary font-medium flex-1",children:N.name}),A!==null&&o.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:A?"#22c55e":"#6b7280"},title:A?"Entry condition met":"Entry condition not met"})]}),o.jsx(Hs,{className:"opacity-0 group-hover:opacity-100",onClick:B=>{B.stopPropagation(),c(!1),f(N.id)}})]},N.id)})}),o.jsx(D0,{label:"Manage Workflows...",onClick:T})]}),o.jsx(O0,{isOpen:!!u,onClose:()=>f(null),initialEditId:u})]})}const Y5=(e,r)=>{if(!r)return!0;const i=r.toLowerCase().split(/\s+/),s=e.toLowerCase().split(/\s+/);return i.every(c=>{for(const u of s){let f=0;for(let l=0;l<u.length&&f<c.length;l++)u[l]===c[f]&&f++;if(f===c.length)return!0}return!1})};function X5({isOpen:e,onClose:r,onCloseComplete:i,onSelectCommand:s,onSelectWorkflow:c,onCloseCompleteAction:u,textareaContent:f}){const l=on(G=>G.fetchCommands),d=Ct(G=>G.fetchWorkflows),p=kt(G=>G.fetchAgents),g=on(G=>G.defaults),m=on(G=>G.userItems),b=Ct(G=>G.defaults),_=Ct(G=>G.userItems),k=kt(G=>G.defaults),C=kt(G=>G.userItems),y=Ce(G=>{var I;return(I=G.currentSession)==null?void 0:I.mode}),x=Ce(G=>{var I;return((I=G.currentSession)==null?void 0:I.dangerLevel)??"normal"}),v=Ce(G=>G.switchMode),S=Ce(G=>G.switchDangerLevel),j=Ce(G=>{var I;return(I=G.currentSession)==null?void 0:I.projectId}),T=Ce(G=>G.createSession),N=H.useRef(void 0),[D,A]=H.useState(""),[M,B]=H.useState(0),$=H.useRef(null),V=H.useRef(!1);H.useEffect(()=>{e&&(V.current=!0)},[e]),H.useEffect(()=>{if(e){l(),d(),p(),A(""),B(0);const G=setTimeout(()=>{var I;return(I=$.current)==null?void 0:I.focus()},50);return()=>clearTimeout(G)}},[e,l,d,p]),H.useEffect(()=>{var G;!e&&V.current&&(i==null||i(),(G=N.current)==null||G.call(N),N.current=void 0)},[e,i]);const W=(G,I)=>{const R=new Set(I.map(z=>z.id));return[...G.filter(z=>!R.has(z.id)),...I]},F=[{id:"create-session",name:"New Session",prefix:"Action > Create",action:()=>j&&T(j)},{id:"navigate-session",name:"Another Session",prefix:"Action > Navigate to",action:()=>{N.current=u,r()}},...W(k,C).filter(G=>!G.subagent&&G.id!==y).map(G=>({id:G.id,name:G.name,prefix:"Agent > Switch to",action:()=>v(G.id)})),...W(g,m).map(G=>({id:G.id,name:G.name,prefix:"Command > Launch",action:()=>s(G.id,f)})),...W(b,_).map(G=>({id:G.id,name:G.name,prefix:"Workflow > Run",action:()=>c(G.id)})),...["normal","dangerous"].filter(G=>G!==x).map(G=>({id:G,name:G.charAt(0).toUpperCase()+G.slice(1),prefix:"Mode > Switch to",action:()=>S(G)}))].filter(G=>Y5(`${G.prefix} ${G.name}`,D)),P=F.length-1,Z=G=>{var I;switch(G.key){case"ArrowDown":G.preventDefault(),B(R=>Math.min(R+1,P));break;case"ArrowUp":G.preventDefault(),B(R=>Math.max(R-1,0));break;case"Enter":G.preventDefault(),(I=F[M])==null||I.action(),r();break;case"Escape":G.preventDefault(),r();break}};return e?tc.createPortal(o.jsxs("div",{className:"fixed inset-0 z-50 flex items-start justify-center pt-[15vh] p-4",children:[o.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:r}),o.jsxs("div",{className:"relative w-full max-w-md bg-bg-secondary border border-border rounded shadow-xl",children:[o.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 border-b border-border",children:[o.jsx("input",{ref:$,type:"text",value:D,onChange:G=>{A(G.target.value),B(0)},onKeyDown:Z,placeholder:"Search...",className:"flex-1 bg-transparent text-sm focus:outline-none placeholder:text-text-muted"}),o.jsx(Rh,{onClick:r,className:"shrink-0","aria-label":"Close"})]}),o.jsx("div",{className:"overflow-y-auto max-h-[60vh] p-2",children:F.length===0?o.jsx("div",{className:"px-3 py-4 text-center text-text-muted text-sm",children:g.length+m.length+b.length+_.length>0?"No matches":"No agents, commands, or workflows yet"}):F.map((G,I)=>o.jsxs("button",{type:"button",onClick:()=>{G.action(),r()},className:`w-full text-left px-3 py-2 rounded text-sm transition-colors ${I===M?"bg-accent-primary/20 text-text-primary":"text-text-secondary hover:bg-bg-tertiary hover:text-text-primary"}`,children:[o.jsxs("span",{className:"text-text-muted font-normal",children:[G.prefix," "]}),o.jsx("span",{children:G.name})]},G.id))})]})]}),document.body):null}function Z5(e){return e==="criterion"}function Q5(e){var r,i;return e.role!=="assistant"||e.subAgentId||(r=e.content)!=null&&r.trim()||(i=e.thinkingContent)!=null&&i.trim()||!e.toolCalls||e.toolCalls.length===0?!1:e.toolCalls.every(s=>Z5(s.name))}function J5(e,r=[]){const i=[];let s=null,c=[],u,f=1;const l=new Map,d=new Map,p=[];for(const _ of r)_.type==="message"?l.set(_.message.id,_):_.type==="subagent"?d.set(_.subAgentId,_):_.type==="criteria-batch"&&p.push(_);let g=0;const m=()=>{if(c.length>0){const _=p[g];_&&_.type==="criteria-batch"&&_.toolCalls.length===c.length&&_.toolCalls.every((C,y)=>{var x;return C.id===((x=c[y])==null?void 0:x.id)})?i.push(_):i.push({type:"criteria-batch",toolCalls:[...c]}),g++,c=[]}},b=()=>{if(!s)return;const _=s,k=d.get(_.subAgentId);k&&k.type==="subagent"&&k.messages.length===_.messages.length&&k.messages.every((y,x)=>y===_.messages[x])?i.push(k):i.push({type:"subagent",subAgentId:_.subAgentId,subAgentType:_.subAgentType,messages:_.messages}),s=null};for(const _ of e)if(_.role!=="tool"){if(_.contextWindowId&&u&&_.contextWindowId!==u&&(m(),b(),f++,i.push({type:"context-divider",windowSequence:f})),u=_.contextWindowId,Q5(_)){b();for(const k of _.toolCalls)c.push(k);continue}if(m(),_.subAgentId&&_.subAgentType)s&&s.subAgentId===_.subAgentId?s.messages.push(_):(b(),s={subAgentId:_.subAgentId,subAgentType:_.subAgentType,messages:[_]});else{b();const k=l.get(_.id);k&&k.type==="message"&&k.message===_?i.push(k):i.push({type:"message",message:_})}}return m(),b(),i}function eD(e){const{year:r,month:i,day:s}=Kb(e);return`${r}/${i}/${s} ${rc(e)}`}function tD(e,r){return e.length<=r?e:e.substring(0,r)+"..."}const nD=10,rD=150;function iD(e){const r=[];if(e.recentUserPrompts)for(const i of e.recentUserPrompts)r.push({id:i.id,content:i.content,timestamp:i.timestamp,sessionId:e.id,sessionName:e.title||e.id});return r}function sD(e){return[...e].sort((s,c)=>new Date(c.timestamp).getTime()-new Date(s.timestamp).getTime()).slice(0,nD).reverse().map(s=>({id:s.id,content:s.content,timestamp:s.timestamp,formattedTimestamp:eD(s.timestamp),trimmedContent:tD(s.content,rD),sessionId:s.sessionId,sessionName:s.sessionName}))}function aD(e,r,i){const s=[],c=e.filter(u=>u.role==="user"&&!u.isSystemGenerated&&u.messageKind!=="auto-prompt");for(const u of c)s.push({id:u.id,content:u.content,timestamp:u.timestamp,sessionId:i??"",sessionName:"This session"});for(const u of r)i&&u.id===i||s.push(...iD(u));return sD(s)}function oD(e,r=[],i=null){const[s,c]=H.useState(0),[u,f]=H.useState(!1),l=H.useMemo(()=>aD(e,r,i),[e,r,i]),d=H.useCallback(()=>{l.length>0&&(c(l.length-1),f(!0))},[l.length]),p=H.useCallback(()=>{f(!1),c(0)},[]),g=H.useCallback(()=>{c(_=>l.length===0?_:_===0?l.length-1:_-1)},[l.length]),m=H.useCallback(()=>{c(_=>l.length===0?_:_===l.length-1?0:_+1)},[l.length]),b=H.useCallback(()=>{if(l.length===0||!u)return null;const _=l[s];return(_==null?void 0:_.content)??null},[l,s,u]);return{history:l,selectedIndex:s,showHistory:u,openHistory:d,closeHistory:p,navigateUp:g,navigateDown:m,selectCurrent:b}}function lD({criteriaSidebarOpen:e,onCriteriaSidebarToggle:r}={}){const i=e??!0,[s,c]=H.useState(""),[u,f]=H.useState([]),[l,d]=H.useState(!1),[p,g]=H.useState(null),[m,b]=H.useState(!1),[_,k]=H.useState(!1),[C,y]=H.useState(!1),[x,v]=H.useState(null),S=H.useRef(null),j=H.useRef(null),T=H.useRef(null),N=Ce(te=>te.currentSession),D=Ce(te=>te.messages),A=Ce(te=>te.streamingMessage),M=Ce(te=>te.sessions),B=Ce(te=>te.error),$=Ce(te=>te.pendingQuestion),V=Lb(),W=Ce(te=>te.sendMessage),O=Ce(te=>te.clearError),F=Ce(te=>te.acceptAndBuild),P=Ce(te=>te.stopGeneration),Z=Ce(te=>te.launchRunner),G=Ce(te=>te.cancelQueued),I=nw(),{showThinking:R,showVerboseToolOutput:z,showStats:Y,showAgentDefinitions:U,showWorkflowBars:ie}=Nb(),Q=Ct(te=>te.defaults),ee=Ct(te=>te.userItems),X=[...Q,...ee],q=Ct(te=>te.fetchWorkflows),oe=kt(te=>te.defaults),re=kt(te=>te.userItems),ve=[...oe,...re].filter(te=>!te.subagent);H.useEffect(()=>{q()},[q]);const{history:be,selectedIndex:Re,showHistory:Ie,openHistory:He,closeHistory:Ue,navigateUp:je,navigateDown:me,selectCurrent:Te}=oD(D,M,N==null?void 0:N.id);H.useEffect(()=>{const te=Ee=>{v(Ee.detail.stats)};return window.addEventListener("open-turn-stats",te),()=>window.removeEventListener("open-turn-stats",te)},[]);const $e=H.useMemo(()=>A?D.map(te=>te.id===A.id?A:te):D,[D,A]),Lt=H.useRef([]),fe=H.useMemo(()=>{const te=J5($e,Lt.current);return Lt.current=te,te},[$e]),Ae=H.useMemo(()=>R5(D),[D]),{force_scroll_to_bottom:Be,isAutoScrollActive:ot,setAutoScroll:ue}=w0(S,N),_e=H.useCallback(()=>{const te=j.current;if(!te)return;te.style.height="auto";const Ee=Math.min(200,te.scrollHeight);te.style.height=`${Ee}px`},[]);H.useEffect(()=>{if(!(N!=null&&N.id))return;const te=`openfox:draft:${N.id}`,Ee=localStorage.getItem(te);Ee!==null&&c(Ee)},[N==null?void 0:N.id]),H.useEffect(()=>{var te;(te=j.current)==null||te.focus(),_e()},[N==null?void 0:N.id,_e]),H.useEffect(()=>{if(!(N!=null&&N.id))return;const te=`openfox:draft:${N.id}`,Ee=setTimeout(()=>{s?localStorage.setItem(te,s):localStorage.removeItem(te)},500);return()=>clearTimeout(Ee)},[N==null?void 0:N.id,s]),H.useEffect(()=>{_e()},[s,_e]),H.useEffect(()=>{const te=Ee=>{Ee.key==="Escape"&&V&&P(),Ee.key==="ScrollLock"&&ue(!ot)};return window.addEventListener("keydown",te),()=>window.removeEventListener("keydown",te)},[V,P,ot]);const Ne=H.useRef(0);H.useEffect(()=>{const te=Ee=>{if(Ee.key==="Shift"&&!Ee.ctrlKey&&!Ee.metaKey&&!Ee.altKey){const Le=Date.now();Le-Ne.current<300?(Ee.preventDefault(),y(!0),Ne.current=0):Ne.current=Le}};return window.addEventListener("keydown",te),()=>window.removeEventListener("keydown",te)},[]),H.useEffect(()=>{const te=j.current;if(!te)return;const Ee=async Le=>{var Mt;if(document.activeElement!==te)return;const Ve=(Mt=Le.clipboardData)==null?void 0:Mt.items;if(Ve){for(const gn of Array.from(Ve))if(gn.type.startsWith("image/")){Le.preventDefault();const fr=gn.getAsFile();if(!fr)continue;await ah(fr,$i=>f(Br=>[...Br,$i]),g,{filename:"pasted-image"})}}};return te.addEventListener("paste",Ee),()=>te.removeEventListener("paste",Ee)},[]);const Oe=()=>{c(""),f([]),N!=null&&N.id&&localStorage.removeItem(`openfox:draft:${N.id}`)},qe=async te=>{te.preventDefault(),!(!s.trim()&&u.length===0)&&(Be(),W(s,u.length>0?u:void 0),Oe())},Nt=te=>{if((te.ctrlKey||te.metaKey)&&te.code.startsWith("Digit")){const Le=parseInt(te.code.slice(-1),10)-1,Ve=ve[Le];Ve&&(te.preventDefault(),Ce.getState().switchMode(Ve.id));return}if(Ie)switch(te.key){case"Enter":te.preventDefault();const Ee=Te();Ee&&(c(Ee),Ue());return;case"Escape":te.preventDefault(),Ue(),V&&P();return;case"ArrowUp":te.preventDefault(),je();return;case"ArrowDown":te.preventDefault(),me();return}if(te.key==="ArrowUp"&&s.trim()===""&&!Ie){te.preventDefault(),He();return}te.key==="Enter"&&!te.shiftKey&&(te.preventDefault(),qe(te))},Ze=H.useCallback(async te=>{const Ee=te.target.files;if(!(!Ee||Ee.length===0)){g(null);for(const Le of Array.from(Ee))await ah(Le,Ve=>f(Mt=>[...Mt,Ve]),g);T.current&&(T.current.value="")}},[]),Ot=H.useCallback(te=>{te.preventDefault(),te.stopPropagation(),d(!0)},[]),Tt=H.useCallback(te=>{te.preventDefault(),te.stopPropagation(),d(!1)},[]),Yt=H.useCallback(async te=>{te.preventDefault(),te.stopPropagation(),d(!1),g(null);const Ee=te.dataTransfer.files;if(!(!Ee||Ee.length===0))for(const Le of Array.from(Ee))await ah(Le,Ve=>f(Mt=>[...Mt,Ve]),g)},[]),lt=H.useCallback(te=>{f(Ee=>Ee.filter(Le=>Le.id!==te))},[]),Bn=H.useCallback(()=>{var te;(te=T.current)==null||te.click()},[]),Xt=(N==null?void 0:N.mode)==="planner",Us=(N==null?void 0:N.mode)==="builder",pe=((N==null?void 0:N.criteria.length)??0)>0,ye=(N==null?void 0:N.phase)==="done",we=fe.some(te=>te.type==="message"&&te.message.role==="assistant"),We=Xt&&pe&&!V&&we&&!ye,Qe=te=>{const Ee=s.trim()?s:void 0,Le=u.length>0?u:void 0;Xt?F(te,Ee,Le):Us&&Z(Ee,Le,te),Oe()};return o.jsxs(ZC,{criteriaSidebarOpen:i,onCriteriaSidebarToggle:r,messages:$e,children:[$&&o.jsx(g5,{question:$}),o.jsx(e2,{}),x&&o.jsx(a5,{stats:x,onClose:()=>v(null)}),o.jsx(x5,{}),o.jsxs("div",{ref:S,"data-testid":"chat-scroll-container",className:"flex-1 min-w-0 overflow-y-auto relative",children:[o.jsx("div",{className:"pt-4",children:fe.map((te,Ee)=>{if(te.type==="context-divider")return o.jsxs("div",{className:"flex items-center gap-2 feed-item px-2 md:px-4",children:[o.jsx("div",{className:"flex-1 border-t border-border"}),o.jsx("span",{className:"text-[10px] text-text-muted font-medium px-2",children:"Earlier context summarized"}),o.jsx("div",{className:"flex-1 border-t border-border"})]},Ee);if(te.type==="subagent"){const gn=te.messages.some(fr=>fr.isStreaming);return o.jsx("div",{className:"px-2 md:px-4",children:o.jsx(u5,{messages:te.messages,subAgentType:te.subAgentType,subAgentId:te.subAgentId,isStreaming:gn})},Ee)}if(te.type==="criteria-batch")return o.jsx("div",{className:"feed-item px-2 md:px-4",children:o.jsx(_0,{toolCalls:te.toolCalls,criteria:N==null?void 0:N.criteria})},Ee);const Le=te.message;if(Le.role==="assistant")return o.jsx("div",{className:"px-2 md:px-4",children:o.jsx(bf,{message:Le,showStats:Y,showThinking:R,showVerboseToolOutput:z})},Ee);const Ve=!U&&Le.messageKind==="auto-prompt",Mt=!ie&&(Le.messageKind==="workflow-started"||Le.messageKind==="task-completed");return Ve||Mt?null:o.jsx("div",{className:"px-2 md:px-4",children:o.jsx(S0,{message:Le,isLastAssistantMessage:!1,promptContext:Le.role==="user"?Ae[Le.id]:void 0})},Ee)})}),o.jsxs("div",{className:"px-2 md:px-4 pb-4",children:[B&&o.jsx("div",{className:"feed-item bg-red-500/10 border border-red-500/50 rounded p-2",children:o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-red-400 text-sm font-medium",children:B.code}),o.jsx("div",{className:"text-red-300 text-xs mt-0.5",children:B.message})]}),o.jsx(Ja,{onClick:O,className:"text-red-400 hover:text-red-300 p-0.5",size:"sm"})]})}),We&&o.jsx("div",{className:"flex justify-center gap-2 feed-item flex-wrap",children:X.map(te=>{const Ee=te.color??"#3b82f6",Le=parseInt(Ee.slice(1,3),16),Ve=parseInt(Ee.slice(3,5),16),Mt=parseInt(Ee.slice(5,7),16),gn=`rgba(${Le},${Ve},${Mt},0.12)`,fr=`rgba(${Le},${Ve},${Mt},0.22)`,$i=`rgba(${Le},${Ve},${Mt},0.25)`;return o.jsxs("button",{onClick:()=>F(te.id),className:"px-4 py-1.5 rounded text-sm font-medium transition-colors",style:{backgroundColor:gn,color:Ee,border:`1px solid ${$i}`},onMouseEnter:Br=>{Br.currentTarget.style.backgroundColor=fr},onMouseLeave:Br=>{Br.currentTarget.style.backgroundColor=gn},children:["▶ ",te.name]},te.id)})}),V&&o.jsx(v5,{})]})]}),o.jsxs("form",{onSubmit:qe,className:"relative p-2 md:p-4 border-t border-border bg-gradient-to-t from-bg-secondary/50 to-transparent",children:[o.jsxs("button",{type:"button",className:"absolute -top-8 right-2 md:right-4 text-sm text-text-muted hover:text-text-primary z-10 flex items-center gap-1.5",onClick:()=>ue(!ot),children:[o.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${ot?"bg-accent-success":"border border-text-muted"}`}),"live"]}),o.jsx("input",{ref:T,type:"file",accept:".png,.jpg,.jpeg,.gif",onChange:Ze,className:"hidden",multiple:!0}),p&&o.jsx("div",{className:"mb-2 p-2 bg-red-500/10 border border-red-500/50 rounded text-red-300 text-sm",children:p}),u.length>0&&o.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:u.map(te=>o.jsx(b5,{attachment:te,onRemove:lt},te.id))}),Ie&&o.jsx(y5,{history:be,selectedIndex:Re,onSelect:te=>{c(te),Ue()},onEscape:Ue,onNavigate:te=>{te==="up"?je():me()}}),I.length>0&&o.jsx("div",{className:"mb-2 flex flex-wrap gap-1.5",children:I.map(te=>o.jsxs("div",{className:`inline-flex items-center gap-1.5 px-2 py-1 rounded text-xs ${te.mode==="asap"?"bg-amber-500/15 text-amber-300 border border-amber-500/30":"bg-blue-500/15 text-blue-300 border border-blue-500/30"}`,children:[o.jsxs("span",{className:"font-medium",children:[te.mode==="asap"?"ASAP":"Queue",":"]}),o.jsx("span",{className:"truncate max-w-[200px]",children:te.content}),o.jsx(Ja,{onClick:()=>G(te.queueId),size:"sm"})]},te.queueId))}),o.jsxs("div",{className:`flex items-end gap-3 p-3 rounded border transition-colors ${l?"border-accent-primary/50 bg-accent-primary/10":"border-border bg-bg-tertiary/50"}`,onDragOver:Ot,onDragLeave:Tt,onDrop:Yt,children:[o.jsx("button",{type:"button",onClick:Bn,className:"p-3 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"Attach image file",children:o.jsx(aw,{})}),o.jsx("textarea",{ref:j,value:s,onChange:te=>{c(te.target.value),Ie&&Ue()},onKeyDown:Nt,placeholder:"What would you like to build?",className:"flex-1 bg-transparent text-sm placeholder:text-text-muted resize-none overflow-y-auto focus:outline-none",style:{minHeight:"24px",maxHeight:"200px"},spellCheck:!1}),o.jsxs("div",{className:"flex flex-col items-end gap-1",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx(H5,{onSendCommand:(te,Ee,Le,Ve)=>{var gn;Ee&&(N==null?void 0:N.mode)!==Ee&&Ce.getState().switchMode(Ee);const Mt=Le&&Le.trim()?`${Le.trim()}
|
|
149
|
+
`,children:[o.jsxs("div",{className:"text-xs text-text-muted font-mono",children:[p.formattedTimestamp,p.sessionName&&o.jsxs(o.Fragment,{children:[" | ",o.jsx("span",{className:"text-accent-primary font-medium",children:p.sessionName})]})]}),o.jsx("div",{className:"text-sm text-text-primary mt-1",children:p.trimmedContent})]},p.id))})}const on=Yn((e,r)=>({defaults:[],userItems:[],loading:!1,fetchCommands:async()=>{await Lh("/api/commands",e)},fetchCommand:async i=>{try{const s=await ke(`/api/commands/${i}`);return s.ok?await s.json():null}catch{return null}},fetchDefaultContent:async i=>{try{const s=await ke(`/api/commands/defaults/${i}`);return s.ok?await s.json():null}catch{return null}},createCommand:async i=>{const s=await di("POST","/api/commands",i);return s.success&&await r().fetchCommands(),s},updateCommand:async(i,s)=>{const c=await di("PUT",`/api/commands/${i}`,s);return c.success&&await r().fetchCommands(),c},deleteCommand:async i=>{try{const s=await ke(`/api/commands/${i}`,{method:"DELETE"}),c=await s.json();return s.ok?(e(u=>({userItems:u.userItems.filter(f=>f.id!==i)})),{success:!0}):{success:!1,error:c.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateCommand:async i=>{try{const s=await ke(`/api/commands/${i}/duplicate`,{method:"POST"}),c=await s.json();return s.ok?(await r().fetchCommands(),{success:!0}):{success:!1,error:c.error??"Failed to duplicate"}}catch{return{success:!1,error:"Network error"}}}})),_5={maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576};async function S5(e,r={}){const i={..._5,...r};if(!e.type.startsWith("image/"))throw new Error("File is not an image");if(!["image/png","image/jpeg","image/gif"].includes(e.type))throw new Error(`Unsupported image format: ${e.type}. Only PNG, JPG, and GIF are supported.`);if(e.size<=i.maxSizeBytes){const c=await e.arrayBuffer(),u=T5(c),f=`data:${e.type};base64,${u}`,l=await C0(f);return{dataUrl:f,mimeType:e.type,size:e.size,width:l.width,height:l.height}}return await w5(e,i)}async function w5(e,r){const i=await k5(e),s=await C0(i),{width:c,height:u}=C5(s.width,s.height,r.maxWidth,r.maxHeight),f=E5();f.width=c,f.height=u;const l=f.getContext("2d");if(!l)throw new Error("Failed to get canvas context");l.imageSmoothingEnabled=!0,l.imageSmoothingQuality="high",l.drawImage(s,0,0,c,u);let d=r.quality,p;do{if(p=f.toDataURL(e.type.startsWith("image/gif")?"image/png":e.type,d),ub(p)<=r.maxSizeBytes||d<=.3)break;d-=.1}while(!0);const g=ub(p);return{dataUrl:p,mimeType:e.type.startsWith("image/gif")?"image/png":e.type,size:g,width:c,height:u}}function C5(e,r,i,s){const c=e/r;return e>r&&e>i?{width:i,height:Math.round(i/c)}:r>e&&r>s?{width:Math.round(s*c),height:s}:{width:e,height:r}}function k5(e){return new Promise((r,i)=>{const s=N5(),c=new s;c.onload=()=>r(c.result),c.onerror=()=>i(new Error("Failed to read file")),c.readAsDataURL(e)})}function C0(e){return new Promise((r,i)=>{const s=j5(),c=new s;c.onload=()=>r(c),c.onerror=()=>i(new Error("Failed to load image")),c.src=e})}function E5(){var r;const e=yf();if(!((r=e.document)!=null&&r.createElement))throw new Error("Image compression requires browser canvas APIs");return e.document.createElement("canvas")}function j5(){const e=yf();if(!e.Image)throw new Error("Image compression requires browser image APIs");return e.Image}function N5(){const e=yf();if(!e.FileReader)throw new Error("Image compression requires browser file APIs");return e.FileReader}function yf(){return globalThis}function T5(e){const r=new Uint8Array(e);let i="";for(let s=0;s<r.byteLength;s++){const c=r[s];c!==void 0&&(i+=String.fromCharCode(c))}return btoa(i)}function ub(e){const i=e.split(",")[1];return i?Math.round(i.length*3/4):0}function A5(e){return["image/png","image/jpeg","image/gif"].includes(e.type)}function D5(e,r=50*1024*1024){return e.size>r?{valid:!1,error:`Image file is too large (${db(e.size)}). Maximum size is ${db(r)}.`}:{valid:!0}}function db(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}async function ah(e,r,i,s={}){const{maxSizeBytes:c=50*1024*1024,filename:u}=s;if(!A5(e)){i(`Unsupported file type: ${e.type}. Only PNG, JPG, and GIF are supported.`);return}const f=D5(e,c);if(!f.valid){i(f.error??"Image file is too large");return}try{const l=await S5(e,{maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576}),d={id:Eb(),filename:u??e.name,mimeType:l.mimeType,size:l.size,data:l.dataUrl};r(d)}catch(l){const d=l instanceof Error?l.message??"Failed to process image":"Failed to process image";i(d)}}function R5(e){const r={};let i=null;for(const s of e){if(s.role==="user"&&!s.isSystemGenerated){i=s.id;continue}s.role==="assistant"&&s.promptContext&&i&&r[i]===void 0&&(r[i]=s.promptContext)}return r}function oh(e){return{contextWindow:e.contextWindow,temperature:e.temperature??null,topP:e.topP??null,topK:e.topK??null,maxTokens:e.maxTokens??null}}function L5({label:e,children:r}){return o.jsxs("div",{className:"space-y-3",children:[o.jsx("h4",{className:"text-sm font-medium text-text-secondary border-b border-border/50 pb-1",children:e}),r]})}function qa({label:e,value:r,onChange:i,min:s,max:c,step:u=1,helpText:f,defaultValue:l}){const[d,p]=H.useState((r==null?void 0:r.toString())??""),[g,m]=H.useState(r===null);H.useEffect(()=>{p((r==null?void 0:r.toString())??""),m(r===null)},[r]);const b=k=>{if(p(k),k==="")i(null);else{const C=parseFloat(k);isNaN(C)||i(C)}},_=()=>{g?(m(!1),l!==void 0&&(p(l.toString()),i(l))):(m(!0),i(null))};return o.jsxs("div",{children:[o.jsxs("label",{className:"flex items-center gap-2 text-sm font-medium text-text-secondary mb-1",children:[e,o.jsx("button",{type:"button",onClick:_,className:`text-xs px-1.5 py-0.5 rounded border ${g?"border-accent-primary/50 bg-accent-primary/10 text-accent-primary":"border-border text-text-muted hover:text-text-secondary"}`,title:g?"Click to set a custom value":"Click to use default",children:g?"default":"custom"})]}),o.jsx("input",{type:"number",min:s,max:c,step:u,value:d,readOnly:g,onChange:k=>b(k.target.value),onClick:()=>g&&_(),placeholder:g?"Using profile default (click to edit)":"",className:`w-full bg-bg-tertiary border border-border rounded px-3 py-2 text-text-primary focus:outline-none focus:border-accent-primary ${g?"opacity-50 cursor-pointer":""}`}),f&&o.jsx("p",{className:"text-xs text-text-muted mt-1",children:f})]})}function O5({isOpen:e,onClose:r,providerId:i,model:s}){const[c,u]=H.useState(()=>oh(s)),[f,l]=H.useState(!1),d=At(m=>m.updateModelSettings);H.useEffect(()=>{u(oh(s))},[s]);const p=async()=>{if(c.contextWindow<1024||c.contextWindow>1e7)return;l(!0);const m=c.temperature!==(s.temperature??null)||c.topP!==(s.topP??null)||c.topK!==(s.topK??null)||c.maxTokens!==(s.maxTokens??null);await d(i,s.id,{contextWindow:c.contextWindow,...m&&{temperature:c.temperature,topP:c.topP,topK:c.topK,maxTokens:c.maxTokens}}),l(!1),r()},g=()=>{u(oh(s)),r()};return e?o.jsx(jt,{isOpen:e,onClose:r,title:"Model Properties",size:"sm",footer:o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(it,{variant:"secondary",onClick:g,disabled:f,children:"Cancel"}),o.jsx(it,{variant:"primary",onClick:p,disabled:f||c.contextWindow<1024||c.contextWindow>1e7,children:f?"Saving...":"Save"})]}),children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-text-secondary mb-1",children:"Model Name"}),o.jsx("p",{className:"text-text-primary bg-bg-tertiary px-3 py-2 rounded font-mono text-sm break-all",children:s.id})]}),o.jsx(qa,{label:"Context Window",value:c.contextWindow,onChange:m=>m!==null&&u(b=>({...b,contextWindow:m})),min:1024,max:1e7,helpText:"Range: 1,024 - 10,000,000 tokens"}),o.jsxs(L5,{label:"Sampling Parameters",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(qa,{label:"Temperature",value:c.temperature,onChange:m=>u(b=>({...b,temperature:m})),min:0,max:2,step:.1,helpText:"0.0 - 2.0",defaultValue:1}),o.jsx(qa,{label:"Top P",value:c.topP,onChange:m=>u(b=>({...b,topP:m})),min:0,max:1,step:.05,helpText:"0.0 - 1.0",defaultValue:1})]}),o.jsx(qa,{label:"Top K",value:c.topK,onChange:m=>u(b=>({...b,topK:m})),min:1,max:200,helpText:"1 - 200 (leave as default if not supported)"})]}),o.jsx(qa,{label:"Max Tokens",value:c.maxTokens,onChange:m=>u(b=>({...b,maxTokens:m})),min:256,max:32e3,helpText:"Maximum tokens to generate per response"}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-text-secondary mb-1",children:"Source"}),o.jsxs("p",{className:"text-text-primary bg-bg-tertiary px-3 py-2 rounded text-sm",children:[s.source==="backend"&&"Auto-detected from backend",s.source==="user"&&"Manually set",s.source==="default"&&"Default value"]})]})]})}):null}function M5(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function I5(){var F;const[,e]=dr(),r=Ce(P=>P.currentSession),i=Ce(P=>P.setSessionProvider),[s,c]=H.useState(!1),[u,f]=H.useState([]),[l,d]=H.useState(null),p=H.useRef(null),[g,m]=H.useState(null),b=H.useRef(new Set),_=At(P=>P.providers),k=At(P=>P.activeProviderId),C=At(P=>P.model);At(P=>P.backend);const y=At(P=>P.llmStatus),x=At(P=>P.activating),v=At(P=>P.activateProvider),S=At(P=>P.refreshModel),j=At(P=>P.refreshProviderModels);H.useEffect(()=>{function P(Z){p.current&&!p.current.contains(Z.target)&&(c(!1),f([]),b.current=new Set)}return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[]),H.useEffect(()=>{if(s){const P=_.map(Z=>Z.id);f(P),P.forEach(Z=>{b.current.has(Z)||(b.current.add(Z),D(Z))})}},[s,_]),_.find(P=>P.id===k);const T=y==="disconnected",N=C?((F=C.split("/").pop())==null?void 0:F.replace(/-/g," "))??C:"detecting...",D=async P=>{d(P);try{await j(P)}catch{}finally{d(null)}},A=P=>{u.includes(P.id)?f(u.filter(Z=>Z!==P.id)):(f([...u,P.id]),D(P.id))},M=async P=>{if(P.id===k){A(P);return}r?(i(P.id,void 0),At.getState().syncFromSession(P.id,""),c(!1),f([])):await v(P.id)&&(c(!1),f([]))},B=P=>{A(P)},$=async(P,Z)=>{P.stopPropagation(),b.current.delete(Z),await j(Z),await D(Z)},V=(P,Z)=>{m({providerId:P,model:Z})},W=()=>{m(null)},O=async(P,Z)=>{if(console.log("[ProviderSelector.handleModelClick] providerId:",P,"model:",Z),r){console.log("[ProviderSelector.handleModelClick] Calling setSessionProvider"),i(P,Z),At.getState().syncFromSession(P,Z),f([]),c(!1);return}d("activating");try{(await ke(`/api/providers/${P}/activate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:Z})})).ok&&(await At.getState().fetchConfig(),f([]),c(!1))}catch{}finally{d(null)}};return _.length===0?o.jsxs("button",{type:"button",onClick:()=>S(),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors group",title:T?"LLM server is offline. Click to retry.":C??"Click to refresh model",children:[T?o.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"LLM offline"}):o.jsx("span",{className:"text-sm text-accent-primary",children:N}),o.jsx("span",{className:"text-text-muted opacity-0 group-hover:opacity-100 transition-opacity",children:"↻"})]}):o.jsxs("div",{className:"relative",ref:p,children:[o.jsxs("button",{type:"button",onClick:()=>c(!s),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors group",title:"Click to switch provider or model",children:[T?o.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"offline"}):o.jsx("span",{className:"text-sm text-accent-primary",children:N}),o.jsx(ur,{className:"w-3 h-3 text-text-muted transition-transform",rotate:s?180:0})]}),s&&o.jsxs("div",{className:"absolute bottom-full right-0 mb-1 w-72 bg-bg-secondary border border-border rounded-lg shadow-lg z-50 overflow-hidden",children:[o.jsx("div",{className:"py-1",children:_.map(P=>{var Z;return o.jsxs("div",{children:[o.jsxs("div",{className:`px-3 py-2 flex items-center justify-between ${P.id===k?"bg-bg-tertiary":"hover:bg-bg-tertiary"} ${x?"opacity-50 cursor-wait":"cursor-pointer"}`,children:[o.jsxs("div",{onClick:()=>!x&&M(P),className:"flex flex-col min-w-0 flex-1 cursor-pointer",children:[o.jsx("span",{className:`text-sm font-medium truncate ${P.id===k?"text-accent-primary":"text-text-primary"}`,children:P.name}),o.jsx("span",{className:"text-xs text-text-muted truncate",children:P.backend!=="auto"&&z1(P.backend)})]}),o.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[P.id===k?o.jsx("span",{className:"text-accent-success",title:"Active",children:o.jsx(Mr,{className:"w-4 h-4"})}):o.jsx("span",{className:"w-4"}),o.jsx("button",{type:"button",onClick:G=>{G.stopPropagation(),$(G,P.id)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Refresh models",children:o.jsx(yw,{className:`w-4 h-4 ${l===P.id?"animate-spin":""} ${P.id===k?"text-accent-primary":"text-text-muted"}`})}),o.jsx("button",{type:"button",onClick:G=>{G.stopPropagation(),B(P)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Show models",children:o.jsx(ur,{className:`w-4 h-4 transition-transform ${u.includes(P.id)?"rotate-180":""} ${P.id===k?"text-accent-primary":"text-text-muted"}`})})]})]}),u.includes(P.id)&&o.jsx("div",{className:"bg-bg-primary border-t border-border",children:l===P.id?o.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"Loading models..."}):(Z=P.models)!=null&&Z.length?P.models.map(G=>{var I;return o.jsxs("button",{type:"button",onClick:()=>O(P.id,G.id),disabled:l==="activating",className:`w-full px-4 py-1.5 text-left hover:bg-bg-tertiary transition-colors text-sm flex items-center justify-between group ${l==="activating"?"opacity-50 cursor-wait":""} ${C===G.id?"text-accent-primary":"text-text-secondary"}`,children:[o.jsx("span",{className:"truncate flex-1",children:((I=G.id.split("/").pop())==null?void 0:I.replace(/-/g," "))??G.id}),o.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[o.jsx("span",{className:"text-xs text-text-muted",children:M5(G.contextWindow)}),o.jsx("button",{type:"button",onClick:R=>{R.stopPropagation(),V(P.id,G)},className:"opacity-0 group-hover:opacity-100 p-0.5 hover:bg-bg-tertiary rounded transition-opacity",title:"Edit model context",children:o.jsx(uw,{className:"w-3 h-3 text-text-muted"})})]}),C===G.id&&o.jsx("span",{className:"text-accent-success flex-shrink-0 ml-1",children:o.jsx(Mr,{className:"w-3.5 h-3.5"})})]},G.id)}):o.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"No models available"})})]},P.id)})}),o.jsx("div",{className:"border-t border-border px-3 py-2",children:o.jsx("button",{onClick:()=>e("/onboarding"),className:"text-xs text-accent-primary hover:underline",children:"Manage providers"})})]}),g&&o.jsx(O5,{isOpen:!0,onClose:W,providerId:g.providerId,model:g.model})]})}function B5(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function z5({onClick:e}){return o.jsx("button",{type:"button",onClick:e,className:"p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",title:"View",children:o.jsx(ec,{})})}function k0({isOpen:e,onClose:r,initialEditId:i}){const s=on(me=>me.defaults),c=on(me=>me.userItems),u=on(me=>me.loading),f=on(me=>me.fetchCommands),l=on(me=>me.fetchCommand),d=on(me=>me.fetchDefaultContent),p=on(me=>me.createCommand),g=on(me=>me.updateCommand),m=on(me=>me.deleteCommand),[b,_]=H.useState(null),[k,C]=H.useState(null),{view:y,editingId:x,formError:v,saving:S,formData:j,setView:T,setEditingId:N,setFormError:D,setFormData:A,setSaving:M}=Wb(),{requestDelete:B,clearConfirm:$,isConfirming:V}=Oh(),W=H.useRef(!1),O=kt(me=>me.defaults),F=kt(me=>me.userItems),P=kt(me=>me.fetchAgents),G=[...O,...F].filter(me=>!me.subagent),I=H.useRef(f),R=H.useRef(P),z=H.useRef(l),Y=H.useRef(d),U=H.useRef(i),ie=H.useRef(T),Q=H.useRef(N),ee=H.useRef(D),X=H.useRef($);H.useEffect(()=>{I.current=f,R.current=P,z.current=l,Y.current=d,U.current=i,ie.current=T,Q.current=N,ee.current=D,X.current=$}),H.useEffect(()=>{if(e)if(I.current(),R.current(),W.current||(X.current(),W.current=!0),U.current){const me=s.some(Te=>Te.id===U.current);ie.current("edit"),Q.current(U.current),ee.current(""),me?Y.current(U.current).then(Te=>{Te&&A({name:Te.metadata.name+" (copy)",id:`${U.current}-copy-${Date.now()}`,prompt:Te.prompt,agentMode:Te.metadata.agentMode??"",isDefault:!0})}):z.current(U.current).then(Te=>{Te&&A({name:Te.metadata.name,id:Te.metadata.id,prompt:Te.prompt,agentMode:Te.metadata.agentMode??"",isDefault:!1})})}else ie.current("list"),Q.current(null);else W.current=!1},[e]);const q=async me=>{_(me);const Te=await d(me);C((Te==null?void 0:Te.prompt)??null)},oe=async me=>{if(s.some($e=>$e.id===me)){const $e=await d(me);$e&&(N(null),A({name:`${$e.metadata.name} (copy)`,id:`${me}-copy-${Date.now()}`,prompt:$e.prompt,agentMode:$e.metadata.agentMode??"",isDefault:!0}),D(""),T("edit"))}else{const $e=await l(me);$e&&(N(null),A({name:`${$e.metadata.name} (copy)`,id:`${me}-copy-${Date.now()}`,prompt:$e.prompt,agentMode:$e.metadata.agentMode??"",isDefault:!1}),D(""),T("edit"))}},re=()=>{A({name:"",id:"",prompt:"",agentMode:"",isDefault:!1}),N(null),T("edit")},ve=async me=>{const Te=await l(me);Te&&(N(me),A({name:Te.metadata.name,id:Te.metadata.id,prompt:Te.prompt,agentMode:Te.metadata.agentMode??"",isDefault:!1}),D(""),T("edit"))},be=async me=>{await m(me),$()},Re=async()=>{const me=x??j.id;if(!me||!j.name||!j.prompt){D("Name and message are required.");return}M(!0),D("");const Te={metadata:{id:me,name:j.name,...j.agentMode?{agentMode:j.agentMode}:{}},prompt:j.prompt},$e=x?await g(x,Te):await p(Te);if(M(!1),!$e.success){D($e.error??"Failed to save command.");return}i?r():T("list")},Ie=()=>{i?r():(T("list"),_(null),C(null))},He=me=>{A(Te=>({...Te,name:me})),(!x||j.isDefault)&&A(Te=>({...Te,id:B5(me)}))},Ue=()=>{_(null),C(null),T("list")},je=()=>{b&&(_(null),T("edit"),N(b),d(b).then(me=>{me&&A({name:`${me.metadata.name} (copy)`,id:`${b}-copy-${Date.now()}`,prompt:me.prompt,agentMode:me.metadata.agentMode??"",isDefault:!0})}))};if(b){const me=s.find(Te=>Te.id===b);return o.jsx(jt,{isOpen:e,onClose:Ue,title:`Default: ${(me==null?void 0:me.name)??b}`,size:"xl",children:o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"space-y-3 mb-3",children:[o.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-muted",children:[o.jsx("span",{className:"px-1.5 py-0.5 rounded bg-bg-tertiary text-text-secondary",children:"Built-in"}),o.jsx("span",{className:"font-mono",children:b})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Name"}),o.jsx("div",{className:"px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm",children:me==null?void 0:me.name})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Agent Mode"}),o.jsx("div",{className:"px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm text-text-muted",children:(me==null?void 0:me.agentMode)||"None"})]})]}),o.jsxs("div",{className:"flex-1 min-h-[120px] border-t border-border pt-3 flex flex-col",children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Message"}),o.jsx("textarea",{value:k??"",readOnly:!0,placeholder:"...",className:"flex-1 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-none opacity-60"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 mt-3 border-t border-border flex-shrink-0",children:[o.jsx(it,{variant:"secondary",onClick:Ue,children:"Close"}),o.jsx(it,{variant:"primary",onClick:je,children:"Duplicate & Customize"})]})]})})}return y==="edit"?o.jsx(jt,{isOpen:e,onClose:Ie,title:x?"Edit Command":"New Command",size:"xl",children:o.jsxs("div",{className:"flex flex-col h-full",children:[v&&o.jsx(Bh,{message:v}),o.jsxs("div",{className:"space-y-3 mb-3",children:[o.jsx(qb,{name:j.name,id:j.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Command",idPlaceholder:"my-command",readOnlyId:!!x&&!j.isDefault,onNameChange:He,onIdChange:me=>A(Te=>({...Te,id:me}))}),o.jsxs("div",{children:[o.jsxs("label",{className:"block text-xs text-text-secondary mb-1",children:["Agent Mode ",o.jsx("span",{className:"text-text-muted",children:"(optional)"})]}),o.jsxs("select",{value:j.agentMode,onChange:me=>A(Te=>({...Te,agentMode:me.target.value})),className:"w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",children:[o.jsx("option",{value:"",children:"None (keep current mode)"}),G.map(me=>o.jsx("option",{value:me.id,children:me.name},me.id))]})]})]}),o.jsxs("div",{className:"flex-1 min-h-[120px] border-t border-border pt-3 flex flex-col",children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Message"}),o.jsx("textarea",{value:j.prompt,onChange:me=>A(Te=>({...Te,prompt:me.target.value})),placeholder:"The message that will be sent when this command is triggered...",className:"h-80 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 mt-3 border-t border-border flex-shrink-0",children:[o.jsx(it,{variant:"secondary",onClick:Ie,children:"Cancel"}),o.jsx(it,{variant:"primary",onClick:Re,disabled:S||!j.name||!j.prompt,children:S?"Saving...":"Save"})]})]})}):o.jsxs(jt,{isOpen:e,onClose:r,title:"Commands",size:"lg",children:[o.jsx(Fb,{description:"Commands are pre-defined messages you can send with a single click.",onNew:re}),o.jsxs($b,{loading:u,hasItems:s.length>0||c.length>0,loadingLabel:"Loading commands...",emptyLabel:"No commands created yet.",children:[s.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Built-in"}),o.jsx("div",{className:"space-y-2",children:s.map(me=>o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsx("div",{className:"min-w-0 flex-1 mr-3",children:o.jsx("span",{className:"text-text-primary text-sm font-medium",children:me.name})}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx(z5,{onClick:()=>q(me.id)}),o.jsx(Qa,{onClick:()=>oe(me.id)})]})]},me.id))})]}),c.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Custom"}),o.jsx("div",{className:"space-y-2",children:c.map(me=>o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsx("div",{className:"min-w-0 flex-1 mr-3",children:o.jsx("div",{className:"flex items-center gap-2",children:o.jsx("span",{className:"text-text-primary text-sm font-medium",children:me.name})})}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx(Hs,{onClick:()=>ve(me.id)}),o.jsx(Qa,{onClick:()=>oe(me.id)}),V(me.id,"delete")?o.jsx(Mh,{onConfirm:()=>be(me.id),onCancel:$}):o.jsx(Ih,{onClick:()=>B(me.id)})]})]},me.id))})]})]})]})}function E0({items:e,isOpen:r,onOpen:i,onClose:s,filterFn:c}){const[u,f]=H.useState(""),[l,d]=H.useState(0),p=H.useRef(null),g=H.useRef(null);H.useEffect(()=>{r&&(f(""),d(0),requestAnimationFrame(()=>{var y;return(y=g.current)==null?void 0:y.focus()}))},[r]),H.useEffect(()=>{if(!r)return;const y=x=>{p.current&&!p.current.contains(x.target)&&s()};return document.addEventListener("mousedown",y),()=>document.removeEventListener("mousedown",y)},[r,s]);const m=H.useCallback(()=>{r?s():i()},[r,i,s]),b=H.useCallback(y=>{f(y),d(0)},[]),_=H.useCallback(y=>{const x=e.filter(v=>c(v,u));switch(y.key){case"ArrowDown":y.preventDefault(),d(v=>Math.min(v+1,x.length-1));break;case"ArrowUp":y.preventDefault(),d(v=>Math.max(v-1,0));break;case"Enter":y.preventDefault();break;case"Escape":y.preventDefault(),s();break}},[e,u,c,s]),k=H.useCallback(()=>{d(0)},[]),C=e.filter(y=>c(y,u));return{isOpen:r,search:u,selectedIndex:l,filtered:C,containerRef:p,searchRef:g,handleToggle:m,handleSearchChange:b,handleKeyDown:_,setSelectedIndex:d,resetSelection:k}}function j0({label:e,isOpen:r,onClick:i,className:s=""}){return o.jsxs("button",{type:"button",onClick:i,className:`flex items-center gap-1 text-sm text-text-muted hover:text-text-primary transition-colors ${s}`,children:[e,o.jsx(ur,{className:"w-3 h-3 transition-transform",rotate:r?180:0})]})}function N0({value:e,onChange:r,onKeyDown:i,ref:s,placeholder:c}){return o.jsx("div",{className:"p-2 border-b border-border",children:o.jsx("input",{ref:s,value:e,onChange:u=>r(u.target.value),onKeyDown:i,placeholder:c,className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary"})})}function T0({children:e,maxHeight:r="max-h-64"}){return o.jsx("div",{className:`overflow-y-auto ${r} p-1`,children:e})}function A0({hasItems:e,message:r}){return o.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:e?"No matches":r})}function D0({label:e,onClick:r}){return o.jsx("div",{className:"border-t border-border p-1",children:o.jsx("button",{type:"button",onClick:r,className:"w-full text-left px-3 py-1.5 rounded text-sm text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors",children:e})})}function H5({onSendCommand:e,onOpenManager:r,textareaContent:i,attachments:s}){const[c,u]=H.useState(!1),[f,l]=H.useState(null),d=on(D=>D.defaults),p=on(D=>D.userItems),g=on(D=>D.fetchCommands),m=[...d,...p],{isOpen:b,search:_,selectedIndex:k,filtered:C,containerRef:y,searchRef:x,handleToggle:v,handleSearchChange:S,handleKeyDown:j}=E0({items:m,isOpen:c,onOpen:()=>u(!0),onClose:()=>u(!1),filterFn:(D,A)=>!A||D.name.toLowerCase().includes(A.toLowerCase())});H.useEffect(()=>{c&&g()},[c,g]);const T=async D=>{const A=await on.getState().fetchCommand(D);A&&e(A.prompt,A.metadata.agentMode,i,s),u(!1)},N=()=>{u(!1),r()};return o.jsxs("div",{ref:y,className:"relative",children:[o.jsx(j0,{label:"Commands",isOpen:b,onClick:v}),b&&o.jsxs("div",{className:"absolute bottom-full right-0 mb-1 w-72 bg-bg-secondary border border-border rounded-lg shadow-xl z-50",onKeyDown:j,children:[o.jsx(N0,{value:_,onChange:S,onKeyDown:j,ref:x,placeholder:"Search commands..."}),o.jsx(T0,{children:C.length===0?o.jsx(A0,{hasItems:m.length>0,message:"No commands yet"}):C.map((D,A)=>o.jsxs("div",{className:`flex items-center gap-1 px-3 py-2 rounded transition-colors group ${A===k?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[o.jsx("button",{type:"button",onClick:()=>T(D.id),className:"flex-1 text-left",children:o.jsx("div",{className:"text-sm text-text-primary font-medium",children:D.name})}),o.jsx(Hs,{className:"opacity-0 group-hover:opacity-100",onClick:M=>{M.stopPropagation(),u(!1),l(D.id)}})]},D.id))}),o.jsx(D0,{label:"Manage Commands...",onClick:N})]}),o.jsx(k0,{isOpen:!!f,onClose:()=>l(null),initialEditId:f})]})}function P5(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function F5(e){let r=1;for(;e.some(i=>i.id===`s${r}`);)r++;return`s${r}`}const U5=[{value:"agent",label:"Agent"},{value:"sub_agent",label:"Sub-Agent"},{value:"shell",label:"Shell"}],R0={all_criteria_passed:"All passed",all_criteria_completed_or_passed:"All completed",any_criteria_blocked:"Blocked",has_pending_criteria:"Pending/Failed",step_result:"Result",always:"Always"},L0=[{value:"all_criteria_passed",label:"All criteria passed"},{value:"all_criteria_completed_or_passed",label:"All criteria completed or passed"},{value:"any_criteria_blocked",label:"Any criteria blocked (retry limit)"},{value:"has_pending_criteria",label:"Has pending or failed criteria"},{value:"step_result",label:"Step result is..."},{value:"always",label:"Always (fallback)"}],Ri=150,Or=54,Ds=80,Ln=30,Rs=70,hb=100,Li=50,Il=50,fb=4;function _f(e,r){if(e.type==="agent"){const i=r.find(s=>s.id===e.toolMode);return{name:(i==null?void 0:i.name)??(e.toolMode||"Agent"),color:(i==null?void 0:i.color)||"#3b82f6"}}if(e.type==="sub_agent"){const i=r.find(s=>s.id===e.subAgentType);return{name:(i==null?void 0:i.name)??(e.subAgentType||"Sub-Agent"),color:(i==null?void 0:i.color)||"#a855f7"}}return{name:"Shell",color:"#22c55e"}}function $5(e,r,i,s){const c=Il+Li+Ri+hb+Ri+Li+Il,u=c/2,f=Il+Li+Ri/2,l=Il+Li+Ri+hb+Ri/2,d=[],p=[],g=new Map,m=e.filter(O=>O.type==="agent"||O.type==="shell"),b=e.filter(O=>O.type==="sub_agent"),_=b.length>0,k=_?f:u,C=m.length>0?l:u,y=Li+Ln/2;if(d.push({id:"$start",type:"terminal",label:"Start",cx:k,cy:y,w:Ds,h:Ln}),g.set("$start",{cx:k,cy:y,w:Ds,h:Ln}),e.length===0){const O=y+Ln/2+Rs*2+Ln/2;return d.push({id:"$done",type:"terminal",label:"Done",cx:k,cy:O,w:Ds,h:Ln}),g.set("$done",{cx:k,cy:O,w:Ds,h:Ln}),{nodes:d,edges:p,width:c,height:O+Ln/2+Li,posMap:g}}const x=y+Ln/2+Rs,v=(O,F)=>{O.forEach((P,Z)=>{const G=x+Z*(Or+Rs)+Or/2,{name:I,color:R}=_f(P,s);d.push({id:P.id,type:"step",label:I,color:R,cx:F,cy:G,w:Ri,h:Or}),g.set(P.id,{cx:F,cy:G,w:Ri,h:Or})})};v(m,k),v(b,C);const S=m.length>0?x+(m.length-1)*(Or+Rs)+Or/2:y,j=_?x+(b.length-1)*(Or+Rs)+Or/2:y,T=Math.max(S,j)+Or/2+Rs+Ln/2;d.push({id:"$done",type:"terminal",label:"Done",cx:k,cy:T,w:Ds,h:Ln}),g.set("$done",{cx:k,cy:T,w:Ds,h:Ln});const N=[];r&&g.has(r)&&N.push({from:"$start",to:r,label:i,edgeKey:"start",direction:"down",backEdgeIndex:0});let D=0;for(const O of e)O.transitions.forEach((F,P)=>{if(!F.goto||!g.has(F.goto))return;const Z=g.get(O.id),G=g.get(F.goto),I=F.when.type==="step_result"?`${F.when.result}`:R0[F.when.type]??F.when.type,R=O.id===F.goto;let z;R?z="back":G.cy>Z.cy+1?z="down":G.cy<Z.cy-1?z="back":z="same",N.push({from:O.id,to:F.goto,label:I,edgeKey:`${O.id}:${P}`,direction:z,backEdgeIndex:z==="back"?D++:0})});const A=new Map,M=new Map,B=new Map,$=new Map;for(const O of N)O.direction==="down"&&(A.set(O.from,(A.get(O.from)??0)+1),M.set(O.to,(M.get(O.to)??0)+1));const V=new Map,W=new Map;for(const O of N){if(O.direction!=="same")continue;const F=[O.from,O.to].sort().join("|");V.set(F,(V.get(F)??0)+1)}for(const O of N){if(O.direction==="back"||O.direction==="same"){let z=0;if(O.direction==="same"){const Y=[O.from,O.to].sort().join("|");z=W.get(Y)??0,W.set(Y,z+1)}p.push({...O,fromPort:0,toPort:0,sameEdgeIndex:z});continue}const F=A.get(O.from)??1,P=M.get(O.to)??1,Z=B.get(O.from)??0,G=$.get(O.to)??0;B.set(O.from,Z+1),$.set(O.to,G+1);const I=F===1?0:-.6+1.2*Z/(F-1),R=P===1?0:-.6+1.2*G/(P-1);p.push({...O,fromPort:I,toPort:R,sameEdgeIndex:0})}return{nodes:d,edges:p,width:c,height:T+Ln/2+Li,posMap:g}}function q5({steps:e,entryStep:r,selectedNodeId:i,selectedEdgeKey:s,startConditionLabel:c,agentTypes:u,isReadOnly:f,onSelectNode:l,onSelectEdge:d,onRemoveStep:p,onCreateTransition:g,onReconnectTo:m,onReconnectFrom:b,onDeleteTransition:_}){const k=H.useRef(null),C=H.useRef(!1),[y,x]=H.useState(null),[v,S]=H.useState(null),[j,T]=H.useState(null),{nodes:N,edges:D,width:A,height:M,posMap:B}=H.useMemo(()=>$5(e,r,c,u),[e,r,c,u]),$=H.useCallback(Q=>{var re;const ee=k.current;if(!ee)return{x:0,y:0};const X=ee.createSVGPoint();X.x=Q.clientX,X.y=Q.clientY;const q=(re=ee.getScreenCTM())==null?void 0:re.inverse();if(!q)return{x:0,y:0};const oe=X.matrixTransform(q);return{x:oe.x,y:oe.y}},[]),V=H.useCallback(Q=>!Q||!v||Q==="$start"?!1:v.type==="reconnect-from"?Q!=="$done":!0,[v]),W=H.useCallback((Q,ee)=>{if(f)return;Q.stopPropagation(),Q.preventDefault();const X=$(Q);S({type:"new",fromNodeId:ee,mouseX:X.x,mouseY:X.y})},[$,f]),O=H.useCallback((Q,ee)=>{if(f)return;Q.stopPropagation(),Q.preventDefault();const X=$(Q);S({type:"reconnect-to",fromNodeId:ee.from,edgeKey:ee.edgeKey,mouseX:X.x,mouseY:X.y})},[$,f]),F=H.useCallback((Q,ee)=>{if(f)return;Q.stopPropagation(),Q.preventDefault();const X=$(Q);S({type:"reconnect-from",fromNodeId:ee.from,fixedTargetId:ee.to,edgeKey:ee.edgeKey,mouseX:X.x,mouseY:X.y})},[$,f]),P=H.useCallback(Q=>{if(!v)return;const ee=$(Q);S(X=>X?{...X,mouseX:ee.x,mouseY:ee.y}:null)},[v,$]),Z=H.useCallback(()=>{v&&(C.current=!0,j&&V(j)&&(v.type==="new"?g(v.fromNodeId,j):v.type==="reconnect-to"?m(v.edgeKey,j):v.type==="reconnect-from"&&b(v.edgeKey,j)),S(null),T(null))},[v,j,V,g,m,b]),G=H.useCallback(()=>{if(C.current){C.current=!1;return}l(null),d(null)},[l,d]);H.useEffect(()=>{if(f)return;const Q=ee=>{ee.target instanceof HTMLInputElement||ee.target instanceof HTMLTextAreaElement||ee.target instanceof HTMLSelectElement||(ee.key==="Delete"||ee.key==="Backspace")&&s&&s!=="start"&&(ee.preventDefault(),_(s),d(null))};return document.addEventListener("keydown",Q),()=>document.removeEventListener("keydown",Q)},[f,s,_,d]);const I=Q=>{const ee=B.get(Q.from),X=B.get(Q.to);if(!ee||!X)return null;let q,oe,re,ve="middle",be,Re;if(Q.direction==="down"){const Ie=ee.cx+Q.fromPort*(ee.w/2-10),He=ee.cy+ee.h/2,Ue=X.cx+Q.toPort*(X.w/2-10),je=X.cy-X.h/2,me=je-He,Te=Ue-Ie;q=`M ${Ie} ${He} C ${Ie} ${He+me*.4}, ${Ue-Te*.2} ${je-me*.1}, ${Ue} ${je}`,oe=Ie+(Ue-Ie)*.5,re=He+me*.6,be={x:Ie,y:He},Re={x:Ue,y:je}}else if(Q.direction==="back"){const Ie=Q.from===Q.to,He=ee.cx>=A/2,Ue=Q.backEdgeIndex*16,je=He?A-20-Ue:20+Ue;if(Ie){const me=ee.cx>=A/2,Te=30+Q.backEdgeIndex*14,$e=ee.cy-ee.h/2,Lt=me?ee.cx+ee.w/2:ee.cx-ee.w/2,fe=me?Lt+Te:Lt-Te,Ae=ee.cx+(me?ee.w/4:-ee.w/4),Be=$e-20-Q.backEdgeIndex*10;q=`M ${Lt} ${ee.cy} C ${fe} ${ee.cy}, ${fe} ${Be}, ${Ae} ${$e}`,oe=fe+10,re=Be+4,ve="middle",be={x:Lt,y:ee.cy},Re={x:Ae,y:$e}}else{const me=He?ee.cx+ee.w/2:ee.cx-ee.w/2,Te=X.cx+(He?X.w/4:-X.w/4),$e=Math.min(ee.cy,X.cy)-X.h/2-18-Q.backEdgeIndex*14;q=`M ${me} ${ee.cy} L ${je} ${ee.cy} L ${je} ${$e} L ${Te} ${$e} L ${Te} ${X.cy-X.h/2}`,oe=je,re=(ee.cy+$e)/2,ve=He?"start":"end",be={x:me,y:ee.cy},Re={x:Te,y:X.cy-X.h/2}}}else{const Ie=X.cx>ee.cx,He=Q.sameEdgeIndex===0?-12:12,Ue=Ie?ee.cx+ee.w/2:ee.cx-ee.w/2,je=Ie?X.cx-X.w/2:X.cx+X.w/2,me=ee.cy+He,Te=X.cy+He,$e=(Ue+je)/2;q=`M ${Ue} ${me} C ${$e} ${me}, ${$e} ${Te}, ${je} ${Te}`,oe=$e,re=(me+Te)/2-6,be={x:Ue,y:me},Re={x:je,y:Te}}return{path:q,labelX:oe,labelY:re,labelAnchor:ve,fromPt:be,toPt:Re}},R=(Q,ee)=>{const X=I(Q);if(!X)return null;const{path:q,labelX:oe,labelY:re,labelAnchor:ve}=X,be=s===Q.edgeKey,Re=Q.label&&!(Q.from==="$start"&&Q.label==="Always");return o.jsxs("g",{children:[o.jsx("path",{d:q,fill:"none",stroke:"transparent",strokeWidth:14,className:"cursor-pointer",onClick:Ie=>{Ie.stopPropagation(),d(be?null:Q.edgeKey)}}),o.jsx("path",{d:q,fill:"none",stroke:be?"#58a6ff":"#484f58",strokeWidth:be?2.2:1.2,markerEnd:be?"url(#arrow-selected)":"url(#arrow)",pointerEvents:"none"}),Re&&o.jsx("text",{x:oe+(ve==="start"?5:ve==="end"?-5:0),y:re+3,textAnchor:ve,className:"text-[8px]",fill:be?"#79c0ff":"#8b949e",style:{paintOrder:"stroke",stroke:"#0d1117",strokeWidth:3,strokeLinejoin:"round"},pointerEvents:"none",children:Q.label})]},ee)},z=()=>{if(!s||v)return null;const Q=D.find(re=>re.edgeKey===s);if(!Q)return null;const ee=I(Q);if(!ee)return null;const{fromPt:X,toPt:q}=ee,oe=6;return o.jsxs(o.Fragment,{children:[Q.edgeKey!=="start"&&o.jsx("circle",{cx:X.x,cy:X.y,r:oe,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:re=>F(re,Q)}),o.jsx("circle",{cx:q.x,cy:q.y,r:oe,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:re=>O(re,Q)})]})},Y=()=>{if(!v)return null;let Q,ee,X,q;if(v.type==="reconnect-from"){const ve=B.get(v.fixedTargetId);if(!ve)return null;Q=v.mouseX,ee=v.mouseY,X=ve.cx,q=ve.cy-ve.h/2}else{const ve=B.get(v.fromNodeId);if(!ve)return null;Q=ve.cx,ee=ve.cy+ve.h/2,X=v.mouseX,q=v.mouseY}const oe=q-ee,re=Math.abs(oe)>10?`M ${Q} ${ee} C ${Q} ${ee+oe*.4}, ${X} ${q-oe*.4}, ${X} ${q}`:`M ${Q} ${ee} L ${X} ${q}`;return o.jsx("path",{d:re,fill:"none",stroke:"#58a6ff",strokeWidth:2,strokeDasharray:"6 3",strokeOpacity:.7,pointerEvents:"none"})},U=Q=>{const ee=Q.cy+Q.h/2,X=(v==null?void 0:v.fromNodeId)===Q.id;return o.jsx("circle",{cx:Q.cx,cy:ee,r:fb,fill:X?"#58a6ff":"#1c2128",stroke:X?"#58a6ff":"#484f58",strokeWidth:1.5,strokeOpacity:X?1:.5,className:"cursor-crosshair",onMouseDown:q=>W(q,Q.id)})},ie=Q=>{const ee=Q.cy-Q.h/2,X=v&&j===Q.id&&V(Q.id);return o.jsx("circle",{cx:Q.cx,cy:ee,r:fb,fill:X?"#3fb950":"#1c2128",stroke:X?"#3fb950":"#484f58",strokeWidth:1.5,strokeOpacity:X?1:.5})};return o.jsxs("svg",{ref:k,viewBox:`0 0 ${A} ${M}`,className:"block w-full",preserveAspectRatio:"xMidYMin meet",onMouseMove:P,onMouseUp:Z,onClick:G,children:[o.jsxs("defs",{children:[o.jsx("marker",{id:"arrow",viewBox:"0 0 10 7",refX:"10",refY:"3.5",markerWidth:"7",markerHeight:"5",orient:"auto",children:o.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:"#484f58"})}),o.jsx("marker",{id:"arrow-selected",viewBox:"0 0 10 7",refX:"10",refY:"3.5",markerWidth:"7",markerHeight:"5",orient:"auto",children:o.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:"#58a6ff"})})]}),D.map((Q,ee)=>R(Q,ee)),N.map(Q=>{const ee=i===Q.id,X=Q.cx-Q.w/2,q=Q.cy-Q.h/2,oe=y===Q.id,re=v&&j===Q.id&&V(Q.id);if(Q.type==="terminal"){const be=Q.id==="$start",Re=be?"#58a6ff":"#3fb950",Ie=be,He=!be;return o.jsxs("g",{onClick:Ue=>{Ue.stopPropagation(),be&&!f&&d("start")},className:be&&!f?"cursor-pointer":void 0,children:[re&&o.jsx("rect",{x:X-3,y:q-3,width:Q.w+6,height:Q.h+6,rx:Q.h/2+3,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),be&&s==="start"&&o.jsx("rect",{x:X-3,y:q-3,width:Q.w+6,height:Q.h+6,rx:Q.h/2+3,fill:"none",stroke:"#58a6ff",strokeOpacity:.5,strokeWidth:2}),o.jsx("rect",{x:X,y:q,width:Q.w,height:Q.h,rx:Q.h/2,fill:Re,fillOpacity:.08,stroke:Re,strokeOpacity:.4,strokeWidth:1.5}),o.jsx("text",{x:Q.cx,y:Q.cy+4,textAnchor:"middle",fill:Re,className:"text-[10px] font-medium",pointerEvents:"none",children:Q.label}),Ie&&U(Q),He&&ie(Q)]},Q.id)}const ve=Q.color??"#6b7280";return o.jsxs("g",{onClick:be=>{be.stopPropagation(),f||l(ee?null:Q.id)},onMouseEnter:()=>x(Q.id),onMouseLeave:()=>x(null),className:f?void 0:"cursor-pointer",children:[re&&o.jsx("rect",{x:X-3,y:q-3,width:Q.w+6,height:Q.h+6,rx:12,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),ee&&o.jsx("rect",{x:X-3,y:q-3,width:Q.w+6,height:Q.h+6,rx:12,fill:"none",stroke:"#58a6ff",strokeOpacity:.5,strokeWidth:2}),o.jsx("rect",{x:X,y:q,width:Q.w,height:Q.h,rx:10,fill:ve,fillOpacity:.08,stroke:ve,strokeOpacity:.6,strokeWidth:ee?2:1.5}),o.jsx("text",{x:Q.cx,y:Q.cy+4,textAnchor:"middle",fill:"#c9d1d9",className:"text-[11px] font-medium",pointerEvents:"none",children:Q.label}),!f&&U(Q),!f&&ie(Q),oe&&!v&&!f&&o.jsxs("g",{onClick:be=>{be.stopPropagation(),p(Q.id)},className:"cursor-pointer",children:[o.jsx("circle",{cx:X+Q.w-2,cy:q+2,r:8,fill:"#0d1117",fillOpacity:.9,stroke:"#f85149",strokeOpacity:.5,strokeWidth:1}),o.jsx("line",{x1:X+Q.w-5,y1:q-1,x2:X+Q.w+1,y2:q+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"}),o.jsx("line",{x1:X+Q.w+1,y1:q-1,x2:X+Q.w-5,y2:q+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"})]})]},Q.id)}),v&&N.map(Q=>V(Q.id)?o.jsx("rect",{x:Q.cx-Q.w/2-8,y:Q.cy-Q.h/2-8,width:Q.w+16,height:Q.h+16,fill:"transparent",rx:12,onMouseEnter:()=>T(Q.id),onMouseLeave:()=>T(null),onMouseUp:ee=>{ee.stopPropagation(),Z()}},`drop-${Q.id}`):null),Y(),z()]})}const er="w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",Bi="w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",ln="block text-[11px] text-text-secondary mb-0.5";function W5({fromLabel:e,toLabel:r,condition:i,fromStep:s,agentTypes:c,onUpdateCondition:u,onDelete:f}){const l=s&&(s.type==="sub_agent"||s.type==="agent")?c.find(p=>p.id===(s.type==="sub_agent"?s.subAgentType:s.toolMode)):void 0,d=(l==null?void 0:l.results)&&l.results.length>0;return o.jsxs("div",{className:"space-y-3 text-sm",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-blue-500/15 text-blue-300",children:"Transition"}),o.jsx("button",{onClick:f,className:"p-1 rounded text-text-muted hover:text-accent-error text-xs",children:"Delete"})]}),o.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-text-secondary",children:[o.jsx("span",{className:"font-medium text-text-primary",children:e}),o.jsx(Ob,{}),o.jsx("span",{className:"font-medium text-text-primary",children:r})]}),o.jsxs("div",{children:[o.jsx("label",{className:ln,children:"Condition"}),o.jsx("select",{value:i.type,onChange:p=>{u(p.target.value==="step_result"?{type:"step_result",result:"success"}:{type:p.target.value})},className:Bi,children:L0.map(p=>o.jsx("option",{value:p.value,children:p.label},p.value))})]}),i.type==="step_result"&&o.jsxs("div",{children:[o.jsx("label",{className:ln,children:"Result"}),d?o.jsx("select",{value:i.result??l.results[0],onChange:p=>{u({type:"step_result",result:p.target.value})},className:Bi,children:l.results.map(p=>o.jsx("option",{value:p,children:p},p))}):o.jsx("input",{type:"text",value:i.result??"success",onChange:p=>u({type:"step_result",result:p.target.value}),placeholder:"e.g. success, passed, failed",className:er})]}),o.jsx("p",{className:"text-text-muted text-[10px]",children:"Drag handles to reconnect. Press Delete to remove."})]})}function lh({variables:e,onInsert:r}){return e.length===0?null:o.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:e.map(i=>o.jsx("button",{type:"button",onClick:()=>r(i.name),title:i.description,className:"px-1.5 py-0.5 rounded text-[10px] font-mono bg-bg-primary border border-border text-text-secondary hover:text-accent-primary hover:border-accent-primary/40 transition-colors",children:`{{${i.name}}}`},i.name))})}function G5({step:e,isEntry:r,agentTypes:i,transitionCount:s,templateVariables:c,onUpdate:u,onRemove:f,onSetEntry:l}){const{color:d,name:p}=_f(e,i);return o.jsxs("div",{className:"space-y-3 text-sm",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold",style:{backgroundColor:d+"20",color:d},children:p}),r&&o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-accent-primary/15 text-accent-primary",children:"Entry"})]}),o.jsxs("div",{className:"flex items-center gap-1",children:[!r&&o.jsx("button",{onClick:l,className:"p-1 rounded text-text-muted hover:text-accent-primary text-xs",children:"Set entry"}),o.jsx("button",{onClick:f,className:"p-1 rounded text-text-muted hover:text-accent-error text-xs",children:"Delete"})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:ln,children:"Type"}),o.jsx("select",{value:e.type,onChange:g=>{const m=g.target.value,b=m==="sub_agent"?"verification":"build";if(m==="agent"){const _=i.find(k=>!k.subagent);u({...e,type:m,phase:b,toolMode:(_==null?void 0:_.id)??"builder",name:(_==null?void 0:_.name)??"Agent"})}else if(m==="sub_agent"){const _=i.find(k=>k.subagent);u({...e,type:m,phase:b,subAgentType:(_==null?void 0:_.id)??"",name:(_==null?void 0:_.name)??"Sub-Agent"})}else u({...e,type:m,phase:b,name:"Shell"})},className:Bi,children:U5.map(g=>o.jsx("option",{value:g.value,children:g.label},g.value))})]}),e.type==="agent"&&o.jsxs("div",{children:[o.jsx("label",{className:ln,children:"Agent Type"}),o.jsx("select",{value:e.toolMode??"builder",onChange:g=>{const m=i.find(b=>b.id===g.target.value);u({...e,toolMode:g.target.value,name:(m==null?void 0:m.name)??g.target.value})},className:Bi,children:i.filter(g=>!g.subagent).map(g=>o.jsx("option",{value:g.id,children:g.name},g.id))})]}),e.type==="sub_agent"&&o.jsxs("div",{children:[o.jsx("label",{className:ln,children:"Sub-Agent Type"}),o.jsxs("select",{value:e.subAgentType??"",onChange:g=>{const m=i.find(b=>b.id===g.target.value);u({...e,subAgentType:g.target.value,name:(m==null?void 0:m.name)??g.target.value})},className:Bi,children:[o.jsx("option",{value:"",children:"— select —"}),i.filter(g=>g.subagent).map(g=>o.jsx("option",{value:g.id,children:g.name},g.id))]})]}),(e.type==="agent"||e.type==="sub_agent")&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("label",{className:ln,children:"Prompt"}),o.jsx("textarea",{value:e.prompt??"",onChange:g=>u({...e,prompt:g.target.value||void 0}),rows:6,className:`${er} resize-y text-xs`,placeholder:"Injected on first entry..."}),o.jsx(lh,{variables:c,onInsert:g=>u({...e,prompt:(e.prompt??"")+`{{${g}}}`})})]}),o.jsxs("div",{children:[o.jsx("label",{className:ln,children:"Nudge Prompt"}),o.jsx("textarea",{value:e.nudgePrompt??"",onChange:g=>u({...e,nudgePrompt:g.target.value||void 0}),rows:6,className:`${er} resize-y text-xs`,placeholder:"Injected on re-entry..."}),o.jsx(lh,{variables:c,onInsert:g=>u({...e,nudgePrompt:(e.nudgePrompt??"")+`{{${g}}}`})})]})]}),e.type==="shell"&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("label",{className:ln,children:"Command"}),o.jsx("textarea",{value:e.command??"",onChange:g=>u({...e,command:g.target.value}),rows:3,className:`${er} font-mono text-xs resize-y`,placeholder:"cd {{workdir}} && npm run lint"}),o.jsx(lh,{variables:c,onInsert:g=>u({...e,command:(e.command??"")+`{{${g}}}`})})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsx("label",{className:ln,children:"Timeout (ms)"}),o.jsx("input",{type:"number",value:e.timeout??6e4,onChange:g=>u({...e,timeout:Number(g.target.value)}),className:`${er} font-mono text-xs`})]}),o.jsxs("div",{children:[o.jsx("label",{className:ln,children:"Success Codes"}),o.jsx("input",{value:(e.successExitCodes??[0]).join(", "),onChange:g=>u({...e,successExitCodes:g.target.value.split(",").map(m=>Number(m.trim())).filter(m=>!isNaN(m))}),className:`${er} font-mono text-xs`})]})]})]}),o.jsx("div",{className:"pt-1 border-t border-border/50",children:o.jsxs("p",{className:"text-text-muted text-[10px]",children:[s," outgoing transition",s!==1?"s":""," — drag from the bottom port to connect."]})})]})}const pb=[];function O0({isOpen:e,onClose:r,initialEditId:i}){const s=Ct(pe=>pe.defaults),c=Ct(pe=>pe.userItems),u=Ct(pe=>pe.loading),f=Ct(pe=>pe.templateVariables),l=Ct(pe=>pe.fetchWorkflows),d=Ct(pe=>pe.fetchWorkflow),p=Ct(pe=>pe.fetchDefaultContent),g=Ct(pe=>pe.fetchTemplateVariables),m=Ct(pe=>pe.createWorkflow),b=Ct(pe=>pe.updateWorkflow),_=Ct(pe=>pe.deleteWorkflow),{requestDelete:k,clearConfirm:C,isConfirming:y}=Oh(),[x,v]=H.useState("list"),[S,j]=H.useState(null),[T,N]=H.useState(!1),[D,A]=H.useState(null),[M,B]=H.useState(null),[$,V]=H.useState(""),[W,O]=H.useState(""),[F,P]=H.useState(""),[Z,G]=H.useState("1.0.0"),[I,R]=H.useState("#3b82f6"),[z,Y]=H.useState(""),[U,ie]=H.useState(50),[Q,ee]=H.useState(pb),[X,q]=H.useState({type:"always"}),[oe,re]=H.useState(""),[ve,be]=H.useState(!1),[Re,Ie]=H.useState([]),[He]=H.useState(null);H.useEffect(()=>{e&&(l(),g(),ke("/api/agents").then(pe=>pe.json()).then(pe=>Ie(pe.agents??[])).catch(()=>{}),A(null),B(null),i?s.some(ye=>ye.id===i)?p(i).then(ye=>{ye&&(V(ye.metadata.name+" (copy)"),O(`${i}-copy-${Date.now()}`),P(ye.metadata.description),G(ye.metadata.version),R(ye.metadata.color??"#3b82f6"),Y(ye.entryStep),ie(ye.settings.maxIterations),ee(ye.steps),q(ye.startCondition??{type:"always"}),re(""),j(null),N(!1),v("edit"))}):d(i).then(ye=>{ye&&(V(ye.metadata.name),O(ye.metadata.id),P(ye.metadata.description),G(ye.metadata.version),R(ye.metadata.color??"#3b82f6"),Y(ye.entryStep),ie(ye.settings.maxIterations),ee(ye.steps),q(ye.startCondition??{type:"always"}),re(""),j(i),N(!1),v("edit"))}):(v("list"),j(null),N(!1)))},[e,l,d,p,g,i]);const Ue=async pe=>{const ye=await d(pe);ye&&(j(pe),V(ye.metadata.name),O(ye.metadata.id),P(ye.metadata.description),G(ye.metadata.version),R(ye.metadata.color??"#3b82f6"),Y(ye.entryStep),ie(ye.settings.maxIterations),ee(ye.steps),q(ye.startCondition??{type:"always"}),re(""),A(null),B(null),v("edit"))},je=async()=>{var Qe;const pe=S??W;if(!pe||!$)return re("Name is required."),!1;if(Q.length===0)return re("Add at least one step."),!1;let ye=z;if(!ye||!Q.some(te=>te.id===ye)){if(ye=((Qe=Q.find(te=>te.id))==null?void 0:Qe.id)??"",!ye)return re("All steps need an ID."),!1;Y(ye)}be(!0),re("");const we={metadata:{id:pe,name:$,description:F,version:Z||"1.0.0",color:I},entryStep:ye,settings:{maxIterations:U},steps:Q,startCondition:X},We=S?await b(S,we):await m(we);return be(!1),We.success?(S||j(pe),!0):(re(We.error??"Failed to save."),!1)},me=async()=>{await je()},Te=async()=>{await je()&&(i?r():v("list"))},$e=()=>{i?r():v("list")},Lt=pe=>{V(pe),S||O(P5(pe))},fe=async pe=>{if(s.some(we=>we.id===pe)){const we=await p(pe);if(!we)return;V(we.metadata.name),O(we.metadata.id),P(we.metadata.description),G(we.metadata.version),R(we.metadata.color??"#3b82f6"),Y(we.entryStep),ie(we.settings.maxIterations),ee(we.steps),q(we.startCondition??{type:"always"}),re(""),j(pe),N(!0)}else{const we=await d(pe);if(!we)return;V(we.metadata.name),O(we.metadata.id),P(we.metadata.description),G(we.metadata.version),R(we.metadata.color??"#3b82f6"),Y(we.entryStep),ie(we.settings.maxIterations),ee(we.steps),q(we.startCondition??{type:"always"}),re(""),j(pe),N(!0)}v("edit")},Ae=async pe=>{const we=s.some(We=>We.id===pe)?await p(pe):await d(pe);we&&(V(we.metadata.name+" (copy)"),O(`${pe}-copy-${Date.now()}`),P(we.metadata.description),G(we.metadata.version),R(we.metadata.color??"#3b82f6"),Y(we.entryStep),ie(we.settings.maxIterations),ee(we.steps),q(we.startCondition??{type:"always"}),re(""),j(null),N(!1),v("edit"))},Be=()=>{j(null),V(""),O(""),P(""),G("1.0.0"),R("#3b82f6"),Y(""),ie(50),ee(structuredClone(pb)),q({type:"always"}),re(""),A(null),B(null),N(!1),v("edit")},ot=async pe=>{await _(pe),C()},ue=H.useCallback(pe=>{A(pe),B(null)},[]),_e=H.useCallback(pe=>{B(pe),A(null)},[]),Ne=D!==null?Number(D):-1,Oe=Ne>=0?Q[Ne]??null:null,qe=H.useCallback(pe=>{ee(ye=>ye.map((we,We)=>We===Ne?pe:we))},[Ne]),Nt=X.type==="step_result"?`${X.result}`:R0[X.type]??X.type,Ze=()=>{const pe=Q.length,ye=F5(Q),we=Re.find(We=>!We.subagent);ee([...Q,{id:ye,name:(we==null?void 0:we.name)??"Agent",type:"agent",phase:"build",toolMode:(we==null?void 0:we.id)??"builder",transitions:[]}]),z||Y(ye),ue(String(pe))},Ot=H.useCallback((pe,ye)=>{pe==="$start"?(Y(ye),_e("start")):ee(we=>{const We=we.find(te=>te.id===pe),Qe=We?We.transitions.length:0;return _e(`${pe}:${Qe}`),we.map(te=>te.id===pe?{...te,transitions:[...te.transitions,{when:{type:"always"},goto:ye}]}:te)})},[_e]),Tt=H.useCallback((pe,ye)=>{if(pe==="start")Y(ye);else{const we=pe.lastIndexOf(":"),We=pe.slice(0,we),Qe=parseInt(pe.slice(we+1));ee(te=>te.map(Ee=>Ee.id===We?{...Ee,transitions:Ee.transitions.map((Le,Ve)=>Ve===Qe?{...Le,goto:ye}:Le)}:Ee))}},[]),Yt=H.useCallback((pe,ye)=>{const we=pe.lastIndexOf(":"),We=pe.slice(0,we),Qe=parseInt(pe.slice(we+1));ee(te=>{const Ee=te.find(Ve=>Ve.id===We);if(!Ee)return te;const Le=Ee.transitions[Qe];return Le?te.map(Ve=>Ve.id===We?{...Ve,transitions:Ve.transitions.filter((Mt,gn)=>gn!==Qe)}:Ve.id===ye?{...Ve,transitions:[...Ve.transitions,Le]}:Ve):te}),B(null)},[]),lt=H.useCallback(pe=>{if(pe==="start")Y("");else{const ye=pe.lastIndexOf(":"),we=pe.slice(0,ye),We=parseInt(pe.slice(ye+1));ee(Qe=>Qe.map(te=>te.id===we?{...te,transitions:te.transitions.filter((Ee,Le)=>Le!==We)}:te))}B(null)},[]),Bn=H.useCallback((pe,ye)=>{if(pe==="start")q(ye);else{const we=pe.lastIndexOf(":"),We=pe.slice(0,we),Qe=parseInt(pe.slice(we+1));ee(te=>te.map(Ee=>Ee.id===We?{...Ee,transitions:Ee.transitions.map((Le,Ve)=>Ve===Qe?{...Le,when:ye}:Le)}:Ee))}},[]),Xt=pe=>_f(pe,Re).name,Us=()=>{if(!M)return null;if(M==="start"){const Le=Q.find(Ve=>Ve.id===z);return{type:"start",fromLabel:"Start",toLabel:Le?Xt(Le):"(none)",condition:X}}const pe=M.lastIndexOf(":"),ye=M.slice(0,pe),we=parseInt(M.slice(pe+1)),We=Q.find(Le=>Le.id===ye);if(!We)return null;const Qe=We.transitions[we];if(!Qe)return null;const te=Q.find(Le=>Le.id===Qe.goto),Ee=Qe.goto==="$done"?"Done":te?Xt(te):Qe.goto;return{type:"step",fromLabel:Xt(We),toLabel:Ee,condition:Qe.when}};if(x==="edit"){const pe=Us();return o.jsxs(jt,{isOpen:e,onClose:$e,title:T?$:S?"Edit Workflow":"New Workflow",size:"full",children:[oe&&o.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded mb-3",children:oe}),o.jsxs("div",{className:"flex items-end gap-3 mb-3 pb-3 border-b border-border flex-wrap",children:[o.jsxs("div",{className:"min-w-[140px]",children:[o.jsx("label",{className:ln,children:"Name"}),o.jsx("input",{value:$,onChange:ye=>Lt(ye.target.value),placeholder:"Workflow name",className:`${er} ${T?"opacity-50":""}`,readOnly:T})]}),o.jsxs("div",{className:"min-w-[100px]",children:[o.jsx("label",{className:ln,children:"ID"}),o.jsx("input",{value:W,readOnly:!0,className:`${er} font-mono opacity-50`})]}),o.jsxs("div",{className:"flex-1 min-w-[140px]",children:[o.jsx("label",{className:ln,children:"Description"}),o.jsx("input",{value:F,onChange:ye=>!T&&P(ye.target.value),readOnly:T,placeholder:"What does this workflow do?",className:`${er} ${T?"opacity-50":""}`})]}),o.jsxs("div",{className:"w-20",children:[o.jsx("label",{className:ln,children:"Max Iter."}),o.jsx("input",{type:"number",value:U,onChange:ye=>!T&&ie(Number(ye.target.value)),readOnly:T,className:`${er} font-mono ${T?"opacity-50":""}`})]}),o.jsxs("div",{children:[o.jsx("label",{className:ln,children:"Color"}),o.jsx("input",{type:"color",value:I,onChange:ye=>!T&&R(ye.target.value),disabled:T,className:`w-8 h-8 rounded border border-border bg-transparent ${T?"opacity-50":"cursor-pointer"}`})]})]}),o.jsxs("div",{className:"flex gap-3",style:{height:"calc(90vh - 220px)",minHeight:300},children:[o.jsxs("div",{className:"flex-1 min-w-0 bg-bg-primary/50 border border-border rounded-lg flex flex-col overflow-hidden",children:[o.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-border/50 shrink-0",children:[o.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wider font-medium",children:"Flow"}),!T&&o.jsx("button",{onClick:Ze,className:"text-[11px] text-accent-primary hover:text-accent-primary/80",children:"+ Add Step"})]}),o.jsxs("div",{className:"flex-1 min-h-0 p-2 overflow-auto",children:[o.jsx(q5,{steps:Q,entryStep:z,selectedNodeId:(Oe==null?void 0:Oe.id)??null,selectedEdgeKey:M,startConditionLabel:Nt,agentTypes:Re,isReadOnly:T,onSelectNode:ye=>{if(ye===null){ue(null);return}const we=Q.findIndex(We=>We.id===ye);ue(we>=0?String(we):null)},onSelectEdge:_e,onRemoveStep:ye=>{var We;const we=Q.findIndex(Qe=>Qe.id===ye);if(ee(Qe=>Qe.filter(te=>te.id!==ye)),Ne===we&&ue(null),z===ye){const Qe=Q.filter(te=>te.id!==ye);Y(((We=Qe[0])==null?void 0:We.id)??"")}},onCreateTransition:Ot,onReconnectTo:Tt,onReconnectFrom:Yt,onDeleteTransition:lt}),Q.length===0&&o.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-text-muted",children:[o.jsx("p",{className:"text-xs mb-2",children:"No steps yet"}),o.jsx("button",{onClick:Ze,className:"px-3 py-1.5 rounded bg-accent-primary/10 text-accent-primary text-xs hover:bg-accent-primary/20",children:"+ Add your first step"})]})]})]}),o.jsxs("div",{className:"w-[300px] shrink-0 border border-border rounded-lg bg-bg-secondary flex flex-col overflow-hidden",children:[o.jsx("div",{className:"px-3 py-1.5 border-b border-border shrink-0",children:o.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wider font-medium",children:"Properties"})}),o.jsx("div",{className:"p-3 overflow-y-auto flex-1 min-h-0",children:T&&(pe||Oe)?o.jsx("p",{className:"text-text-muted text-xs text-center py-8",children:'View only — click "Duplicate & Customize" to edit.'}):pe?pe.type==="start"?o.jsxs("div",{className:"space-y-3 text-sm",children:[o.jsx("div",{className:"flex items-center gap-2",children:o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-blue-500/20 text-blue-300",children:"Start"})}),z&&o.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-text-secondary",children:[o.jsx("span",{className:"text-text-primary font-medium",children:"Start"}),o.jsx(Ob,{}),o.jsx("span",{className:"text-text-primary font-medium",children:pe.toLabel})]}),o.jsxs("div",{children:[o.jsx("label",{className:ln,children:"Activation Condition"}),o.jsx("select",{value:X.type,onChange:ye=>q(ye.target.value==="step_result"?{type:"step_result",result:"success"}:{type:ye.target.value}),className:Bi,children:L0.map(ye=>o.jsx("option",{value:ye.value,children:ye.label},ye.value))})]}),X.type==="step_result"&&o.jsxs("div",{children:[o.jsx("label",{className:ln,children:"Result"}),z&&(()=>{const ye=Q.find(te=>te.id===z),we=ye&&(ye.type==="sub_agent"||ye.type==="agent")?Re.find(te=>te.id===(ye.type==="sub_agent"?ye.subAgentType:ye.toolMode)):void 0,We=(we==null?void 0:we.results)&&we.results.length>0,Qe=(we==null?void 0:we.results)??[];return We?o.jsx("select",{value:X.result??Qe[0],onChange:te=>q({type:"step_result",result:te.target.value}),className:Bi,children:Qe.map(te=>o.jsx("option",{value:te,children:te},te))}):o.jsx("input",{type:"text",value:X.result??"success",onChange:te=>q({type:"step_result",result:te.target.value}),placeholder:"e.g. success, passed, failed",className:er})})()]}),o.jsx("p",{className:"text-text-muted text-[10px]",children:"Workflow only proceeds when this condition is met. Drag the target handle to change entry step."})]}):o.jsx(W5,{fromLabel:pe.fromLabel,toLabel:pe.toLabel,condition:pe.condition,fromStep:pe.type==="step"?Q.find(ye=>ye.id===pe.fromLabel):void 0,agentTypes:Re,onUpdateCondition:ye=>Bn(M,ye),onDelete:()=>lt(M)}):Oe?o.jsx(G5,{step:Oe,isEntry:Oe.id===z,agentTypes:Re,transitionCount:Oe.transitions.length,templateVariables:f,onUpdate:qe,onRemove:()=>{var ye;if(Oe&&(ee(Q.filter((we,We)=>We!==Ne)),ue(null),z===Oe.id)){const we=Q.filter((We,Qe)=>Qe!==Ne);Y(((ye=we[0])==null?void 0:ye.id)??"")}},onSetEntry:()=>Y(Oe.id)}):o.jsxs("p",{className:"text-text-muted text-xs text-center py-8",children:["Click a node or edge to edit.",o.jsx("br",{}),"Drag from a port to connect."]})})]})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 mt-3 border-t border-border",children:[o.jsx(it,{variant:"secondary",onClick:$e,children:"Close"}),T?o.jsx(it,{variant:"primary",onClick:()=>{V($+" (copy)"),O(`${S}-copy-${Date.now()}`),j(null),N(!1)},children:"Duplicate & Customize"}):o.jsxs(o.Fragment,{children:[o.jsx(it,{variant:"secondary",onClick:me,disabled:ve||!$,children:ve?"Saving...":"Save"}),o.jsx(it,{variant:"primary",onClick:Te,disabled:ve||!$,children:"Save & Close"})]})]})]})}return o.jsxs(jt,{isOpen:e,onClose:r,title:"Workflows",size:"lg",children:[o.jsxs("div",{className:"flex items-center justify-between mb-4",children:[o.jsx("p",{className:"text-text-secondary text-sm",children:"Workflows define the orchestrator's step sequence when running tasks."}),o.jsx("div",{className:"flex items-center gap-2 flex-shrink-0 ml-3",children:o.jsx(it,{variant:"primary",size:"sm",onClick:Be,children:"+ New"})})]}),u&&s.length===0&&c.length===0?o.jsx("div",{className:"text-text-muted text-sm",children:"Loading workflows..."}):s.length===0&&c.length===0?o.jsx("div",{className:"text-text-muted text-sm",children:"No workflows installed."}):o.jsxs("div",{className:"space-y-4",children:[s.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Built-in"}),o.jsx("div",{className:"space-y-2",children:s.map(pe=>o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsxs("div",{className:"min-w-0 flex-1 mr-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-text-primary text-sm font-medium",children:pe.name}),o.jsxs("span",{className:"text-text-muted text-xs",children:["v",pe.version]})]}),o.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:pe.description})]}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx("button",{onClick:()=>fe(pe.id),className:"p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",title:"View",children:o.jsx(ec,{})}),o.jsx(Qa,{onClick:()=>Ae(pe.id)})]})]},pe.id))})]}),c.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Custom"}),o.jsx("div",{className:"space-y-2",children:c.map(pe=>o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsxs("div",{className:"min-w-0 flex-1 mr-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-text-primary text-sm font-medium",children:pe.name}),o.jsxs("span",{className:"text-text-muted text-xs",children:["v",pe.version]})]}),o.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:pe.description})]}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx(Qa,{onClick:()=>Ae(pe.id)}),o.jsx(Hs,{onClick:()=>Ue(pe.id)}),y(pe.id,"delete")?o.jsx(Mh,{onConfirm:()=>ot(pe.id),onCancel:()=>{}}):o.jsx(Ih,{onClick:()=>k(pe.id)})]})]},pe.id))})]})]})]})}function V5(e,r){const i=e.startCondition;if(!i||i.type==="always")return!0;switch(i.type){case"has_pending_criteria":return r.some(s=>s.status.type!=="passed");case"all_criteria_passed":return r.length===0||r.every(s=>s.status.type==="passed");case"all_criteria_completed_or_passed":return r.every(s=>s.status.type==="completed"||s.status.type==="passed");case"any_criteria_blocked":return r.some(s=>s.status.type==="failed"&&s.attempts.filter(c=>c.status==="failed").length>=4);case"step_result":return null;default:return null}}function K5({onSelectWorkflow:e,onOpenManager:r,criteria:i}){const[s,c]=H.useState(!1),[u,f]=H.useState(null),l=Ct(N=>N.defaults),d=Ct(N=>N.userItems),p=Ct(N=>N.fetchWorkflows),g=[...l,...d],{isOpen:m,search:b,selectedIndex:_,filtered:k,containerRef:C,searchRef:y,handleToggle:x,handleSearchChange:v,handleKeyDown:S}=E0({items:g,isOpen:s,onOpen:()=>c(!0),onClose:()=>c(!1),filterFn:(N,D)=>!D||N.name.toLowerCase().includes(D.toLowerCase())});H.useEffect(()=>{s&&p()},[s,p]);const j=N=>{e(N),c(!1)},T=()=>{c(!1),r()};return o.jsxs("div",{ref:C,className:"relative",children:[o.jsx(j0,{label:"Workflows",isOpen:m,onClick:x}),m&&o.jsxs("div",{className:"absolute bottom-full right-0 mb-1 w-72 bg-bg-secondary border border-border rounded-lg shadow-xl z-50",onKeyDown:S,children:[o.jsx(N0,{value:b,onChange:v,onKeyDown:S,ref:y,placeholder:"Search workflows..."}),o.jsx(T0,{children:k.length===0?o.jsx(A0,{hasItems:g.length>0,message:"No workflows yet"}):k.map((N,D)=>{const A=V5(N,i),M=N.color??"#3b82f6";return o.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 rounded transition-colors group ${D===_?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[o.jsxs("button",{type:"button",onClick:()=>j(N.id),className:"flex-1 text-left flex items-center gap-2",children:[o.jsx("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:M}}),o.jsx("span",{className:"text-sm text-text-primary font-medium flex-1",children:N.name}),A!==null&&o.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:A?"#22c55e":"#6b7280"},title:A?"Entry condition met":"Entry condition not met"})]}),o.jsx(Hs,{className:"opacity-0 group-hover:opacity-100",onClick:B=>{B.stopPropagation(),c(!1),f(N.id)}})]},N.id)})}),o.jsx(D0,{label:"Manage Workflows...",onClick:T})]}),o.jsx(O0,{isOpen:!!u,onClose:()=>f(null),initialEditId:u})]})}const Y5=(e,r)=>{if(!r)return!0;const i=r.toLowerCase().split(/\s+/),s=e.toLowerCase().split(/\s+/);return i.every(c=>{for(const u of s){let f=0;for(let l=0;l<u.length&&f<c.length;l++)u[l]===c[f]&&f++;if(f===c.length)return!0}return!1})};function X5({isOpen:e,onClose:r,onCloseComplete:i,onSelectCommand:s,onSelectWorkflow:c,onCloseCompleteAction:u,textareaContent:f}){const l=on(G=>G.fetchCommands),d=Ct(G=>G.fetchWorkflows),p=kt(G=>G.fetchAgents),g=on(G=>G.defaults),m=on(G=>G.userItems),b=Ct(G=>G.defaults),_=Ct(G=>G.userItems),k=kt(G=>G.defaults),C=kt(G=>G.userItems),y=Ce(G=>{var I;return(I=G.currentSession)==null?void 0:I.mode}),x=Ce(G=>{var I;return((I=G.currentSession)==null?void 0:I.dangerLevel)??"normal"}),v=Ce(G=>G.switchMode),S=Ce(G=>G.switchDangerLevel),j=Ce(G=>{var I;return(I=G.currentSession)==null?void 0:I.projectId}),T=Ce(G=>G.createSession),N=H.useRef(void 0),[D,A]=H.useState(""),[M,B]=H.useState(0),$=H.useRef(null),V=H.useRef(!1);H.useEffect(()=>{e&&(V.current=!0)},[e]),H.useEffect(()=>{if(e){l(),d(),p(),A(""),B(0);const G=setTimeout(()=>{var I;return(I=$.current)==null?void 0:I.focus()},50);return()=>clearTimeout(G)}},[e,l,d,p]),H.useEffect(()=>{var G;!e&&V.current&&(i==null||i(),(G=N.current)==null||G.call(N),N.current=void 0)},[e,i]);const W=(G,I)=>{const R=new Set(I.map(z=>z.id));return[...G.filter(z=>!R.has(z.id)),...I]},F=[{id:"create-session",name:"New Session",prefix:"Action > Create",action:()=>j&&T(j)},{id:"navigate-session",name:"Another Session",prefix:"Action > Navigate to",action:()=>{N.current=u,r()}},...W(k,C).filter(G=>!G.subagent&&G.id!==y).map(G=>({id:G.id,name:G.name,prefix:"Agent > Switch to",action:()=>v(G.id)})),...W(g,m).map(G=>({id:G.id,name:G.name,prefix:"Command > Launch",action:()=>s(G.id,f)})),...W(b,_).map(G=>({id:G.id,name:G.name,prefix:"Workflow > Run",action:()=>c(G.id)})),...["normal","dangerous"].filter(G=>G!==x).map(G=>({id:G,name:G.charAt(0).toUpperCase()+G.slice(1),prefix:"Mode > Switch to",action:()=>S(G)}))].filter(G=>Y5(`${G.prefix} ${G.name}`,D)),P=F.length-1,Z=G=>{var I;switch(G.key){case"ArrowDown":G.preventDefault(),B(R=>Math.min(R+1,P));break;case"ArrowUp":G.preventDefault(),B(R=>Math.max(R-1,0));break;case"Enter":G.preventDefault(),(I=F[M])==null||I.action(),r();break;case"Escape":G.preventDefault(),r();break}};return e?tc.createPortal(o.jsxs("div",{className:"fixed inset-0 z-50 flex items-start justify-center pt-[15vh] p-4",children:[o.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:r}),o.jsxs("div",{className:"relative w-full max-w-md bg-bg-secondary border border-border rounded shadow-xl",children:[o.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 border-b border-border",children:[o.jsx("input",{ref:$,type:"text",value:D,onChange:G=>{A(G.target.value),B(0)},onKeyDown:Z,placeholder:"Search...",className:"flex-1 bg-transparent text-sm focus:outline-none placeholder:text-text-muted"}),o.jsx(Rh,{onClick:r,className:"shrink-0","aria-label":"Close"})]}),o.jsx("div",{className:"overflow-y-auto max-h-[60vh] p-2",children:F.length===0?o.jsx("div",{className:"px-3 py-4 text-center text-text-muted text-sm",children:g.length+m.length+b.length+_.length>0?"No matches":"No agents, commands, or workflows yet"}):F.map((G,I)=>o.jsxs("button",{type:"button",onClick:()=>{G.action(),r()},className:`w-full text-left px-3 py-2 rounded text-sm transition-colors ${I===M?"bg-accent-primary/20 text-text-primary":"text-text-secondary hover:bg-bg-tertiary hover:text-text-primary"}`,children:[o.jsxs("span",{className:"text-text-muted font-normal",children:[G.prefix," "]}),o.jsx("span",{children:G.name})]},G.id))})]})]}),document.body):null}function Z5(e){return e==="criterion"}function Q5(e){var r,i;return e.role!=="assistant"||e.subAgentId||(r=e.content)!=null&&r.trim()||(i=e.thinkingContent)!=null&&i.trim()||!e.toolCalls||e.toolCalls.length===0?!1:e.toolCalls.every(s=>Z5(s.name))}function J5(e,r=[]){const i=[];let s=null,c=[],u,f=1;const l=new Map,d=new Map,p=[];for(const _ of r)_.type==="message"?l.set(_.message.id,_):_.type==="subagent"?d.set(_.subAgentId,_):_.type==="criteria-batch"&&p.push(_);let g=0;const m=()=>{if(c.length>0){const _=p[g];_&&_.type==="criteria-batch"&&_.toolCalls.length===c.length&&_.toolCalls.every((C,y)=>{var x;return C.id===((x=c[y])==null?void 0:x.id)})?i.push(_):i.push({type:"criteria-batch",toolCalls:[...c]}),g++,c=[]}},b=()=>{if(!s)return;const _=s,k=d.get(_.subAgentId);k&&k.type==="subagent"&&k.messages.length===_.messages.length&&k.messages.every((y,x)=>y===_.messages[x])?i.push(k):i.push({type:"subagent",subAgentId:_.subAgentId,subAgentType:_.subAgentType,messages:_.messages}),s=null};for(const _ of e)if(_.role!=="tool"){if(_.contextWindowId&&u&&_.contextWindowId!==u&&(m(),b(),f++,i.push({type:"context-divider",windowSequence:f})),u=_.contextWindowId,Q5(_)){b();for(const k of _.toolCalls)c.push(k);continue}if(m(),_.subAgentId&&_.subAgentType)s&&s.subAgentId===_.subAgentId?s.messages.push(_):(b(),s={subAgentId:_.subAgentId,subAgentType:_.subAgentType,messages:[_]});else{b();const k=l.get(_.id);k&&k.type==="message"&&k.message===_?i.push(k):i.push({type:"message",message:_})}}return m(),b(),i}function eD(e){const{year:r,month:i,day:s}=Kb(e);return`${r}/${i}/${s} ${rc(e)}`}function tD(e,r){return e.length<=r?e:e.substring(0,r)+"..."}const nD=10,rD=150;function iD(e){const r=[];if(e.recentUserPrompts)for(const i of e.recentUserPrompts)r.push({id:i.id,content:i.content,timestamp:i.timestamp,sessionId:e.id,sessionName:e.title||e.id});return r}function sD(e){return[...e].sort((s,c)=>new Date(c.timestamp).getTime()-new Date(s.timestamp).getTime()).slice(0,nD).reverse().map(s=>({id:s.id,content:s.content,timestamp:s.timestamp,formattedTimestamp:eD(s.timestamp),trimmedContent:tD(s.content,rD),sessionId:s.sessionId,sessionName:s.sessionName}))}function aD(e,r,i){const s=[],c=e.filter(u=>u.role==="user"&&!u.isSystemGenerated&&u.messageKind!=="auto-prompt");for(const u of c)s.push({id:u.id,content:u.content,timestamp:u.timestamp,sessionId:i??"",sessionName:"This session"});for(const u of r)i&&u.id===i||s.push(...iD(u));return sD(s)}function oD(e,r=[],i=null){const[s,c]=H.useState(0),[u,f]=H.useState(!1),l=H.useMemo(()=>aD(e,r,i),[e,r,i]),d=H.useCallback(()=>{l.length>0&&(c(l.length-1),f(!0))},[l.length]),p=H.useCallback(()=>{f(!1),c(0)},[]),g=H.useCallback(()=>{c(_=>l.length===0?_:_===0?l.length-1:_-1)},[l.length]),m=H.useCallback(()=>{c(_=>l.length===0?_:_===l.length-1?0:_+1)},[l.length]),b=H.useCallback(()=>{if(l.length===0||!u)return null;const _=l[s];return(_==null?void 0:_.content)??null},[l,s,u]);return{history:l,selectedIndex:s,showHistory:u,openHistory:d,closeHistory:p,navigateUp:g,navigateDown:m,selectCurrent:b}}function lD({criteriaSidebarOpen:e,onCriteriaSidebarToggle:r}={}){const i=e??!0,[s,c]=H.useState(""),[u,f]=H.useState([]),[l,d]=H.useState(!1),[p,g]=H.useState(null),[m,b]=H.useState(!1),[_,k]=H.useState(!1),[C,y]=H.useState(!1),[x,v]=H.useState(null),S=H.useRef(null),j=H.useRef(null),T=H.useRef(null),N=Ce(te=>te.currentSession),D=Ce(te=>te.messages),A=Ce(te=>te.streamingMessage),M=Ce(te=>te.sessions),B=Ce(te=>te.error),$=Ce(te=>te.pendingQuestion),V=Lb(),W=Ce(te=>te.sendMessage),O=Ce(te=>te.clearError),F=Ce(te=>te.acceptAndBuild),P=Ce(te=>te.stopGeneration),Z=Ce(te=>te.launchRunner),G=Ce(te=>te.cancelQueued),I=nw(),{showThinking:R,showVerboseToolOutput:z,showStats:Y,showAgentDefinitions:U,showWorkflowBars:ie}=Nb(),Q=Ct(te=>te.defaults),ee=Ct(te=>te.userItems),X=[...Q,...ee],q=Ct(te=>te.fetchWorkflows),oe=kt(te=>te.defaults),re=kt(te=>te.userItems),ve=[...oe,...re].filter(te=>!te.subagent);H.useEffect(()=>{q()},[q]);const{history:be,selectedIndex:Re,showHistory:Ie,openHistory:He,closeHistory:Ue,navigateUp:je,navigateDown:me,selectCurrent:Te}=oD(D,M,N==null?void 0:N.id);H.useEffect(()=>{const te=Ee=>{v(Ee.detail.stats)};return window.addEventListener("open-turn-stats",te),()=>window.removeEventListener("open-turn-stats",te)},[]);const $e=H.useMemo(()=>A?D.map(te=>te.id===A.id?A:te):D,[D,A]),Lt=H.useRef([]),fe=H.useMemo(()=>{const te=J5($e,Lt.current);return Lt.current=te,te},[$e]),Ae=H.useMemo(()=>R5(D),[D]),{force_scroll_to_bottom:Be,isAutoScrollActive:ot,setAutoScroll:ue}=w0(S,N),_e=H.useCallback(()=>{const te=j.current;if(!te)return;te.style.height="auto";const Ee=Math.min(200,te.scrollHeight);te.style.height=`${Ee}px`},[]);H.useEffect(()=>{if(!(N!=null&&N.id))return;const te=`openfox:draft:${N.id}`,Ee=localStorage.getItem(te);Ee!==null&&c(Ee)},[N==null?void 0:N.id]),H.useEffect(()=>{var te;(te=j.current)==null||te.focus(),_e()},[N==null?void 0:N.id,_e]),H.useEffect(()=>{if(!(N!=null&&N.id))return;const te=`openfox:draft:${N.id}`,Ee=setTimeout(()=>{s?localStorage.setItem(te,s):localStorage.removeItem(te)},500);return()=>clearTimeout(Ee)},[N==null?void 0:N.id,s]),H.useEffect(()=>{_e()},[s,_e]),H.useEffect(()=>{const te=Ee=>{Ee.key==="Escape"&&V&&P(),Ee.key==="ScrollLock"&&ue(!ot)};return window.addEventListener("keydown",te),()=>window.removeEventListener("keydown",te)},[V,P,ot]);const Ne=H.useRef(0);H.useEffect(()=>{const te=Ee=>{if(Ee.key==="Shift"&&!Ee.ctrlKey&&!Ee.metaKey&&!Ee.altKey){const Le=Date.now();Le-Ne.current<300?(Ee.preventDefault(),y(!0),Ne.current=0):Ne.current=Le}};return window.addEventListener("keydown",te),()=>window.removeEventListener("keydown",te)},[]),H.useEffect(()=>{const te=j.current;if(!te)return;const Ee=async Le=>{var Mt;if(document.activeElement!==te)return;const Ve=(Mt=Le.clipboardData)==null?void 0:Mt.items;if(Ve){for(const gn of Array.from(Ve))if(gn.type.startsWith("image/")){Le.preventDefault();const fr=gn.getAsFile();if(!fr)continue;await ah(fr,$i=>f(Br=>[...Br,$i]),g,{filename:"pasted-image"})}}};return te.addEventListener("paste",Ee),()=>te.removeEventListener("paste",Ee)},[]);const Oe=()=>{c(""),f([]),N!=null&&N.id&&localStorage.removeItem(`openfox:draft:${N.id}`)},qe=async te=>{te.preventDefault(),!(!s.trim()&&u.length===0)&&(Be(),W(s,u.length>0?u:void 0),Oe())},Nt=te=>{if((te.ctrlKey||te.metaKey)&&te.code.startsWith("Digit")){const Le=parseInt(te.code.slice(-1),10)-1,Ve=ve[Le];Ve&&(te.preventDefault(),Ce.getState().switchMode(Ve.id));return}if(Ie)switch(te.key){case"Enter":te.preventDefault();const Ee=Te();Ee&&(c(Ee),Ue());return;case"Escape":te.preventDefault(),Ue(),V&&P();return;case"ArrowUp":te.preventDefault(),je();return;case"ArrowDown":te.preventDefault(),me();return}if(te.key==="ArrowUp"&&s.trim()===""&&!Ie){te.preventDefault(),He();return}te.key==="Enter"&&!te.shiftKey&&(te.preventDefault(),qe(te))},Ze=H.useCallback(async te=>{const Ee=te.target.files;if(!(!Ee||Ee.length===0)){g(null);for(const Le of Array.from(Ee))await ah(Le,Ve=>f(Mt=>[...Mt,Ve]),g);T.current&&(T.current.value="")}},[]),Ot=H.useCallback(te=>{te.preventDefault(),te.stopPropagation(),d(!0)},[]),Tt=H.useCallback(te=>{te.preventDefault(),te.stopPropagation(),d(!1)},[]),Yt=H.useCallback(async te=>{te.preventDefault(),te.stopPropagation(),d(!1),g(null);const Ee=te.dataTransfer.files;if(!(!Ee||Ee.length===0))for(const Le of Array.from(Ee))await ah(Le,Ve=>f(Mt=>[...Mt,Ve]),g)},[]),lt=H.useCallback(te=>{f(Ee=>Ee.filter(Le=>Le.id!==te))},[]),Bn=H.useCallback(()=>{var te;(te=T.current)==null||te.click()},[]),Xt=(N==null?void 0:N.mode)==="planner",Us=(N==null?void 0:N.mode)==="builder",pe=((N==null?void 0:N.criteria.length)??0)>0,ye=(N==null?void 0:N.phase)==="done",we=fe.some(te=>te.type==="message"&&te.message.role==="assistant"),We=Xt&&pe&&!V&&we&&!ye,Qe=te=>{const Ee=s.trim()?s:void 0,Le=u.length>0?u:void 0;Xt?F(te,Ee,Le):Us&&Z(Ee,Le,te),Oe()};return o.jsxs(ZC,{criteriaSidebarOpen:i,onCriteriaSidebarToggle:r,messages:$e,children:[$&&o.jsx(g5,{question:$}),o.jsx(e2,{}),x&&o.jsx(a5,{stats:x,onClose:()=>v(null)}),o.jsx(x5,{}),o.jsxs("div",{ref:S,"data-testid":"chat-scroll-container",className:"flex-1 min-w-0 overflow-y-auto relative",children:[o.jsx("div",{className:"pt-4",children:fe.map((te,Ee)=>{if(te.type==="context-divider")return o.jsxs("div",{className:"flex items-center gap-2 feed-item px-2 md:px-4",children:[o.jsx("div",{className:"flex-1 border-t border-border"}),o.jsx("span",{className:"text-[10px] text-text-muted font-medium px-2",children:"Earlier context summarized"}),o.jsx("div",{className:"flex-1 border-t border-border"})]},Ee);if(te.type==="subagent"){const gn=te.messages.some(fr=>fr.isStreaming);return o.jsx("div",{className:"px-2 md:px-4",children:o.jsx(u5,{messages:te.messages,subAgentType:te.subAgentType,subAgentId:te.subAgentId,isStreaming:gn})},Ee)}if(te.type==="criteria-batch")return o.jsx("div",{className:"feed-item px-2 md:px-4",children:o.jsx(_0,{toolCalls:te.toolCalls,criteria:N==null?void 0:N.criteria})},Ee);const Le=te.message;if(Le.role==="assistant")return o.jsx("div",{className:"px-2 md:px-4",children:o.jsx(bf,{message:Le,showStats:Y,showThinking:R,showVerboseToolOutput:z})},Ee);const Ve=!U&&Le.messageKind==="auto-prompt",Mt=!ie&&(Le.messageKind==="workflow-started"||Le.messageKind==="task-completed");return Ve||Mt?null:o.jsx("div",{className:"px-2 md:px-4",children:o.jsx(S0,{message:Le,isLastAssistantMessage:!1,promptContext:Le.role==="user"?Ae[Le.id]:void 0})},Ee)})}),o.jsxs("div",{className:"px-2 md:px-4 pb-4",children:[B&&o.jsx("div",{className:"feed-item bg-red-500/10 border border-red-500/50 rounded p-2",children:o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-red-400 text-sm font-medium",children:B.code}),o.jsx("div",{className:"text-red-300 text-xs mt-0.5",children:B.message})]}),o.jsx(Ja,{onClick:O,className:"text-red-400 hover:text-red-300 p-0.5",size:"sm"})]})}),We&&o.jsx("div",{className:"flex justify-center gap-2 feed-item flex-wrap",children:X.map(te=>{const Ee=te.color??"#3b82f6",Le=parseInt(Ee.slice(1,3),16),Ve=parseInt(Ee.slice(3,5),16),Mt=parseInt(Ee.slice(5,7),16),gn=`rgba(${Le},${Ve},${Mt},0.12)`,fr=`rgba(${Le},${Ve},${Mt},0.22)`,$i=`rgba(${Le},${Ve},${Mt},0.25)`;return o.jsxs("button",{onClick:()=>F(te.id),className:"px-4 py-1.5 rounded text-sm font-medium transition-colors",style:{backgroundColor:gn,color:Ee,border:`1px solid ${$i}`},onMouseEnter:Br=>{Br.currentTarget.style.backgroundColor=fr},onMouseLeave:Br=>{Br.currentTarget.style.backgroundColor=gn},children:["▶ ",te.name]},te.id)})}),V&&o.jsx(v5,{})]})]}),o.jsxs("form",{onSubmit:qe,className:"relative p-2 md:p-4 border-t border-border bg-gradient-to-t from-bg-secondary/50 to-transparent",children:[o.jsxs("button",{type:"button",className:"absolute -top-8 right-2 md:right-4 text-sm text-text-muted hover:text-text-primary z-10 flex items-center gap-1.5",onClick:()=>ue(!ot),children:[o.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${ot?"bg-accent-success":"border border-text-muted"}`}),"live"]}),o.jsx("input",{ref:T,type:"file",accept:".png,.jpg,.jpeg,.gif",onChange:Ze,className:"hidden",multiple:!0}),p&&o.jsx("div",{className:"mb-2 p-2 bg-red-500/10 border border-red-500/50 rounded text-red-300 text-sm",children:p}),u.length>0&&o.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:u.map(te=>o.jsx(b5,{attachment:te,onRemove:lt},te.id))}),Ie&&o.jsx(y5,{history:be,selectedIndex:Re,onSelect:te=>{c(te),Ue()},onEscape:Ue,onNavigate:te=>{te==="up"?je():me()}}),I.length>0&&o.jsx("div",{className:"mb-2 flex flex-wrap gap-1.5",children:I.map(te=>o.jsxs("div",{className:`inline-flex items-center gap-1.5 px-2 py-1 rounded text-xs ${te.mode==="asap"?"bg-amber-500/15 text-amber-300 border border-amber-500/30":"bg-blue-500/15 text-blue-300 border border-blue-500/30"}`,children:[o.jsxs("span",{className:"font-medium",children:[te.mode==="asap"?"ASAP":"Queue",":"]}),o.jsx("span",{className:"truncate max-w-[200px]",children:te.content}),o.jsx(Ja,{onClick:()=>G(te.queueId),size:"sm"})]},te.queueId))}),o.jsxs("div",{className:`flex items-end gap-3 p-3 rounded border transition-colors ${l?"border-accent-primary/50 bg-accent-primary/10":"border-border bg-bg-tertiary/50"}`,onDragOver:Ot,onDragLeave:Tt,onDrop:Yt,children:[o.jsx("button",{type:"button",onClick:Bn,className:"p-3 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"Attach image file",children:o.jsx(aw,{})}),o.jsx("textarea",{ref:j,value:s,onChange:te=>{c(te.target.value),Ie&&Ue()},onKeyDown:Nt,placeholder:"What would you like to build?",className:"flex-1 bg-transparent text-sm placeholder:text-text-muted resize-none overflow-y-auto focus:outline-none",style:{minHeight:"24px",maxHeight:"200px"},spellCheck:!1}),o.jsxs("div",{className:"flex flex-col items-end gap-1",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx(H5,{onSendCommand:(te,Ee,Le,Ve)=>{var gn;Ee&&(N==null?void 0:N.mode)!==Ee&&Ce.getState().switchMode(Ee);const Mt=Le&&Le.trim()?`${Le.trim()}
|
|
150
150
|
|
|
151
151
|
${te}`:te;(gn=S.current)==null||gn.scrollTo({top:S.current.scrollHeight,behavior:"smooth"}),W(Mt,Ve!=null&&Ve.length?Ve:void 0,{messageKind:"command",isSystemGenerated:!0}),Oe()},onOpenManager:()=>b(!0),textareaContent:s,attachments:u.length>0?u:void 0}),o.jsx(K5,{onSelectWorkflow:Qe,onOpenManager:()=>k(!0),criteria:(N==null?void 0:N.criteria)??[]})]}),o.jsx("div",{className:"flex items-center gap-2",children:o.jsx("button",{type:"button",onClick:()=>{var te;!s.trim()&&u.length===0||((te=S.current)==null||te.scrollTo({top:S.current.scrollHeight,behavior:"smooth"}),W(s,u),Oe())},disabled:!s.trim()&&u.length===0,className:"px-4 py-1.5 rounded bg-accent-primary/20 text-sm text-accent-primary font-medium hover:bg-accent-primary/30 disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:"Send"})})]})]}),o.jsxs("div",{className:"mt-3 flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(p5,{}),o.jsx(m5,{})]}),o.jsx(I5,{})]})]}),o.jsx(k0,{isOpen:m,onClose:()=>b(!1)}),o.jsx(O0,{isOpen:_,onClose:()=>k(!1)}),o.jsx(X5,{isOpen:C,onClose:()=>y(!1),textareaContent:s,onCloseComplete:()=>{var te;return(te=j.current)==null?void 0:te.focus()},onCloseCompleteAction:()=>window.dispatchEvent(new CustomEvent("open-session-dropdown")),onSelectCommand:async(te,Ee)=>{const Le=await on.getState().fetchCommand(te);if(Le){const Ve=Ee!=null&&Ee.trim()?`${Ee.trim()}
|
|
152
152
|
|