openfox 1.6.44 → 1.6.46
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/{auto-compaction-7SL3LN75.js → auto-compaction-GI4VMKB2.js} +4 -4
- package/dist/{chat-handler-O2MS6N7K.js → chat-handler-UYAJHFNJ.js} +6 -6
- package/dist/{chunk-P6GUT2QQ.js → chunk-4DNPYFL4.js} +3 -3
- package/dist/{chunk-57Q2NVVZ.js → chunk-AVMBAUH2.js} +19 -19
- package/dist/{chunk-KSASIV4B.js → chunk-F2VWCCMC.js} +5 -5
- package/dist/{chunk-PYBB34ZK.js → chunk-HYIQFRYJ.js} +9 -6
- package/dist/{chunk-J6YKMO3O.js → chunk-LN5RMI7G.js} +6 -6
- package/dist/{chunk-7F3V7C23.js → chunk-MY66TLAH.js} +7 -5
- package/dist/{chunk-CJNQGEYG.js → chunk-VCALN543.js} +2 -2
- package/dist/{chunk-IHBD5H7A.js → chunk-W62DI5UK.js} +2 -2
- package/dist/{chunk-D4ZLSV6P.js → chunk-WNZIUQ2L.js} +8 -6
- package/dist/cli/dev.js +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/{config-ACVEHBKG.js → config-3TU54V4X.js} +5 -5
- package/dist/{orchestrator-7TPFEM3P.js → orchestrator-WQDVNDB3.js} +5 -5
- package/dist/package.json +1 -1
- package/dist/{processor-EFJ7OJEL.js → processor-7V5FI5X7.js} +2 -2
- package/dist/{protocol-Ct6VfOIJ.d.ts → protocol-_A3Upt5b.d.ts} +1 -0
- package/dist/{provider-RLQMVV2Z.js → provider-J4G7XBDP.js} +7 -7
- package/dist/{serve-Z2THSAIR.js → serve-G3XDWOPI.js} +9 -9
- package/dist/server/index.d.ts +10 -1
- package/dist/server/index.js +7 -7
- package/dist/shared/index.d.ts +2 -2
- package/dist/{tools-A3NNFIKG.js → tools-QXQGYZ4D.js} +4 -4
- package/dist/{vision-fallback-QJ26DCEF.js → vision-fallback-HXPTLQHN.js} +2 -2
- package/dist/web/assets/{index-BMZ3A90k.js → index-BPG5tJZc.js} +2 -2
- package/dist/web/assets/{index-CM8X_jzI.css → index-DFE4PMXP.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: `+f.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 Mx;function b1(){if(Mx)return Hd;Mx=1;var e=ic();function r(m,b){return m===b&&(m!==0||1/m===1/b)||m!==m&&b!==b}var s=typeof Object.is=="function"?Object.is:r,i=e.useState,l=e.useEffect,u=e.useLayoutEffect,h=e.useDebugValue;function c(m,b){var S=b(),k=i({inst:{value:S,getSnapshot:b}}),C=k[0].inst,y=k[1];return u(function(){C.value=S,C.getSnapshot=b,d(C)&&y({inst:C})},[m,S,b]),l(function(){return d(C)&&y({inst:C}),m(function(){d(C)&&y({inst:C})})},[m]),h(S),S}function d(m){var b=m.getSnapshot;m=m.value;try{var S=b();return!s(m,S)}catch{return!0}}function p(m,b){return b()}var g=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?p:c;return Hd.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:g,Hd}var Ix;function y1(){return Ix||(Ix=1,Pd.exports=b1()),Pd.exports}var _1=y1();const S1=a1.useInsertionEffect,w1=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",C1=w1?H.useLayoutEffect:H.useEffect,k1=S1||C1,jb=e=>{const r=H.useRef([e,(...s)=>r[0](...s)]).current;return k1(()=>{r[0]=e}),r[1]},E1="popstate",Oh="pushState",Mh="replaceState",j1="hashchange",Bx=[E1,Oh,Mh,j1],N1=e=>{for(const r of Bx)addEventListener(r,e);return()=>{for(const r of Bx)removeEventListener(r,e)}},Nb=(e,r)=>_1.useSyncExternalStore(N1,e,r),zx=()=>location.search,T1=({ssrSearch:e}={})=>Nb(zx,e!=null?()=>e:zx),Px=()=>location.pathname,A1=({ssrPath:e}={})=>Nb(Px,e!=null?()=>e:Px),D1=(e,{replace:r=!1,state:s=null}={})=>history[r?Mh:Oh](s,"",e),L1=(e={})=>[A1(e),D1],Hx=Symbol.for("wouter_v3");if(typeof history<"u"&&typeof window[Hx]>"u"){for(const e of[Oh,Mh]){const r=history[e];history[e]=function(){const s=r.apply(this,arguments),i=new Event(e);return i.arguments=arguments,dispatchEvent(i),s}}Object.defineProperty(window,Hx,{value:!0})}const R1=(e,r)=>r.toLowerCase().indexOf(e.toLowerCase())?"~"+r:r.slice(e.length)||"/",Tb=(e="")=>e==="/"?"":e,O1=(e,r)=>e[0]==="~"?e.slice(1):Tb(r)+e,M1=(e="",r)=>R1(Fx(Tb(e)),Fx(r)),Fx=e=>{try{return decodeURI(e)}catch{return e}},Ab={hook:L1,searchHook:T1,parser:v1,base:"",ssrPath:void 0,ssrSearch:void 0,ssrContext:void 0,hrefs:e=>e,aroundNav:(e,r,s)=>e(r,s)},Db=H.createContext(Ab),Vi=()=>H.useContext(Db),Lb={},Rb=H.createContext(Lb),I1=()=>H.useContext(Rb),ac=e=>{const[r,s]=e.hook(e);return[M1(e.base,r),jb((i,l)=>e.aroundNav(s,O1(i,e.base),l))]},vr=()=>ac(Vi()),Ih=(e,r,s,i)=>{const{pattern:l,keys:u}=r instanceof RegExp?{keys:!1,pattern:r}:e(r||"*",i),h=l.exec(s)||[],[c,...d]=h;return c!==void 0?[!0,(()=>{const p=u!==!1?Object.fromEntries(u.map((m,b)=>[m,d[b]])):h.groups;let g={...d};return p&&Object.assign(g,p),g})(),...i?[c]:[]]:[!1,null]},Bh=e=>Ih(Vi().parser,e,vr()[0]),B1=({children:e,...r})=>{var g,m,b;const s=Vi(),i=r.hook?Ab:s;let l=i;const[u,h=r.ssrSearch??""]=((g=r.ssrPath)==null?void 0:g.split("?"))??[];u&&(r.ssrSearch=h,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 c=H.useRef({}),d=c.current,p=d;for(let S in i){const k=S==="base"?i[S]+(r[S]??""):r[S]??i[S];d===p&&k!==p[S]&&(c.current=p={...p}),p[S]=k,(k!==i[S]||k!==l[S])&&(l=p)}return H.createElement(Db.Provider,{value:l,children:e})},Ux=({children:e,component:r},s)=>r?H.createElement(r,{params:s}):typeof e=="function"?e(s):e,z1=e=>{let r=H.useRef(Lb);const s=r.current;return r.current=Object.keys(e).length!==Object.keys(s).length||Object.entries(e).some(([i,l])=>l!==s[i])?e:s},Fa=({path:e,nest:r,match:s,...i})=>{const l=Vi(),[u]=ac(l),[h,c,d]=s??Ih(l.parser,e,u,r),p=z1({...I1(),...c});if(!h)return null;const g=d?H.createElement(B1,{base:d},Ux(i,p)):Ux(i,p);return H.createElement(Rb.Provider,{value:p,children:g})},Fn=H.forwardRef((e,r)=>{const s=Vi(),[i,l]=ac(s),{to:u="",href:h=u,onClick:c,asChild:d,children:p,className:g,replace:m,state:b,transition:S,...k}=e,C=jb(v=>{v.ctrlKey||v.metaKey||v.altKey||v.shiftKey||v.button!==0||(c==null||c(v),v.defaultPrevented||(v.preventDefault(),l(h,e)))}),y=s.hrefs(h[0]==="~"?h.slice(1):s.base+h,s);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(i===h):g,children:p,ref:r})}),Ob=e=>Array.isArray(e)?e.flatMap(r=>Ob(r&&r.type===H.Fragment?r.props.children:r)):[e],P1=({children:e,location:r})=>{const s=Vi(),[i]=ac(s);for(const l of Ob(e)){let u=0;if(H.isValidElement(l)&&(u=Ih(s.parser,l.props.path,r||i,l.props.nest))[0])return H.cloneElement(l,{match:u})}return null};function H1(e){return typeof e=="object"&&e!==null&&"type"in e&&"payload"in e}function Mb(){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 F1{constructor(r){hr(this,"ws",null);hr(this,"handlers",new Set);hr(this,"statusHandler",null);hr(this,"baseUrl");hr(this,"isReconnecting",!1);hr(this,"connectingPromise",null);hr(this,"lastCloseCode",0);hr(this,"reconnectAttempts",0);hr(this,"manualReconnectScheduled",!1);this.baseUrl=r}getUrl(){const r=localStorage.getItem("openfox_token");if(r){const s=this.baseUrl.includes("?")?"&":"?";return`${this.baseUrl}${s}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,s;return((r=this.ws)==null?void 0:r.readyState)===WebSocket.OPEN?Promise.resolve():(this.lastCloseCode=0,this.isReconnecting=!1,this.connectingPromise&&((s=this.ws)==null?void 0:s.readyState)===WebSocket.CONNECTING?this.connectingPromise:(this.connectingPromise=new Promise((i,l)=>{try{const u=this.getUrl();this.ws=new WebSocket(u);const h=setTimeout(()=>{var c;((c=this.ws)==null?void 0:c.readyState)===WebSocket.CONNECTING&&(this.ws.close(),l(new Error("Connection timeout")))},5e3);this.ws.onopen=()=>{var c;clearTimeout(h),this.isReconnecting=!1,this.connectingPromise=null,(c=this.statusHandler)==null||c.call(this,"connected"),i()},this.ws.onclose=c=>{var d,p,g;clearTimeout(h),this.lastCloseCode=c.code,((d=this.ws)==null?void 0:d.readyState)===WebSocket.CONNECTING?(this.connectingPromise=null,(p=this.statusHandler)==null||p.call(this,"disconnected"),l(new Error(`Connection closed: ${c.code}`))):(this.connectingPromise=null,(g=this.statusHandler)==null||g.call(this,"disconnected"),this.attemptReconnect())},this.ws.onerror=c=>{clearTimeout(h),console.error("WebSocket error:",c),this.connectingPromise=null,l(c)},this.ws.onmessage=c=>{try{const d=JSON.parse(c.data);H1(d)&&this.handlers.forEach(p=>p(d))}catch(d){console.error("Failed to parse WebSocket message:",d)}}}catch(u){this.connectingPromise=null,l(u)}}),this.connectingPromise))}attemptReconnect(){var l;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,(l=this.statusHandler)==null||l.call(this,"reconnecting");const i=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(()=>{})},i)}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,s){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");const i=Mb(),l={id:i,type:r,payload:s};return this.ws.send(JSON.stringify(l)),i}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 U1=`ws://${window.location.hostname}:${window.location.port||"10469"}/ws`,Vt=new F1(U1),xs=async(e,r,s)=>{try{const i=await ke(r,{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return i.ok?{success:!0}:{success:!1,error:(await i.json()).error}}catch{return{success:!1,error:"Network error"}}};function Ib(e){let r=null;function s(){r===null&&(r=requestAnimationFrame(()=>{r=null,e()}))}return s}let Ml=[];const mr=$n()((e,r)=>{function s(){if(Ml.length===0)return;const l=Ml;Ml=[],e(u=>({logs:[...u.logs,...l]}))}const i=Ib(s);return{workdir:null,status:null,logs:[],config:null,loading:!1,setWorkdir:l=>{r().workdir!==l&&(e({workdir:l,status:null,logs:[],config:null,loading:!0}),l&&(r().fetchStatus(),r().fetchConfig()))},fetchStatus:async()=>{const l=r().workdir;if(l)try{const h=await(await ke(`/api/dev-server?workdir=${encodeURIComponent(l)}`)).json();e({status:h,loading:!1})}catch{e({loading:!1})}},fetchConfig:async()=>{const l=r().workdir;if(l)try{const h=await(await ke(`/api/dev-server/config?workdir=${encodeURIComponent(l)}`)).json();e({config:h.config??null})}catch{}},fetchLogs:async()=>{const l=r().workdir;if(l)try{const c=(await(await ke(`/api/dev-server/logs?workdir=${encodeURIComponent(l)}`)).json()).logs.map(d=>({stream:d.stream,content:d.content}));e({logs:c})}catch{}},start:async()=>{const l=r().workdir;if(l)try{const h=await(await ke(`/api/dev-server/start?workdir=${encodeURIComponent(l)}`,{method:"POST"})).json();e({status:h,logs:[]})}catch{}},stop:async()=>{const l=r().workdir;if(l)try{const h=await(await ke(`/api/dev-server/stop?workdir=${encodeURIComponent(l)}`,{method:"POST"})).json();e({status:h})}catch{}},restart:async()=>{const l=r().workdir;if(l)try{const h=await(await ke(`/api/dev-server/restart?workdir=${encodeURIComponent(l)}`,{method:"POST"})).json();e({status:h,logs:[]})}catch{}},saveConfig:async l=>{const u=r().workdir;if(u)try{const c=await(await ke(`/api/dev-server/config?workdir=${encodeURIComponent(u)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})).json();e({config:c.config??l}),r().fetchStatus()}catch{}},handleMessage:l=>{const u=r().workdir;if(u)switch(l.type){case"devServer.output":{const h=l.payload;if(h.workdir!==u)return;Ml.push({stream:h.stream,content:h.content}),i();break}case"devServer.state":{const h=l.payload;if(h.workdir!==u)return;e(c=>({status:c.status?{...c.status,state:h.state,errorMessage:h.errorMessage}:c.status}));break}}}}});function $1(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 $x(e,r,s){const i=await ke(`/api/providers/${e}/models/${encodeURIComponent(r)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!i.ok){const l=await i.json();throw new Error(l.error??"Failed to update model")}return i.json()}function qx(e,r,s,i){return e.map(l=>l.id===r?{...l,models:l.models.map(u=>u.id===s?{...u,...i,source:"user"}:u)}:l)}const q1=3e4;function W1(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 Lt=$n((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 s=await ke("/api/config");if(!s.ok)throw new Error("Failed to fetch config");const i=await s.json();e({version:i.version,model:i.model,maxContext:i.maxContext,llmUrl:i.llmUrl,llmStatus:i.llmStatus,backend:i.backend,providers:i.providers??[],activeProviderId:i.activeProviderId??null,defaultModelSelection:i.defaultModelSelection??null,loading:!1})}catch(s){e({error:s instanceof Error?s.message:"Unknown error",loading:!1})}},refreshModel:async()=>{try{const s=await ke("/api/model/refresh",{method:"POST"});if(!s.ok)throw new Error("Failed to refresh model");const i=await s.json(),u=Ce.getState().currentSession;if(u!=null&&u.providerId&&u.providerModel){e({llmStatus:i.llmStatus,backend:i.backend});return}e({model:i.model,llmStatus:i.llmStatus,backend:i.backend})}catch(s){console.error("Failed to refresh model:",s)}},activateProvider:async s=>{const{activeProviderId:i,providers:l}=r();if(s===i)return!0;e({activating:!0,error:null});try{const u=await ke(`/api/providers/${s}/activate`,{method:"POST"});if(!u.ok){const c=await u.json();throw new Error(c.error??"Failed to activate provider")}const h=await u.json();return e({activeProviderId:h.activeProviderId,model:h.model,backend:h.backend,providers:l.map(c=>({...c,isActive:c.id===h.activeProviderId})),activating:!1}),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to switch provider",activating:!1}),!1}},syncFromSession:(s,i)=>{const{providers:l}=r();e({activeProviderId:s,model:i,defaultModelSelection:`${s}/${i}`,providers:l.map(u=>({...u,isActive:u.id===s}))})},updateModelContext:async(s,i,l)=>{e({activating:!0,error:null});try{const u=await $x(s,i,{contextWindow:l}),{providers:h}=r();return e({providers:qx(h,s,i,{contextWindow: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 context",activating:!1}),!1}},updateModelSettings:async(s,i,l)=>{e({activating:!0,error:null});try{const u=await $x(s,i,l),{providers:h}=r(),c={...l.contextWindow!==void 0&&{contextWindow:l.contextWindow},...$1({temperature:l.temperature??void 0,topP:l.topP??void 0,topK:l.topK??void 0,maxTokens:l.maxTokens??void 0})};return e({providers:qx(h,s,i,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 settings",activating:!1}),!1}},refreshProviderModels:async s=>{e({activating:!0,error:null});try{const i=await ke(`/api/providers/${s}/refresh`,{method:"POST"});if(!i.ok){const h=await i.json();throw new Error(h.error??"Failed to refresh models")}const l=await i.json(),{providers:u}=r();return e({providers:u.map(h=>h.id===s?{...h,models:l.models}:h),activating:!1}),!0}catch(i){return e({error:i instanceof Error?i.message:"Failed to refresh models",activating:!1}),!1}},startAutoRefresh:()=>{const{autoRefreshInterval:s,refreshModel:i}=r();if(s)return;const l=setInterval(()=>{i()},q1);e({autoRefreshInterval:l})},stopAutoRefresh:()=>{const{autoRefreshInterval:s}=r();s&&(clearInterval(s),e({autoRefreshInterval:null}))},getActiveProvider:()=>{const{providers:s,activeProviderId:i}=r();return s.find(l=>l.id===i)},getModelContext:s=>{const{providers:i,activeProviderId:l}=r(),u=i.find(c=>c.id===l);if(!u)return 2e5;const h=u.models.find(c=>c.id===s);return(h==null?void 0:h.contextWindow)??2e5}})),Qt=$n((e,r)=>({projects:[],currentProject:null,loading:!1,listProjects:async()=>{e({loading:!0});try{const i=await(await ke("/api/projects")).json();e({projects:i.projects??[],loading:!1})}catch{e({loading:!1})}},createProject:async(s,i)=>{try{const l=await ke("/api/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:s,workdir:i})});if(!l.ok)return null;const u=await l.json();return await r().listProjects(),u.project}catch{return null}},loadProject:async s=>{try{const i=await ke(`/api/projects/${s}`);if(!i.ok)return null;const l=await i.json();return e({currentProject:l.project}),r().projects.length===0&&await r().listProjects(),l.project}catch{return null}},updateProject:async(s,i)=>{var l;try{const u=await ke(`/api/projects/${s}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!u.ok)return null;const h=await u.json();return((l=r().currentProject)==null?void 0:l.id)===s&&e({currentProject:h.project}),await r().listProjects(),h.project}catch{return null}},deleteProject:async s=>{var i;try{return(await ke(`/api/projects/${s}`,{method:"DELETE"})).ok?(await r().listProjects(),((i=r().currentProject)==null?void 0:i.id)===s&&e({currentProject:null}),!0):!1}catch{return!1}},clearProject:()=>{e({currentProject:null})}}));let Il=[];const eo=$n()((e,r)=>{function s(){if(Il.length===0)return;const l=Il;Il=[],e(u=>{const h={...u.logs};for(const c of l){const d=h[c.processId]??[];h[c.processId]=[...d,{offset:d.length,content:c.content,timestamp:Date.now(),stream:c.stream}]}return{logs:h}})}const i=Ib(s);return{processes:[],logs:{},loading:!1,setProcesses:l=>e({processes:l}),addProcess:l=>e(u=>({processes:[...u.processes,l]})),updateProcess:(l,u)=>e(h=>({processes:h.processes.map(c=>c.id===l?{...c,...u}:c)})),removeProcess:l=>e(u=>({processes:u.processes.filter(h=>h.id!==l),logs:Object.fromEntries(Object.entries(u.logs).filter(([h])=>h!==l))})),stopProcess:async(l,u)=>{try{(await ke(`/api/sessions/${u}/background-process/${l}/stop`,{method:"POST"})).ok&&r().removeProcess(l)}catch{}},appendLog:(l,u,h)=>{Il.push({processId:l,stream:u,content:h}),i()},setLogs:(l,u)=>e(h=>({logs:{...h.logs,[l]:u}})),clearLogs:l=>e(u=>({logs:{...u.logs,[l]:[]}})),handleMessage:(l,u)=>{switch(l){case"backgroundProcess.started":{const{processId:h,name:c,pid:d,status:p}=u;e(g=>({processes:[...g.processes,{id:h,sessionId:"",name:c,command:"",cwd:"",pid:d,status:p,exitCode:null,createdAt:Date.now(),startedAt:Date.now(),endedAt:null}]}));break}case"backgroundProcess.output":{const h=u.processId,c=u.stream,d=u.content;r().appendLog(h,c,d);break}case"backgroundProcess.exited":{const h=u.processId,c=u.exitCode;e(d=>({processes:d.processes.map(p=>p.id===h?{...p,status:"exited",exitCode:c}:p)}));break}case"backgroundProcess.removed":{const h=u.processId;r().removeProcess(h);break}}}}}),V1=[{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"}],G1=[{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"}],Bb={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"},ms={soundEnabled:!0,browserNotification:!1,customSoundUrl:null},zb={soundEnabled:!1,browserNotification:!1,customSoundUrl:null},ph={soundEnabled:!0,browserNotificationEnabled:!1,events:{complete:{...ms},waiting_for_user:{...ms},phase_done:{...ms},phase_blocked:{...ms},new_message:{...zb}},agentOverrides:{}};function Pb(e,r,s){var u;const i=e.events[r];if(!s)return i;const l=(u=e.agentOverrides[s])==null?void 0:u[r];return l?{soundEnabled:l.soundEnabled??i.soundEnabled,browserNotification:l.browserNotification??i.browserNotification,customSoundUrl:l.customSoundUrl!==void 0?l.customSoundUrl:i.customSoundUrl}:i}const Fs=$n((e,r)=>({settings:ph,loaded:!1,load:()=>{Kt.getState().getSetting(ot.NOTIFICATION_SETTINGS);const i=Kt.subscribe(u=>{const h=u.settings[ot.NOTIFICATION_SETTINGS];if(h!==void 0)try{const c=JSON.parse(h);e({settings:Wx(c),loaded:!0})}catch{e({loaded:!0})}}),l=Kt.getState().settings[ot.NOTIFICATION_SETTINGS];if(l)try{const u=JSON.parse(l);e({settings:Wx(u),loaded:!0})}catch{e({loaded:!0})}return i},update:s=>{e({settings:s}),Fd(s)},updateEvent:(s,i)=>{const l=r().settings,u={...l,events:{...l.events,[s]:{...l.events[s],...i}}};e({settings:u}),Fd(u)},updateAgentOverride:(s,i,l)=>{var d;const u=r().settings,h={...u.agentOverrides};if(l===null){if(h[s]){const p={...h[s]};delete p[i],Object.keys(p).length===0?delete h[s]:h[s]=p}}else h[s]={...h[s],[i]:{...((d=h[s])==null?void 0:d[i])??{},...l}};const c={...u,agentOverrides:h};e({settings:c}),Fd(c)}}));function Fd(e){Kt.getState().setSetting(ot.NOTIFICATION_SETTINGS,JSON.stringify(e))}function Wx(e){var r,s,i,l,u;return{soundEnabled:e.soundEnabled??ph.soundEnabled,browserNotificationEnabled:e.browserNotificationEnabled??ph.browserNotificationEnabled,events:{complete:{...ms,...(r=e.events)==null?void 0:r.complete},waiting_for_user:{...ms,...(s=e.events)==null?void 0:s.waiting_for_user},phase_done:{...ms,...(i=e.events)==null?void 0:i.phase_done},phase_blocked:{...ms,...(l=e.events)==null?void 0:l.phase_blocked},new_message:{...zb,...(u=e.events)==null?void 0:u.new_message}},agentOverrides:e.agentOverrides??{}}}const Vx=new Map;function K1(e){let r=Vx.get(e);return r||(r=new Audio(e),r.volume=.5,Vx.set(e,r)),r}let Hb=typeof Notification<"u"?Notification.permission:"denied";function Y1(){return typeof Notification>"u"?Promise.resolve("denied"):Notification.requestPermission().then(e=>(Hb=e,e))}const X1={complete:"Task Complete",waiting_for_user:"Waiting for Input",phase_done:"Phase Complete",phase_blocked:"Phase Blocked",new_message:"New Message"},Z1={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 Q1(e){typeof Notification>"u"||Hb==="granted"&&(document.hasFocus()||new Notification(X1[e],{body:Z1[e],icon:"/fox.svg",tag:`openfox-${e}`}))}function mo(e,r){const{settings:s}=Fs.getState(),i=Pb(s,e,r);if(s.soundEnabled&&i.soundEnabled){const l=i.customSoundUrl??Bb[e],u=K1(l);u.currentTime=0,u.play().catch(()=>{})}s.browserNotificationEnabled&&i.browserNotification&&Q1(e)}const J1=e=>mo("complete",e),ew=e=>mo("phase_done",e),tw=e=>mo("phase_blocked",e),Gx=e=>mo("waiting_for_user",e),nw=e=>mo("new_message",e);let Ua=!1,fr=null;const Ud=new Set,Wt={messageId:null,deltaContent:"",thinkingContent:"",toolOutput:[]};let Ui=null,mn=null;function $d(){Ui===null&&(Ui=requestAnimationFrame(()=>{Ui=null,mn==null||mn()}))}function Is(){Ui!==null&&(cancelAnimationFrame(Ui),Ui=null)}function Ht(e,r){return r!==null&&e.sessionId===r}function rw(e,r,s){return e.id!==void 0||Ht(e,r)||s===!0&&e.sessionId!==void 0}function sw(e,r){return e.includes(r)?e:[...e,r]}function $a(e,r){return e.filter(s=>s!==r)}function iw(e,r){const s=e.find(l=>l.id===r.id),i=s?{...s,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(l=>l.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(l=>l.status.type==="passed").length,messageCount:r.messages.length};return s?e.map(l=>l.id===r.id?i:l):[i,...e]}function aw(e,r,s){return e.map(i=>{const l=(s==null?void 0:s.id)===i.id?s:null,u=r.find(h=>h.id===i.id);return{...i,title:i.title??(u==null?void 0:u.title),mode:(l==null?void 0:l.mode)??(u==null?void 0:u.mode)??i.mode,phase:(l==null?void 0:l.phase)??(u==null?void 0:u.phase)??i.phase,isRunning:(l==null?void 0:l.isRunning)??(u==null?void 0:u.isRunning)??i.isRunning,messageCount:i.messageCount,recentUserPrompts:i.recentUserPrompts}})}const Kx=new Map;function Qa(e,r){var u;const s=r===((u=e.currentSession)==null?void 0:u.id)?e.currentSession:null,i=e.sessions.find(h=>h.id===r),l=(s==null?void 0:s.mode)??(i==null?void 0:i.mode);return l==="planner"?"planner":l==="builder"?"build":"planner"}function ow(e,r){if(e.type==="chat.done"){const s=e.payload,i=Qa(r,e.sessionId),l=s.agentType??i;s.reason==="complete"&&J1(l),s.reason==="waiting_for_user"&&Gx(l);return}if(e.type==="chat.path_confirmation"){const s=Qa(r,e.sessionId);Gx(s);return}if(e.type==="task.completed"){const s=Qa(r,e.sessionId);ew(s);return}if(e.type==="phase.changed"&&e.sessionId){const s=e.payload,i=Kx.get(e.sessionId)??null;if(Kx.set(e.sessionId,s.phase),i===s.phase)return;const l=Qa(r,e.sessionId);s.phase==="blocked"&&tw(l)}}const Ce=$n((e,r)=>(mn=()=>{const s=Wt;if(!s.messageId)return;const i=s.deltaContent.length>0,l=s.thinkingContent.length>0,u=s.toolOutput.length>0;if(!i&&!l&&!u)return;const h=s.deltaContent,c=s.thinkingContent,d=s.toolOutput;s.deltaContent="",s.thinkingContent="",s.toolOutput=[],e(p=>{var m;const g=p.streamingMessage;if(g&&g.id===s.messageId){let b={...g};if(i&&(b.content=b.content+h),l&&(b.thinkingContent=(b.thinkingContent??"")+c),u){const S=new Set;b.toolCalls=(m=b.toolCalls)==null?void 0:m.map(C=>{const y=d.filter(v=>v.callId===C.id);return y.length===0?C:(S.add(C.id),{...C,streamingOutput:[...C.streamingOutput??[],...y.map(v=>({stream:v.stream,content:v.content,timestamp:Date.now()}))]})});const k=d.filter(C=>!S.has(C.callId));k.length>0&&Wt.toolOutput.push(...k)}return{streamingMessage:b}}if(u){const b=new Set,S=p.messages.map(C=>{var v;if(C.id!==s.messageId)return C;const y=(v=C.toolCalls)==null?void 0:v.map(x=>{const _=d.filter(j=>j.callId===x.id);return _.length===0?x:(b.add(x.id),{...x,streamingOutput:[...x.streamingOutput??[],..._.map(j=>({stream:j.stream,content:j.content,timestamp:Date.now()}))]})});return{...C,toolCalls:y}}),k=d.filter(C=>!b.has(C.callId));return k.length>0&&Wt.toolOutput.push(...k),{messages:S}}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()=>{if(r().connectionStatus==="connected")return;e({connectionStatus:"reconnecting"});let i=!1;try{i=(await(await ke("/api/auth")).json()).requiresAuth}catch{}if(i&&!Vt.hasToken()){e({showPasswordModal:!0,passwordModalRetry:!1,connectionStatus:"reconnecting"});return}Vt.onStatusChange(l=>{var u;if(e({connectionStatus:l}),l==="connected"){r().listSessions(void 0);const h=(u=r().currentSession)==null?void 0:u.id;h&&r().loadSession(h)}});try{if(await Vt.connect(),!Ua){Ua=!0;const l=r().handleServerMessage;fr=Vt.subscribe(l)}}catch(l){console.error("Failed to connect:",l);const u=Vt.getLastCloseCode();if(!Vt.hasToken()&&(u===1006||u===4e3)){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}fr&&(fr(),fr=null),Ua=!1,e({connectionStatus:"disconnected"})}},reconnect:()=>{Vt.disconnect(),fr&&(fr(),fr=null),Ua=!1,e({connectionStatus:"disconnected"}),r().connect()},disconnect:()=>{Vt.disconnect(),fr&&(fr(),fr=null),Ua=!1,e({connectionStatus:"disconnected",showPasswordModal:!1})},submitPassword:async s=>{try{const i=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:s})});if(!i.ok){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}const{token:l}=await i.json();Vt.setToken(l),e({showPasswordModal:!1}),r().connect();const{listProjects:u}=Qt.getState(),{fetchConfig:h}=Lt.getState();u(),h(),r().connect()}catch{e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"})}},cancelPassword:()=>{Vt.clearToken(),e({showPasswordModal:!1,connectionStatus:"disconnected"})},createSession:async(s,i)=>{try{e({pendingSessionCreate:!0});const l=await ke("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectId:s,title:i})});if(!l.ok)return e({pendingSessionCreate:!1}),null;const u=await l.json();return Vt.send("session.load",{sessionId:u.session.id}),u.session}catch{return e({pendingSessionCreate:!1}),null}},loadSession:async s=>{try{const i=r().currentSession;!i||i.id!==s?(Is(),e({currentSession:null,unreadSessionIds:$a(r().unreadSessionIds,s),subAgentContextStates:{},messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,pendingPathConfirmation:null,queuedMessages:[],abortInProgress:!1,error:null})):e({unreadSessionIds:$a(r().unreadSessionIds,s)});const l=await ke(`/api/sessions/${s}`);if(!l.ok)return;const u=await l.json();e({currentSession:u.session,messages:u.messages??[],contextState:u.contextState,queuedMessages:u.queueState??[]}),Vt.send("session.load",{sessionId:s});try{const h=await ke(`/api/sessions/${s}/background-processes`);if(h.ok){const c=await h.json();eo.getState().setProcesses(c.processes??[])}}catch{}}catch{}},listSessions:async(s,i=20)=>{try{const l=new URLSearchParams;l.set("limit",String(i)),s&&l.set("projectId",s);const h=await(await ke(`/api/sessions?${l.toString()}`)).json();e({sessions:h.sessions??[],sessionsHasMore:s?h.hasMore??!1:!0})}catch{}},loadMoreSessions:async s=>{const i=r();if(!(i.sessionsPaginationLoading||!i.sessionsHasMore)){e({sessionsPaginationLoading:!0});try{const l=new URLSearchParams;l.set("limit","20"),l.set("offset",String(i.sessions.length)),l.set("projectId",s);const h=await(await ke(`/api/sessions?${l.toString()}`)).json();e(c=>({sessions:[...c.sessions,...h.sessions??[]],sessionsHasMore:h.hasMore??!1,sessionsPaginationLoading:!1}))}catch{e({sessionsPaginationLoading:!1})}}},deleteSession:async s=>{var i;try{return(await ke(`/api/sessions/${s}`,{method:"DELETE"})).ok?(await r().listSessions(),((i=r().currentSession)==null?void 0:i.id)===s&&r().clearSession(),!0):!1}catch{return!1}},deleteAllSessions:async s=>{try{return(await ke(`/api/projects/${s}/sessions`,{method:"DELETE"})).ok?(await r().listSessions(),!0):!1}catch{return!1}},clearSession:()=>{Is(),e(s=>({currentSession:null,messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,unreadSessionIds:s.currentSession?$a(s.unreadSessionIds,s.currentSession.id):s.unreadSessionIds}))},sendMessage:async(s,i,l)=>{var h;const u=(h=r().currentSession)==null?void 0:h.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:s,attachments:i,messageKind:l==null?void 0:l.messageKind})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(c){console.error("Error sending message:",c)}}},stopGeneration:async()=>{var i;const s=(i=r().currentSession)==null?void 0:i.id;if(s&&!r().abortInProgress){Is(),mn==null||mn(),e({abortInProgress:!0});try{await ke(`/api/sessions/${s}/stop`,{method:"POST"})}catch(l){console.error("Error stopping generation:",l)}}},continueGeneration:async()=>{var i;const s=(i=r().currentSession)==null?void 0:i.id;if(s){e({streamingMessageId:null});try{await ke(`/api/sessions/${s}/continue`,{method:"POST"})}catch(l){console.error("Error continuing generation:",l)}}},launchRunner:(s,i,l)=>{e({streamingMessageId:null});const u={};s!=null&&s.trim()&&(u.content=s),i&&i.length>0&&(u.attachments=i),l&&(u.workflowId=l),Vt.send("runner.launch",u)},switchMode:async s=>{var l;const i=(l=r().currentSession)==null?void 0:l.id;if(i)try{const u=await ke(`/api/sessions/${i}/mode`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:s})});if(!u.ok){console.error("Failed to switch mode:",await u.json());return}const h=await u.json();h.session&&e({currentSession:h.session})}catch(u){console.error("Error switching mode:",u)}},switchDangerLevel:async s=>{var l;const i=(l=r().currentSession)==null?void 0:l.id;if(i)try{const u=await ke(`/api/sessions/${i}/danger-level`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({dangerLevel:s})});if(!u.ok){console.error("Failed to switch danger level:",await u.json());return}const h=await u.json();h.session&&e({currentSession:h.session})}catch(u){console.error("Error switching danger level:",u)}},acceptAndBuild:(s,i,l)=>{e({streamingMessageId:null});const u={};s&&(u.workflowId=s),i!=null&&i.trim()&&(u.content=i),l&&l.length>0&&(u.attachments=l),Vt.send("mode.accept",u)},editCriteria:async s=>{var l;const i=(l=r().currentSession)==null?void 0:l.id;if(i)try{const u=await ke(`/api/sessions/${i}/criteria`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({criteria:s})});u.ok||console.error("Failed to update criteria:",await u.json())}catch(u){console.error("Error updating criteria:",u)}},compactContext:()=>{Vt.send("context.compact",{})},setSessionProvider:async(s,i)=>{var l;try{const u=(l=r().currentSession)==null?void 0:l.id;if(!u)return null;const h=await ke(`/api/sessions/${u}/provider`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerId:s,...i?{model:i}:{}})});if(!h.ok)return null;const c=await h.json();return e({currentSession:c.session,messages:c.messages??[],contextState:c.contextState}),c.session}catch{return null}},updateContextState:s=>{e({contextState:s})},updateSubAgentContextState:(s,i)=>{e(l=>({subAgentContextStates:{...l.subAgentContextStates,[s]:i}}))},clearSubAgentContextState:s=>{e(i=>{const l={...i.subAgentContextStates};return delete l[s],{subAgentContextStates:l}})},confirmPath:async(s,i,l=!1)=>{var h;const u=(h=r().currentSession)==null?void 0:h.id;if(u)try{await ke(`/api/sessions/${u}/confirm-path`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:s,approved:i,alwaysAllow:l})})}catch(c){console.error("Error confirming path:",c)}},answerQuestion:async(s,i)=>{var u;const l=(u=r().currentSession)==null?void 0:u.id;if(l){try{await ke(`/api/sessions/${l}/answer`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:s,answer:i})})}catch(h){console.error("Error answering question:",h)}e({pendingQuestion:null})}},queueAsap:async(s,i,l)=>{var h;const u=(h=r().currentSession)==null?void 0:h.id;if(u)try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:s,attachments:i,messageKind:l})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(c){console.error("Error queueing ASAP message:",c)}},queueCompletion:async(s,i,l)=>{var h;const u=(h=r().currentSession)==null?void 0:h.id;if(u)try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:s,attachments:i,messageKind:l})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(c){console.error("Error queueing completion message:",c)}},cancelQueued:async s=>{var l;const i=(l=r().currentSession)==null?void 0:l.id;if(i)try{const h=await(await ke(`/api/sessions/${i}/queue/${s}`,{method:"DELETE"})).json();h.queueState&&e({queuedMessages:h.queueState})}catch(u){console.error("Error canceling queued message:",u)}},clearError:()=>{e({error:null})},resetPendingSessionCreate:()=>{e({pendingSessionCreate:!1})},handleServerMessage:s=>{var h,c,d,p,g,m,b,S,k,C,y,v,x,_,j,T,N,D,A,z,O,q,G,W;const i=r();ow(s,i);const l=((h=i.currentSession)==null?void 0:h.id)??null,u=()=>{const I=s.sessionId;!I||I===l||e($=>({unreadSessionIds:sw($.unreadSessionIds,I)}))};switch(s.type){case"session.state":{const I=s.payload;if(!rw(s,l,i.pendingSessionCreate))break;Is();const $=I.messages.find(R=>R.isStreaming)??null,B=r().pendingSessionCreate===!0,X=I.pendingConfirmations??[],P=i.pendingPathConfirmation??(X.length>0?X[0]??null:null);if(e({currentSession:I.session,sessions:iw(r().sessions,I.session),unreadSessionIds:$a(r().unreadSessionIds,I.session.id),messages:I.messages,streamingMessageId:($==null?void 0:$.id)??null,streamingMessage:$,currentTodos:[],pendingPathConfirmation:P,error:null,...B?{pendingSessionCreate:I.session.id}:{}}),I.session.providerId&&I.session.providerModel){const R=Lt.getState();R.providers.find(U=>U.id===I.session.providerId)&&R.syncFromSession(I.session.providerId,I.session.providerModel)}break}case"session.list":{const I=s.payload;e($=>({sessions:aw(I.sessions,$.sessions,$.currentSession)}));break}case"session.deleted":{const I=s.payload;e($=>({unreadSessionIds:$a($.unreadSessionIds,I.sessionId)})),r().listSessions();break}case"session.deletedAll":{r().listSessions();break}case"session.running":{const I=s.payload,$=s.sessionId,B=(c=r().currentSession)==null?void 0:c.id,X=$&&$!==B;e(Z=>({sessions:Z.sessions.map(P=>P.id===$?{...P,isRunning:I.isRunning}:P)})),X||e(Z=>({currentSession:Z.currentSession?{...Z.currentSession,isRunning:I.isRunning}:null,...I.isRunning?{}:{abortInProgress:!1,queuedMessages:[]}}));break}case"chat.message":{if(!Ht(s,((d=r().currentSession)==null?void 0:d.id)??null)){u();break}const I=s.payload;e($=>$.messages.some(B=>B.id===I.message.id)?$:{messages:[...$.messages,I.message],streamingMessageId:I.message.isStreaming?I.message.id:$.streamingMessageId,streamingMessage:I.message.isStreaming?I.message:$.streamingMessage});break}case"chat.message_updated":{if(!Ht(s,((p=r().currentSession)==null?void 0:p.id)??null)){u();break}const I=s.payload,$=I.updates.isStreaming===!1&&r().streamingMessageId===I.messageId;$&&(Is(),mn==null||mn()),e(B=>{const X=B.streamingMessage,Z=$;if(X&&X.id===I.messageId){const P={...X,...I.updates};return{messages:B.messages.map(R=>R.id===I.messageId?P:R),streamingMessageId:Z?null:B.streamingMessageId,streamingMessage:Z?null:{...X,...I.updates}}}return{messages:B.messages.map(P=>P.id===I.messageId?{...P,...I.updates}:P),streamingMessageId:Z?null:B.streamingMessageId}});break}case"chat.delta":{if(!Ht(s,((g=r().currentSession)==null?void 0:g.id)??null)){u();break}const I=s.payload;if(!Ud.has(I.messageId)){Ud.add(I.messageId);const $=Qa(r(),s.sessionId);nw($)}Wt.messageId=I.messageId,Wt.deltaContent+=I.content,$d();break}case"chat.thinking":{if(!Ht(s,((m=r().currentSession)==null?void 0:m.id)??null)){u();break}const I=s.payload;Wt.messageId=I.messageId,Wt.thinkingContent+=I.content,$d();break}case"chat.tool_preparing":{if(!Ht(s,((b=r().currentSession)==null?void 0:b.id)??null)){u();break}const I=s.payload;e($=>{const B=$.streamingMessage;return B&&B.id===I.messageId?{streamingMessage:{...B,preparingToolCalls:[...B.preparingToolCalls??[],{index:I.index,name:I.name}]}}:{messages:$.messages.map(X=>X.id===I.messageId?{...X,preparingToolCalls:[...X.preparingToolCalls??[],{index:I.index,name:I.name}]}:X)}});break}case"chat.tool_call":{if(!Ht(s,((S=r().currentSession)==null?void 0:S.id)??null)){u();break}const I=s.payload,$=B=>{var P;const X=(P=B.preparingToolCalls)==null?void 0:P.filter((R,L)=>{var U;return R.name===I.tool?(U=B.preparingToolCalls)==null?void 0:U.slice(0,L).some(ne=>ne.name===I.tool):!0}),Z=Wt.toolOutput.filter(R=>R.callId===I.callId);return Z.length>0&&(Wt.toolOutput=Wt.toolOutput.filter(R=>R.callId!==I.callId)),{...B,toolCalls:[...B.toolCalls??[],{id:I.callId,name:I.tool,arguments:I.args,startedAt:Date.now(),...Z.length>0?{streamingOutput:Z.map(R=>({stream:R.stream,content:R.content,timestamp:Date.now()}))}:{}}],...X&&X.length>0?{preparingToolCalls:X}:{preparingToolCalls:void 0}}};e(B=>{const X=B.streamingMessage;return X&&X.id===I.messageId?{streamingMessage:$(X)}:{messages:B.messages.map(Z=>Z.id===I.messageId?$(Z):Z)}});break}case"chat.tool_output":{if(!Ht(s,((k=r().currentSession)==null?void 0:k.id)??null)){u();break}const I=s.payload;Wt.messageId=I.messageId,Wt.toolOutput.push({messageId:I.messageId,callId:I.callId,stream:I.stream,content:I.output}),$d();break}case"chat.tool_result":{if(!Ht(s,((C=r().currentSession)==null?void 0:C.id)??null)){u();break}const I=s.payload,$=B=>{var Z;const X=(Z=B.toolCalls)==null?void 0:Z.map(P=>P.id===I.callId?{...P,result:I.result}:P);return{...B,toolCalls:X}};e(B=>{const X=B.streamingMessage;return X&&X.id===I.messageId?{streamingMessage:$(X)}:{messages:B.messages.map(Z=>Z.id===I.messageId?$(Z):Z)}});break}case"chat.vision_fallback":{if(!Ht(s,((y=r().currentSession)==null?void 0:y.id)??null)){u();break}const I=s.payload;e($=>{const B=`${I.messageId}-${I.attachmentId}`,X={...$.visionFallbackByMessage};return X[B]={type:I.type,attachmentId:I.attachmentId,filename:I.filename,description:I.description},{visionFallbackByMessage:X}});break}case"chat.todo":{if(!Ht(s,((v=r().currentSession)==null?void 0:v.id)??null)){u();break}const I=s.payload;e({currentTodos:I.todos});break}case"chat.summary":{if(!Ht(s,((x=r().currentSession)==null?void 0:x.id)??null)){u();break}const I=s.payload;e($=>({currentSession:$.currentSession?{...$.currentSession,summary:I.summary}:null}));break}case"chat.progress":{if(!Ht(s,((_=r().currentSession)==null?void 0:_.id)??null)){u();break}const I=s.payload;console.log("Progress:",I.message,I.phase);break}case"chat.format_retry":{if(!Ht(s,((j=r().currentSession)==null?void 0:j.id)??null)){u();break}const I=s.payload;console.log("Format retry:",I.attempt,"/",I.maxAttempts);break}case"chat.done":{if(!Ht(s,((T=r().currentSession)==null?void 0:T.id)??null)){u();break}Is(),mn==null||mn();const I=s.payload,$=I.stats;Wt.messageId=null,Wt.deltaContent="",Wt.thinkingContent="",Wt.toolOutput=[],Ud.delete(I.messageId),e(B=>{const X=B.streamingMessage,Z=X&&X.id===I.messageId?{...X,isStreaming:!1,stats:$??X.stats}:null;return{messages:B.messages.map(P=>P.id===I.messageId?Z??{...P,isStreaming:!1,stats:$??P.stats}:P),streamingMessageId:null,streamingMessage:null,visionFallbackByMessage:{}}});break}case"chat.error":{if(!Ht(s,((N=r().currentSession)==null?void 0:N.id)??null)){u();break}Is(),mn==null||mn();const I=s.payload;console.error("Chat error:",I.error,"recoverable:",I.recoverable),I.recoverable||(Wt.messageId=null,Wt.deltaContent="",Wt.thinkingContent="",Wt.toolOutput=[]),e($=>({error:{code:"CHAT_ERROR",message:I.error},streamingMessageId:I.recoverable?$.streamingMessageId:null,...I.recoverable?{}:{messages:$.streamingMessage?$.messages.map(B=>B.id===$.streamingMessage.id?$.streamingMessage:B):$.messages,streamingMessage:null}}));break}case"chat.path_confirmation":{if(!Ht(s,((D=r().currentSession)==null?void 0:D.id)??null)){u();break}const I=s.payload;e({pendingPathConfirmation:{callId:I.callId,tool:I.tool,paths:I.paths,workdir:I.workdir,reason:I.reason}});break}case"chat.ask_user":{if(!Ht(s,((A=r().currentSession)==null?void 0:A.id)??null)){u();return}const I=s.payload;e({pendingQuestion:{callId:I.callId,question:I.question}});break}case"mode.changed":{if(!Ht(s,((z=r().currentSession)==null?void 0:z.id)??null)){u();break}const I=s.payload;e($=>({currentSession:$.currentSession?{...$.currentSession,mode:I.mode}:null}));break}case"phase.changed":{const I=s.payload,$=s.sessionId,B=(O=r().currentSession)==null?void 0:O.id,X=$&&$!==B;e(Z=>({sessions:Z.sessions.map(P=>P.id===$?{...P,phase:I.phase}:P)})),X||e(Z=>({currentSession:Z.currentSession?{...Z.currentSession,phase:I.phase}:null}));break}case"criteria.updated":{if(!Ht(s,((q=r().currentSession)==null?void 0:q.id)??null)){u();break}const I=s.payload;e($=>({currentSession:$.currentSession?{...$.currentSession,criteria:I.criteria}:null}));break}case"context.state":{const I=s.payload,$=Ht(s,((G=r().currentSession)==null?void 0:G.id)??null);I.subAgentId?$&&r().updateSubAgentContextState(I.subAgentId,I.context):$?e({contextState:I.context}):u();break}case"session.name_generated":{const I=s.payload,$=s.sessionId,B=(W=r().currentSession)==null?void 0:W.id;e(X=>{const Z=X.sessions.map(R=>R.id===$?{...R,title:I.name,updatedAt:new Date().toISOString()}:R),P=B===$?X.currentSession?{...X.currentSession,title:I.name,updatedAt:new Date().toISOString()}:null:X.currentSession;return{sessions:Z,currentSession:P}});break}case"queue.state":{const I=s.payload;e({queuedMessages:I.messages});break}case"devServer.output":case"devServer.state":{mr.getState().handleMessage(s);break}case"backgroundProcess.started":case"backgroundProcess.output":case"backgroundProcess.exited":case"backgroundProcess.removed":{eo.getState().handleMessage(s.type,s.payload);break}case"error":{const I=s.payload;console.error("Server error:",I),e({error:{code:I.code,message:I.message},streamingMessageId:null});break}}}}));function Fb(){return Ce(e=>{var r;return((r=e.currentSession)==null?void 0:r.isRunning)??!1})}function lw(){return Ce(e=>e.queuedMessages)}function cw(){return Ce(e=>e.abortInProgress)}function uw(){const e=Ce(i=>i.connect),r=Ce(i=>i.connectionStatus),s=Fs(i=>i.load);return H.useEffect(()=>{e()},[e]),H.useEffect(()=>{r==="connected"&&s()},[r,s]),{connectionStatus:r}}const dw="modulepreload",hw=function(e){return"/"+e},Yx={},mh=function(r,s,i){let l=Promise.resolve();if(s&&s.length>0){let h=function(p){return Promise.all(p.map(g=>Promise.resolve(g).then(m=>({status:"fulfilled",value:m}),m=>({status:"rejected",reason:m}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),d=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));l=h(s.map(p=>{if(p=hw(p),p in Yx)return;Yx[p]=!0;const g=p.endsWith(".css"),m=g?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${m}`))return;const b=document.createElement("link");if(b.rel=g?"stylesheet":dw,g||(b.as="script"),b.crossOrigin="",b.href=p,d&&b.setAttribute("nonce",d),document.head.appendChild(b),g)return new Promise((S,k)=>{b.addEventListener("load",S),b.addEventListener("error",()=>k(new Error(`Unable to preload CSS for ${p}`)))})}))}function u(h){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=h,window.dispatchEvent(c),!c.defaultPrevented)throw h}return l.then(h=>{for(const c of h||[])c.status==="rejected"&&u(c.reason);return r().catch(u)})},Ub=[{key:"color-bg-primary",category:"background",label:"Primary Background",defaultValue:"13 17 23"},{key:"color-bg-secondary",category:"background",label:"Secondary Background",defaultValue:"22 27 34"},{key:"color-bg-tertiary",category:"background",label:"Tertiary Background",defaultValue:"33 38 45"},{key:"color-primary",category:"surface",label:"Primary Surface",defaultValue:"10 10 10"},{key:"color-secondary",category:"surface",label:"Secondary Surface",defaultValue:"20 20 20"},{key:"color-text-primary",category:"text",label:"Primary Text",defaultValue:"139 148 158"},{key:"color-text-secondary",category:"text",label:"Secondary Text",defaultValue:"139 148 158"},{key:"color-text-muted",category:"text",label:"Muted Text",defaultValue:"72 79 88"},{key:"color-accent-primary",category:"accent",label:"Primary Accent",defaultValue:"88 166 255"},{key:"color-accent-success",category:"accent",label:"Success Accent",defaultValue:"63 185 80"},{key:"color-accent-warning",category:"accent",label:"Warning Accent",defaultValue:"210 153 34"},{key:"color-accent-error",category:"accent",label:"Error Accent",defaultValue:"248 81 73"},{key:"color-border",category:"border",label:"Border",defaultValue:"48 53 60"}],gr=[{id:"dark",name:"Dark",tokens:{"color-bg-primary":"13 17 23","color-bg-secondary":"22 27 34","color-bg-tertiary":"33 38 45","color-primary":"10 10 10","color-secondary":"20 20 20","color-text-primary":"139 148 158","color-text-secondary":"139 148 158","color-text-muted":"72 79 88","color-accent-primary":"88 166 255","color-accent-success":"63 185 80","color-accent-warning":"210 153 34","color-accent-error":"248 81 73","color-border":"48 53 60"}},{id:"light",name:"Light",tokens:{"color-bg-primary":"255 255 255","color-bg-secondary":"250 251 252","color-bg-tertiary":"243 244 246","color-primary":"245 245 245","color-secondary":"229 229 229","color-text-primary":"15 23 42","color-text-secondary":"30 41 59","color-text-muted":"100 116 139","color-accent-primary":"37 99 235","color-accent-success":"22 163 74","color-accent-warning":"217 119 6","color-accent-error":"220 38 38","color-border":"203 213 225"}},{id:"monokai",name:"Monokai",tokens:{"color-bg-primary":"39 40 34","color-bg-secondary":"30 31 28","color-bg-tertiary":"62 61 50","color-primary":"30 31 28","color-secondary":"45 46 39","color-text-primary":"248 248 242","color-text-secondary":"207 207 194","color-text-muted":"117 113 94","color-accent-primary":"102 217 239","color-accent-success":"166 226 46","color-accent-warning":"230 219 116","color-accent-error":"249 38 114","color-border":"73 72 62"}},{id:"dracula",name:"Dracula",tokens:{"color-bg-primary":"40 42 54","color-bg-secondary":"33 34 44","color-bg-tertiary":"68 71 90","color-primary":"30 31 41","color-secondary":"44 46 61","color-text-primary":"248 248 242","color-text-secondary":"230 230 230","color-text-muted":"98 114 164","color-accent-primary":"189 147 249","color-accent-success":"80 250 123","color-accent-warning":"255 184 108","color-accent-error":"255 85 85","color-border":"68 71 90"}},{id:"nord",name:"Nord",tokens:{"color-bg-primary":"46 52 64","color-bg-secondary":"59 66 82","color-bg-tertiary":"67 76 94","color-primary":"46 52 64","color-secondary":"59 66 82","color-text-primary":"236 239 244","color-text-secondary":"229 233 240","color-text-muted":"76 86 106","color-accent-primary":"129 161 193","color-accent-success":"163 190 140","color-accent-warning":"235 203 139","color-accent-error":"191 97 106","color-border":"76 86 106"}}];function Xx(){try{const e=localStorage.getItem("openfox:userPresets");if(e)return JSON.parse(e)}catch{}return[]}const dn=$n((e,r)=>({currentPreset:"dark",basePreset:"",customTokens:{},isCustom:!1,isCustomizing:!1,userPresets:Xx(),applySavedTheme:()=>{const{getSavedTheme:s,applyPreset:i,applyTokens:l}=r(),u=s();if(u)try{const h=JSON.parse(u);h.preset?i(h.preset):h.tokens&&l(h.tokens)}catch{i("dark")}else i("dark")},applyPreset:s=>{gr.find(l=>l.id===s)&&(e({currentPreset:s,basePreset:"",customTokens:{},isCustom:!1,isCustomizing:!1}),r().applyTheme())},startCustomizing:()=>{var l;const{currentPreset:s}=r(),i=((l=gr.find(u=>u.id===s))==null?void 0:l.tokens)??{};e({basePreset:s,customTokens:{...i},isCustom:!0,isCustomizing:!0})},setCustomToken:(s,i)=>{e(l=>({customTokens:{...l.customTokens,[s]:i}})),r().applyTheme()},cancelCustomizing:()=>{r().applyPreset(r().basePreset||r().currentPreset)},saveCustomTheme:()=>{const{customTokens:s}=r();r().saveTheme(JSON.stringify({tokens:s})),e({isCustomizing:!1})},applyTokens:s=>{e({customTokens:s,isCustom:!0,isCustomizing:!1}),r().applyTheme()},getActiveTheme:()=>{var h,c;const{basePreset:s,customTokens:i,isCustom:l}=r();if(l&&s)return{...((h=gr.find(p=>p.id===s))==null?void 0:h.tokens)??{},...i};if(l)return{...Ub.reduce((d,p)=>({...d,[p.key]:p.defaultValue}),{}),...i};const u=gr.find(d=>d.id===r().currentPreset);return(u==null?void 0:u.tokens)??((c=gr[0])==null?void 0:c.tokens)??{}},applyTheme:()=>{if(typeof document>"u")return;const s=r().getActiveTheme(),i=document.documentElement;Object.entries(s).forEach(([l,u])=>{i.style.setProperty(`--${l}`,u)})},getSavedTheme:()=>{try{const s=localStorage.getItem("openfox:theme");if(s){const i=JSON.parse(s);if(i.preset)return JSON.stringify({preset:i.preset});if(i.tokens)return JSON.stringify({tokens:i.tokens})}}catch{return null}return null},saveTheme:s=>{localStorage.setItem("openfox:theme",s),mh(async()=>{const{useSettingsStore:i}=await Promise.resolve().then(()=>Ox);return{useSettingsStore:i}},void 0).then(({useSettingsStore:i})=>{i.getState().setSetting(ot.DISPLAY_THEME,s).catch(()=>{})})},clearCustomTheme:()=>{localStorage.removeItem("openfox:theme"),e({isCustom:!1,isCustomizing:!1,basePreset:""})},reset:()=>{e({currentPreset:"dark",basePreset:"",customTokens:{},isCustom:!1,isCustomizing:!1,userPresets:[]})},addUserPreset:s=>{const{basePreset:i,customTokens:l,currentPreset:u}=r(),h={id:"custom-"+Date.now(),name:s,basePreset:i||u,tokens:{...l}},c=[...r().userPresets,h];e({userPresets:c}),r().saveUserPresets()},applyUserPreset:s=>{const i=r().userPresets[s];i&&(e({currentPreset:i.basePreset,basePreset:i.basePreset,customTokens:{...i.tokens},isCustom:!0,isCustomizing:!1}),r().applyTheme(),r().saveTheme(JSON.stringify({tokens:i.tokens})))},deleteUserPreset:s=>{const i=r().userPresets.filter((l,u)=>u!==s);e({userPresets:i}),r().saveUserPresets()},loadUserPresets:()=>{e({userPresets:Xx()})},saveUserPresets:()=>{localStorage.setItem("openfox:userPresets",JSON.stringify(r().userPresets)),mh(async()=>{const{useSettingsStore:s}=await Promise.resolve().then(()=>Ox);return{useSettingsStore:s}},void 0).then(({useSettingsStore:s})=>{s.getState().setSetting(ot.DISPLAY_USER_PRESETS,JSON.stringify(r().userPresets)).catch(()=>{})})}}));function fw({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 $b({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 pw({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 mw({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 gw({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 Ur({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 xr({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 xw({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 oc({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 vw({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 zh({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 lc({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 Yl({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 bw({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 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 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"})})}function _w({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 Sw({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 ww({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 Zx({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 qb({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 Cw({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 kw({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 Wb({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 Vb({className:e="",size:r="md"}){const s=r==="sm"?"w-4 h-4":"w-6 h-6";return o.jsxs("svg",{className:`animate-spin ${s} ${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 Gb=Vb,Kb=Vb;function Ew({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 jw({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 Nw({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 Tw({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 Aw({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 Dw({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 Lw({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 Yb({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 Xb(){return o.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})})}function Rw({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 Zb({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 Ph({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 Ow({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 gh(){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 Qx(e,r){const s=Vt.ws;!s||s.readyState!==WebSocket.OPEN||s.send(JSON.stringify({id:gh(),type:e,payload:r}))}const ir=$n((e,r)=>({isOpen:!1,sessions:[],workdir:null,setOpen:s=>e({isOpen:s}),toggleOpen:()=>e(s=>({isOpen:!s.isOpen})),setWorkdir:s=>e({workdir:s}),fetchSessions:async()=>{try{const s=await ke("/api/terminals");if(s.ok){const i=await s.json();e({sessions:i});const l=Vt.ws;if(l&&l.readyState===WebSocket.OPEN)for(const u of i)l.send(JSON.stringify({id:gh(),type:"terminal.subscribe",payload:{sessionId:u.id}}))}}catch(s){console.error("Failed to fetch terminals:",s)}},createSession:async s=>{try{const i=await ke("/api/terminals",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workdir:s??r().workdir??void 0})});if(i.ok){const l=await i.json();e(h=>({sessions:[...h.sessions,l]}));const u=Vt.ws;u&&u.readyState===WebSocket.OPEN&&u.send(JSON.stringify({id:gh(),type:"terminal.subscribe",payload:{sessionId:l.id}}))}}catch(i){console.error("Failed to create terminal:",i)}},writeSession:(s,i)=>{Qx("terminal.write",{sessionId:s,data:i})},resizeSession:(s,i,l)=>{Qx("terminal.resize",{sessionId:s,cols:i,rows:l})},killSession:async s=>{try{(await ke(`/api/terminals/${s}`,{method:"DELETE"})).ok&&e(l=>({sessions:l.sessions.filter(u=>u.id!==s)}))}catch(i){console.error("Failed to kill terminal:",i)}},handleMessage:s=>{switch(s.type){case"terminal.exit":{const{sessionId:i}=s.payload||{};i&&e(l=>{const u=l.sessions.filter(h=>h.id!==i);return u.length===0&&l.isOpen?{sessions:[],isOpen:!1}:{sessions:u}});break}}}}));Vt.subscribe(e=>{var r;(r=e.type)!=null&&r.startsWith("terminal.")&&ir.getState().handleMessage(e)});var go=kb();const cc=H.forwardRef(({icon:e,iconSize:r="w-3.5 h-3.5",className:s="",...i},l)=>o.jsx("button",{ref:l,type:"button",className:`p-1 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors ${s}`,...i,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})})}));cc.displayName="IconButton";const Mw="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",qi=H.forwardRef((e,r)=>o.jsx(cc,{ref:r,icon:Mw,title:"Edit",...e}));qi.displayName="EditButton";const Iw="M6 18L18 6M6 6l12 12",Hh=H.forwardRef((e,r)=>o.jsx(cc,{ref:r,icon:Iw,...e}));Hh.displayName="CloseButton";const Bw={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:s="md",minHeight:i,children:l,footer:u,className:h,onClose:c,isOpen:d,closeOnBackdropClick:p=!0,closeOnEscape:g=!0,showCloseButton:m=!0}){const[b,S]=H.useState(!1),k=d!==void 0,C=k?d:b,y=H.useCallback(()=>{k||S(!0)},[k]),v=H.useCallback(()=>{k||S(!1),c==null||c()},[k,c]);H.useEffect(()=>{if(!C||!g)return;const _=j=>{j.key==="Escape"&&v()};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[C,v,g]);const x=e&&(typeof e=="string"?o.jsx("button",{type:"button",onClick:y,className:h,children:e}):o.jsx("span",{onClick:y,className:h,style:{cursor:"pointer"},children:e}));return o.jsxs(o.Fragment,{children:[x,C&&(typeof document<"u"?go.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?v:void 0}),o.jsxs("div",{className:`relative w-full ${Bw[s]} 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(Hh,{onClick:v,className:"ml-auto","aria-label":"Close"})]}),o.jsx("div",{className:"p-4 overflow-y-auto flex-1 min-h-0",style:i?{minHeight:i}:void 0,children:l}),u&&o.jsx("div",{className:"px-4 py-3 border-t border-border",children:u})]})]}),document.body):null)]})}const st=H.forwardRef(({variant:e="secondary",size:r="md",className:s="",children:i,...l},u)=>{const h="rounded font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed",c={primary:"bg-accent-primary/25 text-text-primary 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:`${h} ${c[e]} ${d[r]} ${s}`,...l,children:i})});st.displayName="Button";function zw({value:e,defaultUrl:r,disabled:s,onChange:i}){const l=e??r;return o.jsxs("div",{className:"relative",children:[o.jsx("select",{value:l,disabled:s,onChange:u=>{const h=u.target.value;i(h===r?null:h)},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:G1.map(({url:u,label:h})=>o.jsx("option",{value:u,title:h,children:h.split(" ")[0]},u))}),o.jsx(xr,{className:"absolute right-0.5 top-1/2 -translate-y-1/2 w-3 h-3 pointer-events-none text-text-muted"})]})}const Jx=[{key:"general",label:"General"},{key:"build",label:"Agent"},{key:"sub-agent",label:"Sub-agent"}];function Pw(){const e=Fs(d=>d.settings),r=Fs(d=>d.update),s=Fs(d=>d.updateEvent),i=Fs(d=>d.updateAgentOverride),l=Fs(d=>d.load);H.useEffect(()=>{l()},[l]);const u=async()=>{await Y1()==="granted"&&r({...e,browserNotificationEnabled:!0})},h=(d,p,g,m)=>{d==="general"?s(p,{[g]:m}):i(d,p,{[g]:m})},c=(d,p,g)=>{d==="general"?s(p,{customSoundUrl:g}):i(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(ev,{label:"Sound notifications",description:"Play sounds when events occur",checked:e.soundEnabled,onChange:d=>r({...e,soundEnabled:d})}),o.jsx(ev,{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"}),Jx.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:V1.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})}),Jx.map(p=>{const g=Pb(e,d.key,p.key==="general"?void 0:p.key),m=Bb[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=>h(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=>h(p.key,d.key,"browserNotification",b.target.checked),disabled:!e.browserNotificationEnabled,className:"rounded border-border",title:"Browser"})})]}),g.soundEnabled&&e.soundEnabled&&o.jsx(zw,{value:g.customSoundUrl,defaultUrl:m,disabled:!e.soundEnabled,onChange:b=>c(p.key,d.key,b)})]})},p.key)})]},d.key))})]})})]})]})}function ev({label:e,description:r,checked:s,onChange:i}){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 ${s?"bg-accent-primary":"bg-bg-tertiary border border-border"}`,onClick:l=>{l.preventDefault(),i(!s)},children:o.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white shadow transition-transform ${s?"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 Fh(e,r){r({loading:!0});try{const i=await(await ke(e)).json();r({defaults:i.defaults??[],userItems:i.userItems??[],loading:!1})}catch{r({loading:!1})}}const Pr=$n((e,r)=>({defaults:[],userItems:[],loading:!1,fetchSkills:async()=>{await Fh("/api/skills",e)},toggleSkill:async s=>{try{const l=await(await ke(`/api/skills/${s}/toggle`,{method:"POST"})).json();e(u=>({defaults:u.defaults.map(h=>h.id===s?{...h,enabled:l.enabled}:h),userItems:u.userItems.map(h=>h.id===s?{...h,enabled:l.enabled}:h)}))}catch{}},fetchSkill:async s=>{try{const i=await ke(`/api/skills/${s}`);return i.ok?await i.json():null}catch{return null}},fetchDefaultContent:async s=>{try{const i=await ke(`/api/skills/defaults/${s}`);return i.ok?await i.json():null}catch{return null}},createSkill:async s=>{const i=await xs("POST","/api/skills",s);return i.success&&await r().fetchSkills(),i},updateSkill:async(s,i)=>{const l=await xs("PUT",`/api/skills/${s}`,i);return l.success&&await r().fetchSkills(),l},deleteSkill:async s=>{try{const i=await ke(`/api/skills/${s}`,{method:"DELETE"}),l=await i.json();return i.ok?(e(u=>({userItems:u.userItems.filter(h=>h.id!==s)})),{success:!0}):{success:!1,error:l.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateSkill:async s=>{try{const i=await ke(`/api/skills/${s}/duplicate`,{method:"POST"}),l=await i.json();return i.ok?(await r().fetchSkills(),{success:!0}):{success:!1,error:l.error??"Failed to duplicate"}}catch{return{success:!1,error:"Network error"}}}}));function Uh(){const[e,r]=H.useState({id:null,type:null}),s=H.useCallback(u=>r({id:u,type:"delete"}),[]),i=H.useCallback(()=>r({id:null,type:null}),[]),l=H.useCallback((u,h)=>e.id===u&&e.type===h,[e.id,e.type]);return{requestDelete:s,clearConfirm:i,isConfirming:l}}function $h({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 qh({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(Yb,{})})}function io({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(oc,{})})}function Us({label:e,value:r,onChange:s,placeholder:i,readOnly:l,hint:u,mono:h}){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:c=>s(c.target.value),readOnly:l,placeholder:i,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 ${h?"font-mono":""} ${l?"opacity-60":""}`})]})}function Hw({onCancel:e,onSave:r,saving:s,saveDisabled:i}){return o.jsxs("div",{className:"flex justify-end gap-2 pt-2 border-t border-border",children:[o.jsx(st,{variant:"secondary",onClick:e,children:"Cancel"}),o.jsx(st,{variant:"primary",onClick:r,disabled:s||i,children:s?"Saving...":"Save"})]})}function Wh({message:e}){return o.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded",children:e})}function Qb({description:e,onNew:r,newLabel:s="+ 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(st,{variant:"primary",size:"sm",onClick:r,children:s})})]})}function Jb({isBuiltIn:e,isConfirmingDelete:r,onView:s,onEdit:i,onDuplicate:l,onDelete:u,children:h}){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:h}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[e&&s&&o.jsx("button",{onClick:s,className:"p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",title:"View",children:o.jsx(lc,{})}),o.jsx(io,{onClick:l}),!e&&i&&o.jsx(qi,{onClick:i}),!e&&(r?o.jsx($h,{onConfirm:()=>{u==null||u()},onCancel:()=>{}}):o.jsx(qh,{onClick:()=>u==null?void 0:u()}))]})]})}function Fw({id:e,name:r,description:s,isBuiltIn:i,isConfirmingDelete:l,onView:u,onEdit:h,onDuplicate:c,onDelete:d}){return o.jsxs(Jb,{isBuiltIn:i,isConfirmingDelete:l,onView:u,onEdit:h,onDuplicate:c,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})]}),s&&o.jsx("p",{className:"text-text-muted text-xs truncate",children:s})]})}function ey({loading:e,hasItems:r,loadingLabel:s,emptyLabel:i,children:l}){return e&&!r?o.jsx("div",{className:"text-text-muted text-sm",children:s}):r?o.jsx("div",{className:"space-y-4",children:l}):i?o.jsx("div",{className:"text-text-muted text-sm",children:i}):null}function ty({name:e,id:r,nameLabel:s="Name",idLabel:i="ID",namePlaceholder:l="My Item",idPlaceholder:u="my-item",nameHint:h,readOnlyId:c=!1,readOnlyHint:d="(read-only)",onNameChange:p,onIdChange:g}){return o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Us,{label:s,value:e,onChange:p,placeholder:l,hint:h}),o.jsx(Us,{label:i,value:r,onChange:g,readOnly:c,placeholder:u,hint:c?d:void 0,mono:!0})]})}function ny(e={}){const{initialData:r={}}=e,[s,i]=H.useState("list"),[l,u]=H.useState(null),[h,c]=H.useState(""),[d,p]=H.useState(!1),[g,m]=H.useState(r),b=H.useCallback(()=>{m(r),c(""),u(null)},[r]),S=H.useCallback(v=>{i(v),v==="list"&&b()},[b]),k=H.useCallback(v=>{m(x=>typeof v=="function"?v(x):v)},[]),C=H.useCallback((v,x={})=>{u(v),i("edit"),m({...x}),c("")},[]),y=H.useCallback(()=>{u(null),i("edit"),m(r),c("")},[r]);return{view:s,editingId:l,formError:h,saving:d,formData:g,setView:S,setEditingId:u,setFormError:c,setFormData:k,setSaving:p,resetForm:b,startEditing:C,startNew:y}}function Vh(){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 tv({skill:e,isBuiltIn:r,isConfirmingDelete:s,onView:i,onEdit:l,onDuplicate:u,onDelete:h}){return o.jsx(Fw,{id:e.id,name:e.name,description:e.description,isBuiltIn:r,isConfirmingDelete:s,onView:i,onEdit:l,onDuplicate:u,onDelete:h})}function Uw({isOpen:e}){const r=Pr(I=>I.defaults),s=Pr(I=>I.userItems),i=Pr(I=>I.loading),l=Pr(I=>I.fetchSkills),u=Pr(I=>I.fetchSkill),h=Pr(I=>I.fetchDefaultContent),c=Pr(I=>I.createSkill),d=Pr(I=>I.updateSkill),p=Pr(I=>I.deleteSkill),{view:g,editingId:m,formError:b,saving:S,formData:k,setView:C,setEditingId:y,setFormError:v,setFormData:x,setSaving:_}=ny(),{clearConfirm:j}=Uh();H.useEffect(()=>{e&&(l(),C("list"),y(null),j())},[e,l,j]);const T=(I,$,B,X)=>{x({name:X??I.metadata.name,id:B??I.metadata.id,description:I.metadata.description??"",version:I.metadata.version??"1.0.0",prompt:I.prompt,isReadOnly:$})},N=async I=>{if(r.some(B=>B.id===I)){const B=await h(I);if(!B)return;T(B,!0),y(I),v(""),C("edit")}else{const B=await u(I);if(!B)return;T(B,!0),y(I),v(""),C("edit")}},D=async I=>{const B=r.some(Z=>Z.id===I)?await h(I):await u(I);if(!B)return;const X=`${I}-copy-${Date.now()}`;T(B,!1,X,`${B.metadata.name} (copy)`),y(null),v(""),C("edit")},A=()=>{x({name:"",id:"",description:"",version:"1.0.0",prompt:"",isReadOnly:!1}),C("edit")},z=async I=>{const $=await u(I);$&&(T($,!1),y(I),v(""),C("edit"))},O=async I=>{await p(I),j()},q=async()=>{const I=m??k.id;if(!I||!k.name||!k.prompt){v("Name, ID, and prompt are required.");return}_(!0),v("");const $={metadata:{id:I,name:k.name,description:k.description,version:k.version},prompt:k.prompt},B=m?await d(m,$):await c($);if(_(!1),!B.success){v(B.error??"Failed to save skill.");return}C("list")},G=I=>{x($=>({...$,name:I})),m||x($=>({...$,id:I.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(Wh,{message:b}),o.jsxs("div",{className:"space-y-3 mb-3",children:[o.jsx(ty,{name:k.name,id:k.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Skill",idPlaceholder:"my-skill",readOnlyId:!0,onNameChange:G,onIdChange:()=>{}}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Us,{label:"Description",value:k.description,onChange:I=>x($=>({...$,description:I})),placeholder:"What this skill does...",readOnly:W}),o.jsx(Us,{label:"Version",value:k.version,onChange:I=>x($=>({...$,version:I})),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:I=>x($=>({...$,prompt:I.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(Vh,{}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 border-t border-border flex-shrink-0",children:[o.jsx(st,{variant:"secondary",onClick:()=>C("list"),children:"Cancel"}),W?o.jsx(st,{variant:"primary",onClick:()=>{x(I=>({...I,name:I.name+" (copy)",id:`${m}-copy-${Date.now()}`,isReadOnly:!1})),y(null)},children:"Duplicate & Customize"}):o.jsx(st,{variant:"primary",onClick:q,disabled:S||!k.name||!k.id||!k.prompt,children:S?"Saving...":"Save"})]})]}):o.jsxs("div",{children:[o.jsx(Qb,{description:"Skills provide domain-specific knowledge that agents can load on demand.",onNew:A}),o.jsxs(ey,{loading:i,hasItems:r.length>0||s.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(I=>o.jsx(tv,{skill:I,isBuiltIn:!0,isConfirmingDelete:!1,onView:()=>N(I.id),onDuplicate:()=>D(I.id)},I.id))})]}),s.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:s.map(I=>o.jsx(tv,{skill:I,isBuiltIn:!1,isConfirmingDelete:!1,onView:()=>N(I.id),onEdit:()=>z(I.id),onDuplicate:()=>D(I.id),onDelete:()=>O(I.id)},I.id))})]})]})]})}function $w(e){const r=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);if(r){const s=parseInt(r[1]??"0",16),i=parseInt(r[2]??"0",16),l=parseInt(r[3]??"0",16);return`${s} ${i} ${l}`}return e}function Hs(e){const r=e.split(" ").map(s=>parseInt(s,10));return r.length===3&&r.every(s=>!isNaN(s))?`#${r.map(s=>(s??0).toString(16).padStart(2,"0")).join("")}`:e}function qw({isOpen:e,isNew:r,basePresetId:s,presetName:i,initialTokens:l,onClose:u,onSave:h}){const[c,d]=H.useState(l),[p,g]=H.useState(i);H.useEffect(()=>{d(l),g(i)},[l,i]);const m=(y,v)=>{const x=v.startsWith("#")?$w(v):v;d(_=>({..._,[y]:x}))},b=()=>{h(p.trim()||"Untitled",{...c})},S=Ub.reduce((y,v)=>{const x=v.category;return y[x]||(y[x]=[]),y[x].push(v),y},{}),k={background:"Backgrounds",surface:"Surfaces",text:"Text",accent:"Accents",border:"Border"},C=gr.find(y=>y.id===s);return o.jsx(jt,{isOpen:e,onClose:u,size:"lg",title:r?"New Theme":"Edit Theme",closeOnBackdropClick:!0,closeOnEscape:!0,footer:o.jsxs("div",{className:"flex gap-2 justify-end",children:[o.jsx("button",{type:"button",onClick:u,className:"px-4 py-2 border border-border rounded text-sm text-text-primary hover:bg-bg-tertiary transition-colors",children:"Cancel"}),o.jsx("button",{type:"button",onClick:b,className:"px-4 py-2 bg-accent-primary text-white rounded hover:bg-accent-primary/80 transition-colors text-sm",children:"Save"})]}),children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-muted block mb-1",children:"Name"}),o.jsx("input",{type:"text",value:p,onChange:y=>g(y.target.value),className:"w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-accent-primary"})]}),!r&&o.jsxs("div",{className:"text-xs text-text-muted",children:["Based on ",o.jsx("span",{className:"text-text-primary",children:C==null?void 0:C.name})]}),Object.entries(S).map(([y,v])=>o.jsxs("div",{className:"space-y-3",children:[o.jsx("h4",{className:"text-xs font-medium text-text-muted uppercase",children:k[y]??y}),o.jsx("div",{className:"grid grid-cols-2 gap-3",children:v.map(x=>o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("label",{htmlFor:x.key,className:"text-xs text-text-muted",children:x.label}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"color",id:x.key,value:Hs(c[x.key]??x.defaultValue),onChange:_=>m(x.key,_.target.value),className:"w-8 h-8 rounded cursor-pointer border border-border bg-transparent"}),o.jsx("input",{type:"text",value:c[x.key]??x.defaultValue,onChange:_=>m(x.key,_.target.value),className:"flex-1 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary font-mono focus:outline-none focus:ring-1 focus:ring-accent-primary"})]})]},x.key))})]},y))]})})}function Ww(){const[e,r]=H.useState(null),s=dn(x=>x.currentPreset),i=dn(x=>x.isCustom),l=dn(x=>x.basePreset),u=dn(x=>x.userPresets),h=dn(x=>x.applyPreset),c=dn(x=>x.applyUserPreset),d=dn(x=>x.deleteUserPreset),p=dn(x=>x.saveTheme),g=x=>{h(x),p(JSON.stringify({preset:x}))},m=x=>{c(x)},b=x=>{const _=gr.find(j=>j.id===x);_&&r({type:"new",presetIndex:u.length,basePresetId:x,presetName:_.name+" Copy",tokens:{..._.tokens}})},S=x=>{const _=u[x];if(!_)return;const j=gr.find(N=>N.id===_.basePreset),T=j?{...j.tokens,..._.tokens}:_.tokens;r({type:"edit",presetIndex:x,basePresetId:_.basePreset,presetName:_.name,tokens:T})},k=(x,_)=>{if(!e)return;const j=[...u];if(e.type==="new"){const T={id:"custom-"+Date.now(),name:x,basePreset:e.basePresetId,tokens:_};j.push(T);const N=j.length-1;dn.setState({userPresets:j}),dn.getState().saveUserPresets(),dn.getState().applyUserPreset(N)}else{const T=j[e.presetIndex];T&&(j[e.presetIndex]={...T,name:x,tokens:_}),dn.setState({userPresets:j}),dn.getState().saveUserPresets(),dn.getState().applyUserPreset(e.presetIndex)}r(null)},C=()=>{r(null)},y=(x,_)=>{x.stopPropagation(),d(_)},v=i?l:s;return o.jsxs("div",{className:"space-y-4",children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Theme"}),o.jsx("div",{className:"grid grid-cols-5 gap-2",children:gr.map(x=>o.jsxs("div",{className:"relative group",children:[o.jsxs("button",{type:"button",onClick:()=>g(x.id),className:`w-full flex flex-col items-center gap-2 px-3 py-3 rounded-lg border transition-colors ${v===x.id&&!i?"border-accent-primary bg-bg-tertiary text-text-primary":"border-border bg-bg-secondary text-text-muted hover:border-text-muted"}`,children:[o.jsx("div",{className:"w-8 h-8 rounded border flex items-center justify-center",style:{backgroundColor:Hs(x.tokens["color-bg-primary"]??"#000"),borderColor:Hs(x.tokens["color-border"]??"#000")},children:o.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:Hs(x.tokens["color-text-primary"]??"#fff")}})}),o.jsx("span",{className:"text-xs",children:x.name})]}),o.jsx("button",{type:"button",onClick:_=>{_.stopPropagation(),b(x.id)},className:"absolute top-1 right-1 w-6 h-6 rounded bg-bg-tertiary border border-border flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:border-text-muted",title:"Create custom theme based on this",children:o.jsx("span",{className:"text-xs",children:"✎"})})]},x.id))}),u.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("h4",{className:"text-xs font-medium text-text-muted uppercase",children:"My Themes"}),o.jsx("div",{className:"grid grid-cols-5 gap-2",children:u.map((x,_)=>{const j=gr.find(N=>N.id===x.basePreset),T=j?{...j.tokens,...x.tokens}:x.tokens;return o.jsxs("div",{className:"relative group",children:[o.jsxs("button",{type:"button",onClick:()=>m(_),className:`w-full flex flex-col items-center gap-2 px-3 py-3 rounded-lg border transition-colors ${i&&l===x.basePreset&&v===x.basePreset?"border-accent-primary bg-bg-tertiary text-text-primary":"border-border bg-bg-secondary text-text-muted hover:border-text-muted"}`,children:[o.jsx("div",{className:"w-8 h-8 rounded border flex items-center justify-center",style:{backgroundColor:Hs(T["color-bg-primary"]??"#000"),borderColor:Hs(T["color-border"]??"#000")},children:o.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:Hs(T["color-text-primary"]??"#fff")}})}),o.jsx("span",{className:"text-xs truncate w-full text-center",children:x.name})]}),o.jsx("button",{type:"button",onClick:N=>{N.stopPropagation(),S(_)},className:"absolute top-1 right-1 w-6 h-6 rounded bg-bg-tertiary border border-border flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:border-text-muted",title:"Edit",children:o.jsx("span",{className:"text-xs",children:"✎"})}),o.jsx("button",{type:"button",onClick:N=>y(N,_),className:"absolute -top-1 -left-1 w-5 h-5 rounded-full bg-accent-error text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-20",children:o.jsx(Ph,{className:"w-3 h-3"})})]},x.id)})})]}),e&&o.jsx(qw,{isOpen:!0,isNew:e.type==="new",presetIndex:e.presetIndex,basePresetId:e.basePresetId,presetName:e.presetName,initialTokens:e.tokens,onClose:C,onSave:k})]})}function Vw({isOpen:e,onClose:r}){const[s,i]=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(qa,{label:"Instructions",active:s==="instructions",onClick:()=>i("instructions")}),o.jsx(qa,{label:"Skills",active:s==="skills",onClick:()=>i("skills")}),o.jsx(qa,{label:"Notifications",active:s==="notifications",onClick:()=>i("notifications")}),o.jsx(qa,{label:"Display",active:s==="display",onClick:()=>i("display")}),o.jsx(qa,{label:"Advanced",active:s==="advanced",onClick:()=>i("advanced")})]}),s==="instructions"&&o.jsx(Xw,{isOpen:e}),s==="skills"&&o.jsx(Uw,{isOpen:e}),s==="notifications"&&o.jsx("div",{className:"max-h-[60vh] overflow-y-auto",children:o.jsx(Pw,{})}),s==="display"&&o.jsx(Yw,{}),s==="advanced"&&o.jsx(Gw,{onClose:r})]})})}function Gw({onClose:e}){const[,r]=vr();function s(){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(st,{variant:"secondary",onClick:s,children:"Launch Onboarding"})]})})}function Kw(){return o.jsx(Ww,{})}function Yw(){const e=Kt(g=>g.settings),r=Kt(g=>g.loading),s=Kt(g=>g.getSetting),i=Kt(g=>g.setSetting),l=r[ot.DISPLAY_SHOW_THINKING]??!1,u=[{key:ot.DISPLAY_SHOW_THINKING,label:"Show thinking blocks",description:"Display AI reasoning content in the feed"},{key:ot.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT,label:"Show expanded tool output",description:"Always show full tool call details instead of compact view"},{key:ot.DISPLAY_SHOW_STATS,label:"Show stats bar",description:"Display model, tokens, and timing information"},{key:ot.DISPLAY_SHOW_AGENT_DEFINITIONS,label:"Show agent definitions",description:"Display agent definition injections in the feed"},{key:ot.DISPLAY_SHOW_WORKFLOW_BARS,label:"Show workflow bars",description:"Display workflow start and end markers"}],h=Object.fromEntries(u.map(g=>[g.key,e[g.key]??"true"])),[c,d]=H.useState(()=>Object.fromEntries(u.map(g=>[g.key,h[g.key]==="true"])));H.useEffect(()=>{u.forEach(g=>s(g.key))},[s]),H.useEffect(()=>{d(Object.fromEntries(u.map(g=>[g.key,h[g.key]==="true"])))},[JSON.stringify(h)]);const p=async g=>{const m=String(!c[g]);d(b=>({...b,[g]:!b[g]})),await i(g,m)};return l?o.jsx("div",{className:"text-sm text-text-muted",children:"Loading..."}):o.jsxs("div",{className:"space-y-6",children:[o.jsx(Kw,{}),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 ${c[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 ${c[g]?"translate-x-6":"translate-x-1"}`})})]},g))})]})]})}function qa({label:e,active:r,onClick:s}){return o.jsx("button",{onClick:s,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 Xw({isOpen:e}){const r=Kt(y=>y.settings),s=Kt(y=>y.loading),i=Kt(y=>y.getSetting),l=Kt(y=>y.setSetting),u=r[ot.GLOBAL_INSTRUCTIONS]??"",h=s[ot.GLOBAL_INSTRUCTIONS]??!1,[c,d]=H.useState(u),[p,g]=H.useState(!1),[m,b]=H.useState(!1);H.useEffect(()=>{e&&i(ot.GLOBAL_INSTRUCTIONS)},[e,i]),H.useEffect(()=>{d(u),g(!1)},[u]);const S=async()=>{b(!0),l(ot.GLOBAL_INSTRUCTIONS,c),b(!1),g(!1)},k=()=>{d(u),g(!1)},C=h||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:c,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(Vh,{}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(st,{variant:"secondary",onClick:k,disabled:!p,children:"Discard"}),o.jsx(st,{variant:"primary",onClick:S,disabled:!p||C,children:m?"Saving...":"Save"})]})]})}var qd={exports:{}},nv;function Zw(){return nv||(nv=1,(function(e,r){(function(s,i){e.exports=i()})(globalThis,(()=>(()=>{var s={4567:function(h,c,d){var p=this&&this.__decorate||function(x,_,j,T){var N,D=arguments.length,A=D<3?_:T===null?T=Object.getOwnPropertyDescriptor(_,j):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(x,_,j,T);else for(var z=x.length-1;z>=0;z--)(N=x[z])&&(A=(D<3?N(A):D>3?N(_,j,A):N(_,j))||A);return D>3&&A&&Object.defineProperty(_,j,A),A},g=this&&this.__param||function(x,_){return function(j,T){_(j,T,x)}};Object.defineProperty(c,"__esModule",{value:!0}),c.AccessibilityManager=void 0;const m=d(9042),b=d(9924),S=d(844),k=d(4725),C=d(2585),y=d(3656);let v=c.AccessibilityManager=class extends S.Disposable{constructor(x,_,j,T){super(),this._terminal=x,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 Mx;function b1(){if(Mx)return Hd;Mx=1;var e=ic();function r(m,b){return m===b&&(m!==0||1/m===1/b)||m!==m&&b!==b}var s=typeof Object.is=="function"?Object.is:r,i=e.useState,l=e.useEffect,u=e.useLayoutEffect,h=e.useDebugValue;function c(m,b){var S=b(),k=i({inst:{value:S,getSnapshot:b}}),C=k[0].inst,y=k[1];return u(function(){C.value=S,C.getSnapshot=b,d(C)&&y({inst:C})},[m,S,b]),l(function(){return d(C)&&y({inst:C}),m(function(){d(C)&&y({inst:C})})},[m]),h(S),S}function d(m){var b=m.getSnapshot;m=m.value;try{var S=b();return!s(m,S)}catch{return!0}}function p(m,b){return b()}var g=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?p:c;return Hd.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:g,Hd}var Ix;function y1(){return Ix||(Ix=1,Pd.exports=b1()),Pd.exports}var _1=y1();const S1=a1.useInsertionEffect,w1=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",C1=w1?H.useLayoutEffect:H.useEffect,k1=S1||C1,jb=e=>{const r=H.useRef([e,(...s)=>r[0](...s)]).current;return k1(()=>{r[0]=e}),r[1]},E1="popstate",Oh="pushState",Mh="replaceState",j1="hashchange",Bx=[E1,Oh,Mh,j1],N1=e=>{for(const r of Bx)addEventListener(r,e);return()=>{for(const r of Bx)removeEventListener(r,e)}},Nb=(e,r)=>_1.useSyncExternalStore(N1,e,r),zx=()=>location.search,T1=({ssrSearch:e}={})=>Nb(zx,e!=null?()=>e:zx),Px=()=>location.pathname,A1=({ssrPath:e}={})=>Nb(Px,e!=null?()=>e:Px),D1=(e,{replace:r=!1,state:s=null}={})=>history[r?Mh:Oh](s,"",e),L1=(e={})=>[A1(e),D1],Hx=Symbol.for("wouter_v3");if(typeof history<"u"&&typeof window[Hx]>"u"){for(const e of[Oh,Mh]){const r=history[e];history[e]=function(){const s=r.apply(this,arguments),i=new Event(e);return i.arguments=arguments,dispatchEvent(i),s}}Object.defineProperty(window,Hx,{value:!0})}const R1=(e,r)=>r.toLowerCase().indexOf(e.toLowerCase())?"~"+r:r.slice(e.length)||"/",Tb=(e="")=>e==="/"?"":e,O1=(e,r)=>e[0]==="~"?e.slice(1):Tb(r)+e,M1=(e="",r)=>R1(Fx(Tb(e)),Fx(r)),Fx=e=>{try{return decodeURI(e)}catch{return e}},Ab={hook:L1,searchHook:T1,parser:v1,base:"",ssrPath:void 0,ssrSearch:void 0,ssrContext:void 0,hrefs:e=>e,aroundNav:(e,r,s)=>e(r,s)},Db=H.createContext(Ab),Vi=()=>H.useContext(Db),Lb={},Rb=H.createContext(Lb),I1=()=>H.useContext(Rb),ac=e=>{const[r,s]=e.hook(e);return[M1(e.base,r),jb((i,l)=>e.aroundNav(s,O1(i,e.base),l))]},vr=()=>ac(Vi()),Ih=(e,r,s,i)=>{const{pattern:l,keys:u}=r instanceof RegExp?{keys:!1,pattern:r}:e(r||"*",i),h=l.exec(s)||[],[c,...d]=h;return c!==void 0?[!0,(()=>{const p=u!==!1?Object.fromEntries(u.map((m,b)=>[m,d[b]])):h.groups;let g={...d};return p&&Object.assign(g,p),g})(),...i?[c]:[]]:[!1,null]},Bh=e=>Ih(Vi().parser,e,vr()[0]),B1=({children:e,...r})=>{var g,m,b;const s=Vi(),i=r.hook?Ab:s;let l=i;const[u,h=r.ssrSearch??""]=((g=r.ssrPath)==null?void 0:g.split("?"))??[];u&&(r.ssrSearch=h,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 c=H.useRef({}),d=c.current,p=d;for(let S in i){const k=S==="base"?i[S]+(r[S]??""):r[S]??i[S];d===p&&k!==p[S]&&(c.current=p={...p}),p[S]=k,(k!==i[S]||k!==l[S])&&(l=p)}return H.createElement(Db.Provider,{value:l,children:e})},Ux=({children:e,component:r},s)=>r?H.createElement(r,{params:s}):typeof e=="function"?e(s):e,z1=e=>{let r=H.useRef(Lb);const s=r.current;return r.current=Object.keys(e).length!==Object.keys(s).length||Object.entries(e).some(([i,l])=>l!==s[i])?e:s},Fa=({path:e,nest:r,match:s,...i})=>{const l=Vi(),[u]=ac(l),[h,c,d]=s??Ih(l.parser,e,u,r),p=z1({...I1(),...c});if(!h)return null;const g=d?H.createElement(B1,{base:d},Ux(i,p)):Ux(i,p);return H.createElement(Rb.Provider,{value:p,children:g})},Fn=H.forwardRef((e,r)=>{const s=Vi(),[i,l]=ac(s),{to:u="",href:h=u,onClick:c,asChild:d,children:p,className:g,replace:m,state:b,transition:S,...k}=e,C=jb(v=>{v.ctrlKey||v.metaKey||v.altKey||v.shiftKey||v.button!==0||(c==null||c(v),v.defaultPrevented||(v.preventDefault(),l(h,e)))}),y=s.hrefs(h[0]==="~"?h.slice(1):s.base+h,s);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(i===h):g,children:p,ref:r})}),Ob=e=>Array.isArray(e)?e.flatMap(r=>Ob(r&&r.type===H.Fragment?r.props.children:r)):[e],P1=({children:e,location:r})=>{const s=Vi(),[i]=ac(s);for(const l of Ob(e)){let u=0;if(H.isValidElement(l)&&(u=Ih(s.parser,l.props.path,r||i,l.props.nest))[0])return H.cloneElement(l,{match:u})}return null};function H1(e){return typeof e=="object"&&e!==null&&"type"in e&&"payload"in e}function Mb(){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 F1{constructor(r){hr(this,"ws",null);hr(this,"handlers",new Set);hr(this,"statusHandler",null);hr(this,"baseUrl");hr(this,"isReconnecting",!1);hr(this,"connectingPromise",null);hr(this,"lastCloseCode",0);hr(this,"reconnectAttempts",0);hr(this,"manualReconnectScheduled",!1);this.baseUrl=r}getUrl(){const r=localStorage.getItem("openfox_token");if(r){const s=this.baseUrl.includes("?")?"&":"?";return`${this.baseUrl}${s}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,s;return((r=this.ws)==null?void 0:r.readyState)===WebSocket.OPEN?Promise.resolve():(this.lastCloseCode=0,this.isReconnecting=!1,this.connectingPromise&&((s=this.ws)==null?void 0:s.readyState)===WebSocket.CONNECTING?this.connectingPromise:(this.connectingPromise=new Promise((i,l)=>{try{const u=this.getUrl();this.ws=new WebSocket(u);const h=setTimeout(()=>{var c;((c=this.ws)==null?void 0:c.readyState)===WebSocket.CONNECTING&&(this.ws.close(),l(new Error("Connection timeout")))},5e3);this.ws.onopen=()=>{var c;clearTimeout(h),this.isReconnecting=!1,this.connectingPromise=null,(c=this.statusHandler)==null||c.call(this,"connected"),i()},this.ws.onclose=c=>{var d,p,g;clearTimeout(h),this.lastCloseCode=c.code,((d=this.ws)==null?void 0:d.readyState)===WebSocket.CONNECTING?(this.connectingPromise=null,(p=this.statusHandler)==null||p.call(this,"disconnected"),l(new Error(`Connection closed: ${c.code}`))):(this.connectingPromise=null,(g=this.statusHandler)==null||g.call(this,"disconnected"),this.attemptReconnect())},this.ws.onerror=c=>{clearTimeout(h),console.error("WebSocket error:",c),this.connectingPromise=null,l(c)},this.ws.onmessage=c=>{try{const d=JSON.parse(c.data);H1(d)&&this.handlers.forEach(p=>p(d))}catch(d){console.error("Failed to parse WebSocket message:",d)}}}catch(u){this.connectingPromise=null,l(u)}}),this.connectingPromise))}attemptReconnect(){var l;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,(l=this.statusHandler)==null||l.call(this,"reconnecting");const i=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(()=>{})},i)}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,s){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");const i=Mb(),l={id:i,type:r,payload:s};return this.ws.send(JSON.stringify(l)),i}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 U1=`ws://${window.location.hostname}:${window.location.port||"10469"}/ws`,Vt=new F1(U1),xs=async(e,r,s)=>{try{const i=await ke(r,{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return i.ok?{success:!0}:{success:!1,error:(await i.json()).error}}catch{return{success:!1,error:"Network error"}}};function Ib(e){let r=null;function s(){r===null&&(r=requestAnimationFrame(()=>{r=null,e()}))}return s}let Ml=[];const mr=$n()((e,r)=>{function s(){if(Ml.length===0)return;const l=Ml;Ml=[],e(u=>({logs:[...u.logs,...l]}))}const i=Ib(s);return{workdir:null,status:null,logs:[],config:null,loading:!1,setWorkdir:l=>{r().workdir!==l&&(e({workdir:l,status:null,logs:[],config:null,loading:!0}),l&&(r().fetchStatus(),r().fetchConfig()))},fetchStatus:async()=>{const l=r().workdir;if(l)try{const h=await(await ke(`/api/dev-server?workdir=${encodeURIComponent(l)}`)).json();e({status:h,loading:!1})}catch{e({loading:!1})}},fetchConfig:async()=>{const l=r().workdir;if(l)try{const h=await(await ke(`/api/dev-server/config?workdir=${encodeURIComponent(l)}`)).json();e({config:h.config??null})}catch{}},fetchLogs:async()=>{const l=r().workdir;if(l)try{const c=(await(await ke(`/api/dev-server/logs?workdir=${encodeURIComponent(l)}`)).json()).logs.map(d=>({stream:d.stream,content:d.content}));e({logs:c})}catch{}},start:async()=>{const l=r().workdir;if(l)try{const h=await(await ke(`/api/dev-server/start?workdir=${encodeURIComponent(l)}`,{method:"POST"})).json();e({status:h,logs:[]})}catch{}},stop:async()=>{const l=r().workdir;if(l)try{const h=await(await ke(`/api/dev-server/stop?workdir=${encodeURIComponent(l)}`,{method:"POST"})).json();e({status:h})}catch{}},restart:async()=>{const l=r().workdir;if(l)try{const h=await(await ke(`/api/dev-server/restart?workdir=${encodeURIComponent(l)}`,{method:"POST"})).json();e({status:h,logs:[]})}catch{}},saveConfig:async l=>{const u=r().workdir;if(u)try{const c=await(await ke(`/api/dev-server/config?workdir=${encodeURIComponent(u)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})).json();e({config:c.config??l}),r().fetchStatus()}catch{}},handleMessage:l=>{const u=r().workdir;if(u)switch(l.type){case"devServer.output":{const h=l.payload;if(h.workdir!==u)return;Ml.push({stream:h.stream,content:h.content}),i();break}case"devServer.state":{const h=l.payload;if(h.workdir!==u)return;e(c=>({status:c.status?{...c.status,state:h.state,errorMessage:h.errorMessage}:c.status}));break}}}}});function $1(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 $x(e,r,s){const i=await ke(`/api/providers/${e}/models/${encodeURIComponent(r)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!i.ok){const l=await i.json();throw new Error(l.error??"Failed to update model")}return i.json()}function qx(e,r,s,i){return e.map(l=>l.id===r?{...l,models:l.models.map(u=>u.id===s?{...u,...i,source:"user"}:u)}:l)}const q1=3e4;function W1(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 Lt=$n((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 s=await ke("/api/config");if(!s.ok)throw new Error("Failed to fetch config");const i=await s.json();e({version:i.version,model:i.model,maxContext:i.maxContext,llmUrl:i.llmUrl,llmStatus:i.llmStatus,backend:i.backend,providers:i.providers??[],activeProviderId:i.activeProviderId??null,defaultModelSelection:i.defaultModelSelection??null,loading:!1})}catch(s){e({error:s instanceof Error?s.message:"Unknown error",loading:!1})}},refreshModel:async()=>{try{const s=await ke("/api/model/refresh",{method:"POST"});if(!s.ok)throw new Error("Failed to refresh model");const i=await s.json(),u=Ce.getState().currentSession;if(u!=null&&u.providerId&&u.providerModel){e({llmStatus:i.llmStatus,backend:i.backend});return}e({model:i.model,llmStatus:i.llmStatus,backend:i.backend})}catch(s){console.error("Failed to refresh model:",s)}},activateProvider:async s=>{const{activeProviderId:i,providers:l}=r();if(s===i)return!0;e({activating:!0,error:null});try{const u=await ke(`/api/providers/${s}/activate`,{method:"POST"});if(!u.ok){const c=await u.json();throw new Error(c.error??"Failed to activate provider")}const h=await u.json();return e({activeProviderId:h.activeProviderId,model:h.model,backend:h.backend,providers:l.map(c=>({...c,isActive:c.id===h.activeProviderId})),activating:!1}),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to switch provider",activating:!1}),!1}},syncFromSession:(s,i)=>{const{providers:l}=r();e({activeProviderId:s,model:i,defaultModelSelection:`${s}/${i}`,providers:l.map(u=>({...u,isActive:u.id===s}))})},updateModelContext:async(s,i,l)=>{e({activating:!0,error:null});try{const u=await $x(s,i,{contextWindow:l}),{providers:h}=r();return e({providers:qx(h,s,i,{contextWindow: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 context",activating:!1}),!1}},updateModelSettings:async(s,i,l)=>{e({activating:!0,error:null});try{const u=await $x(s,i,l),{providers:h}=r(),c={...l.contextWindow!==void 0&&{contextWindow:l.contextWindow},...$1({temperature:l.temperature??void 0,topP:l.topP??void 0,topK:l.topK??void 0,maxTokens:l.maxTokens??void 0}),...l.supportsVision!==void 0&&{supportsVision:l.supportsVision}};return e({providers:qx(h,s,i,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 settings",activating:!1}),!1}},refreshProviderModels:async s=>{e({activating:!0,error:null});try{const i=await ke(`/api/providers/${s}/refresh`,{method:"POST"});if(!i.ok){const h=await i.json();throw new Error(h.error??"Failed to refresh models")}const l=await i.json(),{providers:u}=r();return e({providers:u.map(h=>h.id===s?{...h,models:l.models}:h),activating:!1}),!0}catch(i){return e({error:i instanceof Error?i.message:"Failed to refresh models",activating:!1}),!1}},startAutoRefresh:()=>{const{autoRefreshInterval:s,refreshModel:i}=r();if(s)return;const l=setInterval(()=>{i()},q1);e({autoRefreshInterval:l})},stopAutoRefresh:()=>{const{autoRefreshInterval:s}=r();s&&(clearInterval(s),e({autoRefreshInterval:null}))},getActiveProvider:()=>{const{providers:s,activeProviderId:i}=r();return s.find(l=>l.id===i)},getModelContext:s=>{const{providers:i,activeProviderId:l}=r(),u=i.find(c=>c.id===l);if(!u)return 2e5;const h=u.models.find(c=>c.id===s);return(h==null?void 0:h.contextWindow)??2e5}})),Qt=$n((e,r)=>({projects:[],currentProject:null,loading:!1,listProjects:async()=>{e({loading:!0});try{const i=await(await ke("/api/projects")).json();e({projects:i.projects??[],loading:!1})}catch{e({loading:!1})}},createProject:async(s,i)=>{try{const l=await ke("/api/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:s,workdir:i})});if(!l.ok)return null;const u=await l.json();return await r().listProjects(),u.project}catch{return null}},loadProject:async s=>{try{const i=await ke(`/api/projects/${s}`);if(!i.ok)return null;const l=await i.json();return e({currentProject:l.project}),r().projects.length===0&&await r().listProjects(),l.project}catch{return null}},updateProject:async(s,i)=>{var l;try{const u=await ke(`/api/projects/${s}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!u.ok)return null;const h=await u.json();return((l=r().currentProject)==null?void 0:l.id)===s&&e({currentProject:h.project}),await r().listProjects(),h.project}catch{return null}},deleteProject:async s=>{var i;try{return(await ke(`/api/projects/${s}`,{method:"DELETE"})).ok?(await r().listProjects(),((i=r().currentProject)==null?void 0:i.id)===s&&e({currentProject:null}),!0):!1}catch{return!1}},clearProject:()=>{e({currentProject:null})}}));let Il=[];const eo=$n()((e,r)=>{function s(){if(Il.length===0)return;const l=Il;Il=[],e(u=>{const h={...u.logs};for(const c of l){const d=h[c.processId]??[];h[c.processId]=[...d,{offset:d.length,content:c.content,timestamp:Date.now(),stream:c.stream}]}return{logs:h}})}const i=Ib(s);return{processes:[],logs:{},loading:!1,setProcesses:l=>e({processes:l}),addProcess:l=>e(u=>({processes:[...u.processes,l]})),updateProcess:(l,u)=>e(h=>({processes:h.processes.map(c=>c.id===l?{...c,...u}:c)})),removeProcess:l=>e(u=>({processes:u.processes.filter(h=>h.id!==l),logs:Object.fromEntries(Object.entries(u.logs).filter(([h])=>h!==l))})),stopProcess:async(l,u)=>{try{(await ke(`/api/sessions/${u}/background-process/${l}/stop`,{method:"POST"})).ok&&r().removeProcess(l)}catch{}},appendLog:(l,u,h)=>{Il.push({processId:l,stream:u,content:h}),i()},setLogs:(l,u)=>e(h=>({logs:{...h.logs,[l]:u}})),clearLogs:l=>e(u=>({logs:{...u.logs,[l]:[]}})),handleMessage:(l,u)=>{switch(l){case"backgroundProcess.started":{const{processId:h,name:c,pid:d,status:p}=u;e(g=>({processes:[...g.processes,{id:h,sessionId:"",name:c,command:"",cwd:"",pid:d,status:p,exitCode:null,createdAt:Date.now(),startedAt:Date.now(),endedAt:null}]}));break}case"backgroundProcess.output":{const h=u.processId,c=u.stream,d=u.content;r().appendLog(h,c,d);break}case"backgroundProcess.exited":{const h=u.processId,c=u.exitCode;e(d=>({processes:d.processes.map(p=>p.id===h?{...p,status:"exited",exitCode:c}:p)}));break}case"backgroundProcess.removed":{const h=u.processId;r().removeProcess(h);break}}}}}),V1=[{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"}],G1=[{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"}],Bb={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"},ms={soundEnabled:!0,browserNotification:!1,customSoundUrl:null},zb={soundEnabled:!1,browserNotification:!1,customSoundUrl:null},ph={soundEnabled:!0,browserNotificationEnabled:!1,events:{complete:{...ms},waiting_for_user:{...ms},phase_done:{...ms},phase_blocked:{...ms},new_message:{...zb}},agentOverrides:{}};function Pb(e,r,s){var u;const i=e.events[r];if(!s)return i;const l=(u=e.agentOverrides[s])==null?void 0:u[r];return l?{soundEnabled:l.soundEnabled??i.soundEnabled,browserNotification:l.browserNotification??i.browserNotification,customSoundUrl:l.customSoundUrl!==void 0?l.customSoundUrl:i.customSoundUrl}:i}const Fs=$n((e,r)=>({settings:ph,loaded:!1,load:()=>{Kt.getState().getSetting(ot.NOTIFICATION_SETTINGS);const i=Kt.subscribe(u=>{const h=u.settings[ot.NOTIFICATION_SETTINGS];if(h!==void 0)try{const c=JSON.parse(h);e({settings:Wx(c),loaded:!0})}catch{e({loaded:!0})}}),l=Kt.getState().settings[ot.NOTIFICATION_SETTINGS];if(l)try{const u=JSON.parse(l);e({settings:Wx(u),loaded:!0})}catch{e({loaded:!0})}return i},update:s=>{e({settings:s}),Fd(s)},updateEvent:(s,i)=>{const l=r().settings,u={...l,events:{...l.events,[s]:{...l.events[s],...i}}};e({settings:u}),Fd(u)},updateAgentOverride:(s,i,l)=>{var d;const u=r().settings,h={...u.agentOverrides};if(l===null){if(h[s]){const p={...h[s]};delete p[i],Object.keys(p).length===0?delete h[s]:h[s]=p}}else h[s]={...h[s],[i]:{...((d=h[s])==null?void 0:d[i])??{},...l}};const c={...u,agentOverrides:h};e({settings:c}),Fd(c)}}));function Fd(e){Kt.getState().setSetting(ot.NOTIFICATION_SETTINGS,JSON.stringify(e))}function Wx(e){var r,s,i,l,u;return{soundEnabled:e.soundEnabled??ph.soundEnabled,browserNotificationEnabled:e.browserNotificationEnabled??ph.browserNotificationEnabled,events:{complete:{...ms,...(r=e.events)==null?void 0:r.complete},waiting_for_user:{...ms,...(s=e.events)==null?void 0:s.waiting_for_user},phase_done:{...ms,...(i=e.events)==null?void 0:i.phase_done},phase_blocked:{...ms,...(l=e.events)==null?void 0:l.phase_blocked},new_message:{...zb,...(u=e.events)==null?void 0:u.new_message}},agentOverrides:e.agentOverrides??{}}}const Vx=new Map;function K1(e){let r=Vx.get(e);return r||(r=new Audio(e),r.volume=.5,Vx.set(e,r)),r}let Hb=typeof Notification<"u"?Notification.permission:"denied";function Y1(){return typeof Notification>"u"?Promise.resolve("denied"):Notification.requestPermission().then(e=>(Hb=e,e))}const X1={complete:"Task Complete",waiting_for_user:"Waiting for Input",phase_done:"Phase Complete",phase_blocked:"Phase Blocked",new_message:"New Message"},Z1={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 Q1(e){typeof Notification>"u"||Hb==="granted"&&(document.hasFocus()||new Notification(X1[e],{body:Z1[e],icon:"/fox.svg",tag:`openfox-${e}`}))}function mo(e,r){const{settings:s}=Fs.getState(),i=Pb(s,e,r);if(s.soundEnabled&&i.soundEnabled){const l=i.customSoundUrl??Bb[e],u=K1(l);u.currentTime=0,u.play().catch(()=>{})}s.browserNotificationEnabled&&i.browserNotification&&Q1(e)}const J1=e=>mo("complete",e),ew=e=>mo("phase_done",e),tw=e=>mo("phase_blocked",e),Gx=e=>mo("waiting_for_user",e),nw=e=>mo("new_message",e);let Ua=!1,fr=null;const Ud=new Set,Wt={messageId:null,deltaContent:"",thinkingContent:"",toolOutput:[]};let Ui=null,mn=null;function $d(){Ui===null&&(Ui=requestAnimationFrame(()=>{Ui=null,mn==null||mn()}))}function Is(){Ui!==null&&(cancelAnimationFrame(Ui),Ui=null)}function Ht(e,r){return r!==null&&e.sessionId===r}function rw(e,r,s){return e.id!==void 0||Ht(e,r)||s===!0&&e.sessionId!==void 0}function sw(e,r){return e.includes(r)?e:[...e,r]}function $a(e,r){return e.filter(s=>s!==r)}function iw(e,r){const s=e.find(l=>l.id===r.id),i=s?{...s,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(l=>l.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(l=>l.status.type==="passed").length,messageCount:r.messages.length};return s?e.map(l=>l.id===r.id?i:l):[i,...e]}function aw(e,r,s){return e.map(i=>{const l=(s==null?void 0:s.id)===i.id?s:null,u=r.find(h=>h.id===i.id);return{...i,title:i.title??(u==null?void 0:u.title),mode:(l==null?void 0:l.mode)??(u==null?void 0:u.mode)??i.mode,phase:(l==null?void 0:l.phase)??(u==null?void 0:u.phase)??i.phase,isRunning:(l==null?void 0:l.isRunning)??(u==null?void 0:u.isRunning)??i.isRunning,messageCount:i.messageCount,recentUserPrompts:i.recentUserPrompts}})}const Kx=new Map;function Qa(e,r){var u;const s=r===((u=e.currentSession)==null?void 0:u.id)?e.currentSession:null,i=e.sessions.find(h=>h.id===r),l=(s==null?void 0:s.mode)??(i==null?void 0:i.mode);return l==="planner"?"planner":l==="builder"?"build":"planner"}function ow(e,r){if(e.type==="chat.done"){const s=e.payload,i=Qa(r,e.sessionId),l=s.agentType??i;s.reason==="complete"&&J1(l),s.reason==="waiting_for_user"&&Gx(l);return}if(e.type==="chat.path_confirmation"){const s=Qa(r,e.sessionId);Gx(s);return}if(e.type==="task.completed"){const s=Qa(r,e.sessionId);ew(s);return}if(e.type==="phase.changed"&&e.sessionId){const s=e.payload,i=Kx.get(e.sessionId)??null;if(Kx.set(e.sessionId,s.phase),i===s.phase)return;const l=Qa(r,e.sessionId);s.phase==="blocked"&&tw(l)}}const Ce=$n((e,r)=>(mn=()=>{const s=Wt;if(!s.messageId)return;const i=s.deltaContent.length>0,l=s.thinkingContent.length>0,u=s.toolOutput.length>0;if(!i&&!l&&!u)return;const h=s.deltaContent,c=s.thinkingContent,d=s.toolOutput;s.deltaContent="",s.thinkingContent="",s.toolOutput=[],e(p=>{var m;const g=p.streamingMessage;if(g&&g.id===s.messageId){let b={...g};if(i&&(b.content=b.content+h),l&&(b.thinkingContent=(b.thinkingContent??"")+c),u){const S=new Set;b.toolCalls=(m=b.toolCalls)==null?void 0:m.map(C=>{const y=d.filter(v=>v.callId===C.id);return y.length===0?C:(S.add(C.id),{...C,streamingOutput:[...C.streamingOutput??[],...y.map(v=>({stream:v.stream,content:v.content,timestamp:Date.now()}))]})});const k=d.filter(C=>!S.has(C.callId));k.length>0&&Wt.toolOutput.push(...k)}return{streamingMessage:b}}if(u){const b=new Set,S=p.messages.map(C=>{var v;if(C.id!==s.messageId)return C;const y=(v=C.toolCalls)==null?void 0:v.map(x=>{const _=d.filter(j=>j.callId===x.id);return _.length===0?x:(b.add(x.id),{...x,streamingOutput:[...x.streamingOutput??[],..._.map(j=>({stream:j.stream,content:j.content,timestamp:Date.now()}))]})});return{...C,toolCalls:y}}),k=d.filter(C=>!b.has(C.callId));return k.length>0&&Wt.toolOutput.push(...k),{messages:S}}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()=>{if(r().connectionStatus==="connected")return;e({connectionStatus:"reconnecting"});let i=!1;try{i=(await(await ke("/api/auth")).json()).requiresAuth}catch{}if(i&&!Vt.hasToken()){e({showPasswordModal:!0,passwordModalRetry:!1,connectionStatus:"reconnecting"});return}Vt.onStatusChange(l=>{var u;if(e({connectionStatus:l}),l==="connected"){r().listSessions(void 0);const h=(u=r().currentSession)==null?void 0:u.id;h&&r().loadSession(h)}});try{if(await Vt.connect(),!Ua){Ua=!0;const l=r().handleServerMessage;fr=Vt.subscribe(l)}}catch(l){console.error("Failed to connect:",l);const u=Vt.getLastCloseCode();if(!Vt.hasToken()&&(u===1006||u===4e3)){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}fr&&(fr(),fr=null),Ua=!1,e({connectionStatus:"disconnected"})}},reconnect:()=>{Vt.disconnect(),fr&&(fr(),fr=null),Ua=!1,e({connectionStatus:"disconnected"}),r().connect()},disconnect:()=>{Vt.disconnect(),fr&&(fr(),fr=null),Ua=!1,e({connectionStatus:"disconnected",showPasswordModal:!1})},submitPassword:async s=>{try{const i=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:s})});if(!i.ok){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}const{token:l}=await i.json();Vt.setToken(l),e({showPasswordModal:!1}),r().connect();const{listProjects:u}=Qt.getState(),{fetchConfig:h}=Lt.getState();u(),h(),r().connect()}catch{e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"})}},cancelPassword:()=>{Vt.clearToken(),e({showPasswordModal:!1,connectionStatus:"disconnected"})},createSession:async(s,i)=>{try{e({pendingSessionCreate:!0});const l=await ke("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectId:s,title:i})});if(!l.ok)return e({pendingSessionCreate:!1}),null;const u=await l.json();return Vt.send("session.load",{sessionId:u.session.id}),u.session}catch{return e({pendingSessionCreate:!1}),null}},loadSession:async s=>{try{const i=r().currentSession;!i||i.id!==s?(Is(),e({currentSession:null,unreadSessionIds:$a(r().unreadSessionIds,s),subAgentContextStates:{},messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,pendingPathConfirmation:null,queuedMessages:[],abortInProgress:!1,error:null})):e({unreadSessionIds:$a(r().unreadSessionIds,s)});const l=await ke(`/api/sessions/${s}`);if(!l.ok)return;const u=await l.json();e({currentSession:u.session,messages:u.messages??[],contextState:u.contextState,queuedMessages:u.queueState??[]}),Vt.send("session.load",{sessionId:s});try{const h=await ke(`/api/sessions/${s}/background-processes`);if(h.ok){const c=await h.json();eo.getState().setProcesses(c.processes??[])}}catch{}}catch{}},listSessions:async(s,i=20)=>{try{const l=new URLSearchParams;l.set("limit",String(i)),s&&l.set("projectId",s);const h=await(await ke(`/api/sessions?${l.toString()}`)).json();e({sessions:h.sessions??[],sessionsHasMore:s?h.hasMore??!1:!0})}catch{}},loadMoreSessions:async s=>{const i=r();if(!(i.sessionsPaginationLoading||!i.sessionsHasMore)){e({sessionsPaginationLoading:!0});try{const l=new URLSearchParams;l.set("limit","20"),l.set("offset",String(i.sessions.length)),l.set("projectId",s);const h=await(await ke(`/api/sessions?${l.toString()}`)).json();e(c=>({sessions:[...c.sessions,...h.sessions??[]],sessionsHasMore:h.hasMore??!1,sessionsPaginationLoading:!1}))}catch{e({sessionsPaginationLoading:!1})}}},deleteSession:async s=>{var i;try{return(await ke(`/api/sessions/${s}`,{method:"DELETE"})).ok?(await r().listSessions(),((i=r().currentSession)==null?void 0:i.id)===s&&r().clearSession(),!0):!1}catch{return!1}},deleteAllSessions:async s=>{try{return(await ke(`/api/projects/${s}/sessions`,{method:"DELETE"})).ok?(await r().listSessions(),!0):!1}catch{return!1}},clearSession:()=>{Is(),e(s=>({currentSession:null,messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,unreadSessionIds:s.currentSession?$a(s.unreadSessionIds,s.currentSession.id):s.unreadSessionIds}))},sendMessage:async(s,i,l)=>{var h;const u=(h=r().currentSession)==null?void 0:h.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:s,attachments:i,messageKind:l==null?void 0:l.messageKind})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(c){console.error("Error sending message:",c)}}},stopGeneration:async()=>{var i;const s=(i=r().currentSession)==null?void 0:i.id;if(s&&!r().abortInProgress){Is(),mn==null||mn(),e({abortInProgress:!0});try{await ke(`/api/sessions/${s}/stop`,{method:"POST"})}catch(l){console.error("Error stopping generation:",l)}}},continueGeneration:async()=>{var i;const s=(i=r().currentSession)==null?void 0:i.id;if(s){e({streamingMessageId:null});try{await ke(`/api/sessions/${s}/continue`,{method:"POST"})}catch(l){console.error("Error continuing generation:",l)}}},launchRunner:(s,i,l)=>{e({streamingMessageId:null});const u={};s!=null&&s.trim()&&(u.content=s),i&&i.length>0&&(u.attachments=i),l&&(u.workflowId=l),Vt.send("runner.launch",u)},switchMode:async s=>{var l;const i=(l=r().currentSession)==null?void 0:l.id;if(i)try{const u=await ke(`/api/sessions/${i}/mode`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:s})});if(!u.ok){console.error("Failed to switch mode:",await u.json());return}const h=await u.json();h.session&&e({currentSession:h.session})}catch(u){console.error("Error switching mode:",u)}},switchDangerLevel:async s=>{var l;const i=(l=r().currentSession)==null?void 0:l.id;if(i)try{const u=await ke(`/api/sessions/${i}/danger-level`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({dangerLevel:s})});if(!u.ok){console.error("Failed to switch danger level:",await u.json());return}const h=await u.json();h.session&&e({currentSession:h.session})}catch(u){console.error("Error switching danger level:",u)}},acceptAndBuild:(s,i,l)=>{e({streamingMessageId:null});const u={};s&&(u.workflowId=s),i!=null&&i.trim()&&(u.content=i),l&&l.length>0&&(u.attachments=l),Vt.send("mode.accept",u)},editCriteria:async s=>{var l;const i=(l=r().currentSession)==null?void 0:l.id;if(i)try{const u=await ke(`/api/sessions/${i}/criteria`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({criteria:s})});u.ok||console.error("Failed to update criteria:",await u.json())}catch(u){console.error("Error updating criteria:",u)}},compactContext:()=>{Vt.send("context.compact",{})},setSessionProvider:async(s,i)=>{var l;try{const u=(l=r().currentSession)==null?void 0:l.id;if(!u)return null;const h=await ke(`/api/sessions/${u}/provider`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerId:s,...i?{model:i}:{}})});if(!h.ok)return null;const c=await h.json();return e({currentSession:c.session,messages:c.messages??[],contextState:c.contextState}),c.session}catch{return null}},updateContextState:s=>{e({contextState:s})},updateSubAgentContextState:(s,i)=>{e(l=>({subAgentContextStates:{...l.subAgentContextStates,[s]:i}}))},clearSubAgentContextState:s=>{e(i=>{const l={...i.subAgentContextStates};return delete l[s],{subAgentContextStates:l}})},confirmPath:async(s,i,l=!1)=>{var h;const u=(h=r().currentSession)==null?void 0:h.id;if(u)try{await ke(`/api/sessions/${u}/confirm-path`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:s,approved:i,alwaysAllow:l})})}catch(c){console.error("Error confirming path:",c)}},answerQuestion:async(s,i)=>{var u;const l=(u=r().currentSession)==null?void 0:u.id;if(l){try{await ke(`/api/sessions/${l}/answer`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:s,answer:i})})}catch(h){console.error("Error answering question:",h)}e({pendingQuestion:null})}},queueAsap:async(s,i,l)=>{var h;const u=(h=r().currentSession)==null?void 0:h.id;if(u)try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:s,attachments:i,messageKind:l})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(c){console.error("Error queueing ASAP message:",c)}},queueCompletion:async(s,i,l)=>{var h;const u=(h=r().currentSession)==null?void 0:h.id;if(u)try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:s,attachments:i,messageKind:l})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(c){console.error("Error queueing completion message:",c)}},cancelQueued:async s=>{var l;const i=(l=r().currentSession)==null?void 0:l.id;if(i)try{const h=await(await ke(`/api/sessions/${i}/queue/${s}`,{method:"DELETE"})).json();h.queueState&&e({queuedMessages:h.queueState})}catch(u){console.error("Error canceling queued message:",u)}},clearError:()=>{e({error:null})},resetPendingSessionCreate:()=>{e({pendingSessionCreate:!1})},handleServerMessage:s=>{var h,c,d,p,g,m,b,S,k,C,y,v,x,_,j,T,N,D,A,z,O,q,G,W;const i=r();ow(s,i);const l=((h=i.currentSession)==null?void 0:h.id)??null,u=()=>{const I=s.sessionId;!I||I===l||e($=>({unreadSessionIds:sw($.unreadSessionIds,I)}))};switch(s.type){case"session.state":{const I=s.payload;if(!rw(s,l,i.pendingSessionCreate))break;Is();const $=I.messages.find(R=>R.isStreaming)??null,B=r().pendingSessionCreate===!0,X=I.pendingConfirmations??[],P=i.pendingPathConfirmation??(X.length>0?X[0]??null:null);if(e({currentSession:I.session,sessions:iw(r().sessions,I.session),unreadSessionIds:$a(r().unreadSessionIds,I.session.id),messages:I.messages,streamingMessageId:($==null?void 0:$.id)??null,streamingMessage:$,currentTodos:[],pendingPathConfirmation:P,error:null,...B?{pendingSessionCreate:I.session.id}:{}}),I.session.providerId&&I.session.providerModel){const R=Lt.getState();R.providers.find(U=>U.id===I.session.providerId)&&R.syncFromSession(I.session.providerId,I.session.providerModel)}break}case"session.list":{const I=s.payload;e($=>({sessions:aw(I.sessions,$.sessions,$.currentSession)}));break}case"session.deleted":{const I=s.payload;e($=>({unreadSessionIds:$a($.unreadSessionIds,I.sessionId)})),r().listSessions();break}case"session.deletedAll":{r().listSessions();break}case"session.running":{const I=s.payload,$=s.sessionId,B=(c=r().currentSession)==null?void 0:c.id,X=$&&$!==B;e(Z=>({sessions:Z.sessions.map(P=>P.id===$?{...P,isRunning:I.isRunning}:P)})),X||e(Z=>({currentSession:Z.currentSession?{...Z.currentSession,isRunning:I.isRunning}:null,...I.isRunning?{}:{abortInProgress:!1,queuedMessages:[]}}));break}case"chat.message":{if(!Ht(s,((d=r().currentSession)==null?void 0:d.id)??null)){u();break}const I=s.payload;e($=>$.messages.some(B=>B.id===I.message.id)?$:{messages:[...$.messages,I.message],streamingMessageId:I.message.isStreaming?I.message.id:$.streamingMessageId,streamingMessage:I.message.isStreaming?I.message:$.streamingMessage});break}case"chat.message_updated":{if(!Ht(s,((p=r().currentSession)==null?void 0:p.id)??null)){u();break}const I=s.payload,$=I.updates.isStreaming===!1&&r().streamingMessageId===I.messageId;$&&(Is(),mn==null||mn()),e(B=>{const X=B.streamingMessage,Z=$;if(X&&X.id===I.messageId){const P={...X,...I.updates};return{messages:B.messages.map(R=>R.id===I.messageId?P:R),streamingMessageId:Z?null:B.streamingMessageId,streamingMessage:Z?null:{...X,...I.updates}}}return{messages:B.messages.map(P=>P.id===I.messageId?{...P,...I.updates}:P),streamingMessageId:Z?null:B.streamingMessageId}});break}case"chat.delta":{if(!Ht(s,((g=r().currentSession)==null?void 0:g.id)??null)){u();break}const I=s.payload;if(!Ud.has(I.messageId)){Ud.add(I.messageId);const $=Qa(r(),s.sessionId);nw($)}Wt.messageId=I.messageId,Wt.deltaContent+=I.content,$d();break}case"chat.thinking":{if(!Ht(s,((m=r().currentSession)==null?void 0:m.id)??null)){u();break}const I=s.payload;Wt.messageId=I.messageId,Wt.thinkingContent+=I.content,$d();break}case"chat.tool_preparing":{if(!Ht(s,((b=r().currentSession)==null?void 0:b.id)??null)){u();break}const I=s.payload;e($=>{const B=$.streamingMessage;return B&&B.id===I.messageId?{streamingMessage:{...B,preparingToolCalls:[...B.preparingToolCalls??[],{index:I.index,name:I.name}]}}:{messages:$.messages.map(X=>X.id===I.messageId?{...X,preparingToolCalls:[...X.preparingToolCalls??[],{index:I.index,name:I.name}]}:X)}});break}case"chat.tool_call":{if(!Ht(s,((S=r().currentSession)==null?void 0:S.id)??null)){u();break}const I=s.payload,$=B=>{var P;const X=(P=B.preparingToolCalls)==null?void 0:P.filter((R,L)=>{var U;return R.name===I.tool?(U=B.preparingToolCalls)==null?void 0:U.slice(0,L).some(ne=>ne.name===I.tool):!0}),Z=Wt.toolOutput.filter(R=>R.callId===I.callId);return Z.length>0&&(Wt.toolOutput=Wt.toolOutput.filter(R=>R.callId!==I.callId)),{...B,toolCalls:[...B.toolCalls??[],{id:I.callId,name:I.tool,arguments:I.args,startedAt:Date.now(),...Z.length>0?{streamingOutput:Z.map(R=>({stream:R.stream,content:R.content,timestamp:Date.now()}))}:{}}],...X&&X.length>0?{preparingToolCalls:X}:{preparingToolCalls:void 0}}};e(B=>{const X=B.streamingMessage;return X&&X.id===I.messageId?{streamingMessage:$(X)}:{messages:B.messages.map(Z=>Z.id===I.messageId?$(Z):Z)}});break}case"chat.tool_output":{if(!Ht(s,((k=r().currentSession)==null?void 0:k.id)??null)){u();break}const I=s.payload;Wt.messageId=I.messageId,Wt.toolOutput.push({messageId:I.messageId,callId:I.callId,stream:I.stream,content:I.output}),$d();break}case"chat.tool_result":{if(!Ht(s,((C=r().currentSession)==null?void 0:C.id)??null)){u();break}const I=s.payload,$=B=>{var Z;const X=(Z=B.toolCalls)==null?void 0:Z.map(P=>P.id===I.callId?{...P,result:I.result}:P);return{...B,toolCalls:X}};e(B=>{const X=B.streamingMessage;return X&&X.id===I.messageId?{streamingMessage:$(X)}:{messages:B.messages.map(Z=>Z.id===I.messageId?$(Z):Z)}});break}case"chat.vision_fallback":{if(!Ht(s,((y=r().currentSession)==null?void 0:y.id)??null)){u();break}const I=s.payload;e($=>{const B=`${I.messageId}-${I.attachmentId}`,X={...$.visionFallbackByMessage};return X[B]={type:I.type,attachmentId:I.attachmentId,filename:I.filename,description:I.description},{visionFallbackByMessage:X}});break}case"chat.todo":{if(!Ht(s,((v=r().currentSession)==null?void 0:v.id)??null)){u();break}const I=s.payload;e({currentTodos:I.todos});break}case"chat.summary":{if(!Ht(s,((x=r().currentSession)==null?void 0:x.id)??null)){u();break}const I=s.payload;e($=>({currentSession:$.currentSession?{...$.currentSession,summary:I.summary}:null}));break}case"chat.progress":{if(!Ht(s,((_=r().currentSession)==null?void 0:_.id)??null)){u();break}const I=s.payload;console.log("Progress:",I.message,I.phase);break}case"chat.format_retry":{if(!Ht(s,((j=r().currentSession)==null?void 0:j.id)??null)){u();break}const I=s.payload;console.log("Format retry:",I.attempt,"/",I.maxAttempts);break}case"chat.done":{if(!Ht(s,((T=r().currentSession)==null?void 0:T.id)??null)){u();break}Is(),mn==null||mn();const I=s.payload,$=I.stats;Wt.messageId=null,Wt.deltaContent="",Wt.thinkingContent="",Wt.toolOutput=[],Ud.delete(I.messageId),e(B=>{const X=B.streamingMessage,Z=X&&X.id===I.messageId?{...X,isStreaming:!1,stats:$??X.stats}:null;return{messages:B.messages.map(P=>P.id===I.messageId?Z??{...P,isStreaming:!1,stats:$??P.stats}:P),streamingMessageId:null,streamingMessage:null,visionFallbackByMessage:{}}});break}case"chat.error":{if(!Ht(s,((N=r().currentSession)==null?void 0:N.id)??null)){u();break}Is(),mn==null||mn();const I=s.payload;console.error("Chat error:",I.error,"recoverable:",I.recoverable),I.recoverable||(Wt.messageId=null,Wt.deltaContent="",Wt.thinkingContent="",Wt.toolOutput=[]),e($=>({error:{code:"CHAT_ERROR",message:I.error},streamingMessageId:I.recoverable?$.streamingMessageId:null,...I.recoverable?{}:{messages:$.streamingMessage?$.messages.map(B=>B.id===$.streamingMessage.id?$.streamingMessage:B):$.messages,streamingMessage:null}}));break}case"chat.path_confirmation":{if(!Ht(s,((D=r().currentSession)==null?void 0:D.id)??null)){u();break}const I=s.payload;e({pendingPathConfirmation:{callId:I.callId,tool:I.tool,paths:I.paths,workdir:I.workdir,reason:I.reason}});break}case"chat.ask_user":{if(!Ht(s,((A=r().currentSession)==null?void 0:A.id)??null)){u();return}const I=s.payload;e({pendingQuestion:{callId:I.callId,question:I.question}});break}case"mode.changed":{if(!Ht(s,((z=r().currentSession)==null?void 0:z.id)??null)){u();break}const I=s.payload;e($=>({currentSession:$.currentSession?{...$.currentSession,mode:I.mode}:null}));break}case"phase.changed":{const I=s.payload,$=s.sessionId,B=(O=r().currentSession)==null?void 0:O.id,X=$&&$!==B;e(Z=>({sessions:Z.sessions.map(P=>P.id===$?{...P,phase:I.phase}:P)})),X||e(Z=>({currentSession:Z.currentSession?{...Z.currentSession,phase:I.phase}:null}));break}case"criteria.updated":{if(!Ht(s,((q=r().currentSession)==null?void 0:q.id)??null)){u();break}const I=s.payload;e($=>({currentSession:$.currentSession?{...$.currentSession,criteria:I.criteria}:null}));break}case"context.state":{const I=s.payload,$=Ht(s,((G=r().currentSession)==null?void 0:G.id)??null);I.subAgentId?$&&r().updateSubAgentContextState(I.subAgentId,I.context):$?e({contextState:I.context}):u();break}case"session.name_generated":{const I=s.payload,$=s.sessionId,B=(W=r().currentSession)==null?void 0:W.id;e(X=>{const Z=X.sessions.map(R=>R.id===$?{...R,title:I.name,updatedAt:new Date().toISOString()}:R),P=B===$?X.currentSession?{...X.currentSession,title:I.name,updatedAt:new Date().toISOString()}:null:X.currentSession;return{sessions:Z,currentSession:P}});break}case"queue.state":{const I=s.payload;e({queuedMessages:I.messages});break}case"devServer.output":case"devServer.state":{mr.getState().handleMessage(s);break}case"backgroundProcess.started":case"backgroundProcess.output":case"backgroundProcess.exited":case"backgroundProcess.removed":{eo.getState().handleMessage(s.type,s.payload);break}case"error":{const I=s.payload;console.error("Server error:",I),e({error:{code:I.code,message:I.message},streamingMessageId:null});break}}}}));function Fb(){return Ce(e=>{var r;return((r=e.currentSession)==null?void 0:r.isRunning)??!1})}function lw(){return Ce(e=>e.queuedMessages)}function cw(){return Ce(e=>e.abortInProgress)}function uw(){const e=Ce(i=>i.connect),r=Ce(i=>i.connectionStatus),s=Fs(i=>i.load);return H.useEffect(()=>{e()},[e]),H.useEffect(()=>{r==="connected"&&s()},[r,s]),{connectionStatus:r}}const dw="modulepreload",hw=function(e){return"/"+e},Yx={},mh=function(r,s,i){let l=Promise.resolve();if(s&&s.length>0){let h=function(p){return Promise.all(p.map(g=>Promise.resolve(g).then(m=>({status:"fulfilled",value:m}),m=>({status:"rejected",reason:m}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),d=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));l=h(s.map(p=>{if(p=hw(p),p in Yx)return;Yx[p]=!0;const g=p.endsWith(".css"),m=g?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${m}`))return;const b=document.createElement("link");if(b.rel=g?"stylesheet":dw,g||(b.as="script"),b.crossOrigin="",b.href=p,d&&b.setAttribute("nonce",d),document.head.appendChild(b),g)return new Promise((S,k)=>{b.addEventListener("load",S),b.addEventListener("error",()=>k(new Error(`Unable to preload CSS for ${p}`)))})}))}function u(h){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=h,window.dispatchEvent(c),!c.defaultPrevented)throw h}return l.then(h=>{for(const c of h||[])c.status==="rejected"&&u(c.reason);return r().catch(u)})},Ub=[{key:"color-bg-primary",category:"background",label:"Primary Background",defaultValue:"13 17 23"},{key:"color-bg-secondary",category:"background",label:"Secondary Background",defaultValue:"22 27 34"},{key:"color-bg-tertiary",category:"background",label:"Tertiary Background",defaultValue:"33 38 45"},{key:"color-primary",category:"surface",label:"Primary Surface",defaultValue:"10 10 10"},{key:"color-secondary",category:"surface",label:"Secondary Surface",defaultValue:"20 20 20"},{key:"color-text-primary",category:"text",label:"Primary Text",defaultValue:"139 148 158"},{key:"color-text-secondary",category:"text",label:"Secondary Text",defaultValue:"139 148 158"},{key:"color-text-muted",category:"text",label:"Muted Text",defaultValue:"72 79 88"},{key:"color-accent-primary",category:"accent",label:"Primary Accent",defaultValue:"88 166 255"},{key:"color-accent-success",category:"accent",label:"Success Accent",defaultValue:"63 185 80"},{key:"color-accent-warning",category:"accent",label:"Warning Accent",defaultValue:"210 153 34"},{key:"color-accent-error",category:"accent",label:"Error Accent",defaultValue:"248 81 73"},{key:"color-border",category:"border",label:"Border",defaultValue:"48 53 60"}],gr=[{id:"dark",name:"Dark",tokens:{"color-bg-primary":"13 17 23","color-bg-secondary":"22 27 34","color-bg-tertiary":"33 38 45","color-primary":"10 10 10","color-secondary":"20 20 20","color-text-primary":"139 148 158","color-text-secondary":"139 148 158","color-text-muted":"72 79 88","color-accent-primary":"88 166 255","color-accent-success":"63 185 80","color-accent-warning":"210 153 34","color-accent-error":"248 81 73","color-border":"48 53 60"}},{id:"light",name:"Light",tokens:{"color-bg-primary":"255 255 255","color-bg-secondary":"250 251 252","color-bg-tertiary":"243 244 246","color-primary":"245 245 245","color-secondary":"229 229 229","color-text-primary":"15 23 42","color-text-secondary":"30 41 59","color-text-muted":"100 116 139","color-accent-primary":"37 99 235","color-accent-success":"22 163 74","color-accent-warning":"217 119 6","color-accent-error":"220 38 38","color-border":"203 213 225"}},{id:"monokai",name:"Monokai",tokens:{"color-bg-primary":"39 40 34","color-bg-secondary":"30 31 28","color-bg-tertiary":"62 61 50","color-primary":"30 31 28","color-secondary":"45 46 39","color-text-primary":"248 248 242","color-text-secondary":"207 207 194","color-text-muted":"117 113 94","color-accent-primary":"102 217 239","color-accent-success":"166 226 46","color-accent-warning":"230 219 116","color-accent-error":"249 38 114","color-border":"73 72 62"}},{id:"dracula",name:"Dracula",tokens:{"color-bg-primary":"40 42 54","color-bg-secondary":"33 34 44","color-bg-tertiary":"68 71 90","color-primary":"30 31 41","color-secondary":"44 46 61","color-text-primary":"248 248 242","color-text-secondary":"230 230 230","color-text-muted":"98 114 164","color-accent-primary":"189 147 249","color-accent-success":"80 250 123","color-accent-warning":"255 184 108","color-accent-error":"255 85 85","color-border":"68 71 90"}},{id:"nord",name:"Nord",tokens:{"color-bg-primary":"46 52 64","color-bg-secondary":"59 66 82","color-bg-tertiary":"67 76 94","color-primary":"46 52 64","color-secondary":"59 66 82","color-text-primary":"236 239 244","color-text-secondary":"229 233 240","color-text-muted":"76 86 106","color-accent-primary":"129 161 193","color-accent-success":"163 190 140","color-accent-warning":"235 203 139","color-accent-error":"191 97 106","color-border":"76 86 106"}}];function Xx(){try{const e=localStorage.getItem("openfox:userPresets");if(e)return JSON.parse(e)}catch{}return[]}const dn=$n((e,r)=>({currentPreset:"dark",basePreset:"",customTokens:{},isCustom:!1,isCustomizing:!1,userPresets:Xx(),applySavedTheme:()=>{const{getSavedTheme:s,applyPreset:i,applyTokens:l}=r(),u=s();if(u)try{const h=JSON.parse(u);h.preset?i(h.preset):h.tokens&&l(h.tokens)}catch{i("dark")}else i("dark")},applyPreset:s=>{gr.find(l=>l.id===s)&&(e({currentPreset:s,basePreset:"",customTokens:{},isCustom:!1,isCustomizing:!1}),r().applyTheme())},startCustomizing:()=>{var l;const{currentPreset:s}=r(),i=((l=gr.find(u=>u.id===s))==null?void 0:l.tokens)??{};e({basePreset:s,customTokens:{...i},isCustom:!0,isCustomizing:!0})},setCustomToken:(s,i)=>{e(l=>({customTokens:{...l.customTokens,[s]:i}})),r().applyTheme()},cancelCustomizing:()=>{r().applyPreset(r().basePreset||r().currentPreset)},saveCustomTheme:()=>{const{customTokens:s}=r();r().saveTheme(JSON.stringify({tokens:s})),e({isCustomizing:!1})},applyTokens:s=>{e({customTokens:s,isCustom:!0,isCustomizing:!1}),r().applyTheme()},getActiveTheme:()=>{var h,c;const{basePreset:s,customTokens:i,isCustom:l}=r();if(l&&s)return{...((h=gr.find(p=>p.id===s))==null?void 0:h.tokens)??{},...i};if(l)return{...Ub.reduce((d,p)=>({...d,[p.key]:p.defaultValue}),{}),...i};const u=gr.find(d=>d.id===r().currentPreset);return(u==null?void 0:u.tokens)??((c=gr[0])==null?void 0:c.tokens)??{}},applyTheme:()=>{if(typeof document>"u")return;const s=r().getActiveTheme(),i=document.documentElement;Object.entries(s).forEach(([l,u])=>{i.style.setProperty(`--${l}`,u)})},getSavedTheme:()=>{try{const s=localStorage.getItem("openfox:theme");if(s){const i=JSON.parse(s);if(i.preset)return JSON.stringify({preset:i.preset});if(i.tokens)return JSON.stringify({tokens:i.tokens})}}catch{return null}return null},saveTheme:s=>{localStorage.setItem("openfox:theme",s),mh(async()=>{const{useSettingsStore:i}=await Promise.resolve().then(()=>Ox);return{useSettingsStore:i}},void 0).then(({useSettingsStore:i})=>{i.getState().setSetting(ot.DISPLAY_THEME,s).catch(()=>{})})},clearCustomTheme:()=>{localStorage.removeItem("openfox:theme"),e({isCustom:!1,isCustomizing:!1,basePreset:""})},reset:()=>{e({currentPreset:"dark",basePreset:"",customTokens:{},isCustom:!1,isCustomizing:!1,userPresets:[]})},addUserPreset:s=>{const{basePreset:i,customTokens:l,currentPreset:u}=r(),h={id:"custom-"+Date.now(),name:s,basePreset:i||u,tokens:{...l}},c=[...r().userPresets,h];e({userPresets:c}),r().saveUserPresets()},applyUserPreset:s=>{const i=r().userPresets[s];i&&(e({currentPreset:i.basePreset,basePreset:i.basePreset,customTokens:{...i.tokens},isCustom:!0,isCustomizing:!1}),r().applyTheme(),r().saveTheme(JSON.stringify({tokens:i.tokens})))},deleteUserPreset:s=>{const i=r().userPresets.filter((l,u)=>u!==s);e({userPresets:i}),r().saveUserPresets()},loadUserPresets:()=>{e({userPresets:Xx()})},saveUserPresets:()=>{localStorage.setItem("openfox:userPresets",JSON.stringify(r().userPresets)),mh(async()=>{const{useSettingsStore:s}=await Promise.resolve().then(()=>Ox);return{useSettingsStore:s}},void 0).then(({useSettingsStore:s})=>{s.getState().setSetting(ot.DISPLAY_USER_PRESETS,JSON.stringify(r().userPresets)).catch(()=>{})})}}));function fw({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 $b({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 pw({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 mw({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 gw({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 Ur({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 xr({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 xw({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 oc({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 vw({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 zh({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 lc({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 Yl({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 bw({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 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 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"})})}function _w({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 Sw({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 ww({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 Zx({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 qb({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 Cw({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 kw({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 Wb({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 Vb({className:e="",size:r="md"}){const s=r==="sm"?"w-4 h-4":"w-6 h-6";return o.jsxs("svg",{className:`animate-spin ${s} ${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 Gb=Vb,Kb=Vb;function Ew({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 jw({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 Nw({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 Tw({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 Aw({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 Dw({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 Lw({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 Yb({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 Xb(){return o.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})})}function Rw({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 Zb({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 Ph({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 Ow({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 gh(){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 Qx(e,r){const s=Vt.ws;!s||s.readyState!==WebSocket.OPEN||s.send(JSON.stringify({id:gh(),type:e,payload:r}))}const ir=$n((e,r)=>({isOpen:!1,sessions:[],workdir:null,setOpen:s=>e({isOpen:s}),toggleOpen:()=>e(s=>({isOpen:!s.isOpen})),setWorkdir:s=>e({workdir:s}),fetchSessions:async()=>{try{const s=await ke("/api/terminals");if(s.ok){const i=await s.json();e({sessions:i});const l=Vt.ws;if(l&&l.readyState===WebSocket.OPEN)for(const u of i)l.send(JSON.stringify({id:gh(),type:"terminal.subscribe",payload:{sessionId:u.id}}))}}catch(s){console.error("Failed to fetch terminals:",s)}},createSession:async s=>{try{const i=await ke("/api/terminals",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workdir:s??r().workdir??void 0})});if(i.ok){const l=await i.json();e(h=>({sessions:[...h.sessions,l]}));const u=Vt.ws;u&&u.readyState===WebSocket.OPEN&&u.send(JSON.stringify({id:gh(),type:"terminal.subscribe",payload:{sessionId:l.id}}))}}catch(i){console.error("Failed to create terminal:",i)}},writeSession:(s,i)=>{Qx("terminal.write",{sessionId:s,data:i})},resizeSession:(s,i,l)=>{Qx("terminal.resize",{sessionId:s,cols:i,rows:l})},killSession:async s=>{try{(await ke(`/api/terminals/${s}`,{method:"DELETE"})).ok&&e(l=>({sessions:l.sessions.filter(u=>u.id!==s)}))}catch(i){console.error("Failed to kill terminal:",i)}},handleMessage:s=>{switch(s.type){case"terminal.exit":{const{sessionId:i}=s.payload||{};i&&e(l=>{const u=l.sessions.filter(h=>h.id!==i);return u.length===0&&l.isOpen?{sessions:[],isOpen:!1}:{sessions:u}});break}}}}));Vt.subscribe(e=>{var r;(r=e.type)!=null&&r.startsWith("terminal.")&&ir.getState().handleMessage(e)});var go=kb();const cc=H.forwardRef(({icon:e,iconSize:r="w-3.5 h-3.5",className:s="",...i},l)=>o.jsx("button",{ref:l,type:"button",className:`p-1 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors ${s}`,...i,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})})}));cc.displayName="IconButton";const Mw="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",qi=H.forwardRef((e,r)=>o.jsx(cc,{ref:r,icon:Mw,title:"Edit",...e}));qi.displayName="EditButton";const Iw="M6 18L18 6M6 6l12 12",Hh=H.forwardRef((e,r)=>o.jsx(cc,{ref:r,icon:Iw,...e}));Hh.displayName="CloseButton";const Bw={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:s="md",minHeight:i,children:l,footer:u,className:h,onClose:c,isOpen:d,closeOnBackdropClick:p=!0,closeOnEscape:g=!0,showCloseButton:m=!0}){const[b,S]=H.useState(!1),k=d!==void 0,C=k?d:b,y=H.useCallback(()=>{k||S(!0)},[k]),v=H.useCallback(()=>{k||S(!1),c==null||c()},[k,c]);H.useEffect(()=>{if(!C||!g)return;const _=j=>{j.key==="Escape"&&v()};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[C,v,g]);const x=e&&(typeof e=="string"?o.jsx("button",{type:"button",onClick:y,className:h,children:e}):o.jsx("span",{onClick:y,className:h,style:{cursor:"pointer"},children:e}));return o.jsxs(o.Fragment,{children:[x,C&&(typeof document<"u"?go.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?v:void 0}),o.jsxs("div",{className:`relative w-full ${Bw[s]} 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(Hh,{onClick:v,className:"ml-auto","aria-label":"Close"})]}),o.jsx("div",{className:"p-4 overflow-y-auto flex-1 min-h-0",style:i?{minHeight:i}:void 0,children:l}),u&&o.jsx("div",{className:"px-4 py-3 border-t border-border",children:u})]})]}),document.body):null)]})}const st=H.forwardRef(({variant:e="secondary",size:r="md",className:s="",children:i,...l},u)=>{const h="rounded font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed",c={primary:"bg-accent-primary/25 text-text-primary 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:`${h} ${c[e]} ${d[r]} ${s}`,...l,children:i})});st.displayName="Button";function zw({value:e,defaultUrl:r,disabled:s,onChange:i}){const l=e??r;return o.jsxs("div",{className:"relative",children:[o.jsx("select",{value:l,disabled:s,onChange:u=>{const h=u.target.value;i(h===r?null:h)},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:G1.map(({url:u,label:h})=>o.jsx("option",{value:u,title:h,children:h.split(" ")[0]},u))}),o.jsx(xr,{className:"absolute right-0.5 top-1/2 -translate-y-1/2 w-3 h-3 pointer-events-none text-text-muted"})]})}const Jx=[{key:"general",label:"General"},{key:"build",label:"Agent"},{key:"sub-agent",label:"Sub-agent"}];function Pw(){const e=Fs(d=>d.settings),r=Fs(d=>d.update),s=Fs(d=>d.updateEvent),i=Fs(d=>d.updateAgentOverride),l=Fs(d=>d.load);H.useEffect(()=>{l()},[l]);const u=async()=>{await Y1()==="granted"&&r({...e,browserNotificationEnabled:!0})},h=(d,p,g,m)=>{d==="general"?s(p,{[g]:m}):i(d,p,{[g]:m})},c=(d,p,g)=>{d==="general"?s(p,{customSoundUrl:g}):i(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(ev,{label:"Sound notifications",description:"Play sounds when events occur",checked:e.soundEnabled,onChange:d=>r({...e,soundEnabled:d})}),o.jsx(ev,{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"}),Jx.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:V1.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})}),Jx.map(p=>{const g=Pb(e,d.key,p.key==="general"?void 0:p.key),m=Bb[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=>h(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=>h(p.key,d.key,"browserNotification",b.target.checked),disabled:!e.browserNotificationEnabled,className:"rounded border-border",title:"Browser"})})]}),g.soundEnabled&&e.soundEnabled&&o.jsx(zw,{value:g.customSoundUrl,defaultUrl:m,disabled:!e.soundEnabled,onChange:b=>c(p.key,d.key,b)})]})},p.key)})]},d.key))})]})})]})]})}function ev({label:e,description:r,checked:s,onChange:i}){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 ${s?"bg-accent-primary":"bg-bg-tertiary border border-border"}`,onClick:l=>{l.preventDefault(),i(!s)},children:o.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white shadow transition-transform ${s?"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 Fh(e,r){r({loading:!0});try{const i=await(await ke(e)).json();r({defaults:i.defaults??[],userItems:i.userItems??[],loading:!1})}catch{r({loading:!1})}}const Pr=$n((e,r)=>({defaults:[],userItems:[],loading:!1,fetchSkills:async()=>{await Fh("/api/skills",e)},toggleSkill:async s=>{try{const l=await(await ke(`/api/skills/${s}/toggle`,{method:"POST"})).json();e(u=>({defaults:u.defaults.map(h=>h.id===s?{...h,enabled:l.enabled}:h),userItems:u.userItems.map(h=>h.id===s?{...h,enabled:l.enabled}:h)}))}catch{}},fetchSkill:async s=>{try{const i=await ke(`/api/skills/${s}`);return i.ok?await i.json():null}catch{return null}},fetchDefaultContent:async s=>{try{const i=await ke(`/api/skills/defaults/${s}`);return i.ok?await i.json():null}catch{return null}},createSkill:async s=>{const i=await xs("POST","/api/skills",s);return i.success&&await r().fetchSkills(),i},updateSkill:async(s,i)=>{const l=await xs("PUT",`/api/skills/${s}`,i);return l.success&&await r().fetchSkills(),l},deleteSkill:async s=>{try{const i=await ke(`/api/skills/${s}`,{method:"DELETE"}),l=await i.json();return i.ok?(e(u=>({userItems:u.userItems.filter(h=>h.id!==s)})),{success:!0}):{success:!1,error:l.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateSkill:async s=>{try{const i=await ke(`/api/skills/${s}/duplicate`,{method:"POST"}),l=await i.json();return i.ok?(await r().fetchSkills(),{success:!0}):{success:!1,error:l.error??"Failed to duplicate"}}catch{return{success:!1,error:"Network error"}}}}));function Uh(){const[e,r]=H.useState({id:null,type:null}),s=H.useCallback(u=>r({id:u,type:"delete"}),[]),i=H.useCallback(()=>r({id:null,type:null}),[]),l=H.useCallback((u,h)=>e.id===u&&e.type===h,[e.id,e.type]);return{requestDelete:s,clearConfirm:i,isConfirming:l}}function $h({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 qh({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(Yb,{})})}function io({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(oc,{})})}function Us({label:e,value:r,onChange:s,placeholder:i,readOnly:l,hint:u,mono:h}){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:c=>s(c.target.value),readOnly:l,placeholder:i,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 ${h?"font-mono":""} ${l?"opacity-60":""}`})]})}function Hw({onCancel:e,onSave:r,saving:s,saveDisabled:i}){return o.jsxs("div",{className:"flex justify-end gap-2 pt-2 border-t border-border",children:[o.jsx(st,{variant:"secondary",onClick:e,children:"Cancel"}),o.jsx(st,{variant:"primary",onClick:r,disabled:s||i,children:s?"Saving...":"Save"})]})}function Wh({message:e}){return o.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded",children:e})}function Qb({description:e,onNew:r,newLabel:s="+ 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(st,{variant:"primary",size:"sm",onClick:r,children:s})})]})}function Jb({isBuiltIn:e,isConfirmingDelete:r,onView:s,onEdit:i,onDuplicate:l,onDelete:u,children:h}){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:h}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[e&&s&&o.jsx("button",{onClick:s,className:"p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",title:"View",children:o.jsx(lc,{})}),o.jsx(io,{onClick:l}),!e&&i&&o.jsx(qi,{onClick:i}),!e&&(r?o.jsx($h,{onConfirm:()=>{u==null||u()},onCancel:()=>{}}):o.jsx(qh,{onClick:()=>u==null?void 0:u()}))]})]})}function Fw({id:e,name:r,description:s,isBuiltIn:i,isConfirmingDelete:l,onView:u,onEdit:h,onDuplicate:c,onDelete:d}){return o.jsxs(Jb,{isBuiltIn:i,isConfirmingDelete:l,onView:u,onEdit:h,onDuplicate:c,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})]}),s&&o.jsx("p",{className:"text-text-muted text-xs truncate",children:s})]})}function ey({loading:e,hasItems:r,loadingLabel:s,emptyLabel:i,children:l}){return e&&!r?o.jsx("div",{className:"text-text-muted text-sm",children:s}):r?o.jsx("div",{className:"space-y-4",children:l}):i?o.jsx("div",{className:"text-text-muted text-sm",children:i}):null}function ty({name:e,id:r,nameLabel:s="Name",idLabel:i="ID",namePlaceholder:l="My Item",idPlaceholder:u="my-item",nameHint:h,readOnlyId:c=!1,readOnlyHint:d="(read-only)",onNameChange:p,onIdChange:g}){return o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Us,{label:s,value:e,onChange:p,placeholder:l,hint:h}),o.jsx(Us,{label:i,value:r,onChange:g,readOnly:c,placeholder:u,hint:c?d:void 0,mono:!0})]})}function ny(e={}){const{initialData:r={}}=e,[s,i]=H.useState("list"),[l,u]=H.useState(null),[h,c]=H.useState(""),[d,p]=H.useState(!1),[g,m]=H.useState(r),b=H.useCallback(()=>{m(r),c(""),u(null)},[r]),S=H.useCallback(v=>{i(v),v==="list"&&b()},[b]),k=H.useCallback(v=>{m(x=>typeof v=="function"?v(x):v)},[]),C=H.useCallback((v,x={})=>{u(v),i("edit"),m({...x}),c("")},[]),y=H.useCallback(()=>{u(null),i("edit"),m(r),c("")},[r]);return{view:s,editingId:l,formError:h,saving:d,formData:g,setView:S,setEditingId:u,setFormError:c,setFormData:k,setSaving:p,resetForm:b,startEditing:C,startNew:y}}function Vh(){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 tv({skill:e,isBuiltIn:r,isConfirmingDelete:s,onView:i,onEdit:l,onDuplicate:u,onDelete:h}){return o.jsx(Fw,{id:e.id,name:e.name,description:e.description,isBuiltIn:r,isConfirmingDelete:s,onView:i,onEdit:l,onDuplicate:u,onDelete:h})}function Uw({isOpen:e}){const r=Pr(I=>I.defaults),s=Pr(I=>I.userItems),i=Pr(I=>I.loading),l=Pr(I=>I.fetchSkills),u=Pr(I=>I.fetchSkill),h=Pr(I=>I.fetchDefaultContent),c=Pr(I=>I.createSkill),d=Pr(I=>I.updateSkill),p=Pr(I=>I.deleteSkill),{view:g,editingId:m,formError:b,saving:S,formData:k,setView:C,setEditingId:y,setFormError:v,setFormData:x,setSaving:_}=ny(),{clearConfirm:j}=Uh();H.useEffect(()=>{e&&(l(),C("list"),y(null),j())},[e,l,j]);const T=(I,$,B,X)=>{x({name:X??I.metadata.name,id:B??I.metadata.id,description:I.metadata.description??"",version:I.metadata.version??"1.0.0",prompt:I.prompt,isReadOnly:$})},N=async I=>{if(r.some(B=>B.id===I)){const B=await h(I);if(!B)return;T(B,!0),y(I),v(""),C("edit")}else{const B=await u(I);if(!B)return;T(B,!0),y(I),v(""),C("edit")}},D=async I=>{const B=r.some(Z=>Z.id===I)?await h(I):await u(I);if(!B)return;const X=`${I}-copy-${Date.now()}`;T(B,!1,X,`${B.metadata.name} (copy)`),y(null),v(""),C("edit")},A=()=>{x({name:"",id:"",description:"",version:"1.0.0",prompt:"",isReadOnly:!1}),C("edit")},z=async I=>{const $=await u(I);$&&(T($,!1),y(I),v(""),C("edit"))},O=async I=>{await p(I),j()},q=async()=>{const I=m??k.id;if(!I||!k.name||!k.prompt){v("Name, ID, and prompt are required.");return}_(!0),v("");const $={metadata:{id:I,name:k.name,description:k.description,version:k.version},prompt:k.prompt},B=m?await d(m,$):await c($);if(_(!1),!B.success){v(B.error??"Failed to save skill.");return}C("list")},G=I=>{x($=>({...$,name:I})),m||x($=>({...$,id:I.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(Wh,{message:b}),o.jsxs("div",{className:"space-y-3 mb-3",children:[o.jsx(ty,{name:k.name,id:k.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Skill",idPlaceholder:"my-skill",readOnlyId:!0,onNameChange:G,onIdChange:()=>{}}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Us,{label:"Description",value:k.description,onChange:I=>x($=>({...$,description:I})),placeholder:"What this skill does...",readOnly:W}),o.jsx(Us,{label:"Version",value:k.version,onChange:I=>x($=>({...$,version:I})),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:I=>x($=>({...$,prompt:I.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(Vh,{}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 border-t border-border flex-shrink-0",children:[o.jsx(st,{variant:"secondary",onClick:()=>C("list"),children:"Cancel"}),W?o.jsx(st,{variant:"primary",onClick:()=>{x(I=>({...I,name:I.name+" (copy)",id:`${m}-copy-${Date.now()}`,isReadOnly:!1})),y(null)},children:"Duplicate & Customize"}):o.jsx(st,{variant:"primary",onClick:q,disabled:S||!k.name||!k.id||!k.prompt,children:S?"Saving...":"Save"})]})]}):o.jsxs("div",{children:[o.jsx(Qb,{description:"Skills provide domain-specific knowledge that agents can load on demand.",onNew:A}),o.jsxs(ey,{loading:i,hasItems:r.length>0||s.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(I=>o.jsx(tv,{skill:I,isBuiltIn:!0,isConfirmingDelete:!1,onView:()=>N(I.id),onDuplicate:()=>D(I.id)},I.id))})]}),s.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:s.map(I=>o.jsx(tv,{skill:I,isBuiltIn:!1,isConfirmingDelete:!1,onView:()=>N(I.id),onEdit:()=>z(I.id),onDuplicate:()=>D(I.id),onDelete:()=>O(I.id)},I.id))})]})]})]})}function $w(e){const r=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);if(r){const s=parseInt(r[1]??"0",16),i=parseInt(r[2]??"0",16),l=parseInt(r[3]??"0",16);return`${s} ${i} ${l}`}return e}function Hs(e){const r=e.split(" ").map(s=>parseInt(s,10));return r.length===3&&r.every(s=>!isNaN(s))?`#${r.map(s=>(s??0).toString(16).padStart(2,"0")).join("")}`:e}function qw({isOpen:e,isNew:r,basePresetId:s,presetName:i,initialTokens:l,onClose:u,onSave:h}){const[c,d]=H.useState(l),[p,g]=H.useState(i);H.useEffect(()=>{d(l),g(i)},[l,i]);const m=(y,v)=>{const x=v.startsWith("#")?$w(v):v;d(_=>({..._,[y]:x}))},b=()=>{h(p.trim()||"Untitled",{...c})},S=Ub.reduce((y,v)=>{const x=v.category;return y[x]||(y[x]=[]),y[x].push(v),y},{}),k={background:"Backgrounds",surface:"Surfaces",text:"Text",accent:"Accents",border:"Border"},C=gr.find(y=>y.id===s);return o.jsx(jt,{isOpen:e,onClose:u,size:"lg",title:r?"New Theme":"Edit Theme",closeOnBackdropClick:!0,closeOnEscape:!0,footer:o.jsxs("div",{className:"flex gap-2 justify-end",children:[o.jsx("button",{type:"button",onClick:u,className:"px-4 py-2 border border-border rounded text-sm text-text-primary hover:bg-bg-tertiary transition-colors",children:"Cancel"}),o.jsx("button",{type:"button",onClick:b,className:"px-4 py-2 bg-accent-primary text-white rounded hover:bg-accent-primary/80 transition-colors text-sm",children:"Save"})]}),children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-muted block mb-1",children:"Name"}),o.jsx("input",{type:"text",value:p,onChange:y=>g(y.target.value),className:"w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-accent-primary"})]}),!r&&o.jsxs("div",{className:"text-xs text-text-muted",children:["Based on ",o.jsx("span",{className:"text-text-primary",children:C==null?void 0:C.name})]}),Object.entries(S).map(([y,v])=>o.jsxs("div",{className:"space-y-3",children:[o.jsx("h4",{className:"text-xs font-medium text-text-muted uppercase",children:k[y]??y}),o.jsx("div",{className:"grid grid-cols-2 gap-3",children:v.map(x=>o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("label",{htmlFor:x.key,className:"text-xs text-text-muted",children:x.label}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"color",id:x.key,value:Hs(c[x.key]??x.defaultValue),onChange:_=>m(x.key,_.target.value),className:"w-8 h-8 rounded cursor-pointer border border-border bg-transparent"}),o.jsx("input",{type:"text",value:c[x.key]??x.defaultValue,onChange:_=>m(x.key,_.target.value),className:"flex-1 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary font-mono focus:outline-none focus:ring-1 focus:ring-accent-primary"})]})]},x.key))})]},y))]})})}function Ww(){const[e,r]=H.useState(null),s=dn(x=>x.currentPreset),i=dn(x=>x.isCustom),l=dn(x=>x.basePreset),u=dn(x=>x.userPresets),h=dn(x=>x.applyPreset),c=dn(x=>x.applyUserPreset),d=dn(x=>x.deleteUserPreset),p=dn(x=>x.saveTheme),g=x=>{h(x),p(JSON.stringify({preset:x}))},m=x=>{c(x)},b=x=>{const _=gr.find(j=>j.id===x);_&&r({type:"new",presetIndex:u.length,basePresetId:x,presetName:_.name+" Copy",tokens:{..._.tokens}})},S=x=>{const _=u[x];if(!_)return;const j=gr.find(N=>N.id===_.basePreset),T=j?{...j.tokens,..._.tokens}:_.tokens;r({type:"edit",presetIndex:x,basePresetId:_.basePreset,presetName:_.name,tokens:T})},k=(x,_)=>{if(!e)return;const j=[...u];if(e.type==="new"){const T={id:"custom-"+Date.now(),name:x,basePreset:e.basePresetId,tokens:_};j.push(T);const N=j.length-1;dn.setState({userPresets:j}),dn.getState().saveUserPresets(),dn.getState().applyUserPreset(N)}else{const T=j[e.presetIndex];T&&(j[e.presetIndex]={...T,name:x,tokens:_}),dn.setState({userPresets:j}),dn.getState().saveUserPresets(),dn.getState().applyUserPreset(e.presetIndex)}r(null)},C=()=>{r(null)},y=(x,_)=>{x.stopPropagation(),d(_)},v=i?l:s;return o.jsxs("div",{className:"space-y-4",children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Theme"}),o.jsx("div",{className:"grid grid-cols-5 gap-2",children:gr.map(x=>o.jsxs("div",{className:"relative group",children:[o.jsxs("button",{type:"button",onClick:()=>g(x.id),className:`w-full flex flex-col items-center gap-2 px-3 py-3 rounded-lg border transition-colors ${v===x.id&&!i?"border-accent-primary bg-bg-tertiary text-text-primary":"border-border bg-bg-secondary text-text-muted hover:border-text-muted"}`,children:[o.jsx("div",{className:"w-8 h-8 rounded border flex items-center justify-center",style:{backgroundColor:Hs(x.tokens["color-bg-primary"]??"#000"),borderColor:Hs(x.tokens["color-border"]??"#000")},children:o.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:Hs(x.tokens["color-text-primary"]??"#fff")}})}),o.jsx("span",{className:"text-xs",children:x.name})]}),o.jsx("button",{type:"button",onClick:_=>{_.stopPropagation(),b(x.id)},className:"absolute top-1 right-1 w-6 h-6 rounded bg-bg-tertiary border border-border flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:border-text-muted",title:"Create custom theme based on this",children:o.jsx("span",{className:"text-xs",children:"✎"})})]},x.id))}),u.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("h4",{className:"text-xs font-medium text-text-muted uppercase",children:"My Themes"}),o.jsx("div",{className:"grid grid-cols-5 gap-2",children:u.map((x,_)=>{const j=gr.find(N=>N.id===x.basePreset),T=j?{...j.tokens,...x.tokens}:x.tokens;return o.jsxs("div",{className:"relative group",children:[o.jsxs("button",{type:"button",onClick:()=>m(_),className:`w-full flex flex-col items-center gap-2 px-3 py-3 rounded-lg border transition-colors ${i&&l===x.basePreset&&v===x.basePreset?"border-accent-primary bg-bg-tertiary text-text-primary":"border-border bg-bg-secondary text-text-muted hover:border-text-muted"}`,children:[o.jsx("div",{className:"w-8 h-8 rounded border flex items-center justify-center",style:{backgroundColor:Hs(T["color-bg-primary"]??"#000"),borderColor:Hs(T["color-border"]??"#000")},children:o.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:Hs(T["color-text-primary"]??"#fff")}})}),o.jsx("span",{className:"text-xs truncate w-full text-center",children:x.name})]}),o.jsx("button",{type:"button",onClick:N=>{N.stopPropagation(),S(_)},className:"absolute top-1 right-1 w-6 h-6 rounded bg-bg-tertiary border border-border flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:border-text-muted",title:"Edit",children:o.jsx("span",{className:"text-xs",children:"✎"})}),o.jsx("button",{type:"button",onClick:N=>y(N,_),className:"absolute -top-1 -left-1 w-5 h-5 rounded-full bg-accent-error text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-20",children:o.jsx(Ph,{className:"w-3 h-3"})})]},x.id)})})]}),e&&o.jsx(qw,{isOpen:!0,isNew:e.type==="new",presetIndex:e.presetIndex,basePresetId:e.basePresetId,presetName:e.presetName,initialTokens:e.tokens,onClose:C,onSave:k})]})}function Vw({isOpen:e,onClose:r}){const[s,i]=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(qa,{label:"Instructions",active:s==="instructions",onClick:()=>i("instructions")}),o.jsx(qa,{label:"Skills",active:s==="skills",onClick:()=>i("skills")}),o.jsx(qa,{label:"Notifications",active:s==="notifications",onClick:()=>i("notifications")}),o.jsx(qa,{label:"Display",active:s==="display",onClick:()=>i("display")}),o.jsx(qa,{label:"Advanced",active:s==="advanced",onClick:()=>i("advanced")})]}),s==="instructions"&&o.jsx(Xw,{isOpen:e}),s==="skills"&&o.jsx(Uw,{isOpen:e}),s==="notifications"&&o.jsx("div",{className:"max-h-[60vh] overflow-y-auto",children:o.jsx(Pw,{})}),s==="display"&&o.jsx(Yw,{}),s==="advanced"&&o.jsx(Gw,{onClose:r})]})})}function Gw({onClose:e}){const[,r]=vr();function s(){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(st,{variant:"secondary",onClick:s,children:"Launch Onboarding"})]})})}function Kw(){return o.jsx(Ww,{})}function Yw(){const e=Kt(g=>g.settings),r=Kt(g=>g.loading),s=Kt(g=>g.getSetting),i=Kt(g=>g.setSetting),l=r[ot.DISPLAY_SHOW_THINKING]??!1,u=[{key:ot.DISPLAY_SHOW_THINKING,label:"Show thinking blocks",description:"Display AI reasoning content in the feed"},{key:ot.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT,label:"Show expanded tool output",description:"Always show full tool call details instead of compact view"},{key:ot.DISPLAY_SHOW_STATS,label:"Show stats bar",description:"Display model, tokens, and timing information"},{key:ot.DISPLAY_SHOW_AGENT_DEFINITIONS,label:"Show agent definitions",description:"Display agent definition injections in the feed"},{key:ot.DISPLAY_SHOW_WORKFLOW_BARS,label:"Show workflow bars",description:"Display workflow start and end markers"}],h=Object.fromEntries(u.map(g=>[g.key,e[g.key]??"true"])),[c,d]=H.useState(()=>Object.fromEntries(u.map(g=>[g.key,h[g.key]==="true"])));H.useEffect(()=>{u.forEach(g=>s(g.key))},[s]),H.useEffect(()=>{d(Object.fromEntries(u.map(g=>[g.key,h[g.key]==="true"])))},[JSON.stringify(h)]);const p=async g=>{const m=String(!c[g]);d(b=>({...b,[g]:!b[g]})),await i(g,m)};return l?o.jsx("div",{className:"text-sm text-text-muted",children:"Loading..."}):o.jsxs("div",{className:"space-y-6",children:[o.jsx(Kw,{}),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 ${c[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 ${c[g]?"translate-x-6":"translate-x-1"}`})})]},g))})]})]})}function qa({label:e,active:r,onClick:s}){return o.jsx("button",{onClick:s,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 Xw({isOpen:e}){const r=Kt(y=>y.settings),s=Kt(y=>y.loading),i=Kt(y=>y.getSetting),l=Kt(y=>y.setSetting),u=r[ot.GLOBAL_INSTRUCTIONS]??"",h=s[ot.GLOBAL_INSTRUCTIONS]??!1,[c,d]=H.useState(u),[p,g]=H.useState(!1),[m,b]=H.useState(!1);H.useEffect(()=>{e&&i(ot.GLOBAL_INSTRUCTIONS)},[e,i]),H.useEffect(()=>{d(u),g(!1)},[u]);const S=async()=>{b(!0),l(ot.GLOBAL_INSTRUCTIONS,c),b(!1),g(!1)},k=()=>{d(u),g(!1)},C=h||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:c,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(Vh,{}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(st,{variant:"secondary",onClick:k,disabled:!p,children:"Discard"}),o.jsx(st,{variant:"primary",onClick:S,disabled:!p||C,children:m?"Saving...":"Save"})]})]})}var qd={exports:{}},nv;function Zw(){return nv||(nv=1,(function(e,r){(function(s,i){e.exports=i()})(globalThis,(()=>(()=>{var s={4567:function(h,c,d){var p=this&&this.__decorate||function(x,_,j,T){var N,D=arguments.length,A=D<3?_:T===null?T=Object.getOwnPropertyDescriptor(_,j):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(x,_,j,T);else for(var z=x.length-1;z>=0;z--)(N=x[z])&&(A=(D<3?N(A):D>3?N(_,j,A):N(_,j))||A);return D>3&&A&&Object.defineProperty(_,j,A),A},g=this&&this.__param||function(x,_){return function(j,T){_(j,T,x)}};Object.defineProperty(c,"__esModule",{value:!0}),c.AccessibilityManager=void 0;const m=d(9042),b=d(9924),S=d(844),k=d(4725),C=d(2585),y=d(3656);let v=c.AccessibilityManager=class extends S.Disposable{constructor(x,_,j,T){super(),this._terminal=x,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,S.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(x){for(let _=0;_<x;_++)this._handleChar(" ")}_handleChar(x){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==x&&(this._charsToAnnounce+=x):this._charsToAnnounce+=x,x===`
|
|
59
59
|
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=m.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(x){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(x)||this._charsToConsume.push(x)}_refreshRows(x,_){this._liveRegionDebouncer.refresh(x,_,this._terminal.rows)}_renderRows(x,_){const j=this._terminal.buffer,T=j.lines.length.toString();for(let N=x;N<=_;N++){const D=j.lines.get(j.ydisp+N),A=[],z=(D==null?void 0:D.translateToString(!0,void 0,void 0,A))||"",O=(j.ydisp+N+1).toString(),q=this._rowElements[N];q&&(z.length===0?(q.innerText=" ",this._rowColumns.set(q,[0,1])):(q.textContent=z,this._rowColumns.set(q,A)),q.setAttribute("aria-posinset",O),q.setAttribute("aria-setsize",T))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(x,_){const j=x.target,T=this._rowElements[_===0?1:this._rowElements.length-2];if(j.getAttribute("aria-posinset")===(_===0?"1":`${this._terminal.buffer.lines.length}`)||x.relatedTarget!==T)return;let N,D;if(_===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),_===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(_===0?-1:1),this._rowElements[_===0?1:this._rowElements.length-2].focus(),x.preventDefault(),x.stopImmediatePropagation()}_handleSelectionChange(){var z;if(this._rowElements.length===0)return;const x=document.getSelection();if(!x)return;if(x.isCollapsed)return void(this._rowContainer.contains(x.anchorNode)&&this._terminal.clearSelection());if(!x.anchorNode||!x.focusNode)return void console.error("anchorNode and/or focusNode are null");let _={node:x.anchorNode,offset:x.anchorOffset},j={node:x.focusNode,offset:x.focusOffset};if((_.node.compareDocumentPosition(j.node)&Node.DOCUMENT_POSITION_PRECEDING||_.node===j.node&&_.offset>j.offset)&&([_,j]=[j,_]),_.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(_={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(_.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:((z=T.textContent)==null?void 0:z.length)??0}),!this._rowContainer.contains(j.node))return;const N=({node:O,offset:q})=>{const G=O instanceof Text?O.parentNode:O;let W=parseInt(G==null?void 0:G.getAttribute("aria-posinset"),10)-1;if(isNaN(W))return console.warn("row is invalid. Race condition?"),null;const I=this._rowColumns.get(G);if(!I)return console.warn("columns is null. Race condition?"),null;let $=q<I.length?I[q]:I.slice(-1)[0]+1;return $>=this._terminal.cols&&(++W,$=0),{row:W,column:$}},D=N(_),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(x){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let _=this._rowContainer.children.length;_<this._terminal.rows;_++)this._rowElements[_]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[_]);for(;this._rowElements.length>x;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const x=this._coreBrowserService.mainDocument.createElement("div");return x.setAttribute("role","listitem"),x.tabIndex=-1,this._refreshRowDimensions(x),x}_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 x=0;x<this._terminal.rows;x++)this._refreshRowDimensions(this._rowElements[x])}}_refreshRowDimensions(x){x.style.height=`${this._renderService.dimensions.css.cell.height}px`}};c.AccessibilityManager=v=p([g(1,C.IInstantiationService),g(2,k.ICoreBrowserService),g(3,k.IRenderService)],v)},3614:(h,c)=>{function d(b){return b.replace(/\r?\n/g,"\r")}function p(b,S){return S?"\x1B[200~"+b+"\x1B[201~":b}function g(b,S,k,C){b=p(b=d(b),k.decPrivateModes.bracketedPasteMode&&C.rawOptions.ignoreBracketedPasteMode!==!0),k.triggerDataEvent(b,!0),S.value=""}function m(b,S,k){const C=k.getBoundingClientRect(),y=b.clientX-C.left-10,v=b.clientY-C.top-10;S.style.width="20px",S.style.height="20px",S.style.left=`${y}px`,S.style.top=`${v}px`,S.style.zIndex="1000",S.focus()}Object.defineProperty(c,"__esModule",{value:!0}),c.rightClickHandler=c.moveTextAreaUnderMouseCursor=c.paste=c.handlePasteEvent=c.copyHandler=c.bracketTextForPaste=c.prepareTextForTerminal=void 0,c.prepareTextForTerminal=d,c.bracketTextForPaste=p,c.copyHandler=function(b,S){b.clipboardData&&b.clipboardData.setData("text/plain",S.selectionText),b.preventDefault()},c.handlePasteEvent=function(b,S,k,C){b.stopPropagation(),b.clipboardData&&g(b.clipboardData.getData("text/plain"),S,k,C)},c.paste=g,c.moveTextAreaUnderMouseCursor=m,c.rightClickHandler=function(b,S,k,C,y){m(b,S,k),y&&C.rightClickSelect(b),S.value=C.selectionText,S.select()}},7239:(h,c,d)=>{Object.defineProperty(c,"__esModule",{value:!0}),c.ColorContrastCache=void 0;const p=d(1505);c.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:(h,c)=>{Object.defineProperty(c,"__esModule",{value:!0}),c.addDisposableDomListener=void 0,c.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(h,c,d){var p=this&&this.__decorate||function(v,x,_,j){var T,N=arguments.length,D=N<3?x:j===null?j=Object.getOwnPropertyDescriptor(x,_):j;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")D=Reflect.decorate(v,x,_,j);else for(var A=v.length-1;A>=0;A--)(T=v[A])&&(D=(N<3?T(D):N>3?T(x,_,D):T(x,_))||D);return N>3&&D&&Object.defineProperty(x,_,D),D},g=this&&this.__param||function(v,x){return function(_,j){x(_,j,v)}};Object.defineProperty(c,"__esModule",{value:!0}),c.Linkifier=void 0;const m=d(3656),b=d(8460),S=d(844),k=d(2585),C=d(4725);let y=c.Linkifier=class extends S.Disposable{get currentLink(){return this._currentLink}constructor(v,x,_,j,T){super(),this._element=v,this._mouseService=x,this._renderService=_,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,S.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,S.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(v){this._lastMouseEvent=v;const x=this._positionFromMouseEvent(v,this._element,this._mouseService);if(!x)return;this._isMouseOut=!1;const _=v.composedPath();for(let j=0;j<_.length;j++){const T=_[j];if(T.classList.contains("xterm"))break;if(T.classList.contains("xterm-hover"))return}this._lastBufferCell&&x.x===this._lastBufferCell.x&&x.y===this._lastBufferCell.y||(this._handleHover(x),this._lastBufferCell=x)}_handleHover(v){if(this._activeLine!==v.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(v,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,v)||(this._clearCurrentLink(),this._askForLink(v,!0))}_askForLink(v,x){var j,T;this._activeProviderReplies&&x||((j=this._activeProviderReplies)==null||j.forEach((N=>{N==null||N.forEach((D=>{D.link.dispose&&D.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=v.y);let _=!1;for(const[N,D]of this._linkProviderService.linkProviders.entries())x?(T=this._activeProviderReplies)!=null&&T.get(N)&&(_=this._checkLinkProviderResult(N,v,_)):D.provideLinks(v.y,(A=>{var O,q;if(this._isMouseOut)return;const z=A==null?void 0:A.map((G=>({link:G})));(O=this._activeProviderReplies)==null||O.set(N,z),_=this._checkLinkProviderResult(N,v,_),((q=this._activeProviderReplies)==null?void 0:q.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(v.y,this._activeProviderReplies)}))}_removeIntersectingLinks(v,x){const _=new Set;for(let j=0;j<x.size;j++){const T=x.get(j);if(T)for(let N=0;N<T.length;N++){const D=T[N],A=D.link.range.start.y<v?0:D.link.range.start.x,z=D.link.range.end.y>v?this._bufferService.cols:D.link.range.end.x;for(let O=A;O<=z;O++){if(_.has(O)){T.splice(N--,1);break}_.add(O)}}}}_checkLinkProviderResult(v,x,_){var N;if(!this._activeProviderReplies)return _;const j=this._activeProviderReplies.get(v);let T=!1;for(let D=0;D<v;D++)this._activeProviderReplies.has(D)&&!this._activeProviderReplies.get(D)||(T=!0);if(!T&&j){const D=j.find((A=>this._linkAtPosition(A.link,x)));D&&(_=!0,this._handleNewLink(D))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!_)for(let D=0;D<this._activeProviderReplies.size;D++){const A=(N=this._activeProviderReplies.get(D))==null?void 0:N.find((z=>this._linkAtPosition(z.link,x)));if(A){_=!0,this._handleNewLink(A);break}}return _}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(v){if(!this._currentLink)return;const x=this._positionFromMouseEvent(v,this._element,this._mouseService);x&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,x)&&this._currentLink.link.activate(v,this._currentLink.link.text)}_clearCurrentLink(v,x){this._currentLink&&this._lastMouseEvent&&(!v||!x||this._currentLink.link.range.start.y>=v&&this._currentLink.link.range.end.y<=x)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,S.disposeArray)(this._linkCacheDisposables))}_handleNewLink(v){if(!this._lastMouseEvent)return;const x=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);x&&this._linkAtPosition(v.link,x)&&(this._currentLink=v,this._currentLink.state={decorations:{underline:v.link.decorations===void 0||v.link.decorations.underline,pointerCursor:v.link.decorations===void 0||v.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,v.link,this._lastMouseEvent),v.link.decorations={},Object.defineProperties(v.link.decorations,{pointerCursor:{get:()=>{var _,j;return(j=(_=this._currentLink)==null?void 0:_.state)==null?void 0:j.decorations.pointerCursor},set:_=>{var j;(j=this._currentLink)!=null&&j.state&&this._currentLink.state.decorations.pointerCursor!==_&&(this._currentLink.state.decorations.pointerCursor=_,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",_))}},underline:{get:()=>{var _,j;return(j=(_=this._currentLink)==null?void 0:_.state)==null?void 0:j.decorations.underline},set:_=>{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)!==_&&(this._currentLink.state.decorations.underline=_,this._currentLink.state.isHovered&&this._fireUnderlineEvent(v.link,_))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((_=>{if(!this._currentLink)return;const j=_.start===0?0:_.start+1+this._bufferService.buffer.ydisp,T=this._bufferService.buffer.ydisp+1+_.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(v,x,_){var j;(j=this._currentLink)!=null&&j.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(x,!0),this._currentLink.state.decorations.pointerCursor&&v.classList.add("xterm-cursor-pointer")),x.hover&&x.hover(_,x.text)}_fireUnderlineEvent(v,x){const _=v.range,j=this._bufferService.buffer.ydisp,T=this._createLinkUnderlineEvent(_.start.x-1,_.start.y-j-1,_.end.x,_.end.y-j-1,void 0);(x?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(T)}_linkLeave(v,x,_){var j;(j=this._currentLink)!=null&&j.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(x,!1),this._currentLink.state.decorations.pointerCursor&&v.classList.remove("xterm-cursor-pointer")),x.leave&&x.leave(_,x.text)}_linkAtPosition(v,x){const _=v.range.start.y*this._bufferService.cols+v.range.start.x,j=v.range.end.y*this._bufferService.cols+v.range.end.x,T=x.y*this._bufferService.cols+x.x;return _<=T&&T<=j}_positionFromMouseEvent(v,x,_){const j=_.getCoords(v,x,this._bufferService.cols,this._bufferService.rows);if(j)return{x:j[0],y:j[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(v,x,_,j,T){return{x1:v,y1:x,x2:_,y2:j,cols:this._bufferService.cols,fg:T}}};c.Linkifier=y=p([g(1,C.IMouseService),g(2,C.IRenderService),g(3,k.IBufferService),g(4,C.ILinkProviderService)],y)},9042:(h,c)=>{Object.defineProperty(c,"__esModule",{value:!0}),c.tooMuchOutput=c.promptLabel=void 0,c.promptLabel="Terminal input",c.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(h,c,d){var p=this&&this.__decorate||function(C,y,v,x){var _,j=arguments.length,T=j<3?y:x===null?x=Object.getOwnPropertyDescriptor(y,v):x;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")T=Reflect.decorate(C,y,v,x);else for(var N=C.length-1;N>=0;N--)(_=C[N])&&(T=(j<3?_(T):j>3?_(y,v,T):_(y,v))||T);return j>3&&T&&Object.defineProperty(y,v,T),T},g=this&&this.__param||function(C,y){return function(v,x){y(v,x,C)}};Object.defineProperty(c,"__esModule",{value:!0}),c.OscLinkProvider=void 0;const m=d(511),b=d(2585);let S=c.OscLinkProvider=class{constructor(C,y,v){this._bufferService=C,this._optionsService=y,this._oscLinkService=v}provideLinks(C,y){var z;const v=this._bufferService.buffer.lines.get(C-1);if(!v)return void y(void 0);const x=[],_=this._optionsService.rawOptions.linkHandler,j=new m.CellData,T=v.getTrimmedLength();let N=-1,D=-1,A=!1;for(let O=0;O<T;O++)if(D!==-1||v.hasContent(O)){if(v.loadCell(O,j),j.hasExtendedAttrs()&&j.extended.urlId){if(D===-1){D=O,N=j.extended.urlId;continue}A=j.extended.urlId!==N}else D!==-1&&(A=!0);if(A||D!==-1&&O===T-1){const q=(z=this._oscLinkService.getLinkData(N))==null?void 0:z.uri;if(q){const G={start:{x:D+1,y:C},end:{x:O+(A||O!==T-1?0:1),y:C}};let W=!1;if(!(_!=null&&_.allowNonHttpProtocols))try{const I=new URL(q);["http:","https:"].includes(I.protocol)||(W=!0)}catch{W=!0}W||x.push({text:q,range:G,activate:(I,$)=>_?_.activate(I,$,G):k(0,$),hover:(I,$)=>{var B;return(B=_==null?void 0:_.hover)==null?void 0:B.call(_,I,$,G)},leave:(I,$)=>{var B;return(B=_==null?void 0:_.leave)==null?void 0:B.call(_,I,$,G)}})}A=!1,j.hasExtendedAttrs()&&j.extended.urlId?(D=O,N=j.extended.urlId):(D=-1,N=-1)}}y(x)}};function k(C,y){if(confirm(`Do you want to navigate to ${y}?
|
|
60
60
|
|
|
@@ -146,7 +146,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
146
146
|
`,children:s?"Reconnecting...":"Reconnect"})]})}function kA(){const e=cw(),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 EA({attachment:e,onRemove:r}){const s=i=>i<1024?`${i} B`:i<1048576?`${(i/1024).toFixed(1)} KB`:`${(i/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(ao,{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:s(e.size)})]})}function jA({history:e,selectedIndex:r,onSelect:s,onEscape:i,onNavigate:l}){const u=H.useRef(null),h=H.useRef(null);H.useEffect(()=>{h.current&&u.current&&h.current.scrollIntoView({block:"nearest",behavior:"smooth"})},[r]);const c=p=>{switch(p.key){case"Enter":p.preventDefault(),e[r]&&s(e[r].content);break;case"Escape":p.preventDefault(),i();break;case"ArrowUp":p.preventDefault(),l("up");break;case"ArrowDown":p.preventDefault(),l("down");break}},d=p=>{s(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:c,children:e.map((p,g)=>o.jsxs("div",{ref:g===r?h: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 hn=$n((e,r)=>({defaults:[],userItems:[],loading:!1,fetchCommands:async()=>{await Fh("/api/commands",e)},fetchCommand:async s=>{try{const i=await ke(`/api/commands/${s}`);return i.ok?await i.json():null}catch{return null}},fetchDefaultContent:async s=>{try{const i=await ke(`/api/commands/defaults/${s}`);return i.ok?await i.json():null}catch{return null}},createCommand:async s=>{const i=await xs("POST","/api/commands",s);return i.success&&await r().fetchCommands(),i},updateCommand:async(s,i)=>{const l=await xs("PUT",`/api/commands/${s}`,i);return l.success&&await r().fetchCommands(),l},deleteCommand:async s=>{try{const i=await ke(`/api/commands/${s}`,{method:"DELETE"}),l=await i.json();return i.ok?(e(u=>({userItems:u.userItems.filter(h=>h.id!==s)})),{success:!0}):{success:!1,error:l.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateCommand:async s=>{try{const i=await ke(`/api/commands/${s}/duplicate`,{method:"POST"}),l=await i.json();return i.ok?(await r().fetchCommands(),{success:!0}):{success:!1,error:l.error??"Failed to duplicate"}}catch{return{success:!1,error:"Network error"}}}})),NA={maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576};async function TA(e,r={}){const s={...NA,...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<=s.maxSizeBytes){const l=await e.arrayBuffer(),u=IA(l),h=`data:${e.type};base64,${u}`,c=await M0(h);return{dataUrl:h,mimeType:e.type,size:e.size,width:c.width,height:c.height}}return await AA(e,s)}async function AA(e,r){const s=await LA(e),i=await M0(s),{width:l,height:u}=DA(i.width,i.height,r.maxWidth,r.maxHeight),h=RA();h.width=l,h.height=u;const c=h.getContext("2d");if(!c)throw new Error("Failed to get canvas context");c.imageSmoothingEnabled=!0,c.imageSmoothingQuality="high",c.drawImage(i,0,0,l,u);let d=r.quality,p;do{if(p=h.toDataURL(e.type.startsWith("image/gif")?"image/png":e.type,d),vb(p)<=r.maxSizeBytes||d<=.3)break;d-=.1}while(!0);const g=vb(p);return{dataUrl:p,mimeType:e.type.startsWith("image/gif")?"image/png":e.type,size:g,width:l,height:u}}function DA(e,r,s,i){const l=e/r;return e>r&&e>s?{width:s,height:Math.round(s/l)}:r>e&&r>i?{width:Math.round(i*l),height:i}:{width:e,height:r}}function LA(e){return new Promise((r,s)=>{const i=MA(),l=new i;l.onload=()=>r(l.result),l.onerror=()=>s(new Error("Failed to read file")),l.readAsDataURL(e)})}function M0(e){return new Promise((r,s)=>{const i=OA(),l=new i;l.onload=()=>r(l),l.onerror=()=>s(new Error("Failed to load image")),l.src=e})}function RA(){var r;const e=Nf();if(!((r=e.document)!=null&&r.createElement))throw new Error("Image compression requires browser canvas APIs");return e.document.createElement("canvas")}function OA(){const e=Nf();if(!e.Image)throw new Error("Image compression requires browser image APIs");return e.Image}function MA(){const e=Nf();if(!e.FileReader)throw new Error("Image compression requires browser file APIs");return e.FileReader}function Nf(){return globalThis}function IA(e){const r=new Uint8Array(e);let s="";for(let i=0;i<r.byteLength;i++){const l=r[i];l!==void 0&&(s+=String.fromCharCode(l))}return btoa(s)}function vb(e){const s=e.split(",")[1];return s?Math.round(s.length*3/4):0}function BA(e){return["image/png","image/jpeg","image/gif"].includes(e.type)}function zA(e,r=50*1024*1024){return e.size>r?{valid:!1,error:`Image file is too large (${bb(e.size)}). Maximum size is ${bb(r)}.`}:{valid:!0}}function bb(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}async function dh(e,r,s,i={}){const{maxSizeBytes:l=50*1024*1024,filename:u}=i;if(!BA(e)){s(`Unsupported file type: ${e.type}. Only PNG, JPG, and GIF are supported.`);return}const h=zA(e,l);if(!h.valid){s(h.error??"Image file is too large");return}try{const c=await TA(e,{maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576}),d={id:Mb(),filename:u??e.name,mimeType:c.mimeType,size:c.size,data:c.dataUrl};r(d)}catch(c){const d=c instanceof Error?c.message??"Failed to process image":"Failed to process image";s(d)}}function PA(e){const r={};let s=null;for(const i of e){if(i.role==="user"&&!i.isSystemGenerated){s=i.id;continue}i.role==="assistant"&&i.promptContext&&s&&r[s]===void 0&&(r[s]=i.promptContext)}return r}function hh(e){return{contextWindow:e.contextWindow,temperature:e.temperature??null,topP:e.topP??null,topK:e.topK??null,maxTokens:e.maxTokens??null}}function HA({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 Za({label:e,value:r,onChange:s,min:i,max:l,step:u=1,helpText:h,defaultValue:c}){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==="")s(null);else{const C=parseFloat(k);isNaN(C)||s(C)}},S=()=>{g?(m(!1),c!==void 0&&(p(c.toString()),s(c))):(m(!0),s(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:S,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:i,max:l,step:u,value:d,readOnly:g,onChange:k=>b(k.target.value),onClick:()=>g&&S(),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":""}`}),h&&o.jsx("p",{className:"text-xs text-text-muted mt-1",children:h})]})}function FA({isOpen:e,onClose:r,providerId:s,model:i}){const[l,u]=H.useState(()=>hh(i)),[h,c]=H.useState(!1),d=Lt(m=>m.updateModelSettings);H.useEffect(()=>{u(hh(i))},[i]);const p=async()=>{if(l.contextWindow<1024||l.contextWindow>1e7)return;c(!0);const m=l.temperature!==(i.temperature??null)||l.topP!==(i.topP??null)||l.topK!==(i.topK??null)||l.maxTokens!==(i.maxTokens??null);await d(s,i.id,{contextWindow:l.contextWindow,...m&&{temperature:l.temperature,topP:l.topP,topK:l.topK,maxTokens:l.maxTokens}}),c(!1),r()},g=()=>{u(hh(i)),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(st,{variant:"secondary",onClick:g,disabled:h,children:"Cancel"}),o.jsx(st,{variant:"primary",onClick:p,disabled:h||l.contextWindow<1024||l.contextWindow>1e7,children:h?"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:i.id})]}),o.jsx(Za,{label:"Context Window",value:l.contextWindow,onChange:m=>m!==null&&u(b=>({...b,contextWindow:m})),min:1024,max:1e7,helpText:"Range: 1,024 - 10,000,000 tokens"}),o.jsxs(HA,{label:"Sampling Parameters",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Za,{label:"Temperature",value:l.temperature,onChange:m=>u(b=>({...b,temperature:m})),min:0,max:2,step:.1,helpText:"0.0 - 2.0",defaultValue:1}),o.jsx(Za,{label:"Top P",value:l.topP,onChange:m=>u(b=>({...b,topP:m})),min:0,max:1,step:.05,helpText:"0.0 - 1.0",defaultValue:1})]}),o.jsx(Za,{label:"Top K",value:l.topK,onChange:m=>u(b=>({...b,topK:m})),min:1,max:200,helpText:"1 - 200 (leave as default if not supported)"})]}),o.jsx(Za,{label:"Max Tokens",value:l.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:[i.source==="backend"&&"Auto-detected from backend",i.source==="user"&&"Manually set",i.source==="default"&&"Default value"]})]})]})}):null}function UA(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function $A(){var $;const[,e]=vr(),r=Ce(B=>B.currentSession),s=Ce(B=>B.setSessionProvider),[i,l]=H.useState(!1),[u,h]=H.useState([]),[c,d]=H.useState(null),p=H.useRef(null),[g,m]=H.useState(null),b=H.useRef(new Set),S=Lt(B=>B.providers),k=Lt(B=>B.activeProviderId),C=Lt(B=>B.model);Lt(B=>B.backend);const y=Lt(B=>B.llmStatus),v=Lt(B=>B.activating),x=Lt(B=>B.activateProvider),_=Lt(B=>B.refreshModel),j=Lt(B=>B.refreshProviderModels);H.useEffect(()=>{function B(X){p.current&&!p.current.contains(X.target)&&(l(!1),h([]),b.current=new Set)}return document.addEventListener("mousedown",B),()=>document.removeEventListener("mousedown",B)},[]),H.useEffect(()=>{if(i){const B=S.map(X=>X.id);h(B),B.forEach(X=>{b.current.has(X)||(b.current.add(X),D(X))})}},[i,S]),S.find(B=>B.id===k);const T=y==="disconnected",N=C?(($=C.split("/").pop())==null?void 0:$.replace(/-/g," "))??C:"detecting...",D=async B=>{d(B);try{await j(B)}catch{}finally{d(null)}},A=B=>{u.includes(B.id)?h(u.filter(X=>X!==B.id)):(h([...u,B.id]),D(B.id))},z=async B=>{if(B.id===k){A(B);return}r?(s(B.id,void 0),Lt.getState().syncFromSession(B.id,""),l(!1),h([])):await x(B.id)&&(l(!1),h([]))},O=B=>{A(B)},q=async(B,X)=>{B.stopPropagation(),b.current.delete(X),await j(X),await D(X)},G=(B,X)=>{m({providerId:B,model:X})},W=()=>{m(null)},I=async(B,X)=>{if(console.log("[ProviderSelector.handleModelClick] providerId:",B,"model:",X),r){console.log("[ProviderSelector.handleModelClick] Calling setSessionProvider"),s(B,X),Lt.getState().syncFromSession(B,X),h([]),l(!1);return}d("activating");try{(await ke(`/api/providers/${B}/activate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:X})})).ok&&(await Lt.getState().fetchConfig(),h([]),l(!1))}catch{}finally{d(null)}};return S.length===0?o.jsxs("button",{type:"button",onClick:()=>_(),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:()=>l(!i),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(xr,{className:"w-3 h-3 text-text-muted transition-transform",rotate:i?180:0})]}),i&&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:S.map(B=>{var X;return o.jsxs("div",{children:[o.jsxs("div",{className:`px-3 py-2 flex items-center justify-between ${B.id===k?"bg-bg-tertiary":"hover:bg-bg-tertiary"} ${v?"opacity-50 cursor-wait":"cursor-pointer"}`,children:[o.jsxs("div",{onClick:()=>!v&&z(B),className:"flex flex-col min-w-0 flex-1 cursor-pointer",children:[o.jsx("span",{className:`text-sm font-medium truncate ${B.id===k?"text-accent-primary":"text-text-primary"}`,children:B.name}),o.jsx("span",{className:"text-xs text-text-muted truncate",children:B.backend!=="auto"&&W1(B.backend)})]}),o.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[B.id===k?o.jsx("span",{className:"text-accent-success",title:"Active",children:o.jsx(Ur,{className:"w-4 h-4"})}):o.jsx("span",{className:"w-4"}),o.jsx("button",{type:"button",onClick:Z=>{Z.stopPropagation(),q(Z,B.id)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Refresh models",children:o.jsx(jw,{className:`w-4 h-4 ${c===B.id?"animate-spin":""} ${B.id===k?"text-accent-primary":"text-text-muted"}`})}),o.jsx("button",{type:"button",onClick:Z=>{Z.stopPropagation(),O(B)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Show models",children:o.jsx(xr,{className:`w-4 h-4 transition-transform ${u.includes(B.id)?"rotate-180":""} ${B.id===k?"text-accent-primary":"text-text-muted"}`})})]})]}),u.includes(B.id)&&o.jsx("div",{className:"bg-bg-primary border-t border-border",children:c===B.id?o.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"Loading models..."}):(X=B.models)!=null&&X.length?B.models.map(Z=>{var P;return o.jsxs("button",{type:"button",onClick:()=>I(B.id,Z.id),disabled:c==="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 ${c==="activating"?"opacity-50 cursor-wait":""} ${C===Z.id?"text-accent-primary":"text-text-secondary"}`,children:[o.jsx("span",{className:"truncate flex-1",children:((P=Z.id.split("/").pop())==null?void 0:P.replace(/-/g," "))??Z.id}),o.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[o.jsx("span",{className:"text-xs text-text-muted",children:UA(Z.contextWindow)}),o.jsx("button",{type:"button",onClick:R=>{R.stopPropagation(),G(B.id,Z)},className:"opacity-0 group-hover:opacity-100 p-0.5 hover:bg-bg-tertiary rounded transition-opacity",title:"Edit model context",children:o.jsx(vw,{className:"w-3 h-3 text-text-muted"})})]}),C===Z.id&&o.jsx("span",{className:"text-accent-success flex-shrink-0 ml-1",children:o.jsx(Ur,{className:"w-3.5 h-3.5"})})]},Z.id)}):o.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"No models available"})})]},B.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(FA,{isOpen:!0,onClose:W,providerId:g.providerId,model:g.model})]})}function qA(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function WA({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(lc,{})})}function I0({isOpen:e,onClose:r,initialEditId:s}){const i=hn(fe=>fe.defaults),l=hn(fe=>fe.userItems),u=hn(fe=>fe.loading),h=hn(fe=>fe.fetchCommands),c=hn(fe=>fe.fetchCommand),d=hn(fe=>fe.fetchDefaultContent),p=hn(fe=>fe.createCommand),g=hn(fe=>fe.updateCommand),m=hn(fe=>fe.deleteCommand),[b,S]=H.useState(null),[k,C]=H.useState(null),{view:y,editingId:v,formError:x,saving:_,formData:j,setView:T,setEditingId:N,setFormError:D,setFormData:A,setSaving:z}=ny(),{requestDelete:O,clearConfirm:q,isConfirming:G}=Uh(),W=H.useRef(!1),I=At(fe=>fe.defaults),$=At(fe=>fe.userItems),B=At(fe=>fe.fetchAgents),Z=[...I,...$].filter(fe=>!fe.subagent),P=H.useRef(h),R=H.useRef(B),L=H.useRef(c),U=H.useRef(d),F=H.useRef(s),ne=H.useRef(T),Q=H.useRef(N),ee=H.useRef(D),Y=H.useRef(q);H.useEffect(()=>{P.current=h,R.current=B,L.current=c,U.current=d,F.current=s,ne.current=T,Q.current=N,ee.current=D,Y.current=q}),H.useEffect(()=>{if(e)if(P.current(),R.current(),W.current||(Y.current(),W.current=!0),F.current){const fe=i.some(je=>je.id===F.current);ne.current("edit"),Q.current(F.current),ee.current(""),fe?U.current(F.current).then(je=>{je&&A({name:je.metadata.name+" (copy)",id:`${F.current}-copy-${Date.now()}`,prompt:je.prompt,agentMode:je.metadata.agentMode??"",isDefault:!0})}):L.current(F.current).then(je=>{je&&A({name:je.metadata.name,id:je.metadata.id,prompt:je.prompt,agentMode:je.metadata.agentMode??"",isDefault:!1})})}else ne.current("list"),Q.current(null);else W.current=!1},[e]);const V=async fe=>{S(fe);const je=await d(fe);C((je==null?void 0:je.prompt)??null)},oe=async fe=>{if(i.some(Ue=>Ue.id===fe)){const Ue=await d(fe);Ue&&(N(null),A({name:`${Ue.metadata.name} (copy)`,id:`${fe}-copy-${Date.now()}`,prompt:Ue.prompt,agentMode:Ue.metadata.agentMode??"",isDefault:!0}),D(""),T("edit"))}else{const Ue=await c(fe);Ue&&(N(null),A({name:`${Ue.metadata.name} (copy)`,id:`${fe}-copy-${Date.now()}`,prompt:Ue.prompt,agentMode:Ue.metadata.agentMode??"",isDefault:!1}),D(""),T("edit"))}},re=()=>{A({name:"",id:"",prompt:"",agentMode:"",isDefault:!1}),N(null),T("edit")},ve=async fe=>{const je=await c(fe);je&&(N(fe),A({name:je.metadata.name,id:je.metadata.id,prompt:je.prompt,agentMode:je.metadata.agentMode??"",isDefault:!1}),D(""),T("edit"))},be=async fe=>{await m(fe),q()},Le=async()=>{const fe=v??j.id;if(!fe||!j.name||!j.prompt){D("Name and message are required.");return}z(!0),D("");const je={metadata:{id:fe,name:j.name,...j.agentMode?{agentMode:j.agentMode}:{}},prompt:j.prompt},Ue=v?await g(v,je):await p(je);if(z(!1),!Ue.success){D(Ue.error??"Failed to save command.");return}s?r():T("list")},Oe=()=>{s?r():(T("list"),S(null),C(null))},ze=fe=>{A(je=>({...je,name:fe})),(!v||j.isDefault)&&A(je=>({...je,id:qA(fe)}))},We=()=>{S(null),C(null),T("list")},Ee=()=>{b&&(S(null),T("edit"),N(b),d(b).then(fe=>{fe&&A({name:`${fe.metadata.name} (copy)`,id:`${b}-copy-${Date.now()}`,prompt:fe.prompt,agentMode:fe.metadata.agentMode??"",isDefault:!0})}))};if(b){const fe=i.find(je=>je.id===b);return o.jsx(jt,{isOpen:e,onClose:We,title:`Default: ${(fe==null?void 0:fe.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:fe==null?void 0:fe.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:(fe==null?void 0:fe.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(st,{variant:"secondary",onClick:We,children:"Close"}),o.jsx(st,{variant:"primary",onClick:Ee,children:"Duplicate & Customize"})]})]})})}return y==="edit"?o.jsx(jt,{isOpen:e,onClose:Oe,title:v?"Edit Command":"New Command",size:"xl",children:o.jsxs("div",{className:"flex flex-col h-full",children:[x&&o.jsx(Wh,{message:x}),o.jsxs("div",{className:"space-y-3 mb-3",children:[o.jsx(ty,{name:j.name,id:j.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Command",idPlaceholder:"my-command",readOnlyId:!!v&&!j.isDefault,onNameChange:ze,onIdChange:fe=>A(je=>({...je,id:fe}))}),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:fe=>A(je=>({...je,agentMode:fe.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)"}),Z.map(fe=>o.jsx("option",{value:fe.id,children:fe.name},fe.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:fe=>A(je=>({...je,prompt:fe.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(st,{variant:"secondary",onClick:Oe,children:"Cancel"}),o.jsx(st,{variant:"primary",onClick:Le,disabled:_||!j.name||!j.prompt,children:_?"Saving...":"Save"})]})]})}):o.jsxs(jt,{isOpen:e,onClose:r,title:"Commands",size:"lg",children:[o.jsx(Qb,{description:"Commands are pre-defined messages you can send with a single click.",onNew:re}),o.jsxs(ey,{loading:u,hasItems:i.length>0||l.length>0,loadingLabel:"Loading commands...",emptyLabel:"No commands created yet.",children:[i.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:i.map(fe=>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:fe.name})}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx(WA,{onClick:()=>V(fe.id)}),o.jsx(io,{onClick:()=>oe(fe.id)})]})]},fe.id))})]}),l.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:l.map(fe=>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:fe.name})})}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx(qi,{onClick:()=>ve(fe.id)}),o.jsx(io,{onClick:()=>oe(fe.id)}),G(fe.id,"delete")?o.jsx($h,{onConfirm:()=>be(fe.id),onCancel:q}):o.jsx(qh,{onClick:()=>O(fe.id)})]})]},fe.id))})]})]})]})}function VA(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function GA(e){let r=1;for(;e.some(s=>s.id===`s${r}`);)r++;return`s${r}`}const KA=[{value:"agent",label:"Agent"},{value:"sub_agent",label:"Sub-Agent"},{value:"shell",label:"Shell"}],B0={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"},z0=[{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)"}],zs=150,Fr=54,zi=80,Pn=30,Pi=70,yb=100,Ps=50,ql=50,_b=4;function Tf(e,r){if(e.type==="agent"){const s=r.find(i=>i.id===e.toolMode);return{name:(s==null?void 0:s.name)??(e.toolMode||"Agent"),color:(s==null?void 0:s.color)||"#3b82f6"}}if(e.type==="sub_agent"){const s=r.find(i=>i.id===e.subAgentType);return{name:(s==null?void 0:s.name)??(e.subAgentType||"Sub-Agent"),color:(s==null?void 0:s.color)||"#a855f7"}}return{name:"Shell",color:"#22c55e"}}function YA(e,r,s,i){const l=ql+Ps+zs+yb+zs+Ps+ql,u=l/2,h=ql+Ps+zs/2,c=ql+Ps+zs+yb+zs/2,d=[],p=[],g=new Map,m=e.filter(I=>I.type==="agent"||I.type==="shell"),b=e.filter(I=>I.type==="sub_agent"),S=b.length>0,k=S?h:u,C=m.length>0?c:u,y=Ps+Pn/2;if(d.push({id:"$start",type:"terminal",label:"Start",cx:k,cy:y,w:zi,h:Pn}),g.set("$start",{cx:k,cy:y,w:zi,h:Pn}),e.length===0){const I=y+Pn/2+Pi*2+Pn/2;return d.push({id:"$done",type:"terminal",label:"Done",cx:k,cy:I,w:zi,h:Pn}),g.set("$done",{cx:k,cy:I,w:zi,h:Pn}),{nodes:d,edges:p,width:l,height:I+Pn/2+Ps,posMap:g}}const v=y+Pn/2+Pi,x=(I,$)=>{I.forEach((B,X)=>{const Z=v+X*(Fr+Pi)+Fr/2,{name:P,color:R}=Tf(B,i);d.push({id:B.id,type:"step",label:P,color:R,cx:$,cy:Z,w:zs,h:Fr}),g.set(B.id,{cx:$,cy:Z,w:zs,h:Fr})})};x(m,k),x(b,C);const _=m.length>0?v+(m.length-1)*(Fr+Pi)+Fr/2:y,j=S?v+(b.length-1)*(Fr+Pi)+Fr/2:y,T=Math.max(_,j)+Fr/2+Pi+Pn/2;d.push({id:"$done",type:"terminal",label:"Done",cx:k,cy:T,w:zi,h:Pn}),g.set("$done",{cx:k,cy:T,w:zi,h:Pn});const N=[];r&&g.has(r)&&N.push({from:"$start",to:r,label:s,edgeKey:"start",direction:"down",backEdgeIndex:0});let D=0;for(const I of e)I.transitions.forEach(($,B)=>{if(!$.goto||!g.has($.goto))return;const X=g.get(I.id),Z=g.get($.goto),P=$.when.type==="step_result"?`${$.when.result}`:B0[$.when.type]??$.when.type,R=I.id===$.goto;let L;R?L="back":Z.cy>X.cy+1?L="down":Z.cy<X.cy-1?L="back":L="same",N.push({from:I.id,to:$.goto,label:P,edgeKey:`${I.id}:${B}`,direction:L,backEdgeIndex:L==="back"?D++:0})});const A=new Map,z=new Map,O=new Map,q=new Map;for(const I of N)I.direction==="down"&&(A.set(I.from,(A.get(I.from)??0)+1),z.set(I.to,(z.get(I.to)??0)+1));const G=new Map,W=new Map;for(const I of N){if(I.direction!=="same")continue;const $=[I.from,I.to].sort().join("|");G.set($,(G.get($)??0)+1)}for(const I of N){if(I.direction==="back"||I.direction==="same"){let L=0;if(I.direction==="same"){const U=[I.from,I.to].sort().join("|");L=W.get(U)??0,W.set(U,L+1)}p.push({...I,fromPort:0,toPort:0,sameEdgeIndex:L});continue}const $=A.get(I.from)??1,B=z.get(I.to)??1,X=O.get(I.from)??0,Z=q.get(I.to)??0;O.set(I.from,X+1),q.set(I.to,Z+1);const P=$===1?0:-.6+1.2*X/($-1),R=B===1?0:-.6+1.2*Z/(B-1);p.push({...I,fromPort:P,toPort:R,sameEdgeIndex:0})}return{nodes:d,edges:p,width:l,height:T+Pn/2+Ps,posMap:g}}function XA({steps:e,entryStep:r,selectedNodeId:s,selectedEdgeKey:i,startConditionLabel:l,agentTypes:u,isReadOnly:h,onSelectNode:c,onSelectEdge:d,onRemoveStep:p,onCreateTransition:g,onReconnectTo:m,onReconnectFrom:b,onDeleteTransition:S}){const k=H.useRef(null),C=H.useRef(!1),[y,v]=H.useState(null),[x,_]=H.useState(null),[j,T]=H.useState(null),{nodes:N,edges:D,width:A,height:z,posMap:O}=H.useMemo(()=>YA(e,r,l,u),[e,r,l,u]),q=H.useCallback(Q=>{var re;const ee=k.current;if(!ee)return{x:0,y:0};const Y=ee.createSVGPoint();Y.x=Q.clientX,Y.y=Q.clientY;const V=(re=ee.getScreenCTM())==null?void 0:re.inverse();if(!V)return{x:0,y:0};const oe=Y.matrixTransform(V);return{x:oe.x,y:oe.y}},[]),G=H.useCallback(Q=>!Q||!x||Q==="$start"?!1:x.type==="reconnect-from"?Q!=="$done":!0,[x]),W=H.useCallback((Q,ee)=>{if(h)return;Q.stopPropagation(),Q.preventDefault();const Y=q(Q);_({type:"new",fromNodeId:ee,mouseX:Y.x,mouseY:Y.y})},[q,h]),I=H.useCallback((Q,ee)=>{if(h)return;Q.stopPropagation(),Q.preventDefault();const Y=q(Q);_({type:"reconnect-to",fromNodeId:ee.from,edgeKey:ee.edgeKey,mouseX:Y.x,mouseY:Y.y})},[q,h]),$=H.useCallback((Q,ee)=>{if(h)return;Q.stopPropagation(),Q.preventDefault();const Y=q(Q);_({type:"reconnect-from",fromNodeId:ee.from,fixedTargetId:ee.to,edgeKey:ee.edgeKey,mouseX:Y.x,mouseY:Y.y})},[q,h]),B=H.useCallback(Q=>{if(!x)return;const ee=q(Q);_(Y=>Y?{...Y,mouseX:ee.x,mouseY:ee.y}:null)},[x,q]),X=H.useCallback(()=>{x&&(C.current=!0,j&&G(j)&&(x.type==="new"?g(x.fromNodeId,j):x.type==="reconnect-to"?m(x.edgeKey,j):x.type==="reconnect-from"&&b(x.edgeKey,j)),_(null),T(null))},[x,j,G,g,m,b]),Z=H.useCallback(()=>{if(C.current){C.current=!1;return}c(null),d(null)},[c,d]);H.useEffect(()=>{if(h)return;const Q=ee=>{ee.target instanceof HTMLInputElement||ee.target instanceof HTMLTextAreaElement||ee.target instanceof HTMLSelectElement||(ee.key==="Delete"||ee.key==="Backspace")&&i&&i!=="start"&&(ee.preventDefault(),S(i),d(null))};return document.addEventListener("keydown",Q),()=>document.removeEventListener("keydown",Q)},[h,i,S,d]);const P=Q=>{const ee=O.get(Q.from),Y=O.get(Q.to);if(!ee||!Y)return null;let V,oe,re,ve="middle",be,Le;if(Q.direction==="down"){const Oe=ee.cx+Q.fromPort*(ee.w/2-10),ze=ee.cy+ee.h/2,We=Y.cx+Q.toPort*(Y.w/2-10),Ee=Y.cy-Y.h/2,fe=Ee-ze,je=We-Oe;V=`M ${Oe} ${ze} C ${Oe} ${ze+fe*.4}, ${We-je*.2} ${Ee-fe*.1}, ${We} ${Ee}`,oe=Oe+(We-Oe)*.5,re=ze+fe*.6,be={x:Oe,y:ze},Le={x:We,y:Ee}}else if(Q.direction==="back"){const Oe=Q.from===Q.to,ze=ee.cx>=A/2,We=Q.backEdgeIndex*16,Ee=ze?A-20-We:20+We;if(Oe){const fe=ee.cx>=A/2,je=30+Q.backEdgeIndex*14,Ue=ee.cy-ee.h/2,It=fe?ee.cx+ee.w/2:ee.cx-ee.w/2,pe=fe?It+je:It-je,Ne=ee.cx+(fe?ee.w/4:-ee.w/4),Me=Ue-20-Q.backEdgeIndex*10;V=`M ${It} ${ee.cy} C ${pe} ${ee.cy}, ${pe} ${Me}, ${Ne} ${Ue}`,oe=pe+10,re=Me+4,ve="middle",be={x:It,y:ee.cy},Le={x:Ne,y:Ue}}else{const fe=ze?ee.cx+ee.w/2:ee.cx-ee.w/2,je=Y.cx+(ze?Y.w/4:-Y.w/4),Ue=Math.min(ee.cy,Y.cy)-Y.h/2-18-Q.backEdgeIndex*14;V=`M ${fe} ${ee.cy} L ${Ee} ${ee.cy} L ${Ee} ${Ue} L ${je} ${Ue} L ${je} ${Y.cy-Y.h/2}`,oe=Ee,re=(ee.cy+Ue)/2,ve=ze?"start":"end",be={x:fe,y:ee.cy},Le={x:je,y:Y.cy-Y.h/2}}}else{const Oe=Y.cx>ee.cx,ze=Q.sameEdgeIndex===0?-12:12,We=Oe?ee.cx+ee.w/2:ee.cx-ee.w/2,Ee=Oe?Y.cx-Y.w/2:Y.cx+Y.w/2,fe=ee.cy+ze,je=Y.cy+ze,Ue=(We+Ee)/2;V=`M ${We} ${fe} C ${Ue} ${fe}, ${Ue} ${je}, ${Ee} ${je}`,oe=Ue,re=(fe+je)/2-6,be={x:We,y:fe},Le={x:Ee,y:je}}return{path:V,labelX:oe,labelY:re,labelAnchor:ve,fromPt:be,toPt:Le}},R=(Q,ee)=>{const Y=P(Q);if(!Y)return null;const{path:V,labelX:oe,labelY:re,labelAnchor:ve}=Y,be=i===Q.edgeKey,Le=Q.label&&!(Q.from==="$start"&&Q.label==="Always");return o.jsxs("g",{children:[o.jsx("path",{d:V,fill:"none",stroke:"transparent",strokeWidth:14,className:"cursor-pointer",onClick:Oe=>{Oe.stopPropagation(),d(be?null:Q.edgeKey)}}),o.jsx("path",{d:V,fill:"none",stroke:be?"#58a6ff":"#484f58",strokeWidth:be?2.2:1.2,markerEnd:be?"url(#arrow-selected)":"url(#arrow)",pointerEvents:"none"}),Le&&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)},L=()=>{if(!i||x)return null;const Q=D.find(re=>re.edgeKey===i);if(!Q)return null;const ee=P(Q);if(!ee)return null;const{fromPt:Y,toPt:V}=ee,oe=6;return o.jsxs(o.Fragment,{children:[Q.edgeKey!=="start"&&o.jsx("circle",{cx:Y.x,cy:Y.y,r:oe,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:re=>$(re,Q)}),o.jsx("circle",{cx:V.x,cy:V.y,r:oe,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:re=>I(re,Q)})]})},U=()=>{if(!x)return null;let Q,ee,Y,V;if(x.type==="reconnect-from"){const ve=O.get(x.fixedTargetId);if(!ve)return null;Q=x.mouseX,ee=x.mouseY,Y=ve.cx,V=ve.cy-ve.h/2}else{const ve=O.get(x.fromNodeId);if(!ve)return null;Q=ve.cx,ee=ve.cy+ve.h/2,Y=x.mouseX,V=x.mouseY}const oe=V-ee,re=Math.abs(oe)>10?`M ${Q} ${ee} C ${Q} ${ee+oe*.4}, ${Y} ${V-oe*.4}, ${Y} ${V}`:`M ${Q} ${ee} L ${Y} ${V}`;return o.jsx("path",{d:re,fill:"none",stroke:"#58a6ff",strokeWidth:2,strokeDasharray:"6 3",strokeOpacity:.7,pointerEvents:"none"})},F=Q=>{const ee=Q.cy+Q.h/2,Y=(x==null?void 0:x.fromNodeId)===Q.id;return o.jsx("circle",{cx:Q.cx,cy:ee,r:_b,fill:Y?"#58a6ff":"#1c2128",stroke:Y?"#58a6ff":"#484f58",strokeWidth:1.5,strokeOpacity:Y?1:.5,className:"cursor-crosshair",onMouseDown:V=>W(V,Q.id)})},ne=Q=>{const ee=Q.cy-Q.h/2,Y=x&&j===Q.id&&G(Q.id);return o.jsx("circle",{cx:Q.cx,cy:ee,r:_b,fill:Y?"#3fb950":"#1c2128",stroke:Y?"#3fb950":"#484f58",strokeWidth:1.5,strokeOpacity:Y?1:.5})};return o.jsxs("svg",{ref:k,viewBox:`0 0 ${A} ${z}`,className:"block w-full",preserveAspectRatio:"xMidYMin meet",onMouseMove:B,onMouseUp:X,onClick:Z,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=s===Q.id,Y=Q.cx-Q.w/2,V=Q.cy-Q.h/2,oe=y===Q.id,re=x&&j===Q.id&&G(Q.id);if(Q.type==="terminal"){const be=Q.id==="$start",Le=be?"#58a6ff":"#3fb950",Oe=be,ze=!be;return o.jsxs("g",{onClick:We=>{We.stopPropagation(),be&&!h&&d("start")},className:be&&!h?"cursor-pointer":void 0,children:[re&&o.jsx("rect",{x:Y-3,y:V-3,width:Q.w+6,height:Q.h+6,rx:Q.h/2+3,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),be&&i==="start"&&o.jsx("rect",{x:Y-3,y:V-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:Y,y:V,width:Q.w,height:Q.h,rx:Q.h/2,fill:Le,fillOpacity:.08,stroke:Le,strokeOpacity:.4,strokeWidth:1.5}),o.jsx("text",{x:Q.cx,y:Q.cy+4,textAnchor:"middle",fill:Le,className:"text-[10px] font-medium",pointerEvents:"none",children:Q.label}),Oe&&F(Q),ze&&ne(Q)]},Q.id)}const ve=Q.color??"#6b7280";return o.jsxs("g",{onClick:be=>{be.stopPropagation(),h||c(ee?null:Q.id)},onMouseEnter:()=>v(Q.id),onMouseLeave:()=>v(null),className:h?void 0:"cursor-pointer",children:[re&&o.jsx("rect",{x:Y-3,y:V-3,width:Q.w+6,height:Q.h+6,rx:12,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),ee&&o.jsx("rect",{x:Y-3,y:V-3,width:Q.w+6,height:Q.h+6,rx:12,fill:"none",stroke:"#58a6ff",strokeOpacity:.5,strokeWidth:2}),o.jsx("rect",{x:Y,y:V,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}),!h&&F(Q),!h&&ne(Q),oe&&!x&&!h&&o.jsxs("g",{onClick:be=>{be.stopPropagation(),p(Q.id)},className:"cursor-pointer",children:[o.jsx("circle",{cx:Y+Q.w-2,cy:V+2,r:8,fill:"#0d1117",fillOpacity:.9,stroke:"#f85149",strokeOpacity:.5,strokeWidth:1}),o.jsx("line",{x1:Y+Q.w-5,y1:V-1,x2:Y+Q.w+1,y2:V+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"}),o.jsx("line",{x1:Y+Q.w+1,y1:V-1,x2:Y+Q.w-5,y2:V+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"})]})]},Q.id)}),x&&N.map(Q=>G(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(),X()}},`drop-${Q.id}`):null),U(),L()]})}const ar="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",qs="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",fn="block text-[11px] text-text-secondary mb-0.5";function ZA({fromLabel:e,toLabel:r,condition:s,fromStep:i,agentTypes:l,onUpdateCondition:u,onDelete:h}){const c=i&&(i.type==="sub_agent"||i.type==="agent")?l.find(p=>p.id===(i.type==="sub_agent"?i.subAgentType:i.toolMode)):void 0,d=(c==null?void 0:c.results)&&c.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:h,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($b,{}),o.jsx("span",{className:"font-medium text-text-primary",children:r})]}),o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Condition"}),o.jsx("select",{value:s.type,onChange:p=>{u(p.target.value==="step_result"?{type:"step_result",result:"success"}:{type:p.target.value})},className:qs,children:z0.map(p=>o.jsx("option",{value:p.value,children:p.label},p.value))})]}),s.type==="step_result"&&o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Result"}),d?o.jsx("select",{value:s.result??c.results[0],onChange:p=>{u({type:"step_result",result:p.target.value})},className:qs,children:c.results.map(p=>o.jsx("option",{value:p,children:p},p))}):o.jsx("input",{type:"text",value:s.result??"success",onChange:p=>u({type:"step_result",result:p.target.value}),placeholder:"e.g. success, passed, failed",className:ar})]}),o.jsx("p",{className:"text-text-muted text-[10px]",children:"Drag handles to reconnect. Press Delete to remove."})]})}function fh({variables:e,onInsert:r}){return e.length===0?null:o.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:e.map(s=>o.jsx("button",{type:"button",onClick:()=>r(s.name),title:s.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:`{{${s.name}}}`},s.name))})}function QA({step:e,isEntry:r,agentTypes:s,transitionCount:i,templateVariables:l,onUpdate:u,onRemove:h,onSetEntry:c}){const{color:d,name:p}=Tf(e,s);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:c,className:"p-1 rounded text-text-muted hover:text-accent-primary text-xs",children:"Set entry"}),o.jsx("button",{onClick:h,className:"p-1 rounded text-text-muted hover:text-accent-error text-xs",children:"Delete"})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:fn,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 S=s.find(k=>!k.subagent);u({...e,type:m,phase:b,toolMode:(S==null?void 0:S.id)??"builder",name:(S==null?void 0:S.name)??"Agent"})}else if(m==="sub_agent"){const S=s.find(k=>k.subagent);u({...e,type:m,phase:b,subAgentType:(S==null?void 0:S.id)??"",name:(S==null?void 0:S.name)??"Sub-Agent"})}else u({...e,type:m,phase:b,name:"Shell"})},className:qs,children:KA.map(g=>o.jsx("option",{value:g.value,children:g.label},g.value))})]}),e.type==="agent"&&o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Agent Type"}),o.jsx("select",{value:e.toolMode??"builder",onChange:g=>{const m=s.find(b=>b.id===g.target.value);u({...e,toolMode:g.target.value,name:(m==null?void 0:m.name)??g.target.value})},className:qs,children:s.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:fn,children:"Sub-Agent Type"}),o.jsxs("select",{value:e.subAgentType??"",onChange:g=>{const m=s.find(b=>b.id===g.target.value);u({...e,subAgentType:g.target.value,name:(m==null?void 0:m.name)??g.target.value})},className:qs,children:[o.jsx("option",{value:"",children:"— select —"}),s.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:fn,children:"Prompt"}),o.jsx("textarea",{value:e.prompt??"",onChange:g=>u({...e,prompt:g.target.value||void 0}),rows:6,className:`${ar} resize-y text-xs`,placeholder:"Injected on first entry..."}),o.jsx(fh,{variables:l,onInsert:g=>u({...e,prompt:(e.prompt??"")+`{{${g}}}`})})]}),o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Nudge Prompt"}),o.jsx("textarea",{value:e.nudgePrompt??"",onChange:g=>u({...e,nudgePrompt:g.target.value||void 0}),rows:6,className:`${ar} resize-y text-xs`,placeholder:"Injected on re-entry..."}),o.jsx(fh,{variables:l,onInsert:g=>u({...e,nudgePrompt:(e.nudgePrompt??"")+`{{${g}}}`})})]})]}),e.type==="shell"&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Command"}),o.jsx("textarea",{value:e.command??"",onChange:g=>u({...e,command:g.target.value}),rows:3,className:`${ar} font-mono text-xs resize-y`,placeholder:"cd {{workdir}} && npm run lint"}),o.jsx(fh,{variables:l,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:fn,children:"Timeout (ms)"}),o.jsx("input",{type:"number",value:e.timeout??6e4,onChange:g=>u({...e,timeout:Number(g.target.value)}),className:`${ar} font-mono text-xs`})]}),o.jsxs("div",{children:[o.jsx("label",{className:fn,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:`${ar} 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:[i," outgoing transition",i!==1?"s":""," — drag from the bottom port to connect."]})})]})}const Sb=[];function P0({isOpen:e,onClose:r,initialEditId:s}){const i=Tt(me=>me.defaults),l=Tt(me=>me.userItems),u=Tt(me=>me.loading),h=Tt(me=>me.templateVariables),c=Tt(me=>me.fetchWorkflows),d=Tt(me=>me.fetchWorkflow),p=Tt(me=>me.fetchDefaultContent),g=Tt(me=>me.fetchTemplateVariables),m=Tt(me=>me.createWorkflow),b=Tt(me=>me.updateWorkflow),S=Tt(me=>me.deleteWorkflow),{requestDelete:k,clearConfirm:C,isConfirming:y}=Uh(),[v,x]=H.useState("list"),[_,j]=H.useState(null),[T,N]=H.useState(!1),[D,A]=H.useState(null),[z,O]=H.useState(null),[q,G]=H.useState(""),[W,I]=H.useState(""),[$,B]=H.useState(""),[X,Z]=H.useState("1.0.0"),[P,R]=H.useState("#3b82f6"),[L,U]=H.useState(""),[F,ne]=H.useState(50),[Q,ee]=H.useState(Sb),[Y,V]=H.useState({type:"always"}),[oe,re]=H.useState(""),[ve,be]=H.useState(!1),[Le,Oe]=H.useState([]),[ze]=H.useState(null);H.useEffect(()=>{e&&(c(),g(),ke("/api/agents").then(me=>me.json()).then(me=>Oe(me.agents??[])).catch(()=>{}),A(null),O(null),s?i.some(ye=>ye.id===s)?p(s).then(ye=>{ye&&(G(ye.metadata.name+" (copy)"),I(`${s}-copy-${Date.now()}`),B(ye.metadata.description),Z(ye.metadata.version),R(ye.metadata.color??"#3b82f6"),U(ye.entryStep),ne(ye.settings.maxIterations),ee(ye.steps),V(ye.startCondition??{type:"always"}),re(""),j(null),N(!1),x("edit"))}):d(s).then(ye=>{ye&&(G(ye.metadata.name),I(ye.metadata.id),B(ye.metadata.description),Z(ye.metadata.version),R(ye.metadata.color??"#3b82f6"),U(ye.entryStep),ne(ye.settings.maxIterations),ee(ye.steps),V(ye.startCondition??{type:"always"}),re(""),j(s),N(!1),x("edit"))}):(x("list"),j(null),N(!1)))},[e,c,d,p,g,s]);const We=async me=>{const ye=await d(me);ye&&(j(me),G(ye.metadata.name),I(ye.metadata.id),B(ye.metadata.description),Z(ye.metadata.version),R(ye.metadata.color??"#3b82f6"),U(ye.entryStep),ne(ye.settings.maxIterations),ee(ye.steps),V(ye.startCondition??{type:"always"}),re(""),A(null),O(null),x("edit"))},Ee=async()=>{var Qe;const me=_??W;if(!me||!q)return re("Name is required."),!1;if(Q.length===0)return re("Add at least one step."),!1;let ye=L;if(!ye||!Q.some(He=>He.id===ye)){if(ye=((Qe=Q.find(He=>He.id))==null?void 0:Qe.id)??"",!ye)return re("All steps need an ID."),!1;U(ye)}be(!0),re("");const we={metadata:{id:me,name:q,description:$,version:X||"1.0.0",color:P},entryStep:ye,settings:{maxIterations:F},steps:Q,startCondition:Y},Ve=_?await b(_,we):await m(we);return be(!1),Ve.success?(_||j(me),!0):(re(Ve.error??"Failed to save."),!1)},fe=async()=>{await Ee()},je=async()=>{await Ee()&&(s?r():x("list"))},Ue=()=>{s?r():x("list")},It=me=>{G(me),_||I(VA(me))},pe=async me=>{if(i.some(we=>we.id===me)){const we=await p(me);if(!we)return;G(we.metadata.name),I(we.metadata.id),B(we.metadata.description),Z(we.metadata.version),R(we.metadata.color??"#3b82f6"),U(we.entryStep),ne(we.settings.maxIterations),ee(we.steps),V(we.startCondition??{type:"always"}),re(""),j(me),N(!0)}else{const we=await d(me);if(!we)return;G(we.metadata.name),I(we.metadata.id),B(we.metadata.description),Z(we.metadata.version),R(we.metadata.color??"#3b82f6"),U(we.entryStep),ne(we.settings.maxIterations),ee(we.steps),V(we.startCondition??{type:"always"}),re(""),j(me),N(!0)}x("edit")},Ne=async me=>{const we=i.some(Ve=>Ve.id===me)?await p(me):await d(me);we&&(G(we.metadata.name+" (copy)"),I(`${me}-copy-${Date.now()}`),B(we.metadata.description),Z(we.metadata.version),R(we.metadata.color??"#3b82f6"),U(we.entryStep),ne(we.settings.maxIterations),ee(we.steps),V(we.startCondition??{type:"always"}),re(""),j(null),N(!1),x("edit"))},Me=()=>{j(null),G(""),I(""),B(""),Z("1.0.0"),R("#3b82f6"),U(""),ne(50),ee(structuredClone(Sb)),V({type:"always"}),re(""),A(null),O(null),N(!1),x("edit")},lt=async me=>{await S(me),C()},ue=H.useCallback(me=>{A(me),O(null)},[]),_e=H.useCallback(me=>{O(me),A(null)},[]),Te=D!==null?Number(D):-1,Ie=Te>=0?Q[Te]??null:null,$e=H.useCallback(me=>{ee(ye=>ye.map((we,Ve)=>Ve===Te?me:we))},[Te]),St=Y.type==="step_result"?`${Y.result}`:B0[Y.type]??Y.type,Ye=()=>{const me=Q.length,ye=GA(Q),we=Le.find(Ve=>!Ve.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:[]}]),L||U(ye),ue(String(me))},Dt=H.useCallback((me,ye)=>{me==="$start"?(U(ye),_e("start")):ee(we=>{const Ve=we.find(He=>He.id===me),Qe=Ve?Ve.transitions.length:0;return _e(`${me}:${Qe}`),we.map(He=>He.id===me?{...He,transitions:[...He.transitions,{when:{type:"always"},goto:ye}]}:He)})},[_e]),gt=H.useCallback((me,ye)=>{if(me==="start")U(ye);else{const we=me.lastIndexOf(":"),Ve=me.slice(0,we),Qe=parseInt(me.slice(we+1));ee(He=>He.map(Xt=>Xt.id===Ve?{...Xt,transitions:Xt.transitions.map((Rt,Bt)=>Bt===Qe?{...Rt,goto:ye}:Rt)}:Xt))}},[]),Yt=H.useCallback((me,ye)=>{const we=me.lastIndexOf(":"),Ve=me.slice(0,we),Qe=parseInt(me.slice(we+1));ee(He=>{const Xt=He.find(Bt=>Bt.id===Ve);if(!Xt)return He;const Rt=Xt.transitions[Qe];return Rt?He.map(Bt=>Bt.id===Ve?{...Bt,transitions:Bt.transitions.filter((qr,ie)=>ie!==Qe)}:Bt.id===ye?{...Bt,transitions:[...Bt.transitions,Rt]}:Bt):He}),O(null)},[]),ct=H.useCallback(me=>{if(me==="start")U("");else{const ye=me.lastIndexOf(":"),we=me.slice(0,ye),Ve=parseInt(me.slice(ye+1));ee(Qe=>Qe.map(He=>He.id===we?{...He,transitions:He.transitions.filter((Xt,Rt)=>Rt!==Ve)}:He))}O(null)},[]),qn=H.useCallback((me,ye)=>{if(me==="start")V(ye);else{const we=me.lastIndexOf(":"),Ve=me.slice(0,we),Qe=parseInt(me.slice(we+1));ee(He=>He.map(Xt=>Xt.id===Ve?{...Xt,transitions:Xt.transitions.map((Rt,Bt)=>Bt===Qe?{...Rt,when:ye}:Rt)}:Xt))}},[]),sn=me=>Tf(me,Le).name,Yi=()=>{if(!z)return null;if(z==="start"){const Rt=Q.find(Bt=>Bt.id===L);return{type:"start",fromLabel:"Start",toLabel:Rt?sn(Rt):"(none)",condition:Y}}const me=z.lastIndexOf(":"),ye=z.slice(0,me),we=parseInt(z.slice(me+1)),Ve=Q.find(Rt=>Rt.id===ye);if(!Ve)return null;const Qe=Ve.transitions[we];if(!Qe)return null;const He=Q.find(Rt=>Rt.id===Qe.goto),Xt=Qe.goto==="$done"?"Done":He?sn(He):Qe.goto;return{type:"step",fromLabel:sn(Ve),toLabel:Xt,condition:Qe.when}};if(v==="edit"){const me=Yi();return o.jsxs(jt,{isOpen:e,onClose:Ue,title:T?q:_?"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:fn,children:"Name"}),o.jsx("input",{value:q,onChange:ye=>It(ye.target.value),placeholder:"Workflow name",className:`${ar} ${T?"opacity-50":""}`,readOnly:T})]}),o.jsxs("div",{className:"min-w-[100px]",children:[o.jsx("label",{className:fn,children:"ID"}),o.jsx("input",{value:W,readOnly:!0,className:`${ar} font-mono opacity-50`})]}),o.jsxs("div",{className:"flex-1 min-w-[140px]",children:[o.jsx("label",{className:fn,children:"Description"}),o.jsx("input",{value:$,onChange:ye=>!T&&B(ye.target.value),readOnly:T,placeholder:"What does this workflow do?",className:`${ar} ${T?"opacity-50":""}`})]}),o.jsxs("div",{className:"w-20",children:[o.jsx("label",{className:fn,children:"Max Iter."}),o.jsx("input",{type:"number",value:F,onChange:ye=>!T&&ne(Number(ye.target.value)),readOnly:T,className:`${ar} font-mono ${T?"opacity-50":""}`})]}),o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Color"}),o.jsx("input",{type:"color",value:P,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:Ye,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(XA,{steps:Q,entryStep:L,selectedNodeId:(Ie==null?void 0:Ie.id)??null,selectedEdgeKey:z,startConditionLabel:St,agentTypes:Le,isReadOnly:T,onSelectNode:ye=>{if(ye===null){ue(null);return}const we=Q.findIndex(Ve=>Ve.id===ye);ue(we>=0?String(we):null)},onSelectEdge:_e,onRemoveStep:ye=>{var Ve;const we=Q.findIndex(Qe=>Qe.id===ye);if(ee(Qe=>Qe.filter(He=>He.id!==ye)),Te===we&&ue(null),L===ye){const Qe=Q.filter(He=>He.id!==ye);U(((Ve=Qe[0])==null?void 0:Ve.id)??"")}},onCreateTransition:Dt,onReconnectTo:gt,onReconnectFrom:Yt,onDeleteTransition:ct}),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:Ye,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&&(me||Ie)?o.jsx("p",{className:"text-text-muted text-xs text-center py-8",children:'View only — click "Duplicate & Customize" to edit.'}):me?me.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"})}),L&&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($b,{}),o.jsx("span",{className:"text-text-primary font-medium",children:me.toLabel})]}),o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Activation Condition"}),o.jsx("select",{value:Y.type,onChange:ye=>V(ye.target.value==="step_result"?{type:"step_result",result:"success"}:{type:ye.target.value}),className:qs,children:z0.map(ye=>o.jsx("option",{value:ye.value,children:ye.label},ye.value))})]}),Y.type==="step_result"&&o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Result"}),L&&(()=>{const ye=Q.find(He=>He.id===L),we=ye&&(ye.type==="sub_agent"||ye.type==="agent")?Le.find(He=>He.id===(ye.type==="sub_agent"?ye.subAgentType:ye.toolMode)):void 0,Ve=(we==null?void 0:we.results)&&we.results.length>0,Qe=(we==null?void 0:we.results)??[];return Ve?o.jsx("select",{value:Y.result??Qe[0],onChange:He=>V({type:"step_result",result:He.target.value}),className:qs,children:Qe.map(He=>o.jsx("option",{value:He,children:He},He))}):o.jsx("input",{type:"text",value:Y.result??"success",onChange:He=>V({type:"step_result",result:He.target.value}),placeholder:"e.g. success, passed, failed",className:ar})})()]}),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(ZA,{fromLabel:me.fromLabel,toLabel:me.toLabel,condition:me.condition,fromStep:me.type==="step"?Q.find(ye=>ye.id===me.fromLabel):void 0,agentTypes:Le,onUpdateCondition:ye=>qn(z,ye),onDelete:()=>ct(z)}):Ie?o.jsx(QA,{step:Ie,isEntry:Ie.id===L,agentTypes:Le,transitionCount:Ie.transitions.length,templateVariables:h,onUpdate:$e,onRemove:()=>{var ye;if(Ie&&(ee(Q.filter((we,Ve)=>Ve!==Te)),ue(null),L===Ie.id)){const we=Q.filter((Ve,Qe)=>Qe!==Te);U(((ye=we[0])==null?void 0:ye.id)??"")}},onSetEntry:()=>U(Ie.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(st,{variant:"secondary",onClick:Ue,children:"Close"}),T?o.jsx(st,{variant:"primary",onClick:()=>{G(q+" (copy)"),I(`${_}-copy-${Date.now()}`),j(null),N(!1)},children:"Duplicate & Customize"}):o.jsxs(o.Fragment,{children:[o.jsx(st,{variant:"secondary",onClick:fe,disabled:ve||!q,children:ve?"Saving...":"Save"}),o.jsx(st,{variant:"primary",onClick:je,disabled:ve||!q,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(st,{variant:"primary",size:"sm",onClick:Me,children:"+ New"})})]}),u&&i.length===0&&l.length===0?o.jsx("div",{className:"text-text-muted text-sm",children:"Loading workflows..."}):i.length===0&&l.length===0?o.jsx("div",{className:"text-text-muted text-sm",children:"No workflows installed."}):o.jsxs("div",{className:"space-y-4",children:[i.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:i.map(me=>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:me.name}),o.jsxs("span",{className:"text-text-muted text-xs",children:["v",me.version]})]}),o.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:me.description})]}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx("button",{onClick:()=>pe(me.id),className:"p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",title:"View",children:o.jsx(lc,{})}),o.jsx(io,{onClick:()=>Ne(me.id)})]})]},me.id))})]}),l.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:l.map(me=>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:me.name}),o.jsxs("span",{className:"text-text-muted text-xs",children:["v",me.version]})]}),o.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:me.description})]}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx(io,{onClick:()=>Ne(me.id)}),o.jsx(qi,{onClick:()=>We(me.id)}),y(me.id,"delete")?o.jsx($h,{onConfirm:()=>lt(me.id),onCancel:()=>{}}):o.jsx(qh,{onClick:()=>k(me.id)})]})]},me.id))})]})]})]})}function JA(e,r){const s=e.startCondition;if(!s||s.type==="always")return!0;switch(s.type){case"has_pending_criteria":return r.some(i=>i.status.type!=="passed");case"all_criteria_passed":return r.length===0||r.every(i=>i.status.type==="passed");case"all_criteria_completed_or_passed":return r.every(i=>i.status.type==="completed"||i.status.type==="passed");case"any_criteria_blocked":return r.some(i=>i.status.type==="failed"&&i.attempts.filter(l=>l.status==="failed").length>=4);case"step_result":return null;default:return null}}function e4({onSendCommand:e,onSelectWorkflow:r,onOpenCommandsManager:s,onOpenWorkflowsManager:i,onAttach:l,textareaContent:u,attachments:h,criteria:c}){const[d,p]=H.useState(!1),[g,m]=H.useState("commands"),[b,S]=H.useState(""),[k,C]=H.useState(0),[y,v]=H.useState(null),[x,_]=H.useState(null),j=H.useRef(null),T=H.useRef(null),N=hn(U=>U.defaults),D=hn(U=>U.userItems),A=hn(U=>U.fetchCommands),z=Tt(U=>U.defaults),O=Tt(U=>U.userItems),q=Tt(U=>U.fetchWorkflows),G=[...N,...D],W=[...z,...O];H.useEffect(()=>{d&&(g==="commands"?A():g==="workflows"&&q())},[d,g,A,q]),H.useEffect(()=>{d&&(S(""),C(0),requestAnimationFrame(()=>{var U;return(U=j.current)==null?void 0:U.focus()}))},[d,g]),H.useEffect(()=>{if(!d)return;const U=F=>{var ne;(ne=T.current)!=null&&ne.contains(F.target)||p(!1)};return document.addEventListener("mousedown",U),()=>document.removeEventListener("mousedown",U)},[d]);const I=U=>{switch(U.key){case"ArrowDown":U.preventDefault(),C(F=>{const Q=(g==="commands"?G:W).filter(ee=>{const Y=b.toLowerCase();return!Y||ee.name.toLowerCase().includes(Y)});return Math.min(F+1,Q.length-1)});break;case"ArrowUp":U.preventDefault(),C(F=>Math.max(F-1,0));break;case"Enter":U.preventDefault();break;case"Escape":U.preventDefault(),p(!1);break}},$=U=>{S(U),C(0)},B=G.filter(U=>!b||U.name.toLowerCase().includes(b.toLowerCase())),X=W.filter(U=>!b||U.name.toLowerCase().includes(b.toLowerCase())),Z=async U=>{const F=await hn.getState().fetchCommand(U);F&&e(F.prompt,F.metadata.agentMode,u,h),p(!1)},P=U=>{r(U),p(!1)},R=(U,F)=>{F.stopPropagation(),p(!1),v(U)},L=(U,F)=>{F.stopPropagation(),p(!1),_(U)};return o.jsxs("div",{ref:T,className:"relative",children:[o.jsx("button",{type:"button",onClick:()=>p(!d),className:"px-1.5 py-2 rounded-r bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors border-l border-border/50",title:"More options",children:o.jsx(qb,{className:"w-4 h-4"})}),d&&o.jsxs("div",{className:"absolute bottom-full right-0 mb-1 w-80 bg-bg-secondary border border-border rounded-lg shadow-xl z-50 overflow-hidden",children:[o.jsxs("div",{className:"flex border-b border-border",children:[o.jsx("button",{type:"button",onClick:()=>{m("commands"),S(""),C(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${g==="commands"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Commands"}),o.jsx("button",{type:"button",onClick:()=>{m("workflows"),S(""),C(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${g==="workflows"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Workflows"}),o.jsx("button",{type:"button",onClick:()=>m("attach"),className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${g==="attach"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Attach"})]}),g!=="attach"&&o.jsx("div",{className:"p-2 border-b border-border",children:o.jsx("input",{ref:j,value:b,onChange:U=>$(U.target.value),onKeyDown:I,placeholder:g==="commands"?"Search commands...":"Search workflows...",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"})}),o.jsx("div",{className:"overflow-y-auto max-h-64 p-1",children:g==="commands"?B.length===0?o.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:G.length===0?"No commands yet":"No matches"}):B.map((U,F)=>o.jsxs("div",{className:`flex items-center gap-1 px-3 py-2 rounded transition-colors group ${F===k?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[o.jsx("button",{type:"button",onClick:()=>Z(U.id),className:"flex-1 text-left",children:o.jsx("div",{className:"text-sm text-text-primary font-medium",children:U.name})}),o.jsx(qi,{className:"opacity-0 group-hover:opacity-100",onClick:ne=>R(U.id,ne)})]},U.id)):g==="workflows"?X.length===0?o.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:W.length===0?"No workflows yet":"No matches"}):X.map((U,F)=>{const ne=JA(U,c),Q=U.color??"#3b82f6";return o.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 rounded transition-colors group ${F===k?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[o.jsxs("button",{type:"button",onClick:()=>P(U.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:Q}}),o.jsx("span",{className:"text-sm text-text-primary font-medium flex-1",children:U.name}),ne!==null&&o.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:ne?"#22c55e":"#6b7280"},title:ne?"Entry condition met":"Entry condition not met"})]}),o.jsx(qi,{className:"opacity-0 group-hover:opacity-100",onClick:ee=>L(U.id,ee)})]},U.id)}):o.jsxs("div",{className:"p-4 flex flex-col items-center gap-3",children:[o.jsxs("button",{type:"button",onClick:()=>{l(),p(!1)},className:"flex items-center gap-2 px-4 py-2 rounded bg-bg-tertiary hover:bg-accent-primary/20 text-text-primary transition-colors",children:[o.jsx(pw,{className:"w-4 h-4"}),o.jsx("span",{className:"text-sm font-medium",children:"Attach image"})]}),o.jsx("span",{className:"text-xs text-text-muted",children:"or drag & drop into chat"})]})}),g!=="attach"&&o.jsx("div",{className:"border-t border-border p-1",children:o.jsx("button",{type:"button",onClick:()=>{p(!1),g==="commands"?s():i()},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:g==="commands"?"Manage Commands...":"Manage Workflows..."})})]}),o.jsx(I0,{isOpen:!!y,onClose:()=>v(null),initialEditId:y}),o.jsx(P0,{isOpen:!!x,onClose:()=>_(null),initialEditId:x})]})}function H0(e,r){if(!r)return!0;const s=r.toLowerCase().split(/\s+/),i=e.toLowerCase().split(/\s+/);return s.every(l=>{for(const u of i){let h=0;for(let c=0;c<u.length&&h<l.length;c++)u[c]===l[h]&&h++;if(h===l.length)return!0}return!1})}function F0(e,r,s,i,l){switch(e.key){case"ArrowDown":e.preventDefault(),s(u=>Math.min(u+1,r));break;case"ArrowUp":e.preventDefault(),s(u=>Math.max(u-1,0));break;case"Enter":e.preventDefault(),i();break;case"Escape":e.preventDefault(),l();break}}function t4({isOpen:e,onClose:r,onCloseComplete:s,onSelectCommand:i,onSelectWorkflow:l,onCloseCompleteAction:u,textareaContent:h,onSearchMessages:c,onToggleAutoScroll:d,isAutoScrollActive:p}){const g=hn(L=>L.fetchCommands),m=Tt(L=>L.fetchWorkflows),b=At(L=>L.fetchAgents),S=hn(L=>L.defaults),k=hn(L=>L.userItems),C=Tt(L=>L.defaults),y=Tt(L=>L.userItems),v=At(L=>L.defaults),x=At(L=>L.userItems),_=Ce(L=>{var U;return(U=L.currentSession)==null?void 0:U.mode}),j=Ce(L=>{var U;return((U=L.currentSession)==null?void 0:U.dangerLevel)??"normal"}),T=Ce(L=>L.switchMode),N=Ce(L=>L.switchDangerLevel),D=Ce(L=>{var U;return(U=L.currentSession)==null?void 0:U.projectId}),A=Ce(L=>L.createSession),z=H.useRef(void 0),[O,q]=H.useState(""),[G,W]=H.useState(0),I=H.useRef(null),$=H.useRef(!1);H.useEffect(()=>{e&&($.current=!0)},[e]),H.useEffect(()=>{if(e){g(),m(),b(),q(""),W(0);const L=setTimeout(()=>{var U;return(U=I.current)==null?void 0:U.focus()},50);return()=>clearTimeout(L)}},[e,g,m,b]),H.useEffect(()=>{var L;!e&&$.current&&(s==null||s(),(L=z.current)==null||L.call(z),z.current=void 0)},[e,s]);const B=(L,U)=>{const F=new Set(U.map(ne=>ne.id));return[...L.filter(ne=>!F.has(ne.id)),...U]},Z=[{id:"create-session",name:"New Session",prefix:"Action > Create",action:()=>D&&A(D)},{id:"navigate-session",name:"Another Session",prefix:"Action > Navigate to",action:()=>{z.current=u,r()}},{id:"search-messages",name:"Messages",prefix:"Action > Search",action:()=>{r(),c==null||c()}},{id:"toggle-autoscroll",name:p?"Auto-scroll Off":"Auto-scroll On",prefix:"Action > Toggle",action:()=>{r(),d==null||d(!p)}},...B(v,x).filter(L=>!L.subagent&&L.id!==_).map(L=>({id:L.id,name:L.name,prefix:"Agent > Switch to",action:()=>T(L.id)})),...B(S,k).map(L=>({id:L.id,name:L.name,prefix:"Command > Launch",action:()=>i(L.id,h)})),...B(C,y).map(L=>({id:L.id,name:L.name,prefix:"Workflow > Run",action:()=>l(L.id)})),...["normal","dangerous"].filter(L=>L!==j).map(L=>({id:L,name:L.charAt(0).toUpperCase()+L.slice(1),prefix:"Mode > Switch to",action:()=>N(L)}))].filter(L=>H0(`${L.prefix} ${L.name}`,O)),P=Z.length-1,R=L=>{F0(L,P,W,()=>{var U;(U=Z[G])==null||U.action(),r()},r)};return e?go.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:I,type:"text",value:O,onChange:L=>{q(L.target.value),W(0)},onKeyDown:R,placeholder:"Search...",className:"flex-1 bg-transparent text-sm focus:outline-none placeholder:text-text-muted"}),o.jsx(Hh,{onClick:r,className:"shrink-0","aria-label":"Close"})]}),o.jsx("div",{className:"overflow-y-auto max-h-[60vh] p-2",children:Z.length===0?o.jsx("div",{className:"px-3 py-4 text-center text-text-muted text-sm",children:S.length+k.length+C.length+y.length>0?"No matches":"No agents, commands, or workflows yet"}):Z.map((L,U)=>o.jsxs("button",{type:"button",onClick:()=>{L.action(),r()},className:`w-full text-left px-3 py-2 rounded text-sm transition-colors ${U===G?"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:[L.prefix," "]}),o.jsx("span",{children:L.name})]},L.id))})]})]}),document.body):null}function n4(e){const r=new Date(e),s=new Date;if(r.getDate()===s.getDate()&&r.getMonth()===s.getMonth()&&r.getFullYear()===s.getFullYear())return r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1});const l=r.getFullYear(),u=String(r.getMonth()+1).padStart(2,"0"),h=String(r.getDate()).padStart(2,"0"),c=String(r.getHours()).padStart(2,"0"),d=String(r.getMinutes()).padStart(2,"0");return`${l}/${u}/${h} ${c}:${d}`}function r4({isOpen:e,onClose:r,messages:s,onSelectMessage:i}){const[l,u]=H.useState(""),[h,c]=H.useState(0),d=H.useRef(null),p=H.useRef(!1),g=s.filter(C=>C.role==="user"&&!C.isSystemGenerated&&C.messageKind!=="auto-prompt"&&C.messageKind!=="command");H.useEffect(()=>{e&&(p.current=!0)},[e]),H.useEffect(()=>{if(e){u(""),c(0);const C=setTimeout(()=>{var y;return(y=d.current)==null?void 0:y.focus()},50);return()=>clearTimeout(C)}},[e]);const m=g.filter(C=>H0(C.content,l)),b=m.length-1,S=C=>{F0(C,b,c,()=>{m[h]&&(i(m[h].id),r())},r)},k=C=>{i(C),r()};return e?go.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(Xb,{}),o.jsx("input",{ref:d,type:"text",value:l,onChange:C=>{u(C.target.value),c(0)},onKeyDown:S,placeholder:"Search messages...",className:"flex-1 bg-transparent text-sm focus:outline-none placeholder:text-text-muted"}),o.jsx("button",{type:"button",onClick:r,className:"p-0.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors","aria-label":"Close",children:o.jsx(Ph,{className:"w-4 h-4"})})]}),o.jsx("div",{className:"overflow-y-auto max-h-[60vh] p-2",children:m.length===0?o.jsx("div",{className:"px-3 py-4 text-center text-text-muted text-sm",children:g.length>0?"No matches":"No messages yet"}):m.map((C,y)=>o.jsx("button",{type:"button",onClick:()=>k(C.id),className:`w-full text-left px-3 py-2 rounded text-sm transition-colors ${y===h?"bg-accent-primary/20 text-text-primary":"text-text-secondary hover:bg-bg-tertiary hover:text-text-primary"}`,children:o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsx("span",{className:"truncate flex-1",children:C.content}),o.jsx("span",{className:"text-text-muted text-xs shrink-0",children:n4(C.timestamp)})]})},C.id))})]})]}),document.body):null}function s4(e){return e==="criterion"}function i4(e){var r,s;return e.role!=="assistant"||e.subAgentId||(r=e.content)!=null&&r.trim()||(s=e.thinkingContent)!=null&&s.trim()||!e.toolCalls||e.toolCalls.length===0?!1:e.toolCalls.every(i=>s4(i.name))}function a4(e,r=[]){const s=[];let i=null,l=[],u,h=1;const c=new Map,d=new Map,p=[];for(const S of r)S.type==="message"?c.set(S.message.id,S):S.type==="subagent"?d.set(S.subAgentId,S):S.type==="criteria-batch"&&p.push(S);let g=0;const m=()=>{if(l.length>0){const S=p[g];S&&S.type==="criteria-batch"&&S.toolCalls.length===l.length&&S.toolCalls.every((C,y)=>{var v;return C.id===((v=l[y])==null?void 0:v.id)})?s.push(S):s.push({type:"criteria-batch",toolCalls:[...l]}),g++,l=[]}},b=()=>{if(!i)return;const S=i,k=d.get(S.subAgentId);k&&k.type==="subagent"&&k.messages.length===S.messages.length&&k.messages.every((y,v)=>y===S.messages[v])?s.push(k):s.push({type:"subagent",subAgentId:S.subAgentId,subAgentType:S.subAgentType,messages:S.messages}),i=null};for(const S of e)if(S.role!=="tool"){if(S.contextWindowId&&u&&S.contextWindowId!==u&&(m(),b(),h++,s.push({type:"context-divider",windowSequence:h})),u=S.contextWindowId,i4(S)){b();for(const k of S.toolCalls)l.push(k);continue}if(m(),S.subAgentId&&S.subAgentType)i&&i.subAgentId===S.subAgentId?i.messages.push(S):(b(),i={subAgentId:S.subAgentId,subAgentType:S.subAgentType,messages:[S]});else{b();const k=c.get(S.id);k&&k.type==="message"&&k.message===S?s.push(k):s.push({type:"message",message:S})}}return m(),b(),s}function o4(e){const{year:r,month:s,day:i}=iy(e);return`${r}/${s}/${i} ${uc(e)}`}function l4(e,r){return e.length<=r?e:e.substring(0,r)+"..."}const c4=10,u4=150;function d4(e){const r=[];if(e.recentUserPrompts)for(const s of e.recentUserPrompts)r.push({id:s.id,content:s.content,timestamp:s.timestamp,sessionId:e.id,sessionName:e.title||e.id});return r}function h4(e){return[...e].sort((i,l)=>new Date(l.timestamp).getTime()-new Date(i.timestamp).getTime()).slice(0,c4).reverse().map(i=>({id:i.id,content:i.content,timestamp:i.timestamp,formattedTimestamp:o4(i.timestamp),trimmedContent:l4(i.content,u4),sessionId:i.sessionId,sessionName:i.sessionName}))}function f4(e,r,s){const i=[],l=e.filter(u=>u.role==="user"&&!u.isSystemGenerated&&u.messageKind!=="auto-prompt");for(const u of l)i.push({id:u.id,content:u.content,timestamp:u.timestamp,sessionId:s??"",sessionName:"This session"});for(const u of r)s&&u.id===s||i.push(...d4(u));return h4(i)}function p4(e,r=[],s=null){const[i,l]=H.useState(0),[u,h]=H.useState(!1),c=H.useMemo(()=>f4(e,r,s),[e,r,s]),d=H.useCallback(()=>{c.length>0&&(l(c.length-1),h(!0))},[c.length]),p=H.useCallback(()=>{h(!1),l(0)},[]),g=H.useCallback(()=>{l(S=>c.length===0?S:S===0?c.length-1:S-1)},[c.length]),m=H.useCallback(()=>{l(S=>c.length===0?S:S===c.length-1?0:S+1)},[c.length]),b=H.useCallback(()=>{if(c.length===0||!u)return null;const S=c[i];return(S==null?void 0:S.content)??null},[c,i,u]);return{history:c,selectedIndex:i,showHistory:u,openHistory:d,closeHistory:p,navigateUp:g,navigateDown:m,selectCurrent:b}}function m4({criteriaSidebarOpen:e,onCriteriaSidebarToggle:r}={}){const s=e??!0,[i,l]=H.useState(""),[u,h]=H.useState([]),[c,d]=H.useState(!1),[p,g]=H.useState(null),[m,b]=H.useState(!1),[S,k]=H.useState(!1),[C,y]=H.useState(!1),[v,x]=H.useState(!1),[_,j]=H.useState(null),[T,N]=H.useState(null),D=H.useRef(null),A=H.useRef(null),z=H.useRef(null),O=Ce(ie=>ie.currentSession),q=Ce(ie=>ie.messages),G=Ce(ie=>ie.streamingMessage),W=Ce(ie=>ie.sessions),I=Ce(ie=>ie.error),$=Ce(ie=>ie.pendingQuestion),B=Fb(),X=Ce(ie=>ie.sendMessage),Z=Ce(ie=>ie.clearError),P=Ce(ie=>ie.acceptAndBuild),R=Ce(ie=>ie.stopGeneration),L=Ce(ie=>ie.launchRunner),U=Ce(ie=>ie.cancelQueued),F=lw(),{showThinking:ne,showVerboseToolOutput:Q,showStats:ee,showAgentDefinitions:Y,showWorkflowBars:V}=Rh(),oe=Tt(ie=>ie.defaults),re=Tt(ie=>ie.userItems),ve=[...oe,...re],be=Tt(ie=>ie.fetchWorkflows),Le=At(ie=>ie.defaults),Oe=At(ie=>ie.userItems),ze=[...Le,...Oe].filter(ie=>!ie.subagent);H.useEffect(()=>{be()},[be]);const{history:We,selectedIndex:Ee,showHistory:fe,openHistory:je,closeHistory:Ue,navigateUp:It,navigateDown:pe,selectCurrent:Ne}=p4(q,W,O==null?void 0:O.id),Me=H.useCallback(ie=>{j(ie),St(!1);const Ae=document.querySelector(`[data-message-id="${ie}"]`);Ae&&Ae.scrollIntoView({behavior:"smooth",block:"center"}),setTimeout(()=>j(null),3e3)},[]);H.useEffect(()=>{const ie=Ae=>{N(Ae.detail.stats)};return window.addEventListener("open-turn-stats",ie),()=>window.removeEventListener("open-turn-stats",ie)},[]);const lt=H.useMemo(()=>G?q.map(ie=>ie.id===G.id?G:ie):q,[q,G]),ue=H.useRef([]),_e=H.useMemo(()=>{const ie=a4(lt,ue.current);return ue.current=ie,ie},[lt]),Te=H.useMemo(()=>PA(q),[q]),{force_scroll_to_bottom:Ie,isAutoScrollActive:$e,setAutoScroll:St}=O0(D,O),Ye=H.useCallback(()=>{const ie=A.current;if(!ie)return;ie.style.height="auto";const Ae=Math.min(200,ie.scrollHeight);ie.style.height=`${Ae}px`},[]);H.useEffect(()=>{if(!(O!=null&&O.id))return;const ie=`openfox:draft:${O.id}`,Ae=localStorage.getItem(ie);Ae!==null&&l(Ae)},[O==null?void 0:O.id]),H.useEffect(()=>{var ie;(ie=A.current)==null||ie.focus(),Ye()},[O==null?void 0:O.id,Ye]),H.useEffect(()=>{if(!(O!=null&&O.id))return;const ie=`openfox:draft:${O.id}`,Ae=setTimeout(()=>{i?localStorage.setItem(ie,i):localStorage.removeItem(ie)},500);return()=>clearTimeout(Ae)},[O==null?void 0:O.id,i]),H.useEffect(()=>{Ye()},[i,Ye]),H.useEffect(()=>{const ie=Ae=>{Ae.key==="Escape"&&B&&R(),Ae.key==="ScrollLock"&&St(!$e)};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[B,R,$e]);const Dt=H.useRef(0);H.useEffect(()=>{const ie=Ae=>{if(Ae.key==="Shift"&&!Ae.ctrlKey&&!Ae.metaKey&&!Ae.altKey){const qe=Date.now();qe-Dt.current<300?(Ae.preventDefault(),y(!0),Dt.current=0):Dt.current=qe}};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]),H.useEffect(()=>{const ie=A.current;if(!ie)return;const Ae=async qe=>{var en;if(document.activeElement!==ie)return;const Ct=(en=qe.clipboardData)==null?void 0:en.items;if(Ct){for(const _n of Array.from(Ct))if(_n.type.startsWith("image/")){qe.preventDefault();const yr=_n.getAsFile();if(!yr)continue;await dh(yr,Xs=>h(Sn=>[...Sn,Xs]),g,{filename:"pasted-image"})}}};return ie.addEventListener("paste",Ae),()=>ie.removeEventListener("paste",Ae)},[]);const gt=()=>{l(""),h([]),O!=null&&O.id&&localStorage.removeItem(`openfox:draft:${O.id}`)},Yt=async ie=>{ie.preventDefault(),!(!i.trim()&&u.length===0)&&(Ie(),X(i,u.length>0?u:void 0),gt())},ct=ie=>{if((ie.ctrlKey||ie.metaKey)&&ie.code.startsWith("Digit")){const qe=parseInt(ie.code.slice(-1),10)-1,Ct=ze[qe];Ct&&(ie.preventDefault(),Ce.getState().switchMode(Ct.id));return}if(fe)switch(ie.key){case"Enter":ie.preventDefault();const Ae=Ne();Ae&&(l(Ae),Ue());return;case"Escape":ie.preventDefault(),Ue(),B&&R();return;case"ArrowUp":ie.preventDefault(),It();return;case"ArrowDown":ie.preventDefault(),pe();return}if(ie.key==="ArrowUp"&&i.trim()===""&&!fe){ie.preventDefault(),je();return}ie.key==="Enter"&&!ie.shiftKey&&(ie.preventDefault(),Yt(ie))},qn=H.useCallback(async ie=>{const Ae=ie.target.files;if(!(!Ae||Ae.length===0)){g(null);for(const qe of Array.from(Ae))await dh(qe,Ct=>h(en=>[...en,Ct]),g);z.current&&(z.current.value="")}},[]),sn=H.useCallback(ie=>{ie.preventDefault(),ie.stopPropagation(),d(!0)},[]),Yi=H.useCallback(ie=>{ie.preventDefault(),ie.stopPropagation(),d(!1)},[]),me=H.useCallback(async ie=>{ie.preventDefault(),ie.stopPropagation(),d(!1),g(null);const Ae=ie.dataTransfer.files;if(!(!Ae||Ae.length===0))for(const qe of Array.from(Ae))await dh(qe,Ct=>h(en=>[...en,Ct]),g)},[]),ye=H.useCallback(ie=>{h(Ae=>Ae.filter(qe=>qe.id!==ie))},[]),we=H.useCallback(()=>{var ie;(ie=z.current)==null||ie.click()},[]),Ve=(O==null?void 0:O.mode)==="planner",Qe=(O==null?void 0:O.mode)==="builder",He=((O==null?void 0:O.criteria.length)??0)>0,Xt=(O==null?void 0:O.phase)==="done",Rt=_e.some(ie=>ie.type==="message"&&ie.message.role==="assistant"),Bt=Ve&&He&&!B&&Rt&&!Xt,qr=ie=>{const Ae=i.trim()?i:void 0,qe=u.length>0?u:void 0;Ve?P(ie,Ae,qe):Qe&&L(Ae,qe,ie),gt()};return o.jsxs(o.Fragment,{children:[o.jsxs(s2,{criteriaSidebarOpen:s,onCriteriaSidebarToggle:r,messages:lt,children:[$&&o.jsx(wA,{question:$}),o.jsx(o2,{}),T&&o.jsx(fA,{stats:T,onClose:()=>N(null)}),o.jsx(CA,{}),o.jsxs("div",{ref:D,"data-testid":"chat-scroll-container",className:"flex-1 min-w-0 overflow-y-auto relative bg-primary",children:[o.jsx("div",{className:"pt-4",children:_e.map((ie,Ae)=>{if(ie.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"})]},Ae);if(ie.type==="subagent"){const _n=ie.messages.some(yr=>yr.isStreaming);return o.jsx("div",{className:"px-2 md:px-4",children:o.jsx(xA,{messages:ie.messages,subAgentType:ie.subAgentType,subAgentId:ie.subAgentId,isStreaming:_n})},Ae)}if(ie.type==="criteria-batch")return o.jsx("div",{className:"feed-item px-2 md:px-4",children:o.jsx(L0,{toolCalls:ie.toolCalls,criteria:O==null?void 0:O.criteria})},Ae);const qe=ie.message;if(qe.role==="assistant")return o.jsx("div",{className:"px-2 md:px-4",children:o.jsx(jf,{message:qe,showStats:ee,showThinking:ne,showVerboseToolOutput:Q})},Ae);const Ct=!Y&&qe.messageKind==="auto-prompt",en=!V&&(qe.messageKind==="workflow-started"||qe.messageKind==="task-completed");return Ct||en?null:o.jsx("div",{className:"px-2 md:px-4",children:o.jsx("div",{"data-message-id":qe.id,className:_===qe.id?"rounded animate-highlight-fade":void 0,children:o.jsx(R0,{message:qe,isLastAssistantMessage:!1,promptContext:qe.role==="user"?Te[qe.id]:void 0})})},Ae)})}),o.jsxs("div",{className:"px-2 md:px-4 pb-4",children:[I&&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:I.code}),o.jsx("div",{className:"text-red-300 text-xs mt-0.5",children:I.message})]}),o.jsx(ao,{onClick:Z,className:"text-red-400 hover:text-red-300 p-0.5",size:"sm"})]})}),Bt&&o.jsx("div",{className:"flex justify-center gap-2 feed-item flex-wrap",children:ve.map(ie=>{const Ae=ie.color??"#3b82f6",qe=parseInt(Ae.slice(1,3),16),Ct=parseInt(Ae.slice(3,5),16),en=parseInt(Ae.slice(5,7),16),_n=`rgba(${qe},${Ct},${en},0.12)`,yr=`rgba(${qe},${Ct},${en},0.22)`,Xs=`rgba(${qe},${Ct},${en},0.25)`;return o.jsxs("button",{onClick:()=>P(ie.id),className:"px-4 py-1.5 rounded text-sm font-medium transition-colors",style:{backgroundColor:_n,color:Ae,border:`1px solid ${Xs}`},onMouseEnter:Sn=>{Sn.currentTarget.style.backgroundColor=yr},onMouseLeave:Sn=>{Sn.currentTarget.style.backgroundColor=_n},children:["▶ ",ie.name]},ie.id)})}),B&&o.jsx(kA,{})]})]}),o.jsxs("form",{onSubmit:Yt,className:"relative p-2 md:p-4 bg-secondary",children:[o.jsxs("button",{type:"button",className:"absolute -top-8 right-12 md:right-16 text-sm text-text-muted hover:text-text-primary z-10 flex items-center gap-1.5",onClick:()=>St(!$e),children:[$e?o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-success"}):o.jsx(xr,{className:"w-3 h-3 text-text-muted"}),$e?"live":"scroll to bottom"]}),o.jsx("button",{type:"button",onClick:()=>x(!0),className:"absolute -top-8 right-2 md:right-4 text-sm text-text-muted hover:text-text-primary z-10 flex items-center p-0.5 rounded hover:bg-bg-tertiary transition-colors","aria-label":"Search messages",children:o.jsx(Xb,{})}),o.jsx("input",{ref:z,type:"file",accept:".png,.jpg,.jpeg,.gif",onChange:qn,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(ie=>o.jsx(EA,{attachment:ie,onRemove:ye},ie.id))}),fe&&o.jsx(jA,{history:We,selectedIndex:Ee,onSelect:ie=>{l(ie),Ue()},onEscape:Ue,onNavigate:ie=>{ie==="up"?It():pe()}}),F.length>0&&o.jsx("div",{className:"mb-2 flex flex-wrap gap-1.5",children:F.map(ie=>o.jsxs("div",{className:`inline-flex items-center gap-1.5 px-2 py-1 rounded text-xs ${ie.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:[ie.mode==="asap"?"ASAP":"Queue",":"]}),o.jsx("span",{className:"truncate max-w-[200px]",children:ie.content}),o.jsx(ao,{onClick:()=>U(ie.queueId),size:"sm"})]},ie.queueId))}),o.jsxs("div",{className:`flex items-end gap-3 p-3 rounded transition-colors ${c?"bg-accent-primary/10":"bg-primary"}`,onDragOver:sn,onDragLeave:Yi,onDrop:me,children:[o.jsx("textarea",{ref:A,value:i,onChange:ie=>{l(ie.target.value),fe&&Ue()},onKeyDown:ct,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 items-center self-center",children:[o.jsx("button",{type:"button",onClick:()=>{var ie;!i.trim()&&u.length===0||((ie=D.current)==null||ie.scrollTo({top:D.current.scrollHeight,behavior:"smooth"}),X(i,u),gt())},disabled:!i.trim()&&u.length===0,className:"px-4 py-1.5 rounded-l 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.jsx(e4,{onSendCommand:(ie,Ae,qe,Ct)=>{var _n;Ae&&(O==null?void 0:O.mode)!==Ae&&Ce.getState().switchMode(Ae);const en=qe&&qe.trim()?`${qe.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 hn=$n((e,r)=>({defaults:[],userItems:[],loading:!1,fetchCommands:async()=>{await Fh("/api/commands",e)},fetchCommand:async s=>{try{const i=await ke(`/api/commands/${s}`);return i.ok?await i.json():null}catch{return null}},fetchDefaultContent:async s=>{try{const i=await ke(`/api/commands/defaults/${s}`);return i.ok?await i.json():null}catch{return null}},createCommand:async s=>{const i=await xs("POST","/api/commands",s);return i.success&&await r().fetchCommands(),i},updateCommand:async(s,i)=>{const l=await xs("PUT",`/api/commands/${s}`,i);return l.success&&await r().fetchCommands(),l},deleteCommand:async s=>{try{const i=await ke(`/api/commands/${s}`,{method:"DELETE"}),l=await i.json();return i.ok?(e(u=>({userItems:u.userItems.filter(h=>h.id!==s)})),{success:!0}):{success:!1,error:l.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateCommand:async s=>{try{const i=await ke(`/api/commands/${s}/duplicate`,{method:"POST"}),l=await i.json();return i.ok?(await r().fetchCommands(),{success:!0}):{success:!1,error:l.error??"Failed to duplicate"}}catch{return{success:!1,error:"Network error"}}}})),NA={maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576};async function TA(e,r={}){const s={...NA,...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<=s.maxSizeBytes){const l=await e.arrayBuffer(),u=IA(l),h=`data:${e.type};base64,${u}`,c=await M0(h);return{dataUrl:h,mimeType:e.type,size:e.size,width:c.width,height:c.height}}return await AA(e,s)}async function AA(e,r){const s=await LA(e),i=await M0(s),{width:l,height:u}=DA(i.width,i.height,r.maxWidth,r.maxHeight),h=RA();h.width=l,h.height=u;const c=h.getContext("2d");if(!c)throw new Error("Failed to get canvas context");c.imageSmoothingEnabled=!0,c.imageSmoothingQuality="high",c.drawImage(i,0,0,l,u);let d=r.quality,p;do{if(p=h.toDataURL(e.type.startsWith("image/gif")?"image/png":e.type,d),vb(p)<=r.maxSizeBytes||d<=.3)break;d-=.1}while(!0);const g=vb(p);return{dataUrl:p,mimeType:e.type.startsWith("image/gif")?"image/png":e.type,size:g,width:l,height:u}}function DA(e,r,s,i){const l=e/r;return e>r&&e>s?{width:s,height:Math.round(s/l)}:r>e&&r>i?{width:Math.round(i*l),height:i}:{width:e,height:r}}function LA(e){return new Promise((r,s)=>{const i=MA(),l=new i;l.onload=()=>r(l.result),l.onerror=()=>s(new Error("Failed to read file")),l.readAsDataURL(e)})}function M0(e){return new Promise((r,s)=>{const i=OA(),l=new i;l.onload=()=>r(l),l.onerror=()=>s(new Error("Failed to load image")),l.src=e})}function RA(){var r;const e=Nf();if(!((r=e.document)!=null&&r.createElement))throw new Error("Image compression requires browser canvas APIs");return e.document.createElement("canvas")}function OA(){const e=Nf();if(!e.Image)throw new Error("Image compression requires browser image APIs");return e.Image}function MA(){const e=Nf();if(!e.FileReader)throw new Error("Image compression requires browser file APIs");return e.FileReader}function Nf(){return globalThis}function IA(e){const r=new Uint8Array(e);let s="";for(let i=0;i<r.byteLength;i++){const l=r[i];l!==void 0&&(s+=String.fromCharCode(l))}return btoa(s)}function vb(e){const s=e.split(",")[1];return s?Math.round(s.length*3/4):0}function BA(e){return["image/png","image/jpeg","image/gif"].includes(e.type)}function zA(e,r=50*1024*1024){return e.size>r?{valid:!1,error:`Image file is too large (${bb(e.size)}). Maximum size is ${bb(r)}.`}:{valid:!0}}function bb(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}async function dh(e,r,s,i={}){const{maxSizeBytes:l=50*1024*1024,filename:u}=i;if(!BA(e)){s(`Unsupported file type: ${e.type}. Only PNG, JPG, and GIF are supported.`);return}const h=zA(e,l);if(!h.valid){s(h.error??"Image file is too large");return}try{const c=await TA(e,{maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576}),d={id:Mb(),filename:u??e.name,mimeType:c.mimeType,size:c.size,data:c.dataUrl};r(d)}catch(c){const d=c instanceof Error?c.message??"Failed to process image":"Failed to process image";s(d)}}function PA(e){const r={};let s=null;for(const i of e){if(i.role==="user"&&!i.isSystemGenerated){s=i.id;continue}i.role==="assistant"&&i.promptContext&&s&&r[s]===void 0&&(r[s]=i.promptContext)}return r}function hh(e){return{contextWindow:e.contextWindow,temperature:e.temperature??null,topP:e.topP??null,topK:e.topK??null,maxTokens:e.maxTokens??null,supportsVision:e.supportsVision??null}}function HA({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 Za({label:e,value:r,onChange:s,min:i,max:l,step:u=1,helpText:h,defaultValue:c}){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==="")s(null);else{const C=parseFloat(k);isNaN(C)||s(C)}},S=()=>{g?(m(!1),c!==void 0&&(p(c.toString()),s(c))):(m(!0),s(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:S,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:i,max:l,step:u,value:d,readOnly:g,onChange:k=>b(k.target.value),onClick:()=>g&&S(),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":""}`}),h&&o.jsx("p",{className:"text-xs text-text-muted mt-1",children:h})]})}function FA({isOpen:e,onClose:r,providerId:s,model:i}){const[l,u]=H.useState(()=>hh(i)),[h,c]=H.useState(!1),d=Lt(m=>m.updateModelSettings);H.useEffect(()=>{u(hh(i))},[i]);const p=async()=>{if(l.contextWindow<1024||l.contextWindow>1e7)return;c(!0);const m=l.temperature!==(i.temperature??null)||l.topP!==(i.topP??null)||l.topK!==(i.topK??null)||l.maxTokens!==(i.maxTokens??null)||l.supportsVision!==(i.supportsVision??null);await d(s,i.id,{contextWindow:l.contextWindow,...m&&{temperature:l.temperature,topP:l.topP,topK:l.topK,maxTokens:l.maxTokens,supportsVision:l.supportsVision??void 0}}),c(!1),r()},g=()=>{u(hh(i)),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(st,{variant:"secondary",onClick:g,disabled:h,children:"Cancel"}),o.jsx(st,{variant:"primary",onClick:p,disabled:h||l.contextWindow<1024||l.contextWindow>1e7,children:h?"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:i.id})]}),o.jsx(Za,{label:"Context Window",value:l.contextWindow,onChange:m=>m!==null&&u(b=>({...b,contextWindow:m})),min:1024,max:1e7,helpText:"Range: 1,024 - 10,000,000 tokens"}),o.jsxs(HA,{label:"Sampling Parameters",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Za,{label:"Temperature",value:l.temperature,onChange:m=>u(b=>({...b,temperature:m})),min:0,max:2,step:.1,helpText:"0.0 - 2.0",defaultValue:1}),o.jsx(Za,{label:"Top P",value:l.topP,onChange:m=>u(b=>({...b,topP:m})),min:0,max:1,step:.05,helpText:"0.0 - 1.0",defaultValue:1})]}),o.jsx(Za,{label:"Top K",value:l.topK,onChange:m=>u(b=>({...b,topK:m})),min:1,max:200,helpText:"1 - 200 (leave as default if not supported)"})]}),o.jsx(Za,{label:"Max Tokens",value:l.maxTokens,onChange:m=>u(b=>({...b,maxTokens:m})),min:256,max:32e3,helpText:"Maximum tokens to generate per response"}),o.jsxs("div",{children:[o.jsxs("label",{className:"flex items-center gap-2 text-sm font-medium text-text-secondary mb-1",children:[o.jsx("input",{type:"checkbox",checked:l.supportsVision??!1,onChange:m=>u(b=>({...b,supportsVision:m.target.checked})),className:"rounded border-border bg-bg-tertiary text-accent-primary focus:ring-accent-primary focus:ring-offset-0"}),"Vision Enabled"]}),o.jsx("p",{className:"text-xs text-text-muted",children:"Allow sending images directly to this model. Disable if the model doesn't support vision."})]}),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:[i.source==="backend"&&"Auto-detected from backend",i.source==="user"&&"Manually set",i.source==="default"&&"Default value"]})]})]})}):null}function UA(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function $A(){var $;const[,e]=vr(),r=Ce(B=>B.currentSession),s=Ce(B=>B.setSessionProvider),[i,l]=H.useState(!1),[u,h]=H.useState([]),[c,d]=H.useState(null),p=H.useRef(null),[g,m]=H.useState(null),b=H.useRef(new Set),S=Lt(B=>B.providers),k=Lt(B=>B.activeProviderId),C=Lt(B=>B.model);Lt(B=>B.backend);const y=Lt(B=>B.llmStatus),v=Lt(B=>B.activating),x=Lt(B=>B.activateProvider),_=Lt(B=>B.refreshModel),j=Lt(B=>B.refreshProviderModels);H.useEffect(()=>{function B(X){p.current&&!p.current.contains(X.target)&&(l(!1),h([]),b.current=new Set)}return document.addEventListener("mousedown",B),()=>document.removeEventListener("mousedown",B)},[]),H.useEffect(()=>{if(i){const B=S.map(X=>X.id);h(B),B.forEach(X=>{b.current.has(X)||(b.current.add(X),D(X))})}},[i,S]),S.find(B=>B.id===k);const T=y==="disconnected",N=C?(($=C.split("/").pop())==null?void 0:$.replace(/-/g," "))??C:"detecting...",D=async B=>{d(B);try{await j(B)}catch{}finally{d(null)}},A=B=>{u.includes(B.id)?h(u.filter(X=>X!==B.id)):(h([...u,B.id]),D(B.id))},z=async B=>{if(B.id===k){A(B);return}r?(s(B.id,void 0),Lt.getState().syncFromSession(B.id,""),l(!1),h([])):await x(B.id)&&(l(!1),h([]))},O=B=>{A(B)},q=async(B,X)=>{B.stopPropagation(),b.current.delete(X),await j(X),await D(X)},G=(B,X)=>{m({providerId:B,model:X})},W=()=>{m(null)},I=async(B,X)=>{if(console.log("[ProviderSelector.handleModelClick] providerId:",B,"model:",X),r){console.log("[ProviderSelector.handleModelClick] Calling setSessionProvider"),s(B,X),Lt.getState().syncFromSession(B,X),h([]),l(!1);return}d("activating");try{(await ke(`/api/providers/${B}/activate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:X})})).ok&&(await Lt.getState().fetchConfig(),h([]),l(!1))}catch{}finally{d(null)}};return S.length===0?o.jsxs("button",{type:"button",onClick:()=>_(),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:()=>l(!i),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(xr,{className:"w-3 h-3 text-text-muted transition-transform",rotate:i?180:0})]}),i&&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:S.map(B=>{var X;return o.jsxs("div",{children:[o.jsxs("div",{className:`px-3 py-2 flex items-center justify-between ${B.id===k?"bg-bg-tertiary":"hover:bg-bg-tertiary"} ${v?"opacity-50 cursor-wait":"cursor-pointer"}`,children:[o.jsxs("div",{onClick:()=>!v&&z(B),className:"flex flex-col min-w-0 flex-1 cursor-pointer",children:[o.jsx("span",{className:`text-sm font-medium truncate ${B.id===k?"text-accent-primary":"text-text-primary"}`,children:B.name}),o.jsx("span",{className:"text-xs text-text-muted truncate",children:B.backend!=="auto"&&W1(B.backend)})]}),o.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[B.id===k?o.jsx("span",{className:"text-accent-success",title:"Active",children:o.jsx(Ur,{className:"w-4 h-4"})}):o.jsx("span",{className:"w-4"}),o.jsx("button",{type:"button",onClick:Z=>{Z.stopPropagation(),q(Z,B.id)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Refresh models",children:o.jsx(jw,{className:`w-4 h-4 ${c===B.id?"animate-spin":""} ${B.id===k?"text-accent-primary":"text-text-muted"}`})}),o.jsx("button",{type:"button",onClick:Z=>{Z.stopPropagation(),O(B)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Show models",children:o.jsx(xr,{className:`w-4 h-4 transition-transform ${u.includes(B.id)?"rotate-180":""} ${B.id===k?"text-accent-primary":"text-text-muted"}`})})]})]}),u.includes(B.id)&&o.jsx("div",{className:"bg-bg-primary border-t border-border",children:c===B.id?o.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"Loading models..."}):(X=B.models)!=null&&X.length?B.models.map(Z=>{var P;return o.jsxs("button",{type:"button",onClick:()=>I(B.id,Z.id),disabled:c==="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 ${c==="activating"?"opacity-50 cursor-wait":""} ${C===Z.id?"text-accent-primary":"text-text-secondary"}`,children:[o.jsx("span",{className:"truncate flex-1",children:((P=Z.id.split("/").pop())==null?void 0:P.replace(/-/g," "))??Z.id}),o.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[o.jsx("span",{className:"text-xs text-text-muted",children:UA(Z.contextWindow)}),o.jsx("button",{type:"button",onClick:R=>{R.stopPropagation(),G(B.id,Z)},className:"opacity-0 group-hover:opacity-100 p-0.5 hover:bg-bg-tertiary rounded transition-opacity",title:"Edit model context",children:o.jsx(vw,{className:"w-3 h-3 text-text-muted"})})]}),C===Z.id&&o.jsx("span",{className:"text-accent-success flex-shrink-0 ml-1",children:o.jsx(Ur,{className:"w-3.5 h-3.5"})})]},Z.id)}):o.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"No models available"})})]},B.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(FA,{isOpen:!0,onClose:W,providerId:g.providerId,model:g.model})]})}function qA(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function WA({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(lc,{})})}function I0({isOpen:e,onClose:r,initialEditId:s}){const i=hn(fe=>fe.defaults),l=hn(fe=>fe.userItems),u=hn(fe=>fe.loading),h=hn(fe=>fe.fetchCommands),c=hn(fe=>fe.fetchCommand),d=hn(fe=>fe.fetchDefaultContent),p=hn(fe=>fe.createCommand),g=hn(fe=>fe.updateCommand),m=hn(fe=>fe.deleteCommand),[b,S]=H.useState(null),[k,C]=H.useState(null),{view:y,editingId:v,formError:x,saving:_,formData:j,setView:T,setEditingId:N,setFormError:D,setFormData:A,setSaving:z}=ny(),{requestDelete:O,clearConfirm:q,isConfirming:G}=Uh(),W=H.useRef(!1),I=At(fe=>fe.defaults),$=At(fe=>fe.userItems),B=At(fe=>fe.fetchAgents),Z=[...I,...$].filter(fe=>!fe.subagent),P=H.useRef(h),R=H.useRef(B),L=H.useRef(c),U=H.useRef(d),F=H.useRef(s),ne=H.useRef(T),Q=H.useRef(N),ee=H.useRef(D),Y=H.useRef(q);H.useEffect(()=>{P.current=h,R.current=B,L.current=c,U.current=d,F.current=s,ne.current=T,Q.current=N,ee.current=D,Y.current=q}),H.useEffect(()=>{if(e)if(P.current(),R.current(),W.current||(Y.current(),W.current=!0),F.current){const fe=i.some(je=>je.id===F.current);ne.current("edit"),Q.current(F.current),ee.current(""),fe?U.current(F.current).then(je=>{je&&A({name:je.metadata.name+" (copy)",id:`${F.current}-copy-${Date.now()}`,prompt:je.prompt,agentMode:je.metadata.agentMode??"",isDefault:!0})}):L.current(F.current).then(je=>{je&&A({name:je.metadata.name,id:je.metadata.id,prompt:je.prompt,agentMode:je.metadata.agentMode??"",isDefault:!1})})}else ne.current("list"),Q.current(null);else W.current=!1},[e]);const V=async fe=>{S(fe);const je=await d(fe);C((je==null?void 0:je.prompt)??null)},oe=async fe=>{if(i.some(Ue=>Ue.id===fe)){const Ue=await d(fe);Ue&&(N(null),A({name:`${Ue.metadata.name} (copy)`,id:`${fe}-copy-${Date.now()}`,prompt:Ue.prompt,agentMode:Ue.metadata.agentMode??"",isDefault:!0}),D(""),T("edit"))}else{const Ue=await c(fe);Ue&&(N(null),A({name:`${Ue.metadata.name} (copy)`,id:`${fe}-copy-${Date.now()}`,prompt:Ue.prompt,agentMode:Ue.metadata.agentMode??"",isDefault:!1}),D(""),T("edit"))}},re=()=>{A({name:"",id:"",prompt:"",agentMode:"",isDefault:!1}),N(null),T("edit")},ve=async fe=>{const je=await c(fe);je&&(N(fe),A({name:je.metadata.name,id:je.metadata.id,prompt:je.prompt,agentMode:je.metadata.agentMode??"",isDefault:!1}),D(""),T("edit"))},be=async fe=>{await m(fe),q()},Le=async()=>{const fe=v??j.id;if(!fe||!j.name||!j.prompt){D("Name and message are required.");return}z(!0),D("");const je={metadata:{id:fe,name:j.name,...j.agentMode?{agentMode:j.agentMode}:{}},prompt:j.prompt},Ue=v?await g(v,je):await p(je);if(z(!1),!Ue.success){D(Ue.error??"Failed to save command.");return}s?r():T("list")},Oe=()=>{s?r():(T("list"),S(null),C(null))},ze=fe=>{A(je=>({...je,name:fe})),(!v||j.isDefault)&&A(je=>({...je,id:qA(fe)}))},We=()=>{S(null),C(null),T("list")},Ee=()=>{b&&(S(null),T("edit"),N(b),d(b).then(fe=>{fe&&A({name:`${fe.metadata.name} (copy)`,id:`${b}-copy-${Date.now()}`,prompt:fe.prompt,agentMode:fe.metadata.agentMode??"",isDefault:!0})}))};if(b){const fe=i.find(je=>je.id===b);return o.jsx(jt,{isOpen:e,onClose:We,title:`Default: ${(fe==null?void 0:fe.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:fe==null?void 0:fe.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:(fe==null?void 0:fe.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(st,{variant:"secondary",onClick:We,children:"Close"}),o.jsx(st,{variant:"primary",onClick:Ee,children:"Duplicate & Customize"})]})]})})}return y==="edit"?o.jsx(jt,{isOpen:e,onClose:Oe,title:v?"Edit Command":"New Command",size:"xl",children:o.jsxs("div",{className:"flex flex-col h-full",children:[x&&o.jsx(Wh,{message:x}),o.jsxs("div",{className:"space-y-3 mb-3",children:[o.jsx(ty,{name:j.name,id:j.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Command",idPlaceholder:"my-command",readOnlyId:!!v&&!j.isDefault,onNameChange:ze,onIdChange:fe=>A(je=>({...je,id:fe}))}),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:fe=>A(je=>({...je,agentMode:fe.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)"}),Z.map(fe=>o.jsx("option",{value:fe.id,children:fe.name},fe.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:fe=>A(je=>({...je,prompt:fe.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(st,{variant:"secondary",onClick:Oe,children:"Cancel"}),o.jsx(st,{variant:"primary",onClick:Le,disabled:_||!j.name||!j.prompt,children:_?"Saving...":"Save"})]})]})}):o.jsxs(jt,{isOpen:e,onClose:r,title:"Commands",size:"lg",children:[o.jsx(Qb,{description:"Commands are pre-defined messages you can send with a single click.",onNew:re}),o.jsxs(ey,{loading:u,hasItems:i.length>0||l.length>0,loadingLabel:"Loading commands...",emptyLabel:"No commands created yet.",children:[i.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:i.map(fe=>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:fe.name})}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx(WA,{onClick:()=>V(fe.id)}),o.jsx(io,{onClick:()=>oe(fe.id)})]})]},fe.id))})]}),l.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:l.map(fe=>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:fe.name})})}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx(qi,{onClick:()=>ve(fe.id)}),o.jsx(io,{onClick:()=>oe(fe.id)}),G(fe.id,"delete")?o.jsx($h,{onConfirm:()=>be(fe.id),onCancel:q}):o.jsx(qh,{onClick:()=>O(fe.id)})]})]},fe.id))})]})]})]})}function VA(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function GA(e){let r=1;for(;e.some(s=>s.id===`s${r}`);)r++;return`s${r}`}const KA=[{value:"agent",label:"Agent"},{value:"sub_agent",label:"Sub-Agent"},{value:"shell",label:"Shell"}],B0={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"},z0=[{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)"}],zs=150,Fr=54,zi=80,Pn=30,Pi=70,yb=100,Ps=50,ql=50,_b=4;function Tf(e,r){if(e.type==="agent"){const s=r.find(i=>i.id===e.toolMode);return{name:(s==null?void 0:s.name)??(e.toolMode||"Agent"),color:(s==null?void 0:s.color)||"#3b82f6"}}if(e.type==="sub_agent"){const s=r.find(i=>i.id===e.subAgentType);return{name:(s==null?void 0:s.name)??(e.subAgentType||"Sub-Agent"),color:(s==null?void 0:s.color)||"#a855f7"}}return{name:"Shell",color:"#22c55e"}}function YA(e,r,s,i){const l=ql+Ps+zs+yb+zs+Ps+ql,u=l/2,h=ql+Ps+zs/2,c=ql+Ps+zs+yb+zs/2,d=[],p=[],g=new Map,m=e.filter(I=>I.type==="agent"||I.type==="shell"),b=e.filter(I=>I.type==="sub_agent"),S=b.length>0,k=S?h:u,C=m.length>0?c:u,y=Ps+Pn/2;if(d.push({id:"$start",type:"terminal",label:"Start",cx:k,cy:y,w:zi,h:Pn}),g.set("$start",{cx:k,cy:y,w:zi,h:Pn}),e.length===0){const I=y+Pn/2+Pi*2+Pn/2;return d.push({id:"$done",type:"terminal",label:"Done",cx:k,cy:I,w:zi,h:Pn}),g.set("$done",{cx:k,cy:I,w:zi,h:Pn}),{nodes:d,edges:p,width:l,height:I+Pn/2+Ps,posMap:g}}const v=y+Pn/2+Pi,x=(I,$)=>{I.forEach((B,X)=>{const Z=v+X*(Fr+Pi)+Fr/2,{name:P,color:R}=Tf(B,i);d.push({id:B.id,type:"step",label:P,color:R,cx:$,cy:Z,w:zs,h:Fr}),g.set(B.id,{cx:$,cy:Z,w:zs,h:Fr})})};x(m,k),x(b,C);const _=m.length>0?v+(m.length-1)*(Fr+Pi)+Fr/2:y,j=S?v+(b.length-1)*(Fr+Pi)+Fr/2:y,T=Math.max(_,j)+Fr/2+Pi+Pn/2;d.push({id:"$done",type:"terminal",label:"Done",cx:k,cy:T,w:zi,h:Pn}),g.set("$done",{cx:k,cy:T,w:zi,h:Pn});const N=[];r&&g.has(r)&&N.push({from:"$start",to:r,label:s,edgeKey:"start",direction:"down",backEdgeIndex:0});let D=0;for(const I of e)I.transitions.forEach(($,B)=>{if(!$.goto||!g.has($.goto))return;const X=g.get(I.id),Z=g.get($.goto),P=$.when.type==="step_result"?`${$.when.result}`:B0[$.when.type]??$.when.type,R=I.id===$.goto;let L;R?L="back":Z.cy>X.cy+1?L="down":Z.cy<X.cy-1?L="back":L="same",N.push({from:I.id,to:$.goto,label:P,edgeKey:`${I.id}:${B}`,direction:L,backEdgeIndex:L==="back"?D++:0})});const A=new Map,z=new Map,O=new Map,q=new Map;for(const I of N)I.direction==="down"&&(A.set(I.from,(A.get(I.from)??0)+1),z.set(I.to,(z.get(I.to)??0)+1));const G=new Map,W=new Map;for(const I of N){if(I.direction!=="same")continue;const $=[I.from,I.to].sort().join("|");G.set($,(G.get($)??0)+1)}for(const I of N){if(I.direction==="back"||I.direction==="same"){let L=0;if(I.direction==="same"){const U=[I.from,I.to].sort().join("|");L=W.get(U)??0,W.set(U,L+1)}p.push({...I,fromPort:0,toPort:0,sameEdgeIndex:L});continue}const $=A.get(I.from)??1,B=z.get(I.to)??1,X=O.get(I.from)??0,Z=q.get(I.to)??0;O.set(I.from,X+1),q.set(I.to,Z+1);const P=$===1?0:-.6+1.2*X/($-1),R=B===1?0:-.6+1.2*Z/(B-1);p.push({...I,fromPort:P,toPort:R,sameEdgeIndex:0})}return{nodes:d,edges:p,width:l,height:T+Pn/2+Ps,posMap:g}}function XA({steps:e,entryStep:r,selectedNodeId:s,selectedEdgeKey:i,startConditionLabel:l,agentTypes:u,isReadOnly:h,onSelectNode:c,onSelectEdge:d,onRemoveStep:p,onCreateTransition:g,onReconnectTo:m,onReconnectFrom:b,onDeleteTransition:S}){const k=H.useRef(null),C=H.useRef(!1),[y,v]=H.useState(null),[x,_]=H.useState(null),[j,T]=H.useState(null),{nodes:N,edges:D,width:A,height:z,posMap:O}=H.useMemo(()=>YA(e,r,l,u),[e,r,l,u]),q=H.useCallback(Q=>{var re;const ee=k.current;if(!ee)return{x:0,y:0};const Y=ee.createSVGPoint();Y.x=Q.clientX,Y.y=Q.clientY;const V=(re=ee.getScreenCTM())==null?void 0:re.inverse();if(!V)return{x:0,y:0};const oe=Y.matrixTransform(V);return{x:oe.x,y:oe.y}},[]),G=H.useCallback(Q=>!Q||!x||Q==="$start"?!1:x.type==="reconnect-from"?Q!=="$done":!0,[x]),W=H.useCallback((Q,ee)=>{if(h)return;Q.stopPropagation(),Q.preventDefault();const Y=q(Q);_({type:"new",fromNodeId:ee,mouseX:Y.x,mouseY:Y.y})},[q,h]),I=H.useCallback((Q,ee)=>{if(h)return;Q.stopPropagation(),Q.preventDefault();const Y=q(Q);_({type:"reconnect-to",fromNodeId:ee.from,edgeKey:ee.edgeKey,mouseX:Y.x,mouseY:Y.y})},[q,h]),$=H.useCallback((Q,ee)=>{if(h)return;Q.stopPropagation(),Q.preventDefault();const Y=q(Q);_({type:"reconnect-from",fromNodeId:ee.from,fixedTargetId:ee.to,edgeKey:ee.edgeKey,mouseX:Y.x,mouseY:Y.y})},[q,h]),B=H.useCallback(Q=>{if(!x)return;const ee=q(Q);_(Y=>Y?{...Y,mouseX:ee.x,mouseY:ee.y}:null)},[x,q]),X=H.useCallback(()=>{x&&(C.current=!0,j&&G(j)&&(x.type==="new"?g(x.fromNodeId,j):x.type==="reconnect-to"?m(x.edgeKey,j):x.type==="reconnect-from"&&b(x.edgeKey,j)),_(null),T(null))},[x,j,G,g,m,b]),Z=H.useCallback(()=>{if(C.current){C.current=!1;return}c(null),d(null)},[c,d]);H.useEffect(()=>{if(h)return;const Q=ee=>{ee.target instanceof HTMLInputElement||ee.target instanceof HTMLTextAreaElement||ee.target instanceof HTMLSelectElement||(ee.key==="Delete"||ee.key==="Backspace")&&i&&i!=="start"&&(ee.preventDefault(),S(i),d(null))};return document.addEventListener("keydown",Q),()=>document.removeEventListener("keydown",Q)},[h,i,S,d]);const P=Q=>{const ee=O.get(Q.from),Y=O.get(Q.to);if(!ee||!Y)return null;let V,oe,re,ve="middle",be,Le;if(Q.direction==="down"){const Oe=ee.cx+Q.fromPort*(ee.w/2-10),ze=ee.cy+ee.h/2,We=Y.cx+Q.toPort*(Y.w/2-10),Ee=Y.cy-Y.h/2,fe=Ee-ze,je=We-Oe;V=`M ${Oe} ${ze} C ${Oe} ${ze+fe*.4}, ${We-je*.2} ${Ee-fe*.1}, ${We} ${Ee}`,oe=Oe+(We-Oe)*.5,re=ze+fe*.6,be={x:Oe,y:ze},Le={x:We,y:Ee}}else if(Q.direction==="back"){const Oe=Q.from===Q.to,ze=ee.cx>=A/2,We=Q.backEdgeIndex*16,Ee=ze?A-20-We:20+We;if(Oe){const fe=ee.cx>=A/2,je=30+Q.backEdgeIndex*14,Ue=ee.cy-ee.h/2,It=fe?ee.cx+ee.w/2:ee.cx-ee.w/2,pe=fe?It+je:It-je,Ne=ee.cx+(fe?ee.w/4:-ee.w/4),Me=Ue-20-Q.backEdgeIndex*10;V=`M ${It} ${ee.cy} C ${pe} ${ee.cy}, ${pe} ${Me}, ${Ne} ${Ue}`,oe=pe+10,re=Me+4,ve="middle",be={x:It,y:ee.cy},Le={x:Ne,y:Ue}}else{const fe=ze?ee.cx+ee.w/2:ee.cx-ee.w/2,je=Y.cx+(ze?Y.w/4:-Y.w/4),Ue=Math.min(ee.cy,Y.cy)-Y.h/2-18-Q.backEdgeIndex*14;V=`M ${fe} ${ee.cy} L ${Ee} ${ee.cy} L ${Ee} ${Ue} L ${je} ${Ue} L ${je} ${Y.cy-Y.h/2}`,oe=Ee,re=(ee.cy+Ue)/2,ve=ze?"start":"end",be={x:fe,y:ee.cy},Le={x:je,y:Y.cy-Y.h/2}}}else{const Oe=Y.cx>ee.cx,ze=Q.sameEdgeIndex===0?-12:12,We=Oe?ee.cx+ee.w/2:ee.cx-ee.w/2,Ee=Oe?Y.cx-Y.w/2:Y.cx+Y.w/2,fe=ee.cy+ze,je=Y.cy+ze,Ue=(We+Ee)/2;V=`M ${We} ${fe} C ${Ue} ${fe}, ${Ue} ${je}, ${Ee} ${je}`,oe=Ue,re=(fe+je)/2-6,be={x:We,y:fe},Le={x:Ee,y:je}}return{path:V,labelX:oe,labelY:re,labelAnchor:ve,fromPt:be,toPt:Le}},R=(Q,ee)=>{const Y=P(Q);if(!Y)return null;const{path:V,labelX:oe,labelY:re,labelAnchor:ve}=Y,be=i===Q.edgeKey,Le=Q.label&&!(Q.from==="$start"&&Q.label==="Always");return o.jsxs("g",{children:[o.jsx("path",{d:V,fill:"none",stroke:"transparent",strokeWidth:14,className:"cursor-pointer",onClick:Oe=>{Oe.stopPropagation(),d(be?null:Q.edgeKey)}}),o.jsx("path",{d:V,fill:"none",stroke:be?"#58a6ff":"#484f58",strokeWidth:be?2.2:1.2,markerEnd:be?"url(#arrow-selected)":"url(#arrow)",pointerEvents:"none"}),Le&&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)},L=()=>{if(!i||x)return null;const Q=D.find(re=>re.edgeKey===i);if(!Q)return null;const ee=P(Q);if(!ee)return null;const{fromPt:Y,toPt:V}=ee,oe=6;return o.jsxs(o.Fragment,{children:[Q.edgeKey!=="start"&&o.jsx("circle",{cx:Y.x,cy:Y.y,r:oe,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:re=>$(re,Q)}),o.jsx("circle",{cx:V.x,cy:V.y,r:oe,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:re=>I(re,Q)})]})},U=()=>{if(!x)return null;let Q,ee,Y,V;if(x.type==="reconnect-from"){const ve=O.get(x.fixedTargetId);if(!ve)return null;Q=x.mouseX,ee=x.mouseY,Y=ve.cx,V=ve.cy-ve.h/2}else{const ve=O.get(x.fromNodeId);if(!ve)return null;Q=ve.cx,ee=ve.cy+ve.h/2,Y=x.mouseX,V=x.mouseY}const oe=V-ee,re=Math.abs(oe)>10?`M ${Q} ${ee} C ${Q} ${ee+oe*.4}, ${Y} ${V-oe*.4}, ${Y} ${V}`:`M ${Q} ${ee} L ${Y} ${V}`;return o.jsx("path",{d:re,fill:"none",stroke:"#58a6ff",strokeWidth:2,strokeDasharray:"6 3",strokeOpacity:.7,pointerEvents:"none"})},F=Q=>{const ee=Q.cy+Q.h/2,Y=(x==null?void 0:x.fromNodeId)===Q.id;return o.jsx("circle",{cx:Q.cx,cy:ee,r:_b,fill:Y?"#58a6ff":"#1c2128",stroke:Y?"#58a6ff":"#484f58",strokeWidth:1.5,strokeOpacity:Y?1:.5,className:"cursor-crosshair",onMouseDown:V=>W(V,Q.id)})},ne=Q=>{const ee=Q.cy-Q.h/2,Y=x&&j===Q.id&&G(Q.id);return o.jsx("circle",{cx:Q.cx,cy:ee,r:_b,fill:Y?"#3fb950":"#1c2128",stroke:Y?"#3fb950":"#484f58",strokeWidth:1.5,strokeOpacity:Y?1:.5})};return o.jsxs("svg",{ref:k,viewBox:`0 0 ${A} ${z}`,className:"block w-full",preserveAspectRatio:"xMidYMin meet",onMouseMove:B,onMouseUp:X,onClick:Z,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=s===Q.id,Y=Q.cx-Q.w/2,V=Q.cy-Q.h/2,oe=y===Q.id,re=x&&j===Q.id&&G(Q.id);if(Q.type==="terminal"){const be=Q.id==="$start",Le=be?"#58a6ff":"#3fb950",Oe=be,ze=!be;return o.jsxs("g",{onClick:We=>{We.stopPropagation(),be&&!h&&d("start")},className:be&&!h?"cursor-pointer":void 0,children:[re&&o.jsx("rect",{x:Y-3,y:V-3,width:Q.w+6,height:Q.h+6,rx:Q.h/2+3,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),be&&i==="start"&&o.jsx("rect",{x:Y-3,y:V-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:Y,y:V,width:Q.w,height:Q.h,rx:Q.h/2,fill:Le,fillOpacity:.08,stroke:Le,strokeOpacity:.4,strokeWidth:1.5}),o.jsx("text",{x:Q.cx,y:Q.cy+4,textAnchor:"middle",fill:Le,className:"text-[10px] font-medium",pointerEvents:"none",children:Q.label}),Oe&&F(Q),ze&&ne(Q)]},Q.id)}const ve=Q.color??"#6b7280";return o.jsxs("g",{onClick:be=>{be.stopPropagation(),h||c(ee?null:Q.id)},onMouseEnter:()=>v(Q.id),onMouseLeave:()=>v(null),className:h?void 0:"cursor-pointer",children:[re&&o.jsx("rect",{x:Y-3,y:V-3,width:Q.w+6,height:Q.h+6,rx:12,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),ee&&o.jsx("rect",{x:Y-3,y:V-3,width:Q.w+6,height:Q.h+6,rx:12,fill:"none",stroke:"#58a6ff",strokeOpacity:.5,strokeWidth:2}),o.jsx("rect",{x:Y,y:V,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}),!h&&F(Q),!h&&ne(Q),oe&&!x&&!h&&o.jsxs("g",{onClick:be=>{be.stopPropagation(),p(Q.id)},className:"cursor-pointer",children:[o.jsx("circle",{cx:Y+Q.w-2,cy:V+2,r:8,fill:"#0d1117",fillOpacity:.9,stroke:"#f85149",strokeOpacity:.5,strokeWidth:1}),o.jsx("line",{x1:Y+Q.w-5,y1:V-1,x2:Y+Q.w+1,y2:V+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"}),o.jsx("line",{x1:Y+Q.w+1,y1:V-1,x2:Y+Q.w-5,y2:V+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"})]})]},Q.id)}),x&&N.map(Q=>G(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(),X()}},`drop-${Q.id}`):null),U(),L()]})}const ar="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",qs="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",fn="block text-[11px] text-text-secondary mb-0.5";function ZA({fromLabel:e,toLabel:r,condition:s,fromStep:i,agentTypes:l,onUpdateCondition:u,onDelete:h}){const c=i&&(i.type==="sub_agent"||i.type==="agent")?l.find(p=>p.id===(i.type==="sub_agent"?i.subAgentType:i.toolMode)):void 0,d=(c==null?void 0:c.results)&&c.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:h,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($b,{}),o.jsx("span",{className:"font-medium text-text-primary",children:r})]}),o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Condition"}),o.jsx("select",{value:s.type,onChange:p=>{u(p.target.value==="step_result"?{type:"step_result",result:"success"}:{type:p.target.value})},className:qs,children:z0.map(p=>o.jsx("option",{value:p.value,children:p.label},p.value))})]}),s.type==="step_result"&&o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Result"}),d?o.jsx("select",{value:s.result??c.results[0],onChange:p=>{u({type:"step_result",result:p.target.value})},className:qs,children:c.results.map(p=>o.jsx("option",{value:p,children:p},p))}):o.jsx("input",{type:"text",value:s.result??"success",onChange:p=>u({type:"step_result",result:p.target.value}),placeholder:"e.g. success, passed, failed",className:ar})]}),o.jsx("p",{className:"text-text-muted text-[10px]",children:"Drag handles to reconnect. Press Delete to remove."})]})}function fh({variables:e,onInsert:r}){return e.length===0?null:o.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:e.map(s=>o.jsx("button",{type:"button",onClick:()=>r(s.name),title:s.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:`{{${s.name}}}`},s.name))})}function QA({step:e,isEntry:r,agentTypes:s,transitionCount:i,templateVariables:l,onUpdate:u,onRemove:h,onSetEntry:c}){const{color:d,name:p}=Tf(e,s);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:c,className:"p-1 rounded text-text-muted hover:text-accent-primary text-xs",children:"Set entry"}),o.jsx("button",{onClick:h,className:"p-1 rounded text-text-muted hover:text-accent-error text-xs",children:"Delete"})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:fn,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 S=s.find(k=>!k.subagent);u({...e,type:m,phase:b,toolMode:(S==null?void 0:S.id)??"builder",name:(S==null?void 0:S.name)??"Agent"})}else if(m==="sub_agent"){const S=s.find(k=>k.subagent);u({...e,type:m,phase:b,subAgentType:(S==null?void 0:S.id)??"",name:(S==null?void 0:S.name)??"Sub-Agent"})}else u({...e,type:m,phase:b,name:"Shell"})},className:qs,children:KA.map(g=>o.jsx("option",{value:g.value,children:g.label},g.value))})]}),e.type==="agent"&&o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Agent Type"}),o.jsx("select",{value:e.toolMode??"builder",onChange:g=>{const m=s.find(b=>b.id===g.target.value);u({...e,toolMode:g.target.value,name:(m==null?void 0:m.name)??g.target.value})},className:qs,children:s.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:fn,children:"Sub-Agent Type"}),o.jsxs("select",{value:e.subAgentType??"",onChange:g=>{const m=s.find(b=>b.id===g.target.value);u({...e,subAgentType:g.target.value,name:(m==null?void 0:m.name)??g.target.value})},className:qs,children:[o.jsx("option",{value:"",children:"— select —"}),s.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:fn,children:"Prompt"}),o.jsx("textarea",{value:e.prompt??"",onChange:g=>u({...e,prompt:g.target.value||void 0}),rows:6,className:`${ar} resize-y text-xs`,placeholder:"Injected on first entry..."}),o.jsx(fh,{variables:l,onInsert:g=>u({...e,prompt:(e.prompt??"")+`{{${g}}}`})})]}),o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Nudge Prompt"}),o.jsx("textarea",{value:e.nudgePrompt??"",onChange:g=>u({...e,nudgePrompt:g.target.value||void 0}),rows:6,className:`${ar} resize-y text-xs`,placeholder:"Injected on re-entry..."}),o.jsx(fh,{variables:l,onInsert:g=>u({...e,nudgePrompt:(e.nudgePrompt??"")+`{{${g}}}`})})]})]}),e.type==="shell"&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Command"}),o.jsx("textarea",{value:e.command??"",onChange:g=>u({...e,command:g.target.value}),rows:3,className:`${ar} font-mono text-xs resize-y`,placeholder:"cd {{workdir}} && npm run lint"}),o.jsx(fh,{variables:l,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:fn,children:"Timeout (ms)"}),o.jsx("input",{type:"number",value:e.timeout??6e4,onChange:g=>u({...e,timeout:Number(g.target.value)}),className:`${ar} font-mono text-xs`})]}),o.jsxs("div",{children:[o.jsx("label",{className:fn,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:`${ar} 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:[i," outgoing transition",i!==1?"s":""," — drag from the bottom port to connect."]})})]})}const Sb=[];function P0({isOpen:e,onClose:r,initialEditId:s}){const i=Tt(me=>me.defaults),l=Tt(me=>me.userItems),u=Tt(me=>me.loading),h=Tt(me=>me.templateVariables),c=Tt(me=>me.fetchWorkflows),d=Tt(me=>me.fetchWorkflow),p=Tt(me=>me.fetchDefaultContent),g=Tt(me=>me.fetchTemplateVariables),m=Tt(me=>me.createWorkflow),b=Tt(me=>me.updateWorkflow),S=Tt(me=>me.deleteWorkflow),{requestDelete:k,clearConfirm:C,isConfirming:y}=Uh(),[v,x]=H.useState("list"),[_,j]=H.useState(null),[T,N]=H.useState(!1),[D,A]=H.useState(null),[z,O]=H.useState(null),[q,G]=H.useState(""),[W,I]=H.useState(""),[$,B]=H.useState(""),[X,Z]=H.useState("1.0.0"),[P,R]=H.useState("#3b82f6"),[L,U]=H.useState(""),[F,ne]=H.useState(50),[Q,ee]=H.useState(Sb),[Y,V]=H.useState({type:"always"}),[oe,re]=H.useState(""),[ve,be]=H.useState(!1),[Le,Oe]=H.useState([]),[ze]=H.useState(null);H.useEffect(()=>{e&&(c(),g(),ke("/api/agents").then(me=>me.json()).then(me=>Oe(me.agents??[])).catch(()=>{}),A(null),O(null),s?i.some(ye=>ye.id===s)?p(s).then(ye=>{ye&&(G(ye.metadata.name+" (copy)"),I(`${s}-copy-${Date.now()}`),B(ye.metadata.description),Z(ye.metadata.version),R(ye.metadata.color??"#3b82f6"),U(ye.entryStep),ne(ye.settings.maxIterations),ee(ye.steps),V(ye.startCondition??{type:"always"}),re(""),j(null),N(!1),x("edit"))}):d(s).then(ye=>{ye&&(G(ye.metadata.name),I(ye.metadata.id),B(ye.metadata.description),Z(ye.metadata.version),R(ye.metadata.color??"#3b82f6"),U(ye.entryStep),ne(ye.settings.maxIterations),ee(ye.steps),V(ye.startCondition??{type:"always"}),re(""),j(s),N(!1),x("edit"))}):(x("list"),j(null),N(!1)))},[e,c,d,p,g,s]);const We=async me=>{const ye=await d(me);ye&&(j(me),G(ye.metadata.name),I(ye.metadata.id),B(ye.metadata.description),Z(ye.metadata.version),R(ye.metadata.color??"#3b82f6"),U(ye.entryStep),ne(ye.settings.maxIterations),ee(ye.steps),V(ye.startCondition??{type:"always"}),re(""),A(null),O(null),x("edit"))},Ee=async()=>{var Qe;const me=_??W;if(!me||!q)return re("Name is required."),!1;if(Q.length===0)return re("Add at least one step."),!1;let ye=L;if(!ye||!Q.some(He=>He.id===ye)){if(ye=((Qe=Q.find(He=>He.id))==null?void 0:Qe.id)??"",!ye)return re("All steps need an ID."),!1;U(ye)}be(!0),re("");const we={metadata:{id:me,name:q,description:$,version:X||"1.0.0",color:P},entryStep:ye,settings:{maxIterations:F},steps:Q,startCondition:Y},Ve=_?await b(_,we):await m(we);return be(!1),Ve.success?(_||j(me),!0):(re(Ve.error??"Failed to save."),!1)},fe=async()=>{await Ee()},je=async()=>{await Ee()&&(s?r():x("list"))},Ue=()=>{s?r():x("list")},It=me=>{G(me),_||I(VA(me))},pe=async me=>{if(i.some(we=>we.id===me)){const we=await p(me);if(!we)return;G(we.metadata.name),I(we.metadata.id),B(we.metadata.description),Z(we.metadata.version),R(we.metadata.color??"#3b82f6"),U(we.entryStep),ne(we.settings.maxIterations),ee(we.steps),V(we.startCondition??{type:"always"}),re(""),j(me),N(!0)}else{const we=await d(me);if(!we)return;G(we.metadata.name),I(we.metadata.id),B(we.metadata.description),Z(we.metadata.version),R(we.metadata.color??"#3b82f6"),U(we.entryStep),ne(we.settings.maxIterations),ee(we.steps),V(we.startCondition??{type:"always"}),re(""),j(me),N(!0)}x("edit")},Ne=async me=>{const we=i.some(Ve=>Ve.id===me)?await p(me):await d(me);we&&(G(we.metadata.name+" (copy)"),I(`${me}-copy-${Date.now()}`),B(we.metadata.description),Z(we.metadata.version),R(we.metadata.color??"#3b82f6"),U(we.entryStep),ne(we.settings.maxIterations),ee(we.steps),V(we.startCondition??{type:"always"}),re(""),j(null),N(!1),x("edit"))},Me=()=>{j(null),G(""),I(""),B(""),Z("1.0.0"),R("#3b82f6"),U(""),ne(50),ee(structuredClone(Sb)),V({type:"always"}),re(""),A(null),O(null),N(!1),x("edit")},lt=async me=>{await S(me),C()},ue=H.useCallback(me=>{A(me),O(null)},[]),_e=H.useCallback(me=>{O(me),A(null)},[]),Te=D!==null?Number(D):-1,Ie=Te>=0?Q[Te]??null:null,$e=H.useCallback(me=>{ee(ye=>ye.map((we,Ve)=>Ve===Te?me:we))},[Te]),St=Y.type==="step_result"?`${Y.result}`:B0[Y.type]??Y.type,Ye=()=>{const me=Q.length,ye=GA(Q),we=Le.find(Ve=>!Ve.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:[]}]),L||U(ye),ue(String(me))},Dt=H.useCallback((me,ye)=>{me==="$start"?(U(ye),_e("start")):ee(we=>{const Ve=we.find(He=>He.id===me),Qe=Ve?Ve.transitions.length:0;return _e(`${me}:${Qe}`),we.map(He=>He.id===me?{...He,transitions:[...He.transitions,{when:{type:"always"},goto:ye}]}:He)})},[_e]),gt=H.useCallback((me,ye)=>{if(me==="start")U(ye);else{const we=me.lastIndexOf(":"),Ve=me.slice(0,we),Qe=parseInt(me.slice(we+1));ee(He=>He.map(Xt=>Xt.id===Ve?{...Xt,transitions:Xt.transitions.map((Rt,Bt)=>Bt===Qe?{...Rt,goto:ye}:Rt)}:Xt))}},[]),Yt=H.useCallback((me,ye)=>{const we=me.lastIndexOf(":"),Ve=me.slice(0,we),Qe=parseInt(me.slice(we+1));ee(He=>{const Xt=He.find(Bt=>Bt.id===Ve);if(!Xt)return He;const Rt=Xt.transitions[Qe];return Rt?He.map(Bt=>Bt.id===Ve?{...Bt,transitions:Bt.transitions.filter((qr,ie)=>ie!==Qe)}:Bt.id===ye?{...Bt,transitions:[...Bt.transitions,Rt]}:Bt):He}),O(null)},[]),ct=H.useCallback(me=>{if(me==="start")U("");else{const ye=me.lastIndexOf(":"),we=me.slice(0,ye),Ve=parseInt(me.slice(ye+1));ee(Qe=>Qe.map(He=>He.id===we?{...He,transitions:He.transitions.filter((Xt,Rt)=>Rt!==Ve)}:He))}O(null)},[]),qn=H.useCallback((me,ye)=>{if(me==="start")V(ye);else{const we=me.lastIndexOf(":"),Ve=me.slice(0,we),Qe=parseInt(me.slice(we+1));ee(He=>He.map(Xt=>Xt.id===Ve?{...Xt,transitions:Xt.transitions.map((Rt,Bt)=>Bt===Qe?{...Rt,when:ye}:Rt)}:Xt))}},[]),sn=me=>Tf(me,Le).name,Yi=()=>{if(!z)return null;if(z==="start"){const Rt=Q.find(Bt=>Bt.id===L);return{type:"start",fromLabel:"Start",toLabel:Rt?sn(Rt):"(none)",condition:Y}}const me=z.lastIndexOf(":"),ye=z.slice(0,me),we=parseInt(z.slice(me+1)),Ve=Q.find(Rt=>Rt.id===ye);if(!Ve)return null;const Qe=Ve.transitions[we];if(!Qe)return null;const He=Q.find(Rt=>Rt.id===Qe.goto),Xt=Qe.goto==="$done"?"Done":He?sn(He):Qe.goto;return{type:"step",fromLabel:sn(Ve),toLabel:Xt,condition:Qe.when}};if(v==="edit"){const me=Yi();return o.jsxs(jt,{isOpen:e,onClose:Ue,title:T?q:_?"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:fn,children:"Name"}),o.jsx("input",{value:q,onChange:ye=>It(ye.target.value),placeholder:"Workflow name",className:`${ar} ${T?"opacity-50":""}`,readOnly:T})]}),o.jsxs("div",{className:"min-w-[100px]",children:[o.jsx("label",{className:fn,children:"ID"}),o.jsx("input",{value:W,readOnly:!0,className:`${ar} font-mono opacity-50`})]}),o.jsxs("div",{className:"flex-1 min-w-[140px]",children:[o.jsx("label",{className:fn,children:"Description"}),o.jsx("input",{value:$,onChange:ye=>!T&&B(ye.target.value),readOnly:T,placeholder:"What does this workflow do?",className:`${ar} ${T?"opacity-50":""}`})]}),o.jsxs("div",{className:"w-20",children:[o.jsx("label",{className:fn,children:"Max Iter."}),o.jsx("input",{type:"number",value:F,onChange:ye=>!T&&ne(Number(ye.target.value)),readOnly:T,className:`${ar} font-mono ${T?"opacity-50":""}`})]}),o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Color"}),o.jsx("input",{type:"color",value:P,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:Ye,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(XA,{steps:Q,entryStep:L,selectedNodeId:(Ie==null?void 0:Ie.id)??null,selectedEdgeKey:z,startConditionLabel:St,agentTypes:Le,isReadOnly:T,onSelectNode:ye=>{if(ye===null){ue(null);return}const we=Q.findIndex(Ve=>Ve.id===ye);ue(we>=0?String(we):null)},onSelectEdge:_e,onRemoveStep:ye=>{var Ve;const we=Q.findIndex(Qe=>Qe.id===ye);if(ee(Qe=>Qe.filter(He=>He.id!==ye)),Te===we&&ue(null),L===ye){const Qe=Q.filter(He=>He.id!==ye);U(((Ve=Qe[0])==null?void 0:Ve.id)??"")}},onCreateTransition:Dt,onReconnectTo:gt,onReconnectFrom:Yt,onDeleteTransition:ct}),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:Ye,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&&(me||Ie)?o.jsx("p",{className:"text-text-muted text-xs text-center py-8",children:'View only — click "Duplicate & Customize" to edit.'}):me?me.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"})}),L&&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($b,{}),o.jsx("span",{className:"text-text-primary font-medium",children:me.toLabel})]}),o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Activation Condition"}),o.jsx("select",{value:Y.type,onChange:ye=>V(ye.target.value==="step_result"?{type:"step_result",result:"success"}:{type:ye.target.value}),className:qs,children:z0.map(ye=>o.jsx("option",{value:ye.value,children:ye.label},ye.value))})]}),Y.type==="step_result"&&o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Result"}),L&&(()=>{const ye=Q.find(He=>He.id===L),we=ye&&(ye.type==="sub_agent"||ye.type==="agent")?Le.find(He=>He.id===(ye.type==="sub_agent"?ye.subAgentType:ye.toolMode)):void 0,Ve=(we==null?void 0:we.results)&&we.results.length>0,Qe=(we==null?void 0:we.results)??[];return Ve?o.jsx("select",{value:Y.result??Qe[0],onChange:He=>V({type:"step_result",result:He.target.value}),className:qs,children:Qe.map(He=>o.jsx("option",{value:He,children:He},He))}):o.jsx("input",{type:"text",value:Y.result??"success",onChange:He=>V({type:"step_result",result:He.target.value}),placeholder:"e.g. success, passed, failed",className:ar})})()]}),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(ZA,{fromLabel:me.fromLabel,toLabel:me.toLabel,condition:me.condition,fromStep:me.type==="step"?Q.find(ye=>ye.id===me.fromLabel):void 0,agentTypes:Le,onUpdateCondition:ye=>qn(z,ye),onDelete:()=>ct(z)}):Ie?o.jsx(QA,{step:Ie,isEntry:Ie.id===L,agentTypes:Le,transitionCount:Ie.transitions.length,templateVariables:h,onUpdate:$e,onRemove:()=>{var ye;if(Ie&&(ee(Q.filter((we,Ve)=>Ve!==Te)),ue(null),L===Ie.id)){const we=Q.filter((Ve,Qe)=>Qe!==Te);U(((ye=we[0])==null?void 0:ye.id)??"")}},onSetEntry:()=>U(Ie.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(st,{variant:"secondary",onClick:Ue,children:"Close"}),T?o.jsx(st,{variant:"primary",onClick:()=>{G(q+" (copy)"),I(`${_}-copy-${Date.now()}`),j(null),N(!1)},children:"Duplicate & Customize"}):o.jsxs(o.Fragment,{children:[o.jsx(st,{variant:"secondary",onClick:fe,disabled:ve||!q,children:ve?"Saving...":"Save"}),o.jsx(st,{variant:"primary",onClick:je,disabled:ve||!q,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(st,{variant:"primary",size:"sm",onClick:Me,children:"+ New"})})]}),u&&i.length===0&&l.length===0?o.jsx("div",{className:"text-text-muted text-sm",children:"Loading workflows..."}):i.length===0&&l.length===0?o.jsx("div",{className:"text-text-muted text-sm",children:"No workflows installed."}):o.jsxs("div",{className:"space-y-4",children:[i.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:i.map(me=>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:me.name}),o.jsxs("span",{className:"text-text-muted text-xs",children:["v",me.version]})]}),o.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:me.description})]}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx("button",{onClick:()=>pe(me.id),className:"p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",title:"View",children:o.jsx(lc,{})}),o.jsx(io,{onClick:()=>Ne(me.id)})]})]},me.id))})]}),l.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:l.map(me=>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:me.name}),o.jsxs("span",{className:"text-text-muted text-xs",children:["v",me.version]})]}),o.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:me.description})]}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx(io,{onClick:()=>Ne(me.id)}),o.jsx(qi,{onClick:()=>We(me.id)}),y(me.id,"delete")?o.jsx($h,{onConfirm:()=>lt(me.id),onCancel:()=>{}}):o.jsx(qh,{onClick:()=>k(me.id)})]})]},me.id))})]})]})]})}function JA(e,r){const s=e.startCondition;if(!s||s.type==="always")return!0;switch(s.type){case"has_pending_criteria":return r.some(i=>i.status.type!=="passed");case"all_criteria_passed":return r.length===0||r.every(i=>i.status.type==="passed");case"all_criteria_completed_or_passed":return r.every(i=>i.status.type==="completed"||i.status.type==="passed");case"any_criteria_blocked":return r.some(i=>i.status.type==="failed"&&i.attempts.filter(l=>l.status==="failed").length>=4);case"step_result":return null;default:return null}}function e4({onSendCommand:e,onSelectWorkflow:r,onOpenCommandsManager:s,onOpenWorkflowsManager:i,onAttach:l,textareaContent:u,attachments:h,criteria:c}){const[d,p]=H.useState(!1),[g,m]=H.useState("commands"),[b,S]=H.useState(""),[k,C]=H.useState(0),[y,v]=H.useState(null),[x,_]=H.useState(null),j=H.useRef(null),T=H.useRef(null),N=hn(U=>U.defaults),D=hn(U=>U.userItems),A=hn(U=>U.fetchCommands),z=Tt(U=>U.defaults),O=Tt(U=>U.userItems),q=Tt(U=>U.fetchWorkflows),G=[...N,...D],W=[...z,...O];H.useEffect(()=>{d&&(g==="commands"?A():g==="workflows"&&q())},[d,g,A,q]),H.useEffect(()=>{d&&(S(""),C(0),requestAnimationFrame(()=>{var U;return(U=j.current)==null?void 0:U.focus()}))},[d,g]),H.useEffect(()=>{if(!d)return;const U=F=>{var ne;(ne=T.current)!=null&&ne.contains(F.target)||p(!1)};return document.addEventListener("mousedown",U),()=>document.removeEventListener("mousedown",U)},[d]);const I=U=>{switch(U.key){case"ArrowDown":U.preventDefault(),C(F=>{const Q=(g==="commands"?G:W).filter(ee=>{const Y=b.toLowerCase();return!Y||ee.name.toLowerCase().includes(Y)});return Math.min(F+1,Q.length-1)});break;case"ArrowUp":U.preventDefault(),C(F=>Math.max(F-1,0));break;case"Enter":U.preventDefault();break;case"Escape":U.preventDefault(),p(!1);break}},$=U=>{S(U),C(0)},B=G.filter(U=>!b||U.name.toLowerCase().includes(b.toLowerCase())),X=W.filter(U=>!b||U.name.toLowerCase().includes(b.toLowerCase())),Z=async U=>{const F=await hn.getState().fetchCommand(U);F&&e(F.prompt,F.metadata.agentMode,u,h),p(!1)},P=U=>{r(U),p(!1)},R=(U,F)=>{F.stopPropagation(),p(!1),v(U)},L=(U,F)=>{F.stopPropagation(),p(!1),_(U)};return o.jsxs("div",{ref:T,className:"relative",children:[o.jsx("button",{type:"button",onClick:()=>p(!d),className:"px-1.5 py-2 rounded-r bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors border-l border-border/50",title:"More options",children:o.jsx(qb,{className:"w-4 h-4"})}),d&&o.jsxs("div",{className:"absolute bottom-full right-0 mb-1 w-80 bg-bg-secondary border border-border rounded-lg shadow-xl z-50 overflow-hidden",children:[o.jsxs("div",{className:"flex border-b border-border",children:[o.jsx("button",{type:"button",onClick:()=>{m("commands"),S(""),C(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${g==="commands"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Commands"}),o.jsx("button",{type:"button",onClick:()=>{m("workflows"),S(""),C(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${g==="workflows"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Workflows"}),o.jsx("button",{type:"button",onClick:()=>m("attach"),className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${g==="attach"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Attach"})]}),g!=="attach"&&o.jsx("div",{className:"p-2 border-b border-border",children:o.jsx("input",{ref:j,value:b,onChange:U=>$(U.target.value),onKeyDown:I,placeholder:g==="commands"?"Search commands...":"Search workflows...",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"})}),o.jsx("div",{className:"overflow-y-auto max-h-64 p-1",children:g==="commands"?B.length===0?o.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:G.length===0?"No commands yet":"No matches"}):B.map((U,F)=>o.jsxs("div",{className:`flex items-center gap-1 px-3 py-2 rounded transition-colors group ${F===k?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[o.jsx("button",{type:"button",onClick:()=>Z(U.id),className:"flex-1 text-left",children:o.jsx("div",{className:"text-sm text-text-primary font-medium",children:U.name})}),o.jsx(qi,{className:"opacity-0 group-hover:opacity-100",onClick:ne=>R(U.id,ne)})]},U.id)):g==="workflows"?X.length===0?o.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:W.length===0?"No workflows yet":"No matches"}):X.map((U,F)=>{const ne=JA(U,c),Q=U.color??"#3b82f6";return o.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 rounded transition-colors group ${F===k?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[o.jsxs("button",{type:"button",onClick:()=>P(U.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:Q}}),o.jsx("span",{className:"text-sm text-text-primary font-medium flex-1",children:U.name}),ne!==null&&o.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:ne?"#22c55e":"#6b7280"},title:ne?"Entry condition met":"Entry condition not met"})]}),o.jsx(qi,{className:"opacity-0 group-hover:opacity-100",onClick:ee=>L(U.id,ee)})]},U.id)}):o.jsxs("div",{className:"p-4 flex flex-col items-center gap-3",children:[o.jsxs("button",{type:"button",onClick:()=>{l(),p(!1)},className:"flex items-center gap-2 px-4 py-2 rounded bg-bg-tertiary hover:bg-accent-primary/20 text-text-primary transition-colors",children:[o.jsx(pw,{className:"w-4 h-4"}),o.jsx("span",{className:"text-sm font-medium",children:"Attach image"})]}),o.jsx("span",{className:"text-xs text-text-muted",children:"or drag & drop into chat"})]})}),g!=="attach"&&o.jsx("div",{className:"border-t border-border p-1",children:o.jsx("button",{type:"button",onClick:()=>{p(!1),g==="commands"?s():i()},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:g==="commands"?"Manage Commands...":"Manage Workflows..."})})]}),o.jsx(I0,{isOpen:!!y,onClose:()=>v(null),initialEditId:y}),o.jsx(P0,{isOpen:!!x,onClose:()=>_(null),initialEditId:x})]})}function H0(e,r){if(!r)return!0;const s=r.toLowerCase().split(/\s+/),i=e.toLowerCase().split(/\s+/);return s.every(l=>{for(const u of i){let h=0;for(let c=0;c<u.length&&h<l.length;c++)u[c]===l[h]&&h++;if(h===l.length)return!0}return!1})}function F0(e,r,s,i,l){switch(e.key){case"ArrowDown":e.preventDefault(),s(u=>Math.min(u+1,r));break;case"ArrowUp":e.preventDefault(),s(u=>Math.max(u-1,0));break;case"Enter":e.preventDefault(),i();break;case"Escape":e.preventDefault(),l();break}}function t4({isOpen:e,onClose:r,onCloseComplete:s,onSelectCommand:i,onSelectWorkflow:l,onCloseCompleteAction:u,textareaContent:h,onSearchMessages:c,onToggleAutoScroll:d,isAutoScrollActive:p}){const g=hn(L=>L.fetchCommands),m=Tt(L=>L.fetchWorkflows),b=At(L=>L.fetchAgents),S=hn(L=>L.defaults),k=hn(L=>L.userItems),C=Tt(L=>L.defaults),y=Tt(L=>L.userItems),v=At(L=>L.defaults),x=At(L=>L.userItems),_=Ce(L=>{var U;return(U=L.currentSession)==null?void 0:U.mode}),j=Ce(L=>{var U;return((U=L.currentSession)==null?void 0:U.dangerLevel)??"normal"}),T=Ce(L=>L.switchMode),N=Ce(L=>L.switchDangerLevel),D=Ce(L=>{var U;return(U=L.currentSession)==null?void 0:U.projectId}),A=Ce(L=>L.createSession),z=H.useRef(void 0),[O,q]=H.useState(""),[G,W]=H.useState(0),I=H.useRef(null),$=H.useRef(!1);H.useEffect(()=>{e&&($.current=!0)},[e]),H.useEffect(()=>{if(e){g(),m(),b(),q(""),W(0);const L=setTimeout(()=>{var U;return(U=I.current)==null?void 0:U.focus()},50);return()=>clearTimeout(L)}},[e,g,m,b]),H.useEffect(()=>{var L;!e&&$.current&&(s==null||s(),(L=z.current)==null||L.call(z),z.current=void 0)},[e,s]);const B=(L,U)=>{const F=new Set(U.map(ne=>ne.id));return[...L.filter(ne=>!F.has(ne.id)),...U]},Z=[{id:"create-session",name:"New Session",prefix:"Action > Create",action:()=>D&&A(D)},{id:"navigate-session",name:"Another Session",prefix:"Action > Navigate to",action:()=>{z.current=u,r()}},{id:"search-messages",name:"Messages",prefix:"Action > Search",action:()=>{r(),c==null||c()}},{id:"toggle-autoscroll",name:p?"Auto-scroll Off":"Auto-scroll On",prefix:"Action > Toggle",action:()=>{r(),d==null||d(!p)}},...B(v,x).filter(L=>!L.subagent&&L.id!==_).map(L=>({id:L.id,name:L.name,prefix:"Agent > Switch to",action:()=>T(L.id)})),...B(S,k).map(L=>({id:L.id,name:L.name,prefix:"Command > Launch",action:()=>i(L.id,h)})),...B(C,y).map(L=>({id:L.id,name:L.name,prefix:"Workflow > Run",action:()=>l(L.id)})),...["normal","dangerous"].filter(L=>L!==j).map(L=>({id:L,name:L.charAt(0).toUpperCase()+L.slice(1),prefix:"Mode > Switch to",action:()=>N(L)}))].filter(L=>H0(`${L.prefix} ${L.name}`,O)),P=Z.length-1,R=L=>{F0(L,P,W,()=>{var U;(U=Z[G])==null||U.action(),r()},r)};return e?go.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:I,type:"text",value:O,onChange:L=>{q(L.target.value),W(0)},onKeyDown:R,placeholder:"Search...",className:"flex-1 bg-transparent text-sm focus:outline-none placeholder:text-text-muted"}),o.jsx(Hh,{onClick:r,className:"shrink-0","aria-label":"Close"})]}),o.jsx("div",{className:"overflow-y-auto max-h-[60vh] p-2",children:Z.length===0?o.jsx("div",{className:"px-3 py-4 text-center text-text-muted text-sm",children:S.length+k.length+C.length+y.length>0?"No matches":"No agents, commands, or workflows yet"}):Z.map((L,U)=>o.jsxs("button",{type:"button",onClick:()=>{L.action(),r()},className:`w-full text-left px-3 py-2 rounded text-sm transition-colors ${U===G?"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:[L.prefix," "]}),o.jsx("span",{children:L.name})]},L.id))})]})]}),document.body):null}function n4(e){const r=new Date(e),s=new Date;if(r.getDate()===s.getDate()&&r.getMonth()===s.getMonth()&&r.getFullYear()===s.getFullYear())return r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1});const l=r.getFullYear(),u=String(r.getMonth()+1).padStart(2,"0"),h=String(r.getDate()).padStart(2,"0"),c=String(r.getHours()).padStart(2,"0"),d=String(r.getMinutes()).padStart(2,"0");return`${l}/${u}/${h} ${c}:${d}`}function r4({isOpen:e,onClose:r,messages:s,onSelectMessage:i}){const[l,u]=H.useState(""),[h,c]=H.useState(0),d=H.useRef(null),p=H.useRef(!1),g=s.filter(C=>C.role==="user"&&!C.isSystemGenerated&&C.messageKind!=="auto-prompt"&&C.messageKind!=="command");H.useEffect(()=>{e&&(p.current=!0)},[e]),H.useEffect(()=>{if(e){u(""),c(0);const C=setTimeout(()=>{var y;return(y=d.current)==null?void 0:y.focus()},50);return()=>clearTimeout(C)}},[e]);const m=g.filter(C=>H0(C.content,l)),b=m.length-1,S=C=>{F0(C,b,c,()=>{m[h]&&(i(m[h].id),r())},r)},k=C=>{i(C),r()};return e?go.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(Xb,{}),o.jsx("input",{ref:d,type:"text",value:l,onChange:C=>{u(C.target.value),c(0)},onKeyDown:S,placeholder:"Search messages...",className:"flex-1 bg-transparent text-sm focus:outline-none placeholder:text-text-muted"}),o.jsx("button",{type:"button",onClick:r,className:"p-0.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors","aria-label":"Close",children:o.jsx(Ph,{className:"w-4 h-4"})})]}),o.jsx("div",{className:"overflow-y-auto max-h-[60vh] p-2",children:m.length===0?o.jsx("div",{className:"px-3 py-4 text-center text-text-muted text-sm",children:g.length>0?"No matches":"No messages yet"}):m.map((C,y)=>o.jsx("button",{type:"button",onClick:()=>k(C.id),className:`w-full text-left px-3 py-2 rounded text-sm transition-colors ${y===h?"bg-accent-primary/20 text-text-primary":"text-text-secondary hover:bg-bg-tertiary hover:text-text-primary"}`,children:o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsx("span",{className:"truncate flex-1",children:C.content}),o.jsx("span",{className:"text-text-muted text-xs shrink-0",children:n4(C.timestamp)})]})},C.id))})]})]}),document.body):null}function s4(e){return e==="criterion"}function i4(e){var r,s;return e.role!=="assistant"||e.subAgentId||(r=e.content)!=null&&r.trim()||(s=e.thinkingContent)!=null&&s.trim()||!e.toolCalls||e.toolCalls.length===0?!1:e.toolCalls.every(i=>s4(i.name))}function a4(e,r=[]){const s=[];let i=null,l=[],u,h=1;const c=new Map,d=new Map,p=[];for(const S of r)S.type==="message"?c.set(S.message.id,S):S.type==="subagent"?d.set(S.subAgentId,S):S.type==="criteria-batch"&&p.push(S);let g=0;const m=()=>{if(l.length>0){const S=p[g];S&&S.type==="criteria-batch"&&S.toolCalls.length===l.length&&S.toolCalls.every((C,y)=>{var v;return C.id===((v=l[y])==null?void 0:v.id)})?s.push(S):s.push({type:"criteria-batch",toolCalls:[...l]}),g++,l=[]}},b=()=>{if(!i)return;const S=i,k=d.get(S.subAgentId);k&&k.type==="subagent"&&k.messages.length===S.messages.length&&k.messages.every((y,v)=>y===S.messages[v])?s.push(k):s.push({type:"subagent",subAgentId:S.subAgentId,subAgentType:S.subAgentType,messages:S.messages}),i=null};for(const S of e)if(S.role!=="tool"){if(S.contextWindowId&&u&&S.contextWindowId!==u&&(m(),b(),h++,s.push({type:"context-divider",windowSequence:h})),u=S.contextWindowId,i4(S)){b();for(const k of S.toolCalls)l.push(k);continue}if(m(),S.subAgentId&&S.subAgentType)i&&i.subAgentId===S.subAgentId?i.messages.push(S):(b(),i={subAgentId:S.subAgentId,subAgentType:S.subAgentType,messages:[S]});else{b();const k=c.get(S.id);k&&k.type==="message"&&k.message===S?s.push(k):s.push({type:"message",message:S})}}return m(),b(),s}function o4(e){const{year:r,month:s,day:i}=iy(e);return`${r}/${s}/${i} ${uc(e)}`}function l4(e,r){return e.length<=r?e:e.substring(0,r)+"..."}const c4=10,u4=150;function d4(e){const r=[];if(e.recentUserPrompts)for(const s of e.recentUserPrompts)r.push({id:s.id,content:s.content,timestamp:s.timestamp,sessionId:e.id,sessionName:e.title||e.id});return r}function h4(e){return[...e].sort((i,l)=>new Date(l.timestamp).getTime()-new Date(i.timestamp).getTime()).slice(0,c4).reverse().map(i=>({id:i.id,content:i.content,timestamp:i.timestamp,formattedTimestamp:o4(i.timestamp),trimmedContent:l4(i.content,u4),sessionId:i.sessionId,sessionName:i.sessionName}))}function f4(e,r,s){const i=[],l=e.filter(u=>u.role==="user"&&!u.isSystemGenerated&&u.messageKind!=="auto-prompt");for(const u of l)i.push({id:u.id,content:u.content,timestamp:u.timestamp,sessionId:s??"",sessionName:"This session"});for(const u of r)s&&u.id===s||i.push(...d4(u));return h4(i)}function p4(e,r=[],s=null){const[i,l]=H.useState(0),[u,h]=H.useState(!1),c=H.useMemo(()=>f4(e,r,s),[e,r,s]),d=H.useCallback(()=>{c.length>0&&(l(c.length-1),h(!0))},[c.length]),p=H.useCallback(()=>{h(!1),l(0)},[]),g=H.useCallback(()=>{l(S=>c.length===0?S:S===0?c.length-1:S-1)},[c.length]),m=H.useCallback(()=>{l(S=>c.length===0?S:S===c.length-1?0:S+1)},[c.length]),b=H.useCallback(()=>{if(c.length===0||!u)return null;const S=c[i];return(S==null?void 0:S.content)??null},[c,i,u]);return{history:c,selectedIndex:i,showHistory:u,openHistory:d,closeHistory:p,navigateUp:g,navigateDown:m,selectCurrent:b}}function m4({criteriaSidebarOpen:e,onCriteriaSidebarToggle:r}={}){const s=e??!0,[i,l]=H.useState(""),[u,h]=H.useState([]),[c,d]=H.useState(!1),[p,g]=H.useState(null),[m,b]=H.useState(!1),[S,k]=H.useState(!1),[C,y]=H.useState(!1),[v,x]=H.useState(!1),[_,j]=H.useState(null),[T,N]=H.useState(null),D=H.useRef(null),A=H.useRef(null),z=H.useRef(null),O=Ce(ie=>ie.currentSession),q=Ce(ie=>ie.messages),G=Ce(ie=>ie.streamingMessage),W=Ce(ie=>ie.sessions),I=Ce(ie=>ie.error),$=Ce(ie=>ie.pendingQuestion),B=Fb(),X=Ce(ie=>ie.sendMessage),Z=Ce(ie=>ie.clearError),P=Ce(ie=>ie.acceptAndBuild),R=Ce(ie=>ie.stopGeneration),L=Ce(ie=>ie.launchRunner),U=Ce(ie=>ie.cancelQueued),F=lw(),{showThinking:ne,showVerboseToolOutput:Q,showStats:ee,showAgentDefinitions:Y,showWorkflowBars:V}=Rh(),oe=Tt(ie=>ie.defaults),re=Tt(ie=>ie.userItems),ve=[...oe,...re],be=Tt(ie=>ie.fetchWorkflows),Le=At(ie=>ie.defaults),Oe=At(ie=>ie.userItems),ze=[...Le,...Oe].filter(ie=>!ie.subagent);H.useEffect(()=>{be()},[be]);const{history:We,selectedIndex:Ee,showHistory:fe,openHistory:je,closeHistory:Ue,navigateUp:It,navigateDown:pe,selectCurrent:Ne}=p4(q,W,O==null?void 0:O.id),Me=H.useCallback(ie=>{j(ie),St(!1);const Ae=document.querySelector(`[data-message-id="${ie}"]`);Ae&&Ae.scrollIntoView({behavior:"smooth",block:"center"}),setTimeout(()=>j(null),3e3)},[]);H.useEffect(()=>{const ie=Ae=>{N(Ae.detail.stats)};return window.addEventListener("open-turn-stats",ie),()=>window.removeEventListener("open-turn-stats",ie)},[]);const lt=H.useMemo(()=>G?q.map(ie=>ie.id===G.id?G:ie):q,[q,G]),ue=H.useRef([]),_e=H.useMemo(()=>{const ie=a4(lt,ue.current);return ue.current=ie,ie},[lt]),Te=H.useMemo(()=>PA(q),[q]),{force_scroll_to_bottom:Ie,isAutoScrollActive:$e,setAutoScroll:St}=O0(D,O),Ye=H.useCallback(()=>{const ie=A.current;if(!ie)return;ie.style.height="auto";const Ae=Math.min(200,ie.scrollHeight);ie.style.height=`${Ae}px`},[]);H.useEffect(()=>{if(!(O!=null&&O.id))return;const ie=`openfox:draft:${O.id}`,Ae=localStorage.getItem(ie);Ae!==null&&l(Ae)},[O==null?void 0:O.id]),H.useEffect(()=>{var ie;(ie=A.current)==null||ie.focus(),Ye()},[O==null?void 0:O.id,Ye]),H.useEffect(()=>{if(!(O!=null&&O.id))return;const ie=`openfox:draft:${O.id}`,Ae=setTimeout(()=>{i?localStorage.setItem(ie,i):localStorage.removeItem(ie)},500);return()=>clearTimeout(Ae)},[O==null?void 0:O.id,i]),H.useEffect(()=>{Ye()},[i,Ye]),H.useEffect(()=>{const ie=Ae=>{Ae.key==="Escape"&&B&&R(),Ae.key==="ScrollLock"&&St(!$e)};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[B,R,$e]);const Dt=H.useRef(0);H.useEffect(()=>{const ie=Ae=>{if(Ae.key==="Shift"&&!Ae.ctrlKey&&!Ae.metaKey&&!Ae.altKey){const qe=Date.now();qe-Dt.current<300?(Ae.preventDefault(),y(!0),Dt.current=0):Dt.current=qe}};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]),H.useEffect(()=>{const ie=A.current;if(!ie)return;const Ae=async qe=>{var en;if(document.activeElement!==ie)return;const Ct=(en=qe.clipboardData)==null?void 0:en.items;if(Ct){for(const _n of Array.from(Ct))if(_n.type.startsWith("image/")){qe.preventDefault();const yr=_n.getAsFile();if(!yr)continue;await dh(yr,Xs=>h(Sn=>[...Sn,Xs]),g,{filename:"pasted-image"})}}};return ie.addEventListener("paste",Ae),()=>ie.removeEventListener("paste",Ae)},[]);const gt=()=>{l(""),h([]),O!=null&&O.id&&localStorage.removeItem(`openfox:draft:${O.id}`)},Yt=async ie=>{ie.preventDefault(),!(!i.trim()&&u.length===0)&&(Ie(),X(i,u.length>0?u:void 0),gt())},ct=ie=>{if((ie.ctrlKey||ie.metaKey)&&ie.code.startsWith("Digit")){const qe=parseInt(ie.code.slice(-1),10)-1,Ct=ze[qe];Ct&&(ie.preventDefault(),Ce.getState().switchMode(Ct.id));return}if(fe)switch(ie.key){case"Enter":ie.preventDefault();const Ae=Ne();Ae&&(l(Ae),Ue());return;case"Escape":ie.preventDefault(),Ue(),B&&R();return;case"ArrowUp":ie.preventDefault(),It();return;case"ArrowDown":ie.preventDefault(),pe();return}if(ie.key==="ArrowUp"&&i.trim()===""&&!fe){ie.preventDefault(),je();return}ie.key==="Enter"&&!ie.shiftKey&&(ie.preventDefault(),Yt(ie))},qn=H.useCallback(async ie=>{const Ae=ie.target.files;if(!(!Ae||Ae.length===0)){g(null);for(const qe of Array.from(Ae))await dh(qe,Ct=>h(en=>[...en,Ct]),g);z.current&&(z.current.value="")}},[]),sn=H.useCallback(ie=>{ie.preventDefault(),ie.stopPropagation(),d(!0)},[]),Yi=H.useCallback(ie=>{ie.preventDefault(),ie.stopPropagation(),d(!1)},[]),me=H.useCallback(async ie=>{ie.preventDefault(),ie.stopPropagation(),d(!1),g(null);const Ae=ie.dataTransfer.files;if(!(!Ae||Ae.length===0))for(const qe of Array.from(Ae))await dh(qe,Ct=>h(en=>[...en,Ct]),g)},[]),ye=H.useCallback(ie=>{h(Ae=>Ae.filter(qe=>qe.id!==ie))},[]),we=H.useCallback(()=>{var ie;(ie=z.current)==null||ie.click()},[]),Ve=(O==null?void 0:O.mode)==="planner",Qe=(O==null?void 0:O.mode)==="builder",He=((O==null?void 0:O.criteria.length)??0)>0,Xt=(O==null?void 0:O.phase)==="done",Rt=_e.some(ie=>ie.type==="message"&&ie.message.role==="assistant"),Bt=Ve&&He&&!B&&Rt&&!Xt,qr=ie=>{const Ae=i.trim()?i:void 0,qe=u.length>0?u:void 0;Ve?P(ie,Ae,qe):Qe&&L(Ae,qe,ie),gt()};return o.jsxs(o.Fragment,{children:[o.jsxs(s2,{criteriaSidebarOpen:s,onCriteriaSidebarToggle:r,messages:lt,children:[$&&o.jsx(wA,{question:$}),o.jsx(o2,{}),T&&o.jsx(fA,{stats:T,onClose:()=>N(null)}),o.jsx(CA,{}),o.jsxs("div",{ref:D,"data-testid":"chat-scroll-container",className:"flex-1 min-w-0 overflow-y-auto relative bg-primary",children:[o.jsx("div",{className:"pt-4",children:_e.map((ie,Ae)=>{if(ie.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"})]},Ae);if(ie.type==="subagent"){const _n=ie.messages.some(yr=>yr.isStreaming);return o.jsx("div",{className:"px-2 md:px-4",children:o.jsx(xA,{messages:ie.messages,subAgentType:ie.subAgentType,subAgentId:ie.subAgentId,isStreaming:_n})},Ae)}if(ie.type==="criteria-batch")return o.jsx("div",{className:"feed-item px-2 md:px-4",children:o.jsx(L0,{toolCalls:ie.toolCalls,criteria:O==null?void 0:O.criteria})},Ae);const qe=ie.message;if(qe.role==="assistant")return o.jsx("div",{className:"px-2 md:px-4",children:o.jsx(jf,{message:qe,showStats:ee,showThinking:ne,showVerboseToolOutput:Q})},Ae);const Ct=!Y&&qe.messageKind==="auto-prompt",en=!V&&(qe.messageKind==="workflow-started"||qe.messageKind==="task-completed");return Ct||en?null:o.jsx("div",{className:"px-2 md:px-4",children:o.jsx("div",{"data-message-id":qe.id,className:_===qe.id?"rounded animate-highlight-fade":void 0,children:o.jsx(R0,{message:qe,isLastAssistantMessage:!1,promptContext:qe.role==="user"?Te[qe.id]:void 0})})},Ae)})}),o.jsxs("div",{className:"px-2 md:px-4 pb-4",children:[I&&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:I.code}),o.jsx("div",{className:"text-red-300 text-xs mt-0.5",children:I.message})]}),o.jsx(ao,{onClick:Z,className:"text-red-400 hover:text-red-300 p-0.5",size:"sm"})]})}),Bt&&o.jsx("div",{className:"flex justify-center gap-2 feed-item flex-wrap",children:ve.map(ie=>{const Ae=ie.color??"#3b82f6",qe=parseInt(Ae.slice(1,3),16),Ct=parseInt(Ae.slice(3,5),16),en=parseInt(Ae.slice(5,7),16),_n=`rgba(${qe},${Ct},${en},0.12)`,yr=`rgba(${qe},${Ct},${en},0.22)`,Xs=`rgba(${qe},${Ct},${en},0.25)`;return o.jsxs("button",{onClick:()=>P(ie.id),className:"px-4 py-1.5 rounded text-sm font-medium transition-colors",style:{backgroundColor:_n,color:Ae,border:`1px solid ${Xs}`},onMouseEnter:Sn=>{Sn.currentTarget.style.backgroundColor=yr},onMouseLeave:Sn=>{Sn.currentTarget.style.backgroundColor=_n},children:["▶ ",ie.name]},ie.id)})}),B&&o.jsx(kA,{})]})]}),o.jsxs("form",{onSubmit:Yt,className:"relative p-2 md:p-4 bg-secondary",children:[o.jsxs("button",{type:"button",className:"absolute -top-8 right-12 md:right-16 text-sm text-text-muted hover:text-text-primary z-10 flex items-center gap-1.5",onClick:()=>St(!$e),children:[$e?o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-success"}):o.jsx(xr,{className:"w-3 h-3 text-text-muted"}),$e?"live":"scroll to bottom"]}),o.jsx("button",{type:"button",onClick:()=>x(!0),className:"absolute -top-8 right-2 md:right-4 text-sm text-text-muted hover:text-text-primary z-10 flex items-center p-0.5 rounded hover:bg-bg-tertiary transition-colors","aria-label":"Search messages",children:o.jsx(Xb,{})}),o.jsx("input",{ref:z,type:"file",accept:".png,.jpg,.jpeg,.gif",onChange:qn,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(ie=>o.jsx(EA,{attachment:ie,onRemove:ye},ie.id))}),fe&&o.jsx(jA,{history:We,selectedIndex:Ee,onSelect:ie=>{l(ie),Ue()},onEscape:Ue,onNavigate:ie=>{ie==="up"?It():pe()}}),F.length>0&&o.jsx("div",{className:"mb-2 flex flex-wrap gap-1.5",children:F.map(ie=>o.jsxs("div",{className:`inline-flex items-center gap-1.5 px-2 py-1 rounded text-xs ${ie.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:[ie.mode==="asap"?"ASAP":"Queue",":"]}),o.jsx("span",{className:"truncate max-w-[200px]",children:ie.content}),o.jsx(ao,{onClick:()=>U(ie.queueId),size:"sm"})]},ie.queueId))}),o.jsxs("div",{className:`flex items-end gap-3 p-3 rounded transition-colors ${c?"bg-accent-primary/10":"bg-primary"}`,onDragOver:sn,onDragLeave:Yi,onDrop:me,children:[o.jsx("textarea",{ref:A,value:i,onChange:ie=>{l(ie.target.value),fe&&Ue()},onKeyDown:ct,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 items-center self-center",children:[o.jsx("button",{type:"button",onClick:()=>{var ie;!i.trim()&&u.length===0||((ie=D.current)==null||ie.scrollTo({top:D.current.scrollHeight,behavior:"smooth"}),X(i,u),gt())},disabled:!i.trim()&&u.length===0,className:"px-4 py-1.5 rounded-l 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.jsx(e4,{onSendCommand:(ie,Ae,qe,Ct)=>{var _n;Ae&&(O==null?void 0:O.mode)!==Ae&&Ce.getState().switchMode(Ae);const en=qe&&qe.trim()?`${qe.trim()}
|
|
150
150
|
|
|
151
151
|
${ie}`:ie;(_n=D.current)==null||_n.scrollTo({top:D.current.scrollHeight,behavior:"smooth"}),X(en,Ct!=null&&Ct.length?Ct:void 0,{messageKind:"command",isSystemGenerated:!0}),gt()},onSelectWorkflow:qr,onOpenCommandsManager:()=>b(!0),onOpenWorkflowsManager:()=>k(!0),onAttach:we,textareaContent:i,attachments:u.length>0?u:void 0,criteria:(O==null?void 0:O.criteria)??[]})]})]}),o.jsxs("div",{className:"mt-3 flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(_A,{}),o.jsx(SA,{})]}),o.jsx($A,{})]})]}),o.jsx(I0,{isOpen:m,onClose:()=>b(!1)}),o.jsx(P0,{isOpen:S,onClose:()=>k(!1)}),o.jsx(t4,{isOpen:C,onClose:()=>y(!1),onSearchMessages:()=>x(!0),isAutoScrollActive:$e,onToggleAutoScroll:St,textareaContent:i,onCloseComplete:()=>{var ie;return(ie=A.current)==null?void 0:ie.focus()},onCloseCompleteAction:()=>window.dispatchEvent(new CustomEvent("open-session-dropdown")),onSelectCommand:async(ie,Ae)=>{const qe=await hn.getState().fetchCommand(ie);if(qe){const Ct=Ae!=null&&Ae.trim()?`${Ae.trim()}
|
|
152
152
|
|