openfox 2.0.0-beta.15 → 2.0.0-beta.17
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/{chat-handler-7QLHIQOM.js → chat-handler-LJMW4OK3.js} +6 -6
- package/dist/{chunk-W52UQCER.js → chunk-32GQUDLN.js} +5 -5
- package/dist/{chunk-6CVDQJDV.js → chunk-7ZMMDZU7.js} +388 -17
- package/dist/{chunk-OKLV3ZNN.js → chunk-CK6LGE7G.js} +2 -2
- package/dist/{chunk-LXX2CPM5.js → chunk-FFEAEPJB.js} +1 -133
- package/dist/{chunk-N53OLRIU.js → chunk-HPCGVAS4.js} +12 -42
- package/dist/{chunk-D2QILH47.js → chunk-LEDG5WAN.js} +3 -3
- package/dist/{chunk-K6SMOWET.js → chunk-PRBZSBKW.js} +44 -58
- package/dist/{chunk-AKF52COZ.js → chunk-SN7ZAMHV.js} +6 -6
- package/dist/{chunk-DHAKJSE7.js → chunk-XEK3KII6.js} +2 -2
- package/dist/cli/dev.js +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/{config-B6HYTLT4.js → config-BU66P4KX.js} +2 -7
- package/dist/{events-R7FRQEBE.js → events-ZKWAKWI7.js} +2 -2
- package/dist/{orchestrator-2AK4AYUD.js → orchestrator-LX6FKB6L.js} +5 -5
- package/dist/package.json +2 -1
- package/dist/{processor-IU56GBIW.js → processor-NMYSEBC7.js} +4 -4
- package/dist/{protocol-zn90yuIr.d.ts → protocol-D59sCy9L.d.ts} +3 -3
- package/dist/{provider-2JAXE5EA.js → provider-DTNQYCMV.js} +7 -18
- package/dist/{provider-manager-JMLJSPNX.js → provider-manager-LMHAHLIF.js} +3 -4
- package/dist/{serve-NMNHOT4M.js → serve-KB7IVU5D.js} +9 -10
- package/dist/server/index.d.ts +2 -2
- package/dist/server/index.js +6 -7
- package/dist/shared/index.d.ts +2 -2
- package/dist/{tools-VJMWGBUO.js → tools-BOE5T3KC.js} +4 -4
- package/dist/web/assets/{index-DCu8wsRj.js → index-Bego8SwT.js} +2 -2
- package/dist/web/index.html +1 -1
- package/dist/web/sw.js +1 -1
- package/package.json +2 -1
- package/dist/chunk-4F3C6X4M.js +0 -381
|
@@ -55,7 +55,7 @@ Error generating stack: `+g.message+`
|
|
|
55
55
|
*
|
|
56
56
|
* This source code is licensed under the MIT license found in the
|
|
57
57
|
* LICENSE file in the root directory of this source tree.
|
|
58
|
-
*/var uv;function y2(){if(uv)return Tf;uv=1;var e=Ru();function t(m,_){return m===_&&(m!==0||1/m===1/_)||m!==m&&_!==_}var n=typeof Object.is=="function"?Object.is:t,s=e.useState,a=e.useEffect,l=e.useLayoutEffect,u=e.useDebugValue;function c(m,_){var x=_(),w=s({inst:{value:x,getSnapshot:_}}),k=w[0].inst,y=w[1];return l(function(){k.value=x,k.getSnapshot=_,h(k)&&y({inst:k})},[m,x,_]),a(function(){return h(k)&&y({inst:k}),m(function(){h(k)&&y({inst:k})})},[m]),u(x),x}function h(m){var _=m.getSnapshot;m=m.value;try{var x=_();return!n(m,x)}catch{return!0}}function f(m,_){return _()}var p=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?f:c;return Tf.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:p,Tf}var dv;function v2(){return dv||(dv=1,Nf.exports=y2()),Nf.exports}var b2=v2();const S2=i2.useInsertionEffect,w2=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",C2=w2?R.useLayoutEffect:R.useEffect,k2=S2||C2,Z0=e=>{const t=R.useRef([e,(...n)=>t[0](...n)]).current;return k2(()=>{t[0]=e}),t[1]},E2="popstate",tp="pushState",np="replaceState",j2="hashchange",hv=[E2,tp,np,j2],N2=e=>{for(const t of hv)addEventListener(t,e);return()=>{for(const t of hv)removeEventListener(t,e)}},eS=(e,t)=>b2.useSyncExternalStore(N2,e,t),fv=()=>location.search,T2=({ssrSearch:e}={})=>eS(fv,e!=null?()=>e:fv),mv=()=>location.pathname,A2=({ssrPath:e}={})=>eS(mv,e!=null?()=>e:mv),L2=(e,{replace:t=!1,state:n=null}={})=>history[t?np:tp](n,"",e),D2=(e={})=>[A2(e),L2],pv=Symbol.for("wouter_v3");if(typeof history<"u"&&typeof window[pv]>"u"){for(const e of[tp,np]){const t=history[e];history[e]=function(){const n=t.apply(this,arguments),s=new Event(e);return s.arguments=arguments,dispatchEvent(s),n}}Object.defineProperty(window,pv,{value:!0})}const R2=(e,t)=>t.toLowerCase().indexOf(e.toLowerCase())?"~"+t:t.slice(e.length)||"/",tS=(e="")=>e==="/"?"":e,O2=(e,t)=>e[0]==="~"?e.slice(1):tS(t)+e,M2=(e="",t)=>R2(gv(tS(e)),gv(t)),gv=e=>{try{return decodeURI(e)}catch{return e}},nS={hook:D2,searchHook:T2,parser:_2,base:"",ssrPath:void 0,ssrSearch:void 0,ssrContext:void 0,hrefs:e=>e,aroundNav:(e,t,n)=>e(t,n)},rS=R.createContext(nS),Ha=()=>R.useContext(rS),sS={},iS=R.createContext(sS),I2=()=>R.useContext(iS),Mu=e=>{const[t,n]=e.hook(e);return[M2(e.base,t),Z0((s,a)=>e.aroundNav(n,O2(s,e.base),a))]},cr=()=>Mu(Ha()),rp=(e,t,n,s)=>{const{pattern:a,keys:l}=t instanceof RegExp?{keys:!1,pattern:t}:e(t||"*",s),u=a.exec(n)||[],[c,...h]=u;return c!==void 0?[!0,(()=>{const f=l!==!1?Object.fromEntries(l.map((m,_)=>[m,h[_]])):u.groups;let p={...h};return f&&Object.assign(p,f),p})(),...s?[c]:[]]:[!1,null]},sp=e=>rp(Ha().parser,e,cr()[0]),P2=({children:e,...t})=>{var p,m,_;const n=Ha(),s=t.hook?nS:n;let a=s;const[l,u=t.ssrSearch??""]=((p=t.ssrPath)==null?void 0:p.split("?"))??[];l&&(t.ssrSearch=u,t.ssrPath=l),t.hrefs=t.hrefs??((m=t.hook)==null?void 0:m.hrefs),t.searchHook=t.searchHook??((_=t.hook)==null?void 0:_.searchHook);let c=R.useRef({}),h=c.current,f=h;for(let x in s){const w=x==="base"?s[x]+(t[x]??""):t[x]??s[x];h===f&&w!==f[x]&&(c.current=f={...f}),f[x]=w,(w!==s[x]||w!==a[x])&&(a=f)}return R.createElement(rS.Provider,{value:a,children:e})},xv=({children:e,component:t},n)=>t?R.createElement(t,{params:n}):typeof e=="function"?e(n):e,B2=e=>{let t=R.useRef(sS);const n=t.current;return t.current=Object.keys(e).length!==Object.keys(n).length||Object.entries(e).some(([s,a])=>a!==n[s])?e:n},Ho=({path:e,nest:t,match:n,...s})=>{const a=Ha(),[l]=Mu(a),[u,c,h]=n??rp(a.parser,e,l,t),f=B2({...I2(),...c});if(!u)return null;const p=h?R.createElement(P2,{base:h},xv(s,f)):xv(s,f);return R.createElement(iS.Provider,{value:f,children:p})},Gn=R.forwardRef((e,t)=>{const n=Ha(),[s,a]=Mu(n),{to:l="",href:u=l,onClick:c,asChild:h,children:f,className:p,replace:m,state:_,transition:x,...w}=e,k=Z0(S=>{S.ctrlKey||S.metaKey||S.altKey||S.shiftKey||S.button!==0||(c==null||c(S),S.defaultPrevented||(S.preventDefault(),a(u,e)))}),y=n.hrefs(u[0]==="~"?u.slice(1):n.base+u,n);return h&&R.isValidElement(f)?R.cloneElement(f,{onClick:k,href:y}):R.createElement("a",{...w,onClick:k,href:y,className:p!=null&&p.call?p(s===u):p,children:f,ref:t})}),aS=e=>Array.isArray(e)?e.flatMap(t=>aS(t&&t.type===R.Fragment?t.props.children:t)):[e],z2=({children:e,location:t})=>{const n=Ha(),[s]=Mu(n);for(const a of aS(e)){let l=0;if(R.isValidElement(a)&&(l=rp(n.parser,a.props.path,t||s,a.props.nest))[0])return R.cloneElement(a,{match:l})}return null};function H2(e){return typeof e=="object"&&e!==null&&"type"in e&&"payload"in e}function oS(){if(typeof crypto<"u"&&crypto.randomUUID)try{return crypto.randomUUID()}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}class $2{constructor(t){pe(this,"ws",null);pe(this,"handlers",new Set);pe(this,"statusHandler",null);pe(this,"baseUrl");pe(this,"isReconnecting",!1);pe(this,"connectingPromise",null);pe(this,"lastCloseCode",0);pe(this,"reconnectAttempts",0);pe(this,"manualReconnectScheduled",!1);this.baseUrl=t}getUrl(){const t=localStorage.getItem("openfox_token");if(t){const n=this.baseUrl.includes("?")?"&":"?";return`${this.baseUrl}${n}token=${encodeURIComponent(t)}`}return this.baseUrl}setToken(t){localStorage.setItem("openfox_token",t)}clearToken(){localStorage.removeItem("openfox_token")}hasToken(){return!!localStorage.getItem("openfox_token")}getLastCloseCode(){return this.lastCloseCode}onStatusChange(t){this.statusHandler=t}connect(){var t,n,s;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN?Promise.resolve():(this.lastCloseCode=0,this.isReconnecting=!1,this.connectingPromise&&((n=this.ws)==null?void 0:n.readyState)===WebSocket.CONNECTING?this.connectingPromise:(this.lastCloseCode=0,this.isReconnecting=!1,this.connectingPromise&&((s=this.ws)==null?void 0:s.readyState)===WebSocket.CONNECTING?(console.warn("[WS CLIENT] Connection already in progress, returning existing promise"),this.connectingPromise):(this.connectingPromise=new Promise((a,l)=>{try{const u=this.getUrl();this.ws=new WebSocket(u);const c=setTimeout(()=>{var h;((h=this.ws)==null?void 0:h.readyState)===WebSocket.CONNECTING&&(this.ws.close(),l(new Error("Connection timeout")))},5e3);this.ws.onopen=()=>{var h;clearTimeout(c),this.isReconnecting=!1,this.connectingPromise=null,(h=this.statusHandler)==null||h.call(this,"connected"),a()},this.ws.onclose=h=>{var f,p,m;clearTimeout(c),this.lastCloseCode=h.code,((f=this.ws)==null?void 0:f.readyState)===WebSocket.CONNECTING?(this.connectingPromise=null,(p=this.statusHandler)==null||p.call(this,"disconnected"),l(new Error(`Connection closed: ${h.code}`))):(this.connectingPromise=null,(m=this.statusHandler)==null||m.call(this,"disconnected"),this.attemptReconnect())},this.ws.onerror=h=>{clearTimeout(c),console.error("WebSocket error:",h),this.connectingPromise=null,l(h)},this.ws.onmessage=h=>{try{const f=JSON.parse(h.data);H2(f)&&this.handlers.forEach(p=>p(f))}catch(f){console.error("Failed to parse WebSocket message:",f)}}}catch(u){this.connectingPromise=null,l(u)}}),this.connectingPromise)))}attemptReconnect(){var a;if(([1e3,1005,1006,4e3].includes(this.lastCloseCode)||this.lastCloseCode===0)&&this.hasToken()){console.warn("[WS] Auth failure or initial failure with token - not auto-reconnecting, awaiting user action");return}if(this.isReconnecting||this.manualReconnectScheduled)return;this.isReconnecting=!0,(a=this.statusHandler)==null||a.call(this,"reconnecting");const s=Math.min(1e3*Math.pow(2,this.reconnectAttempts||0),3e4);this.reconnectAttempts=(this.reconnectAttempts||0)+1,setTimeout(()=>{this.isReconnecting=!1,this.manualReconnectScheduled=!1,this.connect().catch(()=>{})},s)}reconnect(){this.manualReconnectScheduled=!0,this.isReconnecting=!1,this.lastCloseCode=0,this.connectingPromise=null,this.connect().catch(()=>{})}disconnect(){this.isReconnecting=!1,this.reconnectAttempts=0,this.ws&&(this.ws.close(),this.ws=null)}resetReconnectAttempts(){this.reconnectAttempts=0}send(t,n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");const s=oS(),a={id:s,type:t,payload:n};return this.ws.send(JSON.stringify(a)),s}subscribe(t){return this.handlers.add(t),()=>this.handlers.delete(t)}get isConnected(){var t;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN}}const U2=window.location.protocol==="https:"?"wss:":"ws:";let ym=window.location.port;ym||(ym=window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"?"10469":window.location.protocol==="https:"?"443":"80");const F2=`${U2}//${window.location.hostname}:${ym}/ws`,zt=new $2(F2);function V2(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}}}function _v(e){e&&we.getState().updateContextState({...e,dynamicContextChanged:e.dynamicContextChanged??!1})}async function yv(e,t,n){const s=await Ne(`/api/providers/${e}/models/${encodeURIComponent(t)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok){const a=await s.json();throw new Error(a.error??"Failed to update model")}return s.json()}function vv(e,t,n,s){return e.map(a=>a.id===t?{...a,models:a.models.map(l=>l.id===n?{...l,...s,source:"user"}:l)}:a)}const G2=3e4;function ip(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 Bt=qn((e,t)=>({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 n=await Ne("/api/config");if(!n.ok)throw new Error("Failed to fetch config");const s=await n.json();e({version:s.version,model:s.model,maxContext:s.maxContext,llmUrl:s.llmUrl,llmStatus:s.llmStatus,backend:s.backend,providers:s.providers??[],activeProviderId:s.activeProviderId??null,defaultModelSelection:s.defaultModelSelection??null,loading:!1})}catch(n){e({error:n instanceof Error?n.message:"Unknown error",loading:!1})}},refreshModel:async()=>{try{const n=await Ne("/api/model/refresh",{method:"POST"});if(!n.ok)throw new Error("Failed to refresh model");const s=await n.json(),l=we.getState().currentSession;if(l!=null&&l.providerId&&l.providerModel){e({llmStatus:s.llmStatus,backend:s.backend});return}e({model:s.model,llmStatus:s.llmStatus,backend:s.backend})}catch(n){console.error("Failed to refresh model:",n)}},activateProvider:async n=>{const{activeProviderId:s,providers:a}=t();if(n===s)return!0;e({activating:!0,error:null});try{const l=await Ne(`/api/providers/${n}/activate`,{method:"POST"});if(!l.ok){const c=await l.json();throw new Error(c.error??"Failed to activate provider")}const u=await l.json();return e({activeProviderId:u.activeProviderId,model:u.model,backend:u.backend,providers:a.map(c=>({...c,isActive:c.id===u.activeProviderId})),activating:!1}),!0}catch(l){return e({error:l instanceof Error?l.message:"Failed to switch provider",activating:!1}),!1}},syncFromSession:(n,s)=>{var c;const{providers:a,defaultModelSelection:l}=t();let u=s;if(!u){const h=l?l.split("/"):[],f=h[0],p=h.slice(1).join("/")??"";if(f===n&&p)u=p;else{const m=a.find(_=>_.id===n);u=((c=m==null?void 0:m.models[0])==null?void 0:c.id)??""}}e({activeProviderId:n,model:u,defaultModelSelection:`${n}/${u}`,providers:a.map(h=>({...h,isActive:h.id===n}))})},updateModelContext:async(n,s,a)=>{e({activating:!0,error:null});try{const l=await yv(n,s,{contextWindow:a}),{providers:u}=t();return e({providers:vv(u,n,s,{contextWindow:a}),activating:!1}),_v(l.contextState),!0}catch(l){return e({error:l instanceof Error?l.message:"Failed to update model context",activating:!1}),!1}},updateModelSettings:async(n,s,a)=>{e({activating:!0,error:null});try{const l=await yv(n,s,a),{providers:u}=t(),c={...a.contextWindow!==void 0&&{contextWindow:a.contextWindow},...V2({temperature:a.temperature??void 0,topP:a.topP??void 0,topK:a.topK??void 0,maxTokens:a.maxTokens??void 0}),...a.supportsVision!==void 0&&{supportsVision:a.supportsVision},...a.thinkingEnabled!==void 0&&{thinkingEnabled:a.thinkingEnabled},...a.thinkingLevel!==void 0&&{thinkingLevel:a.thinkingLevel},...a.nonThinkingEnabled!==void 0&&{nonThinkingEnabled:a.nonThinkingEnabled},...a.thinkingExtraKwargs!==void 0&&{thinkingExtraKwargs:a.thinkingExtraKwargs},...a.nonThinkingExtraKwargs!==void 0&&{nonThinkingExtraKwargs:a.nonThinkingExtraKwargs}};return e({providers:vv(u,n,s,c),activating:!1}),_v(l.contextState),!0}catch(l){return e({error:l instanceof Error?l.message:"Failed to update model settings",activating:!1}),!1}},refreshProviderModels:async n=>{e({activating:!0,error:null});try{const s=await Ne(`/api/providers/${n}/refresh`,{method:"POST"});if(!s.ok){const u=await s.json();throw new Error(u.error??"Failed to refresh models")}const a=await s.json(),{providers:l}=t();return e({providers:l.map(u=>u.id===n?{...u,models:a.models,status:a.status}:u),activating:!1}),!0}catch(s){return e({error:s instanceof Error?s.message:"Failed to refresh models",activating:!1}),!1}},startAutoRefresh:()=>{const{autoRefreshInterval:n,refreshModel:s}=t();if(n)return;const a=setInterval(()=>{s()},G2);e({autoRefreshInterval:a})},stopAutoRefresh:()=>{const{autoRefreshInterval:n}=t();n&&(clearInterval(n),e({autoRefreshInterval:null}))},getActiveProvider:()=>{const{providers:n,activeProviderId:s}=t();return n.find(a=>a.id===s)},getModelContext:n=>{const{providers:s,activeProviderId:a}=t(),l=s.find(c=>c.id===a);if(!l)return 2e5;const u=l.models.find(c=>c.id===n);return(u==null?void 0:u.contextWindow)??2e5}})),Lt=qn((e,t)=>({projects:[],currentProject:null,loading:!1,listProjects:async()=>{e({loading:!0});try{const s=await(await Ne("/api/projects")).json();e({projects:s.projects??[],loading:!1})}catch(n){console.error("Failed to load projects:",n),e({loading:!1})}},createProject:async(n,s)=>{try{const a=await Ne("/api/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:n,workdir:s})});if(!a.ok){const u=await a.json().catch(()=>({}));return{error:{code:u.code||"UNKNOWN",path:u.path,message:u.error}}}const l=await a.json();return await t().listProjects(),l.project}catch{return null}},loadProject:async n=>{try{const s=await Ne(`/api/projects/${n}`);if(!s.ok)return null;const a=await s.json();return e({currentProject:a.project}),t().projects.length===0&&await t().listProjects(),a.project}catch{return null}},updateProject:async(n,s)=>{var a;try{const l=await Ne(`/api/projects/${n}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!l.ok)return null;const u=await l.json();return((a=t().currentProject)==null?void 0:a.id)===n&&e({currentProject:u.project}),await t().listProjects(),u.project}catch{return null}},deleteProject:async n=>{var s;try{return(await Ne(`/api/projects/${n}`,{method:"DELETE"})).ok?(await t().listProjects(),((s=t().currentProject)==null?void 0:s.id)===n&&e({currentProject:null}),!0):!1}catch{return!1}},toggleStar:async(n,s)=>{var a;try{const l=await Ne(`/api/projects/${n}/star`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({isStarred:s})});if(!l.ok)return!1;if(((a=t().currentProject)==null?void 0:a.id)===n){const u=await l.json();e({currentProject:u.project})}return await t().listProjects(),!0}catch{return!1}},clearProject:()=>{e({currentProject:null})}})),Ws=async(e,t,n)=>{try{const s=await Ne(t,{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return s.ok?{success:!0}:{success:!1,error:(await s.json()).error}}catch{return{success:!1,error:"Network error"}}},Iu=async(e,t,n)=>{try{const s=await Ne(e,{method:"POST",body:n?JSON.stringify({destination:n}):void 0,headers:n?{"Content-Type":"application/json"}:void 0}),a=await s.json();return s.ok?(await t(),{success:!0}):{success:!1,error:a.error??"Failed to duplicate"}}catch{return{success:!1,error:"Network error"}}};function lS(e){let t=null;function n(){t===null&&(t=requestAnimationFrame(()=>{t=null,e()}))}return n}let Hc=[];const Zo=qn()((e,t)=>{function n(){if(Hc.length===0)return;const a=Hc;Hc=[],e(l=>{const u={...l.logs};for(const c of a){const h=u[c.processId]??[];u[c.processId]=[...h,{offset:h.length,content:c.content,timestamp:Date.now(),stream:c.stream}]}return{logs:u}})}const s=lS(n);return{processes:[],logs:{},loading:!1,setProcesses:a=>e({processes:a}),addProcess:a=>e(l=>({processes:[...l.processes,a]})),updateProcess:(a,l)=>e(u=>({processes:u.processes.map(c=>c.id===a?{...c,...l}:c)})),removeProcess:a=>e(l=>({processes:l.processes.filter(u=>u.id!==a),logs:Object.fromEntries(Object.entries(l.logs).filter(([u])=>u!==a))})),stopProcess:async(a,l)=>{try{(await Ne(`/api/sessions/${l}/background-process/${a}/stop`,{method:"POST"})).ok&&t().removeProcess(a)}catch{}},appendLog:(a,l,u)=>{Hc.push({processId:a,stream:l,content:u}),s()},setLogs:(a,l)=>e(u=>({logs:{...u.logs,[a]:l}})),clearLogs:a=>e(l=>({logs:{...l.logs,[a]:[]}})),handleMessage:(a,l)=>{switch(a){case"backgroundProcess.started":{const{processId:u,name:c,pid:h,status:f}=l;e(p=>({processes:[...p.processes,{id:u,sessionId:"",name:c,command:"",cwd:"",pid:h,status:f,exitCode:null,createdAt:Date.now(),startedAt:Date.now(),endedAt:null}]}));break}case"backgroundProcess.output":{const u=l.processId,c=l.stream,h=l.content;t().appendLog(u,c,h);break}case"backgroundProcess.exited":{const u=l.processId,c=l.exitCode;e(h=>({processes:h.processes.map(f=>f.id===u?{...f,status:"exited",exitCode:c}:f)}));break}case"backgroundProcess.removed":{const u=l.processId;t().removeProcess(u);break}}}}}),W2={messageId:null,deltaContent:"",thinkingContent:"",toolOutput:[]};let iu=null;function q2(e){iu=e}function yi(){return W2}function Af(){iu==null||iu()}let $c=[];const Rr=qn()((e,t)=>{function n(){if($c.length===0)return;const a=$c;$c=[],e(l=>({logs:[...l.logs,...a]}))}const s=lS(n);return{workdir:null,status:null,logs:[],config:null,loading:!1,setWorkdir:a=>{t().workdir!==a&&(e({workdir:a,status:null,logs:[],config:null,loading:!0}),a&&(t().fetchStatus(),t().fetchConfig()))},fetchStatus:async()=>{const a=t().workdir;if(a)try{const u=await(await Ne(`/api/dev-server?workdir=${encodeURIComponent(a)}`)).json();e({status:u,loading:!1})}catch{e({loading:!1})}},fetchConfig:async()=>{const a=t().workdir;if(a)try{const u=await(await Ne(`/api/dev-server/config?workdir=${encodeURIComponent(a)}`)).json();e({config:u.config??null})}catch{}},fetchLogs:async()=>{const a=t().workdir;if(a)try{const c=(await(await Ne(`/api/dev-server/logs?workdir=${encodeURIComponent(a)}`)).json()).logs.map(h=>({stream:h.stream,content:h.content}));e({logs:c})}catch{}},start:async()=>{const a=t().workdir;if(a)try{const u=await(await Ne(`/api/dev-server/start?workdir=${encodeURIComponent(a)}`,{method:"POST"})).json();e({status:u,logs:[]})}catch{}},stop:async()=>{const a=t().workdir;if(a)try{const u=await(await Ne(`/api/dev-server/stop?workdir=${encodeURIComponent(a)}`,{method:"POST"})).json();e({status:u})}catch{}},restart:async()=>{const a=t().workdir;if(a)try{const u=await(await Ne(`/api/dev-server/restart?workdir=${encodeURIComponent(a)}`,{method:"POST"})).json();e({status:u,logs:[]})}catch{}},saveConfig:async a=>{const l=t().workdir;if(l)try{const c=await(await Ne(`/api/dev-server/config?workdir=${encodeURIComponent(l)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)})).json();e({config:c.config??a}),t().fetchStatus()}catch{}},handleMessage:a=>{const l=t().workdir;if(l)switch(a.type){case"devServer.output":{const u=a.payload;if(u.workdir!==l)return;$c.push({stream:u.stream,content:u.content}),s();break}case"devServer.state":{const u=a.payload;if(u.workdir!==l)return;e(c=>({status:c.status?{...c.status,state:u.state,errorMessage:u.errorMessage}:c.status}));break}}}}}),K2=[{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"}],Y2=[{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"}],cS={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"},Us={soundEnabled:!0,browserNotification:!1,customSoundUrl:null},uS={soundEnabled:!1,browserNotification:!1,customSoundUrl:null},vm={soundEnabled:!0,browserNotificationEnabled:!1,events:{complete:{...Us},waiting_for_user:{...Us},phase_done:{...Us},phase_blocked:{...Us},new_message:{...uS}},agentOverrides:{}};function dS(e,t,n){var l;const s=e.events[t];if(!n)return s;const a=(l=e.agentOverrides[n])==null?void 0:l[t];return a?{soundEnabled:a.soundEnabled??s.soundEnabled,browserNotification:a.browserNotification??s.browserNotification,customSoundUrl:a.customSoundUrl!==void 0?a.customSoundUrl:s.customSoundUrl}:s}const bi=qn((e,t)=>({settings:vm,loaded:!1,load:()=>{an.getState().getSetting(ze.NOTIFICATION_SETTINGS);const s=an.subscribe(l=>{const u=l.settings[ze.NOTIFICATION_SETTINGS];if(u!==void 0)try{const c=JSON.parse(u);e({settings:bv(c),loaded:!0})}catch{e({loaded:!0})}}),a=an.getState().settings[ze.NOTIFICATION_SETTINGS];if(a)try{const l=JSON.parse(a);e({settings:bv(l),loaded:!0})}catch{e({loaded:!0})}return s},update:n=>{e({settings:n}),Lf(n)},updateEvent:(n,s)=>{const a=t().settings,l={...a,events:{...a.events,[n]:{...a.events[n],...s}}};e({settings:l}),Lf(l)},updateAgentOverride:(n,s,a)=>{var h;const l=t().settings,u={...l.agentOverrides};if(a===null){if(u[n]){const f={...u[n]};delete f[s],Object.keys(f).length===0?delete u[n]:u[n]=f}}else u[n]={...u[n],[s]:{...((h=u[n])==null?void 0:h[s])??{},...a}};const c={...l,agentOverrides:u};e({settings:c}),Lf(c)}}));function Lf(e){an.getState().setSetting(ze.NOTIFICATION_SETTINGS,JSON.stringify(e))}function bv(e){var t,n,s,a,l;return{soundEnabled:e.soundEnabled??vm.soundEnabled,browserNotificationEnabled:e.browserNotificationEnabled??vm.browserNotificationEnabled,events:{complete:{...Us,...(t=e.events)==null?void 0:t.complete},waiting_for_user:{...Us,...(n=e.events)==null?void 0:n.waiting_for_user},phase_done:{...Us,...(s=e.events)==null?void 0:s.phase_done},phase_blocked:{...Us,...(a=e.events)==null?void 0:a.phase_blocked},new_message:{...uS,...(l=e.events)==null?void 0:l.new_message}},agentOverrides:e.agentOverrides??{}}}const Sv=new Map;function X2(e){let t=Sv.get(e);return t||(t=new Audio(e),t.volume=.5,Sv.set(e,t)),t}let hS=typeof Notification<"u"?Notification.permission:"denied";function Q2(){return typeof Notification>"u"?Promise.resolve("denied"):Notification.requestPermission().then(e=>(hS=e,e))}const J2={complete:"Task Complete",waiting_for_user:"Waiting for Input",phase_done:"Phase Complete",phase_blocked:"Phase Blocked",new_message:"New Message"},Z2={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 ej(e){typeof Notification>"u"||hS==="granted"&&(document.hasFocus()||new Notification(J2[e],{body:Z2[e],icon:"/fox.svg",tag:`openfox-${e}`}))}function ml(e,t){const{settings:n}=bi.getState(),s=dS(n,e,t);if(n.soundEnabled&&s.soundEnabled){const a=s.customSoundUrl??cS[e],l=X2(a);l.currentTime=0,l.play().catch(()=>{})}n.browserNotificationEnabled&&s.browserNotification&&ej(e)}const tj=e=>ml("complete",e),nj=e=>ml("phase_done",e),rj=e=>ml("phase_blocked",e),wv=e=>ml("waiting_for_user",e),sj=e=>ml("new_message",e),Cv=new Map;function Xo(e,t){var l;const n=t===((l=e.currentSession)==null?void 0:l.id)?e.currentSession:null,s=e.sessions.find(u=>u.id===t),a=(n==null?void 0:n.mode)??(s==null?void 0:s.mode);return a==="planner"?"planner":a==="builder"?"build":"planner"}function ij(e,t){if(e.type==="chat.done"){const n=e.payload,s=Xo(t,e.sessionId),a=n.agentType??s;n.reason==="complete"&&tj(a),n.reason==="waiting_for_user"&&wv(a);return}if(e.type==="chat.path_confirmation"){const n=Xo(t,e.sessionId);wv(n);return}if(e.type==="task.completed"){const n=Xo(t,e.sessionId);nj(n);return}if(e.type==="phase.changed"&&e.sessionId){const n=e.payload,s=Cv.get(e.sessionId)??null;if(Cv.set(e.sessionId,n.phase),s===n.phase)return;const a=Xo(t,e.sessionId);n.phase==="blocked"&&rj(a)}}const Df=new Set;function Gt(e,t){return t!==null&&e.sessionId===t}function aj(e,t,n){return e.id!==void 0||Gt(e,t)||n===!0&&e.sessionId!==void 0}function oj(e,t){return e.includes(t)?e:[...e,t]}function kv(e,t){return e.filter(n=>n!==t)}function lj(e,t){const n=e.find(l=>l.id===t.id),s=t.messageCount??t.messages.length,a=n?{...n,projectId:t.projectId,workdir:t.workdir,mode:t.mode,phase:t.phase,isRunning:t.isRunning&&n.isRunning!==!1,messageCount:s,criteriaCount:t.criteria.length,criteriaCompleted:t.criteria.filter(l=>l.status.type==="passed").length}:{id:t.id,projectId:t.projectId,workdir:t.workdir,mode:t.mode,phase:t.phase,isRunning:t.isRunning,createdAt:"",updatedAt:"",criteriaCount:t.criteria.length,criteriaCompleted:t.criteria.filter(l=>l.status.type==="passed").length,messageCount:s};return n?e.map(l=>l.id===t.id?a:l):[a,...e]}function cj(e,t,n){return e.map(s=>{const a=(n==null?void 0:n.id)===s.id?n:null,l=t.find(u=>u.id===s.id);return{...s,title:s.title??(l==null?void 0:l.title),mode:(a==null?void 0:a.mode)??(l==null?void 0:l.mode)??s.mode,phase:(a==null?void 0:a.phase)??(l==null?void 0:l.phase)??s.phase,isRunning:s.isRunning&&(l==null?void 0:l.isRunning)!==!1,messageCount:s.messageCount,recentUserPrompts:s.recentUserPrompts}})}function Ev(e,t,n,s){var c;const a=e.sessionId,l=(c=n().currentSession)==null?void 0:c.id,u=a&&a!==l;if(t(h=>({sessions:h.sessions.map(f=>f.id===a?s(f):f)})),!u){const h=n().currentSession;if(h){const f=s(h);t(()=>({currentSession:f}))}}}function jv(e,t,n){var u,c,h,f,p,m,_,x,w,k,y,S,v,b,E,T,N,L,A,D,B,q,W;const s=n();ij(e,s);const a=((u=s.currentSession)==null?void 0:u.id)??null,l=()=>{const O=e.sessionId;!O||O===a||t(V=>({unreadSessionIds:oj(V.unreadSessionIds,O)}))};switch(e.type){case"session.state":{const O=e.payload;if(!aj(e,a,s.pendingSessionCreate))break;const V=O.messages.find(z=>z.isStreaming)??null,G=n().pendingSessionCreate===!0;if(t({currentSession:O.session,sessions:lj(n().sessions,O.session),unreadSessionIds:kv(n().unreadSessionIds,O.session.id),messages:O.messages,streamingMessageId:(V==null?void 0:V.id)??null,streamingMessage:V,currentTodos:[],pendingPathConfirmations:O.pendingConfirmations??[],error:null,...G?{pendingSessionCreate:O.session.id}:{}}),O.session.providerId){const z=Bt.getState();z.providers.find(ne=>ne.id===O.session.providerId)&&z.syncFromSession(O.session.providerId,O.session.providerModel??"")}break}case"session.list":{const O=e.payload;t(V=>({sessions:cj(O.sessions,V.sessions,V.currentSession)}));break}case"session.deleted":{const O=e.payload;t(V=>({unreadSessionIds:kv(V.unreadSessionIds,O.sessionId)})),n().listSessions();break}case"session.deletedAll":{n().listSessions();break}case"session.running":{const O=e.payload;Ev(e,t,n,V=>({...V,isRunning:O.isRunning})),O.isRunning||t({abortInProgress:!1,queuedMessages:[]});break}case"chat.message":{if(!Gt(e,((c=n().currentSession)==null?void 0:c.id)??null)){l();break}const O=e.payload;t(V=>{if(V.messages.some(z=>z.id===O.message.id))return V;const G=O.message.role==="user";return{messages:[...V.messages,O.message],sessions:V.sessions.map(z=>z.id===e.sessionId&&G?{...z,messageCount:z.messageCount+1}:z),streamingMessageId:O.message.isStreaming?O.message.id:V.streamingMessageId,streamingMessage:O.message.isStreaming?O.message:V.streamingMessage}});break}case"chat.message_updated":{if(!Gt(e,((h=n().currentSession)==null?void 0:h.id)??null)){l();break}const O=e.payload,V=O.updates.isStreaming===!1&&n().streamingMessageId===O.messageId;t(G=>{const z=G.streamingMessage;if(z&&z.id===O.messageId){const X={...z,...O.updates};return{messages:G.messages.map(ne=>ne.id===O.messageId?X:ne),streamingMessageId:V?null:G.streamingMessageId,streamingMessage:V?null:{...z,...O.updates}}}return{messages:G.messages.map(X=>X.id===O.messageId?{...X,...O.updates}:X),streamingMessageId:V?null:G.streamingMessageId}});break}case"chat.delta":{if(!Gt(e,((f=n().currentSession)==null?void 0:f.id)??null)){l();break}const O=e.payload;if(!Df.has(O.messageId)){Df.add(O.messageId);const G=O.subAgentType?"sub-agent":Xo(n(),e.sessionId);sj(G)}const V=yi();V.messageId=O.messageId,V.deltaContent+=O.content,Af();break}case"chat.thinking":{if(!Gt(e,((p=n().currentSession)==null?void 0:p.id)??null)){l();break}const O=e.payload,V=yi();V.messageId=O.messageId,V.thinkingContent+=O.content,Af();break}case"chat.tool_preparing":{if(!Gt(e,((m=n().currentSession)==null?void 0:m.id)??null)){l();break}const O=e.payload,V=n().streamingMessage;if(!V||V.id!==O.messageId||((_=V.toolCalls)==null?void 0:_.find((z,X)=>X===O.index)))return;t(z=>{const X=z.streamingMessage.preparingToolCalls??[],ne=X.findIndex(M=>M.index===O.index);let F;return ne>=0?F=X.map((M,$)=>$===ne?{...M,arguments:O.arguments}:M):F=[...X,{index:O.index,name:O.name,...O.arguments?{arguments:O.arguments}:{}}],{streamingMessage:{...z.streamingMessage,preparingToolCalls:F}}});break}case"chat.tool_call":{if(!Gt(e,((x=n().currentSession)==null?void 0:x.id)??null)){l();break}const O=e.payload,V=G=>{var F;const z=(F=G.preparingToolCalls)==null?void 0:F.filter((M,$)=>{var P;return M.name===O.tool?(P=G.preparingToolCalls)==null?void 0:P.slice(0,$).some(J=>J.name===O.tool):!0}),X=yi(),ne=X.toolOutput.filter(M=>M.callId===O.callId);return ne.length>0&&(X.toolOutput=X.toolOutput.filter(M=>M.callId!==O.callId)),{...G,toolCalls:[...G.toolCalls??[],{id:O.callId,name:O.tool,arguments:O.args,startedAt:Date.now(),...ne.length>0?{streamingOutput:ne.map(M=>({stream:M.stream,content:M.content,timestamp:Date.now()}))}:{}}],...z&&z.length>0?{preparingToolCalls:z}:{preparingToolCalls:void 0}}};t(G=>{const z=G.streamingMessage;return z&&z.id===O.messageId?{streamingMessage:V(z)}:{messages:G.messages.map(X=>X.id===O.messageId?V(X):X)}});break}case"chat.tool_output":{if(!Gt(e,((w=n().currentSession)==null?void 0:w.id)??null)){l();break}const O=e.payload,V=yi();V.messageId=O.messageId,V.toolOutput.push({messageId:O.messageId,callId:O.callId,stream:O.stream,content:O.output}),Af();break}case"chat.tool_result":{if(!Gt(e,((k=n().currentSession)==null?void 0:k.id)??null)){l();break}const O=e.payload,V=G=>{var X;const z=(X=G.toolCalls)==null?void 0:X.map(ne=>ne.id===O.callId?{...ne,result:O.result}:ne);return{...G,toolCalls:z}};t(G=>{const z=G.streamingMessage;return z&&z.id===O.messageId?{streamingMessage:V(z)}:{messages:G.messages.map(X=>X.id===O.messageId?V(X):X)}});break}case"chat.vision_fallback":{if(!Gt(e,((y=n().currentSession)==null?void 0:y.id)??null)){l();break}const O=e.payload;t(V=>{const G=`${O.messageId}-${O.attachmentId}`,z={...V.visionFallbackByMessage};return z[G]={type:O.type,attachmentId:O.attachmentId,filename:O.filename,description:O.description},{visionFallbackByMessage:z}});break}case"chat.todo":{if(!Gt(e,((S=n().currentSession)==null?void 0:S.id)??null)){l();break}const O=e.payload;t({currentTodos:O.todos});break}case"chat.progress":{if(!Gt(e,((v=n().currentSession)==null?void 0:v.id)??null)){l();break}const O=e.payload;console.warn("Progress:",O.message,O.phase);break}case"chat.format_retry":{if(!Gt(e,((b=n().currentSession)==null?void 0:b.id)??null)){l();break}const O=e.payload;console.warn("Format retry:",O.attempt,"/",O.maxAttempts);break}case"chat.done":{if(!Gt(e,((E=n().currentSession)==null?void 0:E.id)??null)){l();break}const O=yi();O.messageId=null,O.deltaContent="",O.thinkingContent="",O.toolOutput=[],Df.delete(e.payload.messageId);const V=e.payload,G=V.stats;t(z=>{const X=z.streamingMessage,ne=X&&X.id===V.messageId?{...X,isStreaming:!1,stats:G??X.stats}:null;return{messages:z.messages.map(F=>F.id===V.messageId?ne??{...F,isStreaming:!1,stats:G??F.stats,completeReason:V.reason}:F),streamingMessageId:null,streamingMessage:null,visionFallbackByMessage:{}}});break}case"chat.error":{if(!Gt(e,((T=n().currentSession)==null?void 0:T.id)??null)){l();break}const O=yi(),V=e.payload;console.error("Chat error:",V.error,"recoverable:",V.recoverable),V.recoverable||(O.messageId=null,O.deltaContent="",O.thinkingContent="",O.toolOutput=[]),t(G=>({error:{code:"CHAT_ERROR",message:V.error},streamingMessageId:V.recoverable?G.streamingMessageId:null,...V.recoverable?{}:{messages:G.streamingMessage?G.messages.map(z=>z.id===G.streamingMessage.id?G.streamingMessage:z):G.messages,streamingMessage:null}}));break}case"chat.path_confirmation":{if(!Gt(e,((N=n().currentSession)==null?void 0:N.id)??null)){l();break}const O=e.payload,V={callId:O.callId,tool:O.tool,paths:O.paths,workdir:O.workdir,reason:O.reason};t(G=>({pendingPathConfirmations:[...G.pendingPathConfirmations,V]}));break}case"chat.ask_user":{if(!Gt(e,((L=n().currentSession)==null?void 0:L.id)??null)){l();return}const O=e.payload;t({pendingQuestion:{callId:O.callId,question:O.question}});break}case"mode.changed":{if(!Gt(e,((A=n().currentSession)==null?void 0:A.id)??null)){l();break}const O=e.payload;t(V=>({currentSession:V.currentSession?{...V.currentSession,mode:O.mode}:null}));break}case"phase.changed":{const O=e.payload;Ev(e,t,n,V=>({...V,phase:O.phase}));break}case"criteria.updated":{if(!Gt(e,((D=n().currentSession)==null?void 0:D.id)??null)){l();break}const O=e.payload;t(V=>({currentSession:V.currentSession?{...V.currentSession,criteria:O.criteria}:null}));break}case"metadata.updated":{if(!Gt(e,((B=n().currentSession)==null?void 0:B.id)??null)){l();break}const O=e.payload;t(V=>({currentSession:V.currentSession?{...V.currentSession,metadataEntries:{...V.currentSession.metadataEntries,[O.key]:O.entries}}:null}));break}case"context.state":{const O=e.payload,V=Gt(e,((q=n().currentSession)==null?void 0:q.id)??null);O.subAgentId?V&&n().updateSubAgentContextState(O.subAgentId,O.context):V?t({contextState:O.context}):l();break}case"session.name_generated":{const O=e.payload,V=e.sessionId,G=(W=n().currentSession)==null?void 0:W.id;t(z=>{const X=z.sessions.map(F=>F.id===V?{...F,title:O.name,updatedAt:new Date().toISOString()}:F),ne=G===V?z.currentSession?{...z.currentSession,title:O.name,updatedAt:new Date().toISOString()}:null:z.currentSession;return{sessions:X,currentSession:ne}});break}case"queue.state":{const O=e.payload;t({queuedMessages:O.messages??[]});break}case"git.status":{const O=e.payload;t({gitStatus:{branch:O.branch,diff:O.diff}});break}case"devServer.output":case"devServer.state":{Rr.getState().handleMessage(e);break}case"backgroundProcess.started":case"backgroundProcess.output":case"backgroundProcess.exited":case"backgroundProcess.removed":{Zo.getState().handleMessage(e.type,e.payload);break}case"error":{const O=e.payload;console.error("Server error:",O),t({error:{code:O.code,message:O.message},streamingMessageId:null});break}}}let $o=!1,Nr=null;const Rf=new Set,Uc=new Map;function Nv(e,t,n){return e==null?void 0:e.map(s=>{const a=t.filter(l=>l.callId===s.id);return a.length===0?s:(n.add(s.id),{...s,streamingOutput:[...s.streamingOutput??[],...a.map(l=>({stream:l.stream,content:l.content,timestamp:Date.now()}))]})})}async function Tv(e,t,n,s,a){try{const u=await(await Ne(`/api/sessions/${e}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:t,attachments:n,messageKind:s})})).json();u.queueState&&a({queuedMessages:u.queueState})}catch(l){console.error("Error queueing message:",l)}}const we=qn((e,t)=>(q2(()=>{const n=yi();if(!n.messageId)return;const s=n.deltaContent.length>0,a=n.thinkingContent.length>0,l=n.toolOutput.length>0;if(!s&&!a&&!l)return;const u=n.deltaContent,c=n.thinkingContent,h=n.toolOutput;n.deltaContent="",n.thinkingContent="",n.toolOutput=[],e(f=>{const p=f.streamingMessage;if(p&&p.id===n.messageId){const m={...p};if(s&&(m.content=m.content+u),a&&(m.thinkingContent=(m.thinkingContent??"")+c),l){const _=new Set;m.toolCalls=Nv(m.toolCalls,h,_);const x=h.filter(w=>!_.has(w.callId));x.length>0&&n.toolOutput.push(...x)}return{streamingMessage:m}}if(l){const m=new Set,_=f.messages.map(w=>w.id!==n.messageId?w:{...w,toolCalls:Nv(w.toolCalls,h,m)}),x=h.filter(w=>!m.has(w.callId));return x.length>0&&n.toolOutput.push(...x),{messages:_}}return f})}),{connectionStatus:"disconnected",showPasswordModal:!1,passwordModalRetry:!1,sessions:[],currentSession:null,unreadSessionIds:[],messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,subAgentContextStates:{},pendingPathConfirmations:[],pendingQuestion:null,visionFallbackByMessage:{},gitStatus:null,queuedMessages:[],abortInProgress:!1,error:null,sessionsHasMore:!0,sessionsPaginationLoading:!1,pendingSessionCreate:!1,connect:async()=>{if(t().connectionStatus==="connected")return;e({connectionStatus:"reconnecting"});let s=!1;try{s=(await(await Ne("/api/auth")).json()).requiresAuth}catch{}if(s&&!zt.hasToken()){e({showPasswordModal:!0,passwordModalRetry:!1,connectionStatus:"reconnecting"});return}zt.onStatusChange(a=>{var l;if(e({connectionStatus:a}),a==="connected"){t().listSessions(void 0),Lt.getState().listProjects();const u=(l=t().currentSession)==null?void 0:l.id;u&&t().loadSession(u)}});try{await zt.connect(),$o||($o=!0,Nr=zt.subscribe(a=>{jv(a,e,t)}))}catch(a){console.error("Failed to connect:",a);const l=zt.getLastCloseCode();if(!zt.hasToken()&&(l===1006||l===4e3)){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}Nr&&(Nr(),Nr=null),$o=!1,e({connectionStatus:"disconnected"})}},reconnect:()=>{zt.disconnect(),Nr&&(Nr(),Nr=null),$o=!1,e({connectionStatus:"disconnected"}),t().connect()},disconnect:()=>{zt.disconnect(),Nr&&(Nr(),Nr=null),$o=!1,e({connectionStatus:"disconnected",showPasswordModal:!1})},submitPassword:async n=>{try{const s=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:n})});if(!s.ok){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}const{token:a}=await s.json();zt.setToken(a),e({showPasswordModal:!1}),t().connect();const{listProjects:l}=Lt.getState(),{fetchConfig:u}=Bt.getState();l(),u(),t().connect()}catch{e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"})}},cancelPassword:()=>{zt.clearToken(),e({showPasswordModal:!1,connectionStatus:"disconnected"})},createSession:async(n,s)=>{if(t().pendingSessionCreate)return null;try{e({pendingSessionCreate:!0});const l=await Ne("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectId:n,title:s})});if(!l.ok)return e({pendingSessionCreate:!1}),null;const u=await l.json();try{zt.send("session.load",{sessionId:u.session.id})}catch{}return u.session}catch{return e({pendingSessionCreate:!1}),null}},loadSession:async n=>{if(!Rf.has(n)){Rf.add(n);try{const s=t().currentSession;!s||s.id!==n?e({currentSession:null,unreadSessionIds:t().unreadSessionIds.filter(u=>u!==n),subAgentContextStates:{},messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,pendingPathConfirmations:[],queuedMessages:[],abortInProgress:!1,error:null,pendingSessionCreate:!1}):e({unreadSessionIds:t().unreadSessionIds.filter(u=>u!==n)});const a=await Ne(`/api/sessions/${n}`);if(!a.ok)return;const l=await a.json();e({currentSession:l.session,messages:l.messages??[],contextState:l.contextState,queuedMessages:l.queueState??[]}),zt.send("session.load",{sessionId:n});try{const u=await Ne(`/api/sessions/${n}/background-processes`);if(u.ok){const c=await u.json();Zo.getState().setProcesses(c.processes??[])}}catch{}}catch{}finally{Rf.delete(n)}}},listSessions:async(n,s=20)=>{const a=n??"global";if(Uc.has(a))return Uc.get(a);const l=(async()=>{try{const u=new URLSearchParams;u.set("limit",String(s)),n&&u.set("projectId",n);const h=await(await Ne(`/api/sessions?${u.toString()}`)).json(),f=h.sessions??[];e(p=>({sessions:f.map(m=>{var x,w;const _=p.sessions.find(k=>k.id===m.id);return{...m,title:m.title??(_==null?void 0:_.title),mode:((x=p.currentSession)==null?void 0:x.id)===m.id?p.currentSession.mode:(_==null?void 0:_.mode)??m.mode,phase:((w=p.currentSession)==null?void 0:w.id)===m.id?p.currentSession.phase:(_==null?void 0:_.phase)??m.phase,isRunning:m.isRunning&&(_==null?void 0:_.isRunning)!==!1,messageCount:m.messageCount,recentUserPrompts:m.recentUserPrompts}}),sessionsHasMore:n?h.hasMore??!1:!0}))}catch{}finally{Uc.delete(a)}})();return Uc.set(a,l),l},loadMoreSessions:async n=>{const s=t();if(!(s.sessionsPaginationLoading||!s.sessionsHasMore)){e({sessionsPaginationLoading:!0});try{const a=new URLSearchParams;a.set("limit","20"),a.set("offset",String(s.sessions.length)),a.set("projectId",n);const u=await(await Ne(`/api/sessions?${a.toString()}`)).json(),c=u.sessions??[];e(h=>({sessions:[...h.sessions,...c.map(f=>{const p=h.sessions.find(m=>m.id===f.id);return(p==null?void 0:p.isRunning)===!1?{...f,isRunning:!1}:f})],sessionsHasMore:u.hasMore??!1,sessionsPaginationLoading:!1}))}catch{e({sessionsPaginationLoading:!1})}}},deleteSession:async n=>{var s;try{return(await Ne(`/api/sessions/${n}`,{method:"DELETE"})).ok?(await t().listSessions(),((s=t().currentSession)==null?void 0:s.id)===n&&t().clearSession(),!0):!1}catch{return!1}},renameSession:async(n,s)=>{var a;try{const l=await Ne(`/api/sessions/${n}/title`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:s})});if(!l.ok)return!1;if(await t().listSessions(),((a=t().currentSession)==null?void 0:a.id)===n){const c=await l.json();c.session&&e({currentSession:c.session})}return!0}catch{return!1}},deleteAllSessions:async n=>{try{return(await Ne(`/api/projects/${n}/sessions`,{method:"DELETE"})).ok?(await t().listSessions(),!0):!1}catch{return!1}},clearSession:()=>{e(n=>({currentSession:null,messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,pendingSessionCreate:!1,unreadSessionIds:n.currentSession?n.unreadSessionIds.filter(s=>s!==n.currentSession.id):n.unreadSessionIds}))},sendMessage:async(n,s,a)=>{var u;const l=(u=t().currentSession)==null?void 0:u.id;if(l){e({streamingMessageId:null});try{const h=await(await Ne(`/api/sessions/${l}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:n,attachments:s,messageKind:a==null?void 0:a.messageKind})})).json();h.queueState&&e({queuedMessages:h.queueState})}catch(c){console.error("Error sending message:",c)}}},stopGeneration:async()=>{var s;const n=(s=t().currentSession)==null?void 0:s.id;if(n&&!t().abortInProgress){e({abortInProgress:!0});try{await Ne(`/api/sessions/${n}/stop`,{method:"POST"})}catch(a){console.error("Error stopping generation:",a)}}},continueGeneration:async()=>{var s;const n=(s=t().currentSession)==null?void 0:s.id;if(n){e({streamingMessageId:null});try{await Ne(`/api/sessions/${n}/continue`,{method:"POST"})}catch(a){console.error("Error continuing generation:",a)}}},launchRunner:(n,s,a,l)=>{e({streamingMessageId:null});const u={};n!=null&&n.trim()&&(u.content=n),s&&s.length>0&&(u.attachments=s),a&&(u.workflowId=a),l&&(u.subGroup=l),zt.send("runner.launch",u)},switchMode:async n=>{var a;const s=(a=t().currentSession)==null?void 0:a.id;if(s)try{const l=await Ne(`/api/sessions/${s}/mode`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:n})});if(!l.ok){console.error("Failed to switch mode:",await l.json());return}const u=await l.json();u.session&&e({currentSession:u.session})}catch(l){console.error("Error switching mode:",l)}},switchDangerLevel:async n=>{var a;const s=(a=t().currentSession)==null?void 0:a.id;if(s)try{const l=await Ne(`/api/sessions/${s}/danger-level`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({dangerLevel:n})});if(!l.ok){console.error("Failed to switch danger level:",await l.json());return}const u=await l.json();u.session&&e({currentSession:u.session})}catch(l){console.error("Error switching danger level:",l)}},acceptAndBuild:(n,s,a,l)=>{var h;e({streamingMessageId:null});const u={};n&&(u.workflowId=n),s!=null&&s.trim()&&(u.content=s),a&&a.length>0&&(u.attachments=a),l&&(u.subGroup=l);const c=(h=t().currentSession)==null?void 0:h.id;c&&Ne(`/api/sessions/${c}/mode`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:"builder"})}).then(()=>{zt.send("runner.launch",u)})},editCriteria:async n=>{var a;const s=(a=t().currentSession)==null?void 0:a.id;if(s)try{const l=await Ne(`/api/sessions/${s}/criteria`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({criteria:n})});l.ok||console.error("Failed to update criteria:",await l.json())}catch(l){console.error("Error updating criteria:",l)}},compactContext:()=>{zt.send("context.compact",{})},setSessionProvider:async(n,s)=>{var a,l;try{const u=(a=t().currentSession)==null?void 0:a.id;if(!u)return null;const c=await Ne(`/api/sessions/${u}/provider`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerId:n,...s?{model:s}:{}})});if(!c.ok)return null;const h=await c.json();if(e({currentSession:h.session,messages:h.messages??[],contextState:h.contextState}),(l=h.session)!=null&&l.providerId){const f=Bt.getState();f.providers.find(m=>m.id===h.session.providerId)&&f.syncFromSession(h.session.providerId,h.session.providerModel??"")}return h.session}catch{return null}},updateContextState:n=>{e({contextState:n})},updateSubAgentContextState:(n,s)=>{e(a=>({subAgentContextStates:{...a.subAgentContextStates,[n]:s}}))},clearSubAgentContextState:n=>{e(s=>{const a={...s.subAgentContextStates};return delete a[n],{subAgentContextStates:a}})},confirmPath:async(n,s,a=!1)=>{var u;const l=(u=t().currentSession)==null?void 0:u.id;if(l)try{await Ne(`/api/sessions/${l}/confirm-path`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:n,approved:s,alwaysAllow:a})})}catch(c){console.error("Error confirming path:",c)}},answerQuestion:async(n,s)=>{var l;const a=(l=t().currentSession)==null?void 0:l.id;if(a){try{await Ne(`/api/sessions/${a}/answer`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:n,answer:s})})}catch(u){console.error("Error answering question:",u)}e({pendingQuestion:null})}},queueAsap:async(n,s,a)=>{var u;const l=(u=t().currentSession)==null?void 0:u.id;l&&await Tv(l,n,s,a,e)},queueCompletion:async(n,s,a)=>{var u;const l=(u=t().currentSession)==null?void 0:u.id;l&&await Tv(l,n,s,a,e)},cancelQueued:async n=>{var a;const s=(a=t().currentSession)==null?void 0:a.id;if(s)try{const u=await(await Ne(`/api/sessions/${s}/queue/${n}`,{method:"DELETE"})).json();u.queueState&&e({queuedMessages:u.queueState})}catch(l){console.error("Error canceling queued message:",l)}},clearError:()=>{e({error:null})},resetPendingSessionCreate:()=>{e({pendingSessionCreate:!1})},handleServerMessage:n=>{jv(n,e,t)}}));function Pu(){return we(e=>{var t;return((t=e.currentSession)==null?void 0:t.isRunning)??!1})}function uj(){return we(e=>e.abortInProgress)}function dj(){const e=we(s=>s.connect),t=we(s=>s.connectionStatus),n=bi(s=>s.load);return R.useEffect(()=>{e()},[e]),R.useEffect(()=>{t==="connected"&&n()},[t,n]),{connectionStatus:t}}const hj="modulepreload",fj=function(e){return"/"+e},Av={},Z=function(t,n,s){let a=Promise.resolve();if(n&&n.length>0){let u=function(f){return Promise.all(f.map(p=>Promise.resolve(p).then(m=>({status:"fulfilled",value:m}),m=>({status:"rejected",reason:m}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),h=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));a=u(n.map(f=>{if(f=fj(f),f in Av)return;Av[f]=!0;const p=f.endsWith(".css"),m=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${m}`))return;const _=document.createElement("link");if(_.rel=p?"stylesheet":hj,p||(_.as="script"),_.crossOrigin="",_.href=f,h&&_.setAttribute("nonce",h),document.head.appendChild(_),p)return new Promise((x,w)=>{_.addEventListener("load",x),_.addEventListener("error",()=>w(new Error(`Unable to preload CSS for ${f}`)))})}))}function l(u){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=u,window.dispatchEvent(c),!c.defaultPrevented)throw u}return a.then(u=>{for(const c of u||[])c.status==="rejected"&&l(c.reason);return t().catch(l)})},fS=[{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"}],Or=[{id:"system",name:"System",tokens:{}},{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":"255 255 255","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 Lv(){try{const e=localStorage.getItem("openfox:userPresets");if(e)return JSON.parse(e)}catch{}return[]}const Ut=qn((e,t)=>({currentPreset:"dark",basePreset:"",customTokens:{},isCustom:!1,isCustomizing:!1,userPresets:Lv(),followSystemTheme:!0,isSystem:!1,applySavedTheme:()=>{const{getSavedTheme:n,applyPreset:s,applyTokens:a}=t(),l=n();if(l)try{const u=JSON.parse(l);u.preset&&u.tokens?(s(u.preset),e({basePreset:u.preset}),a(u.tokens)):u.preset?s(u.preset):u.tokens&&a(u.tokens)}catch{s("dark")}else s("dark")},applyPreset:n=>{if(Or.find(a=>a.id===n))if(n==="system"){const l=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";e({basePreset:"system",currentPreset:l,customTokens:{},isCustom:!1,isCustomizing:!1,isSystem:!0}),t().applyTheme()}else e({currentPreset:n,basePreset:"",customTokens:{},isCustom:!1,isCustomizing:!1,isSystem:!1}),t().applyTheme()},startCustomizing:()=>{var a;const{currentPreset:n}=t(),s=((a=Or.find(l=>l.id===n))==null?void 0:a.tokens)??{};e({basePreset:n,customTokens:{...s},isCustom:!0,isCustomizing:!0})},setCustomToken:(n,s)=>{e(a=>({customTokens:{...a.customTokens,[n]:s}})),t().applyTheme()},cancelCustomizing:()=>{t().applyPreset(t().basePreset||t().currentPreset)},saveCustomTheme:()=>{const{customTokens:n}=t();t().saveTheme(JSON.stringify({tokens:n})).catch(()=>{}),e({isCustomizing:!1})},applyTokens:n=>{e({customTokens:n,isCustom:!0,isCustomizing:!1}),t().applyTheme()},getActiveTheme:()=>{var u,c;const{basePreset:n,customTokens:s,isCustom:a}=t();if(a&&n)return{...((u=Or.find(f=>f.id===n))==null?void 0:u.tokens)??{},...s};if(a)return{...fS.reduce((h,f)=>({...h,[f.key]:f.defaultValue}),{}),...s};const l=Or.find(h=>h.id===t().currentPreset);return(l==null?void 0:l.tokens)??((c=Or[0])==null?void 0:c.tokens)??{}},applyTheme:()=>{if(typeof document>"u")return;const n=t().getActiveTheme(),s=document.documentElement;Object.entries(n).forEach(([a,l])=>{s.style.setProperty(`--${a}`,l)})},getSavedTheme:()=>{try{const n=localStorage.getItem("openfox:theme");if(!n)return null;if(n[0]!=="{")return JSON.stringify({preset:n});const s=JSON.parse(n);if(s.preset)return JSON.stringify({preset:s.preset});if(s.tokens)return JSON.stringify({tokens:s.tokens})}catch{return null}return null},saveTheme:async n=>{localStorage.setItem("openfox:theme",n);const{useSettingsStore:s}=await Z(async()=>{const{useSettingsStore:a}=await Promise.resolve().then(()=>jf);return{useSettingsStore:a}},void 0);await s.getState().setSetting(ze.DISPLAY_THEME,n)},clearCustomTheme:()=>{localStorage.removeItem("openfox:theme"),e({isCustom:!1,isCustomizing:!1,basePreset:""})},setFollowSystemTheme:n=>{e({followSystemTheme:n}),Z(async()=>{const{useSettingsStore:s,SETTINGS_KEYS:a}=await Promise.resolve().then(()=>jf);return{useSettingsStore:s,SETTINGS_KEYS:a}},void 0).then(({useSettingsStore:s,SETTINGS_KEYS:a})=>{s.getState().setSetting(a.DISPLAY_FOLLOW_SYSTEM_THEME,String(n))})},initSystemThemeListener:()=>{if(typeof window>"u")return()=>{};const n=window.matchMedia("(prefers-color-scheme: dark)"),s=l=>{const{followSystemTheme:u}=t();u&&(t().applyPreset(l?"dark":"light"),t().saveTheme(JSON.stringify({preset:l?"dark":"light"})))},a=l=>s(l.matches);return n.addEventListener("change",a),()=>n.removeEventListener("change",a)},reset:()=>{e({currentPreset:"dark",basePreset:"",customTokens:{},isCustom:!1,isCustomizing:!1,userPresets:[],followSystemTheme:!0})},addUserPreset:n=>{const{basePreset:s,customTokens:a,currentPreset:l}=t(),u={id:"custom-"+Date.now(),name:n,basePreset:s||l,tokens:{...a}},c=[...t().userPresets,u];e({userPresets:c}),t().saveUserPresets()},applyUserPreset:n=>{const s=t().userPresets[n];s&&(e({currentPreset:s.basePreset,basePreset:s.basePreset,customTokens:{...s.tokens},isCustom:!0,isCustomizing:!1}),t().applyTheme(),t().saveTheme(JSON.stringify({preset:s.basePreset,tokens:s.tokens})).catch(()=>{}))},deleteUserPreset:n=>{const s=t().userPresets.filter((a,l)=>l!==n);e({userPresets:s}),t().saveUserPresets()},loadUserPresets:()=>{e({userPresets:Lv()})},saveUserPresets:()=>{localStorage.setItem("openfox:userPresets",JSON.stringify(t().userPresets)),Z(async()=>{const{useSettingsStore:n}=await Promise.resolve().then(()=>jf);return{useSettingsStore:n}},void 0).then(({useSettingsStore:n})=>{n.getState().setSetting(ze.DISPLAY_USER_PRESETS,JSON.stringify(t().userPresets)).catch(()=>{})})}}));function mj({canLoad:e,projectId:t,currentProjectId:n}){const s=Lt(u=>u.loadProject),a=we(u=>u.listSessions),l=we(u=>u.clearSession);R.useEffect(()=>{e&&t&&(n!==t&&s(t),a(t),l())},[e,t,n,s,a,l])}function pj({canLoad:e,projectId:t,sessionId:n,currentProjectId:s,currentSessionId:a}){const l=we(f=>f.loadSession),u=Lt(f=>f.loadProject),c=we(f=>f.listSessions),h=we(f=>f.pendingSessionCreate);R.useEffect(()=>{e&&t&&s!==t&&u(t)},[e,t,s,u]),R.useEffect(()=>{e&&n&&a!==n&&l(n),e&&t&&c(t)},[e,n,a,l,c,h,t])}function gj({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 mS({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 xj({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 _j({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 yj({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M9.5 3.25a2.25 2.25 0 1 1 3 2.122V6A2.5 2.5 0 0 1 10 8.5H6a1 1 0 0 0-1 1v1.128a2.251 2.251 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.5 0v1.836A2.493 2.493 0 0 1 6 7h4a1 1 0 0 0 1-1v-.628A2.25 2.25 0 0 1 9.5 3.25Zm-6 0a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Zm8.25-.75a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM4.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z"})})}function Mr({className:e="w-3.5 h-3.5 text-text-muted"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})}function Sr({className:e="w-3 h-3 text-text-muted",rotate:t}){return o.jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:t!==void 0?{transform:`rotate(${t}deg)`}:void 0,children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"})})}function vj({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 ap({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 bj({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 op({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 uu({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 Bu({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 Sj({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 wj({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 Cj({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 pS({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 kj({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 Dv({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 gS({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 Ej({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 jj({className:e="w-3 h-3",color:t}){return o.jsx("svg",{className:e,fill:t??"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{d:"M8 5v14l11-7z"})})}function qs({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 Nj({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 lp({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 Tj({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 Aj({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 Lj({className:e="w-3.5 h-3.5 text-text-muted"}){return o.jsx("svg",{className:e,fill:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{d:"M10.788 3.21c.448-1.077 1.976-1.077 2.424 0l2.082 5.007 5.404.433c1.164.093 1.636 1.545.749 2.305l-4.117 3.527 1.257 5.273c.271 1.136-.964 2.033-1.96 1.425L12 18.354 7.373 21.18c-.996.608-2.231-.29-1.96-1.425l1.257-5.273-4.117-3.527c-.887-.76-.415-2.212.749-2.305l5.404-.433 2.082-5.006z"})})}function Dj({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:"M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"})})}function xS({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 Rj({className:e="w-3.5 h-3.5 shrink-0",color:t}){return o.jsx("svg",{className:e,fill:"none",stroke:t,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 Oj({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("polyline",{points:"4 17 10 11 4 5"}),o.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function pl({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 cp(){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 Mj({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 bm({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 gl({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 _S({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 Ij({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:"M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"})})}function Pj({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:"M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"})})}function Rv({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:"M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"})})}function Sm(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function Ov(e,t){const n=zt.ws;!n||n.readyState!==WebSocket.OPEN||n.send(JSON.stringify({id:Sm(),type:e,payload:t}))}const _r=qn((e,t)=>({isOpen:!1,sessions:[],workdir:null,setOpen:n=>e({isOpen:n}),toggleOpen:()=>e(n=>({isOpen:!n.isOpen})),setWorkdir:n=>e({workdir:n}),fetchSessions:async n=>{if(!n){e({sessions:[]});return}try{const s=await Ne(`/api/terminals?projectId=${encodeURIComponent(n)}`);if(s.ok){const a=await s.json();e({sessions:a});const l=zt.ws;if(l&&l.readyState===WebSocket.OPEN)for(const u of a)l.send(JSON.stringify({id:Sm(),type:"terminal.subscribe",payload:{sessionId:u.id}}))}}catch(s){console.error("Failed to fetch terminals:",s)}},createSession:async(n,s)=>{try{const a=await Ne("/api/terminals",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workdir:n??t().workdir??void 0,projectId:s})});if(a.ok){const l=await a.json();e(c=>({sessions:[...c.sessions,l]}));const u=zt.ws;u&&u.readyState===WebSocket.OPEN&&u.send(JSON.stringify({id:Sm(),type:"terminal.subscribe",payload:{sessionId:l.id}}))}}catch(a){console.error("Failed to create terminal:",a)}},writeSession:(n,s)=>{Ov("terminal.write",{sessionId:n,data:s})},resizeSession:(n,s,a)=>{Ov("terminal.resize",{sessionId:n,cols:s,rows:a})},killSession:async n=>{try{(await Ne(`/api/terminals/${n}`,{method:"DELETE"})).ok&&e(a=>({sessions:a.sessions.filter(l=>l.id!==n)}))}catch(s){console.error("Failed to kill terminal:",s)}},handleMessage:n=>{switch(n.type){case"terminal.exit":{const{sessionId:s}=n.payload||{};s&&e(a=>{const l=a.sessions.filter(u=>u.id!==s);return l.length===0&&a.isOpen?{sessions:[],isOpen:!1}:{sessions:l}});break}}}}));zt.subscribe(e=>{var t;(t=e.type)!=null&&t.startsWith("terminal.")&&_r.getState().handleMessage(e)});const Aa={terminalToggle:{type:"double-press",key:"Control",threshold:300},quickAction:{type:"double-press",key:"Shift",threshold:300},agentSwitching:[{type:"chord",key:"1",modifiers:["ctrl"]},{type:"chord",key:"2",modifiers:["ctrl"]},{type:"chord",key:"3",modifiers:["ctrl"]},{type:"chord",key:"4",modifiers:["ctrl"]}]};function wm(e){if(!e)return structuredClone(Aa);try{const t=JSON.parse(e);return{terminalToggle:t.terminalToggle??structuredClone(Aa.terminalToggle),quickAction:t.quickAction??structuredClone(Aa.quickAction),agentSwitching:t.agentSwitching??structuredClone(Aa.agentSwitching)}}catch{return structuredClone(Aa)}}function Mv(e){return e.code.startsWith("Digit")?e.code.slice(-1):e.code.startsWith("Key")?e.code.slice(3).toLowerCase():e.key}function yS(e){if(e.type==="double-press")return`Double ${e.key==="Control"?"Ctrl":e.key==="Shift"?"Shift":e.key==="Alt"?"Alt":e.key==="Meta"?"Meta":e.key}`;const t=e.modifiers.map(s=>{switch(s){case"ctrl":return"Ctrl";case"meta":return"⌘";case"alt":return"Alt";case"shift":return"Shift"}}),n=e.key.length===1?e.key.toUpperCase():e.key;return[...t,n].join("+")}function Bj(e){return e.type==="double-press"}function vS(e){return e.type==="chord"}function zj(e,t){return t.length===1&&/^[a-z]$/i.test(t)?e.code===`Key${t.toUpperCase()}`:t.length===1&&/^[0-9]$/.test(t)?e.code===`Digit${t}`:e.key.toLowerCase()===t.toLowerCase()}function bS(e,t){const n=t.modifiers.includes("ctrl"),s=t.modifiers.includes("meta"),a=t.modifiers.includes("alt"),l=t.modifiers.includes("shift");return zj(e,t.key)&&e.ctrlKey===n&&e.metaKey===s&&e.altKey===a&&e.shiftKey===l}function up(){const e=an(t=>t.settings[ze.KEYBINDINGS]);return wm(e)}function Hj(e,t,n){const s=R.useRef(0),a=R.useRef(t);a.current=t,R.useEffect(()=>{if(!e)return;const l=e.threshold??300,u=c=>{if(c.key!==e.key)return;const h=e.key==="Control",f=e.key==="Shift",p=e.key==="Alt",m=e.key==="Meta";if(!h&&c.ctrlKey||!f&&c.shiftKey||!p&&c.altKey||!m&&c.metaKey)return;const _=Date.now();_-s.current<l?(c.preventDefault(),c.stopPropagation(),a.current(),s.current=0):s.current=_};return window.addEventListener("keydown",u,n!=null&&n.capture?!0:void 0),()=>window.removeEventListener("keydown",u,n!=null&&n.capture?!0:void 0)},[e,n==null?void 0:n.capture])}function $j(e,t){const n=R.useRef(t);n.current=t,R.useEffect(()=>{if(!e)return;const s=a=>{bS(a,e)&&(a.preventDefault(),n.current())};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e])}function SS(e,t,n){Hj(e&&Bj(e)?e:void 0,t,n),$j(e&&vS(e)?e:void 0,t)}function Uj(e,t,n){const s=R.useRef(n);s.current=n,R.useEffect(()=>{const a=l=>{for(let u=0;u<e.length;u++){const c=e[u];if(!c)continue;const h=t[u];if(h&&vS(c)&&bS(l,c)){l.preventDefault(),s.current(h.id);return}}};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[e,t])}var $a=Q0();const zu=R.forwardRef(({icon:e,iconSize:t="w-3.5 h-3.5",className:n="",...s},a)=>o.jsx("button",{ref:a,type:"button",className:`p-1 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors ${n}`,...s,children:o.jsx("svg",{className:t,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:e})})}));zu.displayName="IconButton";const Fj="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",Fs=R.forwardRef((e,t)=>o.jsx(zu,{ref:t,icon:Fj,title:"Edit",...e}));Fs.displayName="EditButton";const Vj="M6 18L18 6M6 6l12 12",dp=R.forwardRef((e,t)=>o.jsx(zu,{ref:t,icon:Vj,...e}));dp.displayName="CloseButton";const Gj={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 Dt({label:e,title:t,size:n="md",minHeight:s,children:a,footer:l,className:u,onClose:c,isOpen:h,closeOnBackdropClick:f=!0,closeOnEscape:p=!0,showCloseButton:m=!0}){const[_,x]=R.useState(!1),w=h!==void 0,k=w?h:_,y=R.useCallback(()=>{w||x(!0)},[w]),S=R.useCallback(()=>{w||x(!1),c==null||c()},[w,c]);R.useEffect(()=>{if(!k||!p)return;const b=E=>{E.key==="Escape"&&(E.stopPropagation(),S())};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[k,S,p]);const v=e&&(typeof e=="string"?o.jsx("button",{type:"button",onClick:y,className:u,children:e}):o.jsx("span",{onClick:y,className:u,style:{cursor:"pointer"},children:e}));return o.jsxs(o.Fragment,{children:[v,k&&(typeof document<"u"?$a.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:f?S:void 0}),o.jsxs("div",{className:`relative w-full ${Gj[n]} max-h-[90vh] bg-bg-secondary border border-border rounded shadow-xl flex flex-col`,children:[(t||m)&&o.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border",children:[t&&o.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:t}),m&&o.jsx(dp,{onClick:S,className:"ml-auto","aria-label":"Close"})]}),o.jsx("div",{className:"p-4 overflow-y-auto flex-1 min-h-0",style:s?{minHeight:s}:void 0,children:a}),l&&o.jsx("div",{className:"px-4 py-3 border-t border-border",children:l})]})]}),document.body):null)]})}function Wj({value:e,defaultUrl:t,disabled:n,onChange:s}){const a=e??t;return o.jsxs("div",{className:"relative",children:[o.jsx("select",{value:a,disabled:n,onChange:l=>{const u=l.target.value;s(u===t?null:u)},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:Y2.map(({url:l,label:u})=>o.jsx("option",{value:l,title:u,children:u.split(" ")[0]},l))}),o.jsx(Sr,{className:"absolute right-0.5 top-1/2 -translate-y-1/2 w-3 h-3 pointer-events-none text-text-muted"})]})}const Iv=[{key:"general",label:"General"},{key:"build",label:"Agent"},{key:"sub-agent",label:"Sub-agent"}];function qj(){const e=bi(h=>h.settings),t=bi(h=>h.update),n=bi(h=>h.updateEvent),s=bi(h=>h.updateAgentOverride),a=bi(h=>h.load);R.useEffect(()=>{a()},[a]);const l=async()=>{await Q2()==="granted"&&t({...e,browserNotificationEnabled:!0})},u=(h,f,p,m)=>{h==="general"?n(f,{[p]:m}):s(h,f,{[p]:m})},c=(h,f,p)=>{h==="general"?n(f,{customSoundUrl:p}):s(h,f,{customSoundUrl:p})};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(Pv,{label:"Sound notifications",description:"Play sounds when events occur",checked:e.soundEnabled,onChange:h=>t({...e,soundEnabled:h})}),o.jsx(Pv,{label:"Browser notifications",description:"Show desktop notifications when the window is not focused",checked:e.browserNotificationEnabled,onChange:h=>{h&&typeof Notification<"u"&&Notification.permission!=="granted"?l():t({...e,browserNotificationEnabled:h})}}),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"}),Iv.map(h=>o.jsx("th",{className:"text-center px-2 py-2 text-text-primary font-medium",children:h.label},h.key))]})}),o.jsx("tbody",{children:K2.map(h=>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:h.label})}),Iv.map(f=>{const p=dS(e,h.key,f.key==="general"?void 0:f.key),m=cS[h.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:p.soundEnabled,onChange:_=>u(f.key,h.key,"soundEnabled",_.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:p.browserNotification,onChange:_=>u(f.key,h.key,"browserNotification",_.target.checked),disabled:!e.browserNotificationEnabled,className:"rounded border-border",title:"Browser"})})]}),p.soundEnabled&&e.soundEnabled&&o.jsx(Wj,{value:p.customSoundUrl,defaultUrl:m,disabled:!e.soundEnabled,onChange:_=>c(f.key,h.key,_)})]})},f.key)})]},h.key))})]})})]})]})}function Pv({label:e,description:t,checked:n,onChange:s}){return o.jsxs("label",{className:"flex items-start justify-between gap-3 cursor-pointer group",children:[o.jsxs("div",{className:"flex-1 min-w-0",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 mt-0.5",children:t})]}),o.jsx("div",{className:"flex-shrink-0 pt-0.5",children:o.jsx("div",{className:`relative w-9 h-5 rounded-full transition-colors ${n?"bg-accent-primary":"bg-bg-tertiary border border-border"}`,onClick:a=>{a.preventDefault(),s(!n)},children:o.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white shadow transition-transform ${n?"translate-x-4":"translate-x-0.5"}`})})})]})}const tt=R.forwardRef(({variant:e="secondary",size:t="md",className:n="",children:s,...a},l)=>{const u="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"},h={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:l,className:`${u} ${c[e]} ${h[t]} ${n}`,...a,children:s})});tt.displayName="Button";async function hp(e,t,n){t({loading:!0});try{const a=await(await Ne(e)).json();t({defaults:a.defaults??[],userItems:a.userItems??[],...n?{projectItems:a.projectItems??[]}:{},loading:!1})}catch{t({loading:!1})}}const Tr=qn((e,t)=>({defaults:[],userItems:[],projectItems:[],loading:!1,fetchSkills:async()=>{await hp("/api/skills",e,!0)},toggleSkill:async n=>{try{const a=await(await Ne(`/api/skills/${n}/toggle`,{method:"POST"})).json();e(l=>({defaults:l.defaults.map(u=>u.id===n?{...u,enabled:a.enabled}:u),userItems:l.userItems.map(u=>u.id===n?{...u,enabled:a.enabled}:u)}))}catch{}},fetchSkill:async n=>{try{const s=await Ne(`/api/skills/${n}`);return s.ok?await s.json():null}catch{return null}},fetchDefaultContent:async n=>{try{const s=await Ne(`/api/skills/defaults/${n}`);return s.ok?await s.json():null}catch{return null}},createSkill:async(n,s)=>{const a=await Ws("POST","/api/skills",{...n,destination:s});return a.success&&await t().fetchSkills(),a},updateSkill:async(n,s)=>{const a=await Ws("PUT",`/api/skills/${n}`,s);return a.success&&await t().fetchSkills(),a},deleteSkill:async n=>{try{const s=await Ne(`/api/skills/${n}`,{method:"DELETE"}),a=await s.json();return s.ok?(e(l=>({userItems:l.userItems.filter(u=>u.id!==n)})),{success:!0}):{success:!1,error:a.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateSkill:async(n,s)=>Iu(`/api/skills/${n}/duplicate`,()=>t().fetchSkills(),s)}));function fp(){const[e,t]=R.useState({id:null,type:null}),n=R.useCallback(l=>t({id:l,type:"delete"}),[]),s=R.useCallback(()=>t({id:null,type:null}),[]),a=R.useCallback((l,u)=>e.id===l&&e.type===u,[e.id,e.type]);return{requestDelete:n,clearConfirm:s,isConfirming:a}}function mp({onConfirm:e,onCancel:t}){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:t,className:"px-1.5 py-0.5 rounded text-text-muted text-xs hover:bg-bg-primary transition-colors",children:"Cancel"})]})}function pp({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(pl,{})})}function du({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(ap,{})})}function ji({label:e,value:t,onChange:n,placeholder:s,readOnly:a,hint:l,mono:u}){return o.jsxs("div",{children:[o.jsxs("label",{className:"block text-xs text-text-secondary mb-1",children:[e,l&&o.jsx("span",{className:"text-text-muted ml-1",children:l})]}),o.jsx("input",{value:t,onChange:c=>n(c.target.value),readOnly:a,placeholder:s,className:`w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary ${u?"font-mono":""} ${a?"opacity-60":""}`})]})}function Kj({onCancel:e,onSave:t,saving:n,saveDisabled:s}){return o.jsxs("div",{className:"flex justify-end gap-2 pt-2 border-t border-border",children:[o.jsx(tt,{variant:"secondary",onClick:e,children:"Cancel"}),o.jsx(tt,{variant:"primary",onClick:t,disabled:n||s,children:n?"Saving...":"Save"})]})}function gp({message:e}){return o.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded",children:e})}function wS({description:e,onNew:t,loading:n,hasItems:s,children:a}){return o.jsxs(o.Fragment,{children:[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(tt,{variant:"primary",size:"sm",onClick:t,children:"+ New"})})]}),n&&!s?o.jsx("div",{className:"text-text-muted text-sm",children:"Loading..."}):s?a:o.jsx("div",{className:"text-text-muted text-sm",children:"No items defined."})]})}function CS({label:e="Custom",children:t}){return o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:e}),o.jsx("div",{className:"space-y-2",children:t})]})}function kS({description:e,onNew:t,newLabel:n="+ 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(tt,{variant:"primary",size:"sm",onClick:t,children:n})})]})}function ES({isBuiltIn:e,isConfirmingDelete:t,onView:n,onEdit:s,onDuplicate:a,onDelete:l,children:u}){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:u}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[e&&n&&o.jsx("button",{onClick:n,className:"p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",title:"View",children:o.jsx(uu,{})}),o.jsx(du,{onClick:a}),!e&&s&&o.jsx(Fs,{onClick:s}),!e&&(t?o.jsx(mp,{onConfirm:()=>{l==null||l()},onCancel:()=>{}}):o.jsx(pp,{onClick:()=>l==null?void 0:l()}))]})]})}function Yj({id:e,name:t,description:n,isBuiltIn:s,isConfirmingDelete:a,onView:l,onEdit:u,onDuplicate:c,onDelete:h}){return o.jsxs(ES,{isBuiltIn:s,isConfirmingDelete:a,onView:l,onEdit:u,onDuplicate:c,onDelete:h,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-text-primary text-sm font-medium",children:t}),o.jsx("span",{className:"text-text-muted text-xs font-mono",children:e})]}),n&&o.jsx("p",{className:"text-text-muted text-xs truncate",children:n})]})}function jS({loading:e,hasItems:t,loadingLabel:n,emptyLabel:s,children:a}){return e&&!t?o.jsx("div",{className:"text-text-muted text-sm",children:n}):t?o.jsx("div",{className:"space-y-4",children:a}):s?o.jsx("div",{className:"text-text-muted text-sm",children:s}):null}function NS({name:e,id:t,nameLabel:n="Name",idLabel:s="ID",namePlaceholder:a="My Item",idPlaceholder:l="my-item",nameHint:u,readOnlyId:c=!1,readOnlyHint:h="(read-only)",onNameChange:f,onIdChange:p}){return o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(ji,{label:n,value:e,onChange:f,placeholder:a,hint:u}),o.jsx(ji,{label:s,value:t,onChange:p,readOnly:c,placeholder:l,hint:c?h:void 0,mono:!0})]})}function TS(e={}){const{initialData:t={}}=e,[n,s]=R.useState("list"),[a,l]=R.useState(null),[u,c]=R.useState(""),[h,f]=R.useState(!1),[p,m]=R.useState(t),_=R.useCallback(()=>{m(t),c(""),l(null)},[t]),x=R.useCallback(S=>{s(S),S==="list"&&_()},[_]),w=R.useCallback(S=>{m(v=>typeof S=="function"?S(v):S)},[]),k=R.useCallback((S,v={})=>{l(S),s("edit"),m({...v}),c("")},[]),y=R.useCallback(()=>{l(null),s("edit"),m(t),c("")},[t]);return{view:n,editingId:a,formError:u,saving:h,formData:p,setView:x,setEditingId:l,setFormError:c,setFormData:w,setSaving:f,resetForm:_,startEditing:k,startNew:y}}function Bv({skill:e,isBuiltIn:t,isConfirmingDelete:n,onView:s,onEdit:a,onDuplicate:l,onDelete:u}){return o.jsx(Yj,{id:e.id,name:e.name,description:e.description,isBuiltIn:t,isConfirmingDelete:n,onView:s,onEdit:a,onDuplicate:l,onDelete:u})}function Xj({isOpen:e}){const t=Tr(z=>z.defaults),n=Tr(z=>z.userItems),s=Tr(z=>z.projectItems),a=Tr(z=>z.loading),l=Tr(z=>z.fetchSkills),u=Tr(z=>z.fetchSkill),c=Tr(z=>z.fetchDefaultContent),h=Tr(z=>z.createSkill),f=Tr(z=>z.updateSkill),p=Tr(z=>z.deleteSkill),{view:m,editingId:_,formError:x,saving:w,formData:k,setView:y,setEditingId:S,setFormError:v,setFormData:b,setSaving:E}=TS(),{clearConfirm:T}=fp();R.useEffect(()=>{e&&(l(),y("list"),S(null),T())},[e,l,T]);const N=(z,X,ne,F)=>{b({name:F??z.metadata.name,id:ne??z.metadata.id,description:z.metadata.description??"",version:z.metadata.version??"1.0.0",prompt:z.prompt,isReadOnly:X,destination:"user"})},L=async z=>{if(t.some(ne=>ne.id===z)){const ne=await c(z);if(!ne)return;N(ne,!0),S(z),v(""),y("edit")}else{const ne=await u(z);if(!ne)return;N(ne,!0),S(z),v(""),y("edit")}},A=async z=>{const ne=t.some(M=>M.id===z)?await c(z):await u(z);if(!ne)return;const F=`${z}-copy-${Date.now()}`;N(ne,!1,F,`${ne.metadata.name} (copy)`),S(null),v(""),y("edit")},D=()=>{b({name:"",id:"",description:"",version:"1.0.0",prompt:"",isReadOnly:!1,destination:"user"}),y("edit")},B=async z=>{const X=await u(z);X&&(N(X,!1),S(z),v(""),y("edit"))},q=async z=>{await p(z),T()},W=async()=>{const z=_??k.id;if(!z||!k.name||!k.prompt){v("Name, ID, and prompt are required.");return}E(!0),v("");const X={metadata:{id:z,name:k.name,description:k.description,version:k.version},prompt:k.prompt},ne=_?await f(_,X):await h(X,k.destination);if(E(!1),!ne.success){v(ne.error??"Failed to save skill.");return}y("list")},O=z=>{b(X=>({...X,name:z})),_||b(X=>({...X,id:z.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}))},V=k.isReadOnly;if(m==="edit")return 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:V?k.name:_?"Edit Skill":"New Skill"}),o.jsx("button",{onClick:()=>y("list"),className:"text-text-muted hover:text-text-primary",children:"Cancel"})]}),x&&o.jsx(gp,{message:x}),o.jsxs("div",{className:"space-y-3 mb-3",children:[o.jsx(NS,{name:k.name,id:k.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Skill",idPlaceholder:"my-skill",readOnlyId:!0,onNameChange:O,onIdChange:()=>{}}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(ji,{label:"Description",value:k.description,onChange:z=>b(X=>({...X,description:z})),placeholder:"What this skill does...",readOnly:V}),o.jsx(ji,{label:"Version",value:k.version,onChange:z=>b(X=>({...X,version:z})),placeholder:"1.0.0",readOnly:V})]})]}),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:z=>b(X=>({...X,prompt:z.target.value})),readOnly:V,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.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[o.jsx("label",{className:"text-xs text-text-secondary",children:"Save to:"}),o.jsxs("select",{value:k.destination,onChange:z=>b(X=>({...X,destination:z.target.value})),className:"px-2 py-1 bg-bg-tertiary border border-border rounded text-xs focus:outline-none focus:ring-1 focus:ring-accent-primary",children:[o.jsx("option",{value:"user",children:"Global config"}),o.jsx("option",{value:"project",children:"Project (.openfox/)"})]})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 border-t border-border flex-shrink-0",children:[o.jsx(tt,{variant:"secondary",onClick:()=>y("list"),children:"Cancel"}),V?o.jsx(tt,{variant:"primary",onClick:()=>{b(z=>({...z,name:z.name+" (copy)",id:`${_}-copy-${Date.now()}`,isReadOnly:!1})),S(null)},children:"Duplicate & Customize"}):o.jsx(tt,{variant:"primary",onClick:W,disabled:w||!k.name||!k.id||!k.prompt,children:w?"Saving...":"Save"})]})]});function G({items:z}){return z.map(X=>o.jsx(Bv,{skill:X,isBuiltIn:!1,isConfirmingDelete:!1,onView:()=>L(X.id),onEdit:()=>B(X.id),onDuplicate:()=>A(X.id),onDelete:()=>q(X.id)},X.id))}return o.jsxs("div",{children:[o.jsx(kS,{description:"Skills provide domain-specific knowledge that agents can load on demand.",onNew:D}),o.jsxs(jS,{loading:a,hasItems:t.length>0||n.length>0,loadingLabel:"Loading skills...",emptyLabel:"No skills created yet.",children:[t.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:t.map(z=>o.jsx(Bv,{skill:z,isBuiltIn:!0,isConfirmingDelete:!1,onView:()=>L(z.id),onDuplicate:()=>A(z.id)},z.id))})]}),n.length>0&&o.jsx(CS,{children:o.jsx(G,{items:n})}),s.length>0&&o.jsxs("div",{className:"mt-4",children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Project"}),o.jsx("div",{className:"space-y-2",children:o.jsx(G,{items:s})})]})]})]})}function Hu(){const e=an(a=>a.settings),t=an(a=>a.loading),n=an(a=>a.getSetting),s=an(a=>a.setSetting);return{settings:e,loading:t,getSetting:n,setSetting:s}}function Qj({isOpen:e}){const{settings:t,loading:n,getSetting:s,setSetting:a}=Hu(),l=t[ze.GLOBAL_INSTRUCTIONS]??"",u=n[ze.GLOBAL_INSTRUCTIONS]??!1,[c,h]=R.useState(l),[f,p]=R.useState(!1),[m,_]=R.useState(!1);R.useEffect(()=>{e&&s(ze.GLOBAL_INSTRUCTIONS)},[e,s]),R.useEffect(()=>{h(l),p(!1)},[l]);const x=async()=>{_(!0),await a(ze.GLOBAL_INSTRUCTIONS,c),_(!1),p(!1)},w=()=>{h(l),p(!1)},k=u||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=>{h(y.target.value),p(!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:k})]}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(tt,{variant:"secondary",onClick:w,disabled:!f,children:"Discard"}),o.jsx(tt,{variant:"primary",onClick:x,disabled:!f||k,children:m?"Saving...":"Save"})]})]})}function Jj(e){const t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);if(t){const n=parseInt(t[1]??"0",16),s=parseInt(t[2]??"0",16),a=parseInt(t[3]??"0",16);return`${n} ${s} ${a}`}return e}function vi(e){const t=e.split(" ").map(n=>parseInt(n,10));return t.length===3&&t.every(n=>!isNaN(n))?`#${t.map(n=>(n??0).toString(16).padStart(2,"0")).join("")}`:e}function Zj({isOpen:e,isNew:t,basePresetId:n,presetName:s,initialTokens:a,onClose:l,onSave:u}){const[c,h]=R.useState(a),[f,p]=R.useState(s);R.useEffect(()=>{h(a),p(s)},[a,s]);const m=(y,S)=>{const v=S.startsWith("#")?Jj(S):S;h(b=>({...b,[y]:v}))},_=()=>{u(f.trim()||"Untitled",{...c})},x=fS.reduce((y,S)=>{const v=S.category;return y[v]||(y[v]=[]),y[v].push(S),y},{}),w={background:"Backgrounds",surface:"Surfaces",text:"Text",accent:"Accents",border:"Border"},k=Or.find(y=>y.id===n);return o.jsx(Dt,{isOpen:e,onClose:l,size:"lg",title:t?"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:l,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:_,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:f,onChange:y=>p(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"})]}),!t&&o.jsxs("div",{className:"text-xs text-text-muted",children:["Based on ",o.jsx("span",{className:"text-text-primary",children:k==null?void 0:k.name})]}),Object.entries(x).map(([y,S])=>o.jsxs("div",{className:"space-y-3",children:[o.jsx("h4",{className:"text-xs font-medium text-text-muted uppercase",children:w[y]??y}),o.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:S.map(v=>o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("label",{htmlFor:v.key,className:"text-xs text-text-muted",children:v.label}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"color",id:v.key,value:vi(c[v.key]??v.defaultValue),onChange:b=>m(v.key,b.target.value),className:"w-8 h-8 rounded cursor-pointer border border-border bg-transparent flex-shrink-0"}),o.jsx("input",{type:"text",value:c[v.key]??v.defaultValue,onChange:b=>m(v.key,b.target.value),className:"flex-1 min-w-0 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"})]})]},v.key))})]},y))]})})}function eN(){const[e,t]=R.useState(null),n=Ut(b=>b.currentPreset),s=Ut(b=>b.isCustom),a=Ut(b=>b.basePreset),l=Ut(b=>b.isSystem),u=Ut(b=>b.applyPreset),c=Ut(b=>b.applyUserPreset),h=Ut(b=>b.deleteUserPreset),f=Ut(b=>b.saveTheme),p=Ut(b=>b.userPresets),m=b=>{b==="system"?(u(b),f(JSON.stringify({preset:"system"})).catch(()=>{})):(u(b),f(JSON.stringify({preset:b})).catch(()=>{}))},_=b=>{c(b)},x=b=>{const E=Or.find(T=>T.id===b);E&&t({type:"new",presetIndex:p.length,basePresetId:b,presetName:E.name+" Copy",tokens:{...E.tokens}})},w=b=>{const E=p[b];if(!E)return;const T=Or.find(L=>L.id===E.basePreset),N=T?{...T.tokens,...E.tokens}:E.tokens;t({type:"edit",presetIndex:b,basePresetId:E.basePreset,presetName:E.name,tokens:N})},k=(b,E)=>{if(!e)return;const T=[...p];if(e.type==="new"){const N={id:"custom-"+Date.now(),name:b,basePreset:e.basePresetId,tokens:E};T.push(N);const L=T.length-1;Ut.setState({userPresets:T}),Ut.getState().saveUserPresets(),Ut.getState().applyUserPreset(L)}else{const N=T[e.presetIndex];N&&(T[e.presetIndex]={...N,name:b,tokens:E}),Ut.setState({userPresets:T}),Ut.getState().saveUserPresets(),Ut.getState().applyUserPreset(e.presetIndex)}t(null)},y=()=>{t(null)},S=(b,E)=>{b.stopPropagation(),h(E)},v=l?"system":s?a:n;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:"flex flex-wrap gap-2 pb-2",children:Or.map(b=>{const E=b.id===v&&!s;return o.jsxs("div",{className:"relative group",children:[o.jsxs("button",{type:"button",onClick:()=>m(b.id),className:`flex flex-col items-center gap-2 px-3 py-3 rounded-lg border transition-colors min-w-[80px] ${E?"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:b.id==="system"?"transparent":vi(b.tokens["color-bg-primary"]??"#000"),borderColor:vi(b.tokens["color-border"]??"#000")},children:b.id==="system"?o.jsx("div",{className:"w-4 h-4 rounded-full",style:{background:"linear-gradient(135deg, #000 50%, #fff 50%)"}}):o.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:vi(b.tokens["color-text-primary"]??"#fff")}})}),o.jsx("span",{className:"text-xs",children:b.name})]}),b.id!=="system"&&o.jsx("button",{type:"button",onClick:T=>{T.stopPropagation(),x(b.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:"✎"})})]},b.id)})}),p.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:p.map((b,E)=>{const T=Or.find(L=>L.id===b.basePreset),N=T?{...T.tokens,...b.tokens}:b.tokens;return o.jsxs("div",{className:"relative group",children:[o.jsxs("button",{type:"button",onClick:()=>_(E),className:`w-full flex flex-col items-center gap-2 px-3 py-3 rounded-lg border transition-colors ${s&&a===b.basePreset&&v===b.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:vi(N["color-bg-primary"]??"#000"),borderColor:vi(N["color-border"]??"#000")},children:o.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:vi(N["color-text-primary"]??"#fff")}})}),o.jsx("span",{className:"text-xs truncate w-full text-center",children:b.name})]}),o.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),w(E)},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:L=>S(L,E),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(gl,{className:"w-3 h-3"})})]},b.id)})})]}),e&&o.jsx(Zj,{isOpen:!0,isNew:e.type==="new",presetIndex:e.presetIndex,basePresetId:e.basePresetId,presetName:e.presetName,initialTokens:e.tokens,onClose:y,onSave:k})]})}function tN(){return o.jsx(eN,{})}function nN(){const{settings:e,loading:t,getSetting:n,setSetting:s}=Hu(),a=t[ze.DISPLAY_SHOW_THINKING]??!1,l=[{key:ze.DISPLAY_SHOW_THINKING,label:"Show thinking blocks",description:"Display AI reasoning content in the feed"},{key:ze.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT,label:"Show expanded tool output",description:"Always show full tool call details instead of compact view"},{key:ze.DISPLAY_SHOW_STATS,label:"Show stats bar",description:"Display model, tokens, and timing information"},{key:ze.DISPLAY_SHOW_AGENT_DEFINITIONS,label:"Show agent definitions",description:"Display agent definition injections in the feed"},{key:ze.DISPLAY_SHOW_WORKFLOW_BARS,label:"Show workflow bars",description:"Display workflow start and end markers"},{key:ze.DISPLAY_SHOW_SYNTAX_HIGHLIGHTING,label:"Show syntax highlighting",description:"Nicer formatting, but very slow - does not affect red/green diff coloring"}],u=Object.fromEntries(l.map(p=>[p.key,e[p.key]??"true"])),[c,h]=R.useState(()=>Object.fromEntries(l.map(p=>[p.key,u[p.key]==="true"])));R.useEffect(()=>{l.forEach(p=>n(p.key))},[n]),R.useEffect(()=>{h(Object.fromEntries(l.map(p=>[p.key,u[p.key]==="true"])))},[JSON.stringify(u)]);const f=async p=>{const m=String(!c[p]);h(_=>({..._,[p]:!_[p]})),await s(p,m)};return a?o.jsx("div",{className:"text-sm text-text-muted",children:"Loading..."}):o.jsxs("div",{className:"space-y-6",children:[o.jsx(tN,{}),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:l.map(({key:p,label:m,description:_})=>o.jsxs("label",{className:"flex items-start justify-between gap-3 cursor-pointer",children:[o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("div",{className:"text-sm text-text-primary font-medium",children:m}),o.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:_})]}),o.jsx("button",{type:"button",onClick:()=>f(p),className:`relative inline-flex h-6 w-11 flex-shrink-0 items-center rounded-full transition-colors ${c[p]?"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[p]?"translate-x-6":"translate-x-1"}`})})]},p))})]})]})}function rN({enabled:e,onClick:t}){return o.jsx("button",{type:"button",onClick:t,className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${e?"bg-accent-primary":"bg-bg-tertiary"}`,children:o.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${e?"translate-x-6":"translate-x-1"}`})})}function sN(e){try{return new RegExp(e),!0}catch{return!1}}function iN({value:e,onChange:t}){const[n,s]=R.useState({}),a=(h,f)=>{const p=e.patterns.map((m,_)=>_===h?{...m,...f}:m);t({...e,patterns:p})},l=h=>{const f=e.patterns.filter((p,m)=>m!==h);t({...e,patterns:f})},u=()=>{const h={field:"content",pattern:"",action:"retry",active:!0};t({...e,patterns:[...e.patterns,h]})},c=(h,f)=>{s(p=>({...p,[h]:f.length>0&&!sN(f)})),a(h,{pattern:f})};return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-sm font-medium text-text-primary",children:"Max Retries Per Turn"}),o.jsx("input",{type:"number",min:1,max:100,value:e.maxRetriesPerTurn,onChange:h=>{const f=parseInt(h.target.value,10),p=isNaN(f)?10:Math.max(1,Math.min(100,f));t({...e,maxRetriesPerTurn:p})},className:"mt-1 block w-24 px-2 py-1 text-sm bg-bg-secondary border border-border rounded"})]}),e.patterns.length===0?o.jsx("p",{className:"text-sm text-text-muted",children:"No retry patterns configured."}):o.jsxs("table",{className:"w-full text-sm",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"text-left text-text-muted border-b border-border",children:[o.jsx("th",{className:"pb-2 pr-2 w-12",children:"Active"}),o.jsx("th",{className:"pb-2 pr-2",children:"Field"}),o.jsx("th",{className:"pb-2 pr-2",children:"Pattern"}),o.jsx("th",{className:"pb-2 pr-2",children:"Action"}),o.jsx("th",{className:"pb-2 w-8"})]})}),o.jsx("tbody",{children:e.patterns.map((h,f)=>o.jsxs("tr",{className:"border-b border-border",children:[o.jsx("td",{className:"py-2 pr-2",children:o.jsx("input",{type:"checkbox",checked:h.active,onChange:()=>a(f,{active:!h.active}),className:"accent-accent-primary","aria-label":`Toggle pattern ${f+1}`})}),o.jsx("td",{className:"py-2 pr-2",children:o.jsxs("select",{value:h.field,onChange:p=>a(f,{field:p.target.value}),className:"px-2 py-1 bg-bg-secondary border border-border rounded text-sm",children:[o.jsx("option",{value:"content",children:"content"}),o.jsx("option",{value:"thinking",children:"thinking"}),o.jsx("option",{value:"both",children:"both"})]})}),o.jsx("td",{className:"py-2 pr-2",children:o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("input",{type:"text",value:h.pattern,onChange:p=>c(f,p.target.value),placeholder:"regex pattern",className:"flex-1 px-2 py-1 bg-bg-secondary border border-border rounded text-sm font-mono"}),h.pattern.length>0&&o.jsx("span",{className:`text-sm ${n[f]?"text-red-500":"text-green-500"}`,children:n[f]?"✗":"✓"})]})}),o.jsx("td",{className:"py-2 pr-2 text-text-muted",children:"retry"}),o.jsx("td",{className:"py-2",children:o.jsx("button",{onClick:()=>l(f),title:"Remove pattern",className:"text-text-muted hover:text-red-500 transition-colors",children:"×"})})]},f))})]}),o.jsx(tt,{variant:"secondary",onClick:u,children:"Add Pattern"})]})}function aN({onClose:e}){const[,t]=cr(),{settings:n,getSetting:s,setSetting:a}=Hu(),l=n[ze.DISPLAY_SHOW_OPEN_IN_EDITOR]==="true",u=n[ze.LLM_DYNAMIC_SYSTEM_PROMPT]==="true",[c,h]=R.useState({openInEditor:l,dynamicPrompt:u}),[f,p]=R.useState({patterns:[],maxRetriesPerTurn:10});R.useEffect(()=>{h({openInEditor:l,dynamicPrompt:u})},[l,u]),R.useEffect(()=>{s(ze.DISPLAY_SHOW_OPEN_IN_EDITOR),s(ze.LLM_DYNAMIC_SYSTEM_PROMPT),s(ze.RETRY_PATTERNS)},[s]),R.useEffect(()=>{const k=n[ze.RETRY_PATTERNS];if(k)try{p(JSON.parse(k))}catch{}},[n]);const m=R.useCallback(k=>{p(k),a(ze.RETRY_PATTERNS,JSON.stringify(k))},[a]),_=()=>{const k=!c.openInEditor;h(y=>({...y,openInEditor:k})),a(ze.DISPLAY_SHOW_OPEN_IN_EDITOR,String(k))},x=()=>{const k=!c.dynamicPrompt;h(y=>({...y,dynamicPrompt:k})),a(ze.LLM_DYNAMIC_SYSTEM_PROMPT,String(k))};function w(){e(),t("/onboarding")}return o.jsxs("div",{className:"space-y-6",children:[o.jsx(zv,{title:"Dynamic System Prompt",description:"Rebuild the system prompt on every turn. When disabled, changes are applied on demand via the context header for better cache performance.",enabled:c.dynamicPrompt,onToggle:x,boldTitle:!0}),o.jsx("hr",{className:"border-border"}),o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary mb-3",children:"Auto-Retry Patterns"}),o.jsx("p",{className:"text-xs text-text-muted mb-3",children:'Define regex patterns that, when matched against LLM responses mid-stream, trigger an automatic retry with a "continue" prompt. The content that triggered the match is preserved in the chat feed.'}),o.jsx(iN,{value:f,onChange:m})]}),o.jsx("hr",{className:"border-border"}),o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary mb-3",children:"Integrations"}),o.jsx(zv,{title:'Show "Open in VSCode" links',description:"Display a link on file reads to open the file directly in VS Code.",enabled:c.openInEditor,onToggle:_})]}),o.jsx("hr",{className:"border-border"}),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(tt,{variant:"secondary",onClick:w,children:"Launch Onboarding"})]})]})}function zv({title:e,description:t,enabled:n,onToggle:s,boldTitle:a}){return o.jsxs("label",{className:"flex items-start justify-between gap-3 cursor-pointer",children:[o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("div",{className:`text-sm ${a?"font-medium":""} text-text-primary`,children:e}),o.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:t})]}),o.jsx("div",{className:"flex-shrink-0",children:o.jsx(rN,{enabled:n,onClick:s})})]})}function oN({label:e,binding:t,isRecording:n,onStartRecording:s,onBindingRecorded:a,onCancelRecording:l}){const u=R.useRef(null),c=R.useRef(0),h=R.useRef("");return R.useEffect(()=>{if(!n)return;const f=new Set(["Control","Shift","Alt","Meta"]);let p=[];const m=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){l();return}if(f.has(x.key)){x.ctrlKey&&!p.includes("ctrl")&&p.push("ctrl"),x.metaKey&&!p.includes("meta")&&p.push("meta"),x.altKey&&!p.includes("alt")&&p.push("alt"),x.shiftKey&&!p.includes("shift")&&p.push("shift");return}if(p.length>0||x.ctrlKey||x.metaKey||x.altKey||x.shiftKey){const y=[...p];x.ctrlKey&&!y.includes("ctrl")&&y.push("ctrl"),x.metaKey&&!y.includes("meta")&&y.push("meta"),x.altKey&&!y.includes("alt")&&y.push("alt"),x.shiftKey&&!y.includes("shift")&&y.push("shift"),a({type:"chord",key:Mv(x),modifiers:y});return}const w=Date.now(),k=Mv(x);if(k===h.current&&w-c.current<400){a({type:"double-press",key:k,threshold:300});return}c.current=w,h.current=k},_=x=>{x.key==="Control"&&(p=p.filter(w=>w!=="ctrl")),x.key==="Shift"&&(p=p.filter(w=>w!=="shift")),x.key==="Alt"&&(p=p.filter(w=>w!=="alt")),x.key==="Meta"&&(p=p.filter(w=>w!=="meta"))};return window.addEventListener("keydown",m,!0),window.addEventListener("keyup",_,!0),()=>{window.removeEventListener("keydown",m,!0),window.removeEventListener("keyup",_,!0)}},[n,a,l]),o.jsxs("div",{ref:u,className:`flex items-center justify-between px-3 py-2 rounded transition-colors ${n?"bg-accent-primary/10 ring-1 ring-accent-primary":"hover:bg-bg-tertiary"}`,children:[o.jsx("span",{className:"text-sm text-text-primary",children:e}),o.jsx("div",{className:"flex items-center gap-2",children:n?o.jsx("span",{className:"text-xs text-accent-primary font-medium animate-pulse",children:"Press shortcut..."}):o.jsx("button",{type:"button",onClick:s,className:"px-2 py-0.5 text-xs font-mono bg-bg-tertiary text-text-secondary rounded border border-border hover:border-accent-primary hover:text-accent-primary transition-colors",children:yS(t)})})]})}function lN(){const{settings:e,loading:t,setSetting:n}=Hu(),s=e[ze.KEYBINDINGS],a=t[ze.KEYBINDINGS]??!1,l=wm(s),[u,c]=R.useState(null),h=[{id:"terminalToggle",label:"Toggle Terminal",binding:l.terminalToggle},{id:"quickAction",label:"Quick Action",binding:l.quickAction},...l.agentSwitching.map((_,x)=>({id:`agentSwitching.${x}`,label:`Switch to Agent ${x+1}`,binding:_}))],f=_=>{c(_)},p=R.useCallback(_=>{if(!u)return;const x=wm(s),w=structuredClone(x);if(u.startsWith("agentSwitching.")){const k=parseInt(u.split(".")[1],10);w.agentSwitching[k]=_}else u==="terminalToggle"?w.terminalToggle=_:u==="quickAction"&&(w.quickAction=_);c(null),n(ze.KEYBINDINGS,JSON.stringify(w))},[u,s,n]),m=()=>{n(ze.KEYBINDINGS,JSON.stringify(Aa))};return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Keyboard Shortcuts"}),o.jsx("button",{type:"button",onClick:m,disabled:a,className:"text-xs text-text-muted hover:text-text-primary px-2 py-1 rounded hover:bg-bg-tertiary transition-colors disabled:opacity-30",children:"Reset to defaults"})]}),a?o.jsx("div",{className:"text-sm text-text-muted",children:"Loading..."}):o.jsx("div",{className:"space-y-1",children:h.map(_=>o.jsx(oN,{label:_.label,binding:_.binding,isRecording:u===_.id,onStartRecording:()=>f(_.id),onBindingRecorded:p,onCancelRecording:()=>c(null)},_.id))})]})}function cN({isOpen:e,onClose:t}){const[n,s]=R.useState("instructions"),a=()=>{try{zt.send("context.checkDynamic",{})}catch{}t()};return o.jsx(Dt,{isOpen:e,onClose:a,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 overflow-x-auto scrollbar-hide",children:[o.jsx(Sa,{label:"Instructions",active:n==="instructions",onClick:()=>s("instructions")}),o.jsx(Sa,{label:"Skills",active:n==="skills",onClick:()=>s("skills")}),o.jsx(Sa,{label:"Notifications",active:n==="notifications",onClick:()=>s("notifications")}),o.jsx(Sa,{label:"Display",active:n==="display",onClick:()=>s("display")}),o.jsx(Sa,{label:"Keybindings",active:n==="keybindings",onClick:()=>s("keybindings")}),o.jsx(Sa,{label:"Advanced",active:n==="advanced",onClick:()=>s("advanced")})]}),n==="instructions"&&o.jsx(Qj,{isOpen:e}),n==="skills"&&o.jsx(Xj,{isOpen:e}),n==="notifications"&&o.jsx("div",{className:"max-h-[60vh] overflow-y-auto",children:o.jsx(qj,{})}),n==="display"&&o.jsx(nN,{}),n==="keybindings"&&o.jsx(lN,{}),n==="advanced"&&o.jsx(aN,{onClose:t})]})})}function Sa({label:e,active:t,onClick:n}){return o.jsx("button",{onClick:n,className:`px-4 py-2 text-sm font-medium border-b-2 transition-colors whitespace-nowrap ${t?"border-accent-primary text-accent-primary":"border-transparent text-text-muted hover:text-text-secondary hover:border-border"}`,children:e})}var Of={exports:{}},Hv;function uN(){return Hv||(Hv=1,(function(e,t){(function(n,s){e.exports=s()})(globalThis,(()=>(()=>{var n={4567:function(u,c,h){var f=this&&this.__decorate||function(v,b,E,T){var N,L=arguments.length,A=L<3?b:T===null?T=Object.getOwnPropertyDescriptor(b,E):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(v,b,E,T);else for(var D=v.length-1;D>=0;D--)(N=v[D])&&(A=(L<3?N(A):L>3?N(b,E,A):N(b,E))||A);return L>3&&A&&Object.defineProperty(b,E,A),A},p=this&&this.__param||function(v,b){return function(E,T){b(E,T,v)}};Object.defineProperty(c,"__esModule",{value:!0}),c.AccessibilityManager=void 0;const m=h(9042),_=h(9924),x=h(844),w=h(4725),k=h(2585),y=h(3656);let S=c.AccessibilityManager=class extends x.Disposable{constructor(v,b,E,T){super(),this._terminal=v,this._coreBrowserService=E,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 _.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
|
+
*/var uv;function y2(){if(uv)return Tf;uv=1;var e=Ru();function t(m,_){return m===_&&(m!==0||1/m===1/_)||m!==m&&_!==_}var n=typeof Object.is=="function"?Object.is:t,s=e.useState,a=e.useEffect,l=e.useLayoutEffect,u=e.useDebugValue;function c(m,_){var x=_(),w=s({inst:{value:x,getSnapshot:_}}),k=w[0].inst,y=w[1];return l(function(){k.value=x,k.getSnapshot=_,h(k)&&y({inst:k})},[m,x,_]),a(function(){return h(k)&&y({inst:k}),m(function(){h(k)&&y({inst:k})})},[m]),u(x),x}function h(m){var _=m.getSnapshot;m=m.value;try{var x=_();return!n(m,x)}catch{return!0}}function f(m,_){return _()}var p=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?f:c;return Tf.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:p,Tf}var dv;function v2(){return dv||(dv=1,Nf.exports=y2()),Nf.exports}var b2=v2();const S2=i2.useInsertionEffect,w2=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",C2=w2?R.useLayoutEffect:R.useEffect,k2=S2||C2,Z0=e=>{const t=R.useRef([e,(...n)=>t[0](...n)]).current;return k2(()=>{t[0]=e}),t[1]},E2="popstate",tp="pushState",np="replaceState",j2="hashchange",hv=[E2,tp,np,j2],N2=e=>{for(const t of hv)addEventListener(t,e);return()=>{for(const t of hv)removeEventListener(t,e)}},eS=(e,t)=>b2.useSyncExternalStore(N2,e,t),fv=()=>location.search,T2=({ssrSearch:e}={})=>eS(fv,e!=null?()=>e:fv),mv=()=>location.pathname,A2=({ssrPath:e}={})=>eS(mv,e!=null?()=>e:mv),L2=(e,{replace:t=!1,state:n=null}={})=>history[t?np:tp](n,"",e),D2=(e={})=>[A2(e),L2],pv=Symbol.for("wouter_v3");if(typeof history<"u"&&typeof window[pv]>"u"){for(const e of[tp,np]){const t=history[e];history[e]=function(){const n=t.apply(this,arguments),s=new Event(e);return s.arguments=arguments,dispatchEvent(s),n}}Object.defineProperty(window,pv,{value:!0})}const R2=(e,t)=>t.toLowerCase().indexOf(e.toLowerCase())?"~"+t:t.slice(e.length)||"/",tS=(e="")=>e==="/"?"":e,O2=(e,t)=>e[0]==="~"?e.slice(1):tS(t)+e,M2=(e="",t)=>R2(gv(tS(e)),gv(t)),gv=e=>{try{return decodeURI(e)}catch{return e}},nS={hook:D2,searchHook:T2,parser:_2,base:"",ssrPath:void 0,ssrSearch:void 0,ssrContext:void 0,hrefs:e=>e,aroundNav:(e,t,n)=>e(t,n)},rS=R.createContext(nS),Ha=()=>R.useContext(rS),sS={},iS=R.createContext(sS),I2=()=>R.useContext(iS),Mu=e=>{const[t,n]=e.hook(e);return[M2(e.base,t),Z0((s,a)=>e.aroundNav(n,O2(s,e.base),a))]},cr=()=>Mu(Ha()),rp=(e,t,n,s)=>{const{pattern:a,keys:l}=t instanceof RegExp?{keys:!1,pattern:t}:e(t||"*",s),u=a.exec(n)||[],[c,...h]=u;return c!==void 0?[!0,(()=>{const f=l!==!1?Object.fromEntries(l.map((m,_)=>[m,h[_]])):u.groups;let p={...h};return f&&Object.assign(p,f),p})(),...s?[c]:[]]:[!1,null]},sp=e=>rp(Ha().parser,e,cr()[0]),P2=({children:e,...t})=>{var p,m,_;const n=Ha(),s=t.hook?nS:n;let a=s;const[l,u=t.ssrSearch??""]=((p=t.ssrPath)==null?void 0:p.split("?"))??[];l&&(t.ssrSearch=u,t.ssrPath=l),t.hrefs=t.hrefs??((m=t.hook)==null?void 0:m.hrefs),t.searchHook=t.searchHook??((_=t.hook)==null?void 0:_.searchHook);let c=R.useRef({}),h=c.current,f=h;for(let x in s){const w=x==="base"?s[x]+(t[x]??""):t[x]??s[x];h===f&&w!==f[x]&&(c.current=f={...f}),f[x]=w,(w!==s[x]||w!==a[x])&&(a=f)}return R.createElement(rS.Provider,{value:a,children:e})},xv=({children:e,component:t},n)=>t?R.createElement(t,{params:n}):typeof e=="function"?e(n):e,B2=e=>{let t=R.useRef(sS);const n=t.current;return t.current=Object.keys(e).length!==Object.keys(n).length||Object.entries(e).some(([s,a])=>a!==n[s])?e:n},Ho=({path:e,nest:t,match:n,...s})=>{const a=Ha(),[l]=Mu(a),[u,c,h]=n??rp(a.parser,e,l,t),f=B2({...I2(),...c});if(!u)return null;const p=h?R.createElement(P2,{base:h},xv(s,f)):xv(s,f);return R.createElement(iS.Provider,{value:f,children:p})},Gn=R.forwardRef((e,t)=>{const n=Ha(),[s,a]=Mu(n),{to:l="",href:u=l,onClick:c,asChild:h,children:f,className:p,replace:m,state:_,transition:x,...w}=e,k=Z0(S=>{S.ctrlKey||S.metaKey||S.altKey||S.shiftKey||S.button!==0||(c==null||c(S),S.defaultPrevented||(S.preventDefault(),a(u,e)))}),y=n.hrefs(u[0]==="~"?u.slice(1):n.base+u,n);return h&&R.isValidElement(f)?R.cloneElement(f,{onClick:k,href:y}):R.createElement("a",{...w,onClick:k,href:y,className:p!=null&&p.call?p(s===u):p,children:f,ref:t})}),aS=e=>Array.isArray(e)?e.flatMap(t=>aS(t&&t.type===R.Fragment?t.props.children:t)):[e],z2=({children:e,location:t})=>{const n=Ha(),[s]=Mu(n);for(const a of aS(e)){let l=0;if(R.isValidElement(a)&&(l=rp(n.parser,a.props.path,t||s,a.props.nest))[0])return R.cloneElement(a,{match:l})}return null};function H2(e){return typeof e=="object"&&e!==null&&"type"in e&&"payload"in e}function oS(){if(typeof crypto<"u"&&crypto.randomUUID)try{return crypto.randomUUID()}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}class $2{constructor(t){pe(this,"ws",null);pe(this,"handlers",new Set);pe(this,"statusHandler",null);pe(this,"baseUrl");pe(this,"isReconnecting",!1);pe(this,"connectingPromise",null);pe(this,"lastCloseCode",0);pe(this,"reconnectAttempts",0);pe(this,"manualReconnectScheduled",!1);this.baseUrl=t}getUrl(){const t=localStorage.getItem("openfox_token");if(t){const n=this.baseUrl.includes("?")?"&":"?";return`${this.baseUrl}${n}token=${encodeURIComponent(t)}`}return this.baseUrl}setToken(t){localStorage.setItem("openfox_token",t)}clearToken(){localStorage.removeItem("openfox_token")}hasToken(){return!!localStorage.getItem("openfox_token")}getLastCloseCode(){return this.lastCloseCode}onStatusChange(t){this.statusHandler=t}connect(){var t,n,s;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN?Promise.resolve():(this.lastCloseCode=0,this.isReconnecting=!1,this.connectingPromise&&((n=this.ws)==null?void 0:n.readyState)===WebSocket.CONNECTING?this.connectingPromise:(this.lastCloseCode=0,this.isReconnecting=!1,this.connectingPromise&&((s=this.ws)==null?void 0:s.readyState)===WebSocket.CONNECTING?(console.warn("[WS CLIENT] Connection already in progress, returning existing promise"),this.connectingPromise):(this.connectingPromise=new Promise((a,l)=>{try{const u=this.getUrl();this.ws=new WebSocket(u);const c=setTimeout(()=>{var h;((h=this.ws)==null?void 0:h.readyState)===WebSocket.CONNECTING&&(this.ws.close(),l(new Error("Connection timeout")))},5e3);this.ws.onopen=()=>{var h;clearTimeout(c),this.isReconnecting=!1,this.connectingPromise=null,(h=this.statusHandler)==null||h.call(this,"connected"),a()},this.ws.onclose=h=>{var f,p,m;clearTimeout(c),this.lastCloseCode=h.code,((f=this.ws)==null?void 0:f.readyState)===WebSocket.CONNECTING?(this.connectingPromise=null,(p=this.statusHandler)==null||p.call(this,"disconnected"),l(new Error(`Connection closed: ${h.code}`))):(this.connectingPromise=null,(m=this.statusHandler)==null||m.call(this,"disconnected"),this.attemptReconnect())},this.ws.onerror=h=>{clearTimeout(c),console.error("WebSocket error:",h),this.connectingPromise=null,l(h)},this.ws.onmessage=h=>{try{const f=JSON.parse(h.data);H2(f)&&this.handlers.forEach(p=>p(f))}catch(f){console.error("Failed to parse WebSocket message:",f)}}}catch(u){this.connectingPromise=null,l(u)}}),this.connectingPromise)))}attemptReconnect(){var a;if(([1e3,1005,1006,4e3].includes(this.lastCloseCode)||this.lastCloseCode===0)&&this.hasToken()){console.warn("[WS] Auth failure or initial failure with token - not auto-reconnecting, awaiting user action");return}if(this.isReconnecting||this.manualReconnectScheduled)return;this.isReconnecting=!0,(a=this.statusHandler)==null||a.call(this,"reconnecting");const s=Math.min(1e3*Math.pow(2,this.reconnectAttempts||0),3e4);this.reconnectAttempts=(this.reconnectAttempts||0)+1,setTimeout(()=>{this.isReconnecting=!1,this.manualReconnectScheduled=!1,this.connect().catch(()=>{})},s)}reconnect(){this.manualReconnectScheduled=!0,this.isReconnecting=!1,this.lastCloseCode=0,this.connectingPromise=null,this.connect().catch(()=>{})}disconnect(){this.isReconnecting=!1,this.reconnectAttempts=0,this.ws&&(this.ws.close(),this.ws=null)}resetReconnectAttempts(){this.reconnectAttempts=0}send(t,n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");const s=oS(),a={id:s,type:t,payload:n};return this.ws.send(JSON.stringify(a)),s}subscribe(t){return this.handlers.add(t),()=>this.handlers.delete(t)}get isConnected(){var t;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN}}const U2=window.location.protocol==="https:"?"wss:":"ws:";let ym=window.location.port;ym||(ym=window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"?"10469":window.location.protocol==="https:"?"443":"80");const F2=`${U2}//${window.location.hostname}:${ym}/ws`,zt=new $2(F2);function V2(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}}}function _v(e){e&&we.getState().updateContextState({...e,dynamicContextChanged:e.dynamicContextChanged??!1})}async function yv(e,t,n){const s=await Ne(`/api/providers/${e}/models/${encodeURIComponent(t)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok){const a=await s.json();throw new Error(a.error??"Failed to update model")}return s.json()}function vv(e,t,n,s){return e.map(a=>a.id===t?{...a,models:a.models.map(l=>l.id===n?{...l,...s,source:"user"}:l)}:a)}const G2=3e4;function ip(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"unknown":return""}}const Bt=qn((e,t)=>({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 n=await Ne("/api/config");if(!n.ok)throw new Error("Failed to fetch config");const s=await n.json();e({version:s.version,model:s.model,maxContext:s.maxContext,llmUrl:s.llmUrl,llmStatus:s.llmStatus,backend:s.backend,providers:s.providers??[],activeProviderId:s.activeProviderId??null,defaultModelSelection:s.defaultModelSelection??null,loading:!1})}catch(n){e({error:n instanceof Error?n.message:"Unknown error",loading:!1})}},refreshModel:async()=>{try{const n=await Ne("/api/model/refresh",{method:"POST"});if(!n.ok)throw new Error("Failed to refresh model");const s=await n.json(),l=we.getState().currentSession;if(l!=null&&l.providerId&&l.providerModel){e({llmStatus:s.llmStatus,backend:s.backend});return}e({model:s.model,llmStatus:s.llmStatus,backend:s.backend})}catch(n){console.error("Failed to refresh model:",n)}},activateProvider:async n=>{const{activeProviderId:s,providers:a}=t();if(n===s)return!0;e({activating:!0,error:null});try{const l=await Ne(`/api/providers/${n}/activate`,{method:"POST"});if(!l.ok){const c=await l.json();throw new Error(c.error??"Failed to activate provider")}const u=await l.json();return e({activeProviderId:u.activeProviderId,model:u.model,backend:u.backend,providers:a.map(c=>({...c,isActive:c.id===u.activeProviderId})),activating:!1}),!0}catch(l){return e({error:l instanceof Error?l.message:"Failed to switch provider",activating:!1}),!1}},syncFromSession:(n,s)=>{var c;const{providers:a,defaultModelSelection:l}=t();let u=s;if(!u){const h=l?l.split("/"):[],f=h[0],p=h.slice(1).join("/")??"";if(f===n&&p)u=p;else{const m=a.find(_=>_.id===n);u=((c=m==null?void 0:m.models[0])==null?void 0:c.id)??""}}e({activeProviderId:n,model:u,defaultModelSelection:`${n}/${u}`,providers:a.map(h=>({...h,isActive:h.id===n}))})},updateModelContext:async(n,s,a)=>{e({activating:!0,error:null});try{const l=await yv(n,s,{contextWindow:a}),{providers:u}=t();return e({providers:vv(u,n,s,{contextWindow:a}),activating:!1}),_v(l.contextState),!0}catch(l){return e({error:l instanceof Error?l.message:"Failed to update model context",activating:!1}),!1}},updateModelSettings:async(n,s,a)=>{e({activating:!0,error:null});try{const l=await yv(n,s,a),{providers:u}=t(),c={...a.contextWindow!==void 0&&{contextWindow:a.contextWindow},...V2({temperature:a.temperature??void 0,topP:a.topP??void 0,topK:a.topK??void 0,maxTokens:a.maxTokens??void 0}),...a.supportsVision!==void 0&&{supportsVision:a.supportsVision},...a.thinkingEnabled!==void 0&&{thinkingEnabled:a.thinkingEnabled},...a.thinkingLevel!==void 0&&{thinkingLevel:a.thinkingLevel},...a.nonThinkingEnabled!==void 0&&{nonThinkingEnabled:a.nonThinkingEnabled},...a.thinkingExtraKwargs!==void 0&&{thinkingExtraKwargs:a.thinkingExtraKwargs},...a.nonThinkingExtraKwargs!==void 0&&{nonThinkingExtraKwargs:a.nonThinkingExtraKwargs}};return e({providers:vv(u,n,s,c),activating:!1}),_v(l.contextState),!0}catch(l){return e({error:l instanceof Error?l.message:"Failed to update model settings",activating:!1}),!1}},refreshProviderModels:async n=>{e({activating:!0,error:null});try{const s=await Ne(`/api/providers/${n}/refresh`,{method:"POST"});if(!s.ok){const u=await s.json();throw new Error(u.error??"Failed to refresh models")}const a=await s.json(),{providers:l}=t();return e({providers:l.map(u=>u.id===n?{...u,models:a.models,status:a.status}:u),activating:!1}),!0}catch(s){return e({error:s instanceof Error?s.message:"Failed to refresh models",activating:!1}),!1}},startAutoRefresh:()=>{const{autoRefreshInterval:n,refreshModel:s}=t();if(n)return;const a=setInterval(()=>{s()},G2);e({autoRefreshInterval:a})},stopAutoRefresh:()=>{const{autoRefreshInterval:n}=t();n&&(clearInterval(n),e({autoRefreshInterval:null}))},getActiveProvider:()=>{const{providers:n,activeProviderId:s}=t();return n.find(a=>a.id===s)},getModelContext:n=>{const{providers:s,activeProviderId:a}=t(),l=s.find(c=>c.id===a);if(!l)return 2e5;const u=l.models.find(c=>c.id===n);return(u==null?void 0:u.contextWindow)??2e5}})),Lt=qn((e,t)=>({projects:[],currentProject:null,loading:!1,listProjects:async()=>{e({loading:!0});try{const s=await(await Ne("/api/projects")).json();e({projects:s.projects??[],loading:!1})}catch(n){console.error("Failed to load projects:",n),e({loading:!1})}},createProject:async(n,s)=>{try{const a=await Ne("/api/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:n,workdir:s})});if(!a.ok){const u=await a.json().catch(()=>({}));return{error:{code:u.code||"UNKNOWN",path:u.path,message:u.error}}}const l=await a.json();return await t().listProjects(),l.project}catch{return null}},loadProject:async n=>{try{const s=await Ne(`/api/projects/${n}`);if(!s.ok)return null;const a=await s.json();return e({currentProject:a.project}),t().projects.length===0&&await t().listProjects(),a.project}catch{return null}},updateProject:async(n,s)=>{var a;try{const l=await Ne(`/api/projects/${n}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!l.ok)return null;const u=await l.json();return((a=t().currentProject)==null?void 0:a.id)===n&&e({currentProject:u.project}),await t().listProjects(),u.project}catch{return null}},deleteProject:async n=>{var s;try{return(await Ne(`/api/projects/${n}`,{method:"DELETE"})).ok?(await t().listProjects(),((s=t().currentProject)==null?void 0:s.id)===n&&e({currentProject:null}),!0):!1}catch{return!1}},toggleStar:async(n,s)=>{var a;try{const l=await Ne(`/api/projects/${n}/star`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({isStarred:s})});if(!l.ok)return!1;if(((a=t().currentProject)==null?void 0:a.id)===n){const u=await l.json();e({currentProject:u.project})}return await t().listProjects(),!0}catch{return!1}},clearProject:()=>{e({currentProject:null})}})),Ws=async(e,t,n)=>{try{const s=await Ne(t,{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return s.ok?{success:!0}:{success:!1,error:(await s.json()).error}}catch{return{success:!1,error:"Network error"}}},Iu=async(e,t,n)=>{try{const s=await Ne(e,{method:"POST",body:n?JSON.stringify({destination:n}):void 0,headers:n?{"Content-Type":"application/json"}:void 0}),a=await s.json();return s.ok?(await t(),{success:!0}):{success:!1,error:a.error??"Failed to duplicate"}}catch{return{success:!1,error:"Network error"}}};function lS(e){let t=null;function n(){t===null&&(t=requestAnimationFrame(()=>{t=null,e()}))}return n}let Hc=[];const Zo=qn()((e,t)=>{function n(){if(Hc.length===0)return;const a=Hc;Hc=[],e(l=>{const u={...l.logs};for(const c of a){const h=u[c.processId]??[];u[c.processId]=[...h,{offset:h.length,content:c.content,timestamp:Date.now(),stream:c.stream}]}return{logs:u}})}const s=lS(n);return{processes:[],logs:{},loading:!1,setProcesses:a=>e({processes:a}),addProcess:a=>e(l=>({processes:[...l.processes,a]})),updateProcess:(a,l)=>e(u=>({processes:u.processes.map(c=>c.id===a?{...c,...l}:c)})),removeProcess:a=>e(l=>({processes:l.processes.filter(u=>u.id!==a),logs:Object.fromEntries(Object.entries(l.logs).filter(([u])=>u!==a))})),stopProcess:async(a,l)=>{try{(await Ne(`/api/sessions/${l}/background-process/${a}/stop`,{method:"POST"})).ok&&t().removeProcess(a)}catch{}},appendLog:(a,l,u)=>{Hc.push({processId:a,stream:l,content:u}),s()},setLogs:(a,l)=>e(u=>({logs:{...u.logs,[a]:l}})),clearLogs:a=>e(l=>({logs:{...l.logs,[a]:[]}})),handleMessage:(a,l)=>{switch(a){case"backgroundProcess.started":{const{processId:u,name:c,pid:h,status:f}=l;e(p=>({processes:[...p.processes,{id:u,sessionId:"",name:c,command:"",cwd:"",pid:h,status:f,exitCode:null,createdAt:Date.now(),startedAt:Date.now(),endedAt:null}]}));break}case"backgroundProcess.output":{const u=l.processId,c=l.stream,h=l.content;t().appendLog(u,c,h);break}case"backgroundProcess.exited":{const u=l.processId,c=l.exitCode;e(h=>({processes:h.processes.map(f=>f.id===u?{...f,status:"exited",exitCode:c}:f)}));break}case"backgroundProcess.removed":{const u=l.processId;t().removeProcess(u);break}}}}}),W2={messageId:null,deltaContent:"",thinkingContent:"",toolOutput:[]};let iu=null;function q2(e){iu=e}function yi(){return W2}function Af(){iu==null||iu()}let $c=[];const Rr=qn()((e,t)=>{function n(){if($c.length===0)return;const a=$c;$c=[],e(l=>({logs:[...l.logs,...a]}))}const s=lS(n);return{workdir:null,status:null,logs:[],config:null,loading:!1,setWorkdir:a=>{t().workdir!==a&&(e({workdir:a,status:null,logs:[],config:null,loading:!0}),a&&(t().fetchStatus(),t().fetchConfig()))},fetchStatus:async()=>{const a=t().workdir;if(a)try{const u=await(await Ne(`/api/dev-server?workdir=${encodeURIComponent(a)}`)).json();e({status:u,loading:!1})}catch{e({loading:!1})}},fetchConfig:async()=>{const a=t().workdir;if(a)try{const u=await(await Ne(`/api/dev-server/config?workdir=${encodeURIComponent(a)}`)).json();e({config:u.config??null})}catch{}},fetchLogs:async()=>{const a=t().workdir;if(a)try{const c=(await(await Ne(`/api/dev-server/logs?workdir=${encodeURIComponent(a)}`)).json()).logs.map(h=>({stream:h.stream,content:h.content}));e({logs:c})}catch{}},start:async()=>{const a=t().workdir;if(a)try{const u=await(await Ne(`/api/dev-server/start?workdir=${encodeURIComponent(a)}`,{method:"POST"})).json();e({status:u,logs:[]})}catch{}},stop:async()=>{const a=t().workdir;if(a)try{const u=await(await Ne(`/api/dev-server/stop?workdir=${encodeURIComponent(a)}`,{method:"POST"})).json();e({status:u})}catch{}},restart:async()=>{const a=t().workdir;if(a)try{const u=await(await Ne(`/api/dev-server/restart?workdir=${encodeURIComponent(a)}`,{method:"POST"})).json();e({status:u,logs:[]})}catch{}},saveConfig:async a=>{const l=t().workdir;if(l)try{const c=await(await Ne(`/api/dev-server/config?workdir=${encodeURIComponent(l)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)})).json();e({config:c.config??a}),t().fetchStatus()}catch{}},handleMessage:a=>{const l=t().workdir;if(l)switch(a.type){case"devServer.output":{const u=a.payload;if(u.workdir!==l)return;$c.push({stream:u.stream,content:u.content}),s();break}case"devServer.state":{const u=a.payload;if(u.workdir!==l)return;e(c=>({status:c.status?{...c.status,state:u.state,errorMessage:u.errorMessage}:c.status}));break}}}}}),K2=[{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"}],Y2=[{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"}],cS={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"},Us={soundEnabled:!0,browserNotification:!1,customSoundUrl:null},uS={soundEnabled:!1,browserNotification:!1,customSoundUrl:null},vm={soundEnabled:!0,browserNotificationEnabled:!1,events:{complete:{...Us},waiting_for_user:{...Us},phase_done:{...Us},phase_blocked:{...Us},new_message:{...uS}},agentOverrides:{}};function dS(e,t,n){var l;const s=e.events[t];if(!n)return s;const a=(l=e.agentOverrides[n])==null?void 0:l[t];return a?{soundEnabled:a.soundEnabled??s.soundEnabled,browserNotification:a.browserNotification??s.browserNotification,customSoundUrl:a.customSoundUrl!==void 0?a.customSoundUrl:s.customSoundUrl}:s}const bi=qn((e,t)=>({settings:vm,loaded:!1,load:()=>{an.getState().getSetting(ze.NOTIFICATION_SETTINGS);const s=an.subscribe(l=>{const u=l.settings[ze.NOTIFICATION_SETTINGS];if(u!==void 0)try{const c=JSON.parse(u);e({settings:bv(c),loaded:!0})}catch{e({loaded:!0})}}),a=an.getState().settings[ze.NOTIFICATION_SETTINGS];if(a)try{const l=JSON.parse(a);e({settings:bv(l),loaded:!0})}catch{e({loaded:!0})}return s},update:n=>{e({settings:n}),Lf(n)},updateEvent:(n,s)=>{const a=t().settings,l={...a,events:{...a.events,[n]:{...a.events[n],...s}}};e({settings:l}),Lf(l)},updateAgentOverride:(n,s,a)=>{var h;const l=t().settings,u={...l.agentOverrides};if(a===null){if(u[n]){const f={...u[n]};delete f[s],Object.keys(f).length===0?delete u[n]:u[n]=f}}else u[n]={...u[n],[s]:{...((h=u[n])==null?void 0:h[s])??{},...a}};const c={...l,agentOverrides:u};e({settings:c}),Lf(c)}}));function Lf(e){an.getState().setSetting(ze.NOTIFICATION_SETTINGS,JSON.stringify(e))}function bv(e){var t,n,s,a,l;return{soundEnabled:e.soundEnabled??vm.soundEnabled,browserNotificationEnabled:e.browserNotificationEnabled??vm.browserNotificationEnabled,events:{complete:{...Us,...(t=e.events)==null?void 0:t.complete},waiting_for_user:{...Us,...(n=e.events)==null?void 0:n.waiting_for_user},phase_done:{...Us,...(s=e.events)==null?void 0:s.phase_done},phase_blocked:{...Us,...(a=e.events)==null?void 0:a.phase_blocked},new_message:{...uS,...(l=e.events)==null?void 0:l.new_message}},agentOverrides:e.agentOverrides??{}}}const Sv=new Map;function X2(e){let t=Sv.get(e);return t||(t=new Audio(e),t.volume=.5,Sv.set(e,t)),t}let hS=typeof Notification<"u"?Notification.permission:"denied";function Q2(){return typeof Notification>"u"?Promise.resolve("denied"):Notification.requestPermission().then(e=>(hS=e,e))}const J2={complete:"Task Complete",waiting_for_user:"Waiting for Input",phase_done:"Phase Complete",phase_blocked:"Phase Blocked",new_message:"New Message"},Z2={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 ej(e){typeof Notification>"u"||hS==="granted"&&(document.hasFocus()||new Notification(J2[e],{body:Z2[e],icon:"/fox.svg",tag:`openfox-${e}`}))}function ml(e,t){const{settings:n}=bi.getState(),s=dS(n,e,t);if(n.soundEnabled&&s.soundEnabled){const a=s.customSoundUrl??cS[e],l=X2(a);l.currentTime=0,l.play().catch(()=>{})}n.browserNotificationEnabled&&s.browserNotification&&ej(e)}const tj=e=>ml("complete",e),nj=e=>ml("phase_done",e),rj=e=>ml("phase_blocked",e),wv=e=>ml("waiting_for_user",e),sj=e=>ml("new_message",e),Cv=new Map;function Xo(e,t){var l;const n=t===((l=e.currentSession)==null?void 0:l.id)?e.currentSession:null,s=e.sessions.find(u=>u.id===t),a=(n==null?void 0:n.mode)??(s==null?void 0:s.mode);return a==="planner"?"planner":a==="builder"?"build":"planner"}function ij(e,t){if(e.type==="chat.done"){const n=e.payload,s=Xo(t,e.sessionId),a=n.agentType??s;n.reason==="complete"&&tj(a),n.reason==="waiting_for_user"&&wv(a);return}if(e.type==="chat.path_confirmation"){const n=Xo(t,e.sessionId);wv(n);return}if(e.type==="task.completed"){const n=Xo(t,e.sessionId);nj(n);return}if(e.type==="phase.changed"&&e.sessionId){const n=e.payload,s=Cv.get(e.sessionId)??null;if(Cv.set(e.sessionId,n.phase),s===n.phase)return;const a=Xo(t,e.sessionId);n.phase==="blocked"&&rj(a)}}const Df=new Set;function Gt(e,t){return t!==null&&e.sessionId===t}function aj(e,t,n){return e.id!==void 0||Gt(e,t)||n===!0&&e.sessionId!==void 0}function oj(e,t){return e.includes(t)?e:[...e,t]}function kv(e,t){return e.filter(n=>n!==t)}function lj(e,t){const n=e.find(l=>l.id===t.id),s=t.messageCount??t.messages.length,a=n?{...n,projectId:t.projectId,workdir:t.workdir,mode:t.mode,phase:t.phase,isRunning:t.isRunning&&n.isRunning!==!1,messageCount:s,criteriaCount:t.criteria.length,criteriaCompleted:t.criteria.filter(l=>l.status.type==="passed").length}:{id:t.id,projectId:t.projectId,workdir:t.workdir,mode:t.mode,phase:t.phase,isRunning:t.isRunning,createdAt:"",updatedAt:"",criteriaCount:t.criteria.length,criteriaCompleted:t.criteria.filter(l=>l.status.type==="passed").length,messageCount:s};return n?e.map(l=>l.id===t.id?a:l):[a,...e]}function cj(e,t,n){return e.map(s=>{const a=(n==null?void 0:n.id)===s.id?n:null,l=t.find(u=>u.id===s.id);return{...s,title:s.title??(l==null?void 0:l.title),mode:(a==null?void 0:a.mode)??(l==null?void 0:l.mode)??s.mode,phase:(a==null?void 0:a.phase)??(l==null?void 0:l.phase)??s.phase,isRunning:s.isRunning&&(l==null?void 0:l.isRunning)!==!1,messageCount:s.messageCount,recentUserPrompts:s.recentUserPrompts}})}function Ev(e,t,n,s){var c;const a=e.sessionId,l=(c=n().currentSession)==null?void 0:c.id,u=a&&a!==l;if(t(h=>({sessions:h.sessions.map(f=>f.id===a?s(f):f)})),!u){const h=n().currentSession;if(h){const f=s(h);t(()=>({currentSession:f}))}}}function jv(e,t,n){var u,c,h,f,p,m,_,x,w,k,y,S,v,b,E,T,N,L,A,D,B,q,W;const s=n();ij(e,s);const a=((u=s.currentSession)==null?void 0:u.id)??null,l=()=>{const O=e.sessionId;!O||O===a||t(V=>({unreadSessionIds:oj(V.unreadSessionIds,O)}))};switch(e.type){case"session.state":{const O=e.payload;if(!aj(e,a,s.pendingSessionCreate))break;const V=O.messages.find(z=>z.isStreaming)??null,G=n().pendingSessionCreate===!0;if(t({currentSession:O.session,sessions:lj(n().sessions,O.session),unreadSessionIds:kv(n().unreadSessionIds,O.session.id),messages:O.messages,streamingMessageId:(V==null?void 0:V.id)??null,streamingMessage:V,currentTodos:[],pendingPathConfirmations:O.pendingConfirmations??[],error:null,...G?{pendingSessionCreate:O.session.id}:{}}),O.session.providerId){const z=Bt.getState();z.providers.find(ne=>ne.id===O.session.providerId)&&z.syncFromSession(O.session.providerId,O.session.providerModel??"")}break}case"session.list":{const O=e.payload;t(V=>({sessions:cj(O.sessions,V.sessions,V.currentSession)}));break}case"session.deleted":{const O=e.payload;t(V=>({unreadSessionIds:kv(V.unreadSessionIds,O.sessionId)})),n().listSessions();break}case"session.deletedAll":{n().listSessions();break}case"session.running":{const O=e.payload;Ev(e,t,n,V=>({...V,isRunning:O.isRunning})),O.isRunning||t({abortInProgress:!1,queuedMessages:[]});break}case"chat.message":{if(!Gt(e,((c=n().currentSession)==null?void 0:c.id)??null)){l();break}const O=e.payload;t(V=>{if(V.messages.some(z=>z.id===O.message.id))return V;const G=O.message.role==="user";return{messages:[...V.messages,O.message],sessions:V.sessions.map(z=>z.id===e.sessionId&&G?{...z,messageCount:z.messageCount+1}:z),streamingMessageId:O.message.isStreaming?O.message.id:V.streamingMessageId,streamingMessage:O.message.isStreaming?O.message:V.streamingMessage}});break}case"chat.message_updated":{if(!Gt(e,((h=n().currentSession)==null?void 0:h.id)??null)){l();break}const O=e.payload,V=O.updates.isStreaming===!1&&n().streamingMessageId===O.messageId;t(G=>{const z=G.streamingMessage;if(z&&z.id===O.messageId){const X={...z,...O.updates};return{messages:G.messages.map(ne=>ne.id===O.messageId?X:ne),streamingMessageId:V?null:G.streamingMessageId,streamingMessage:V?null:{...z,...O.updates}}}return{messages:G.messages.map(X=>X.id===O.messageId?{...X,...O.updates}:X),streamingMessageId:V?null:G.streamingMessageId}});break}case"chat.delta":{if(!Gt(e,((f=n().currentSession)==null?void 0:f.id)??null)){l();break}const O=e.payload;if(!Df.has(O.messageId)){Df.add(O.messageId);const G=O.subAgentType?"sub-agent":Xo(n(),e.sessionId);sj(G)}const V=yi();V.messageId=O.messageId,V.deltaContent+=O.content,Af();break}case"chat.thinking":{if(!Gt(e,((p=n().currentSession)==null?void 0:p.id)??null)){l();break}const O=e.payload,V=yi();V.messageId=O.messageId,V.thinkingContent+=O.content,Af();break}case"chat.tool_preparing":{if(!Gt(e,((m=n().currentSession)==null?void 0:m.id)??null)){l();break}const O=e.payload,V=n().streamingMessage;if(!V||V.id!==O.messageId||((_=V.toolCalls)==null?void 0:_.find((z,X)=>X===O.index)))return;t(z=>{const X=z.streamingMessage.preparingToolCalls??[],ne=X.findIndex(M=>M.index===O.index);let F;return ne>=0?F=X.map((M,$)=>$===ne?{...M,arguments:O.arguments}:M):F=[...X,{index:O.index,name:O.name,...O.arguments?{arguments:O.arguments}:{}}],{streamingMessage:{...z.streamingMessage,preparingToolCalls:F}}});break}case"chat.tool_call":{if(!Gt(e,((x=n().currentSession)==null?void 0:x.id)??null)){l();break}const O=e.payload,V=G=>{var F;const z=(F=G.preparingToolCalls)==null?void 0:F.filter((M,$)=>{var P;return M.name===O.tool?(P=G.preparingToolCalls)==null?void 0:P.slice(0,$).some(J=>J.name===O.tool):!0}),X=yi(),ne=X.toolOutput.filter(M=>M.callId===O.callId);return ne.length>0&&(X.toolOutput=X.toolOutput.filter(M=>M.callId!==O.callId)),{...G,toolCalls:[...G.toolCalls??[],{id:O.callId,name:O.tool,arguments:O.args,startedAt:Date.now(),...ne.length>0?{streamingOutput:ne.map(M=>({stream:M.stream,content:M.content,timestamp:Date.now()}))}:{}}],...z&&z.length>0?{preparingToolCalls:z}:{preparingToolCalls:void 0}}};t(G=>{const z=G.streamingMessage;return z&&z.id===O.messageId?{streamingMessage:V(z)}:{messages:G.messages.map(X=>X.id===O.messageId?V(X):X)}});break}case"chat.tool_output":{if(!Gt(e,((w=n().currentSession)==null?void 0:w.id)??null)){l();break}const O=e.payload,V=yi();V.messageId=O.messageId,V.toolOutput.push({messageId:O.messageId,callId:O.callId,stream:O.stream,content:O.output}),Af();break}case"chat.tool_result":{if(!Gt(e,((k=n().currentSession)==null?void 0:k.id)??null)){l();break}const O=e.payload,V=G=>{var X;const z=(X=G.toolCalls)==null?void 0:X.map(ne=>ne.id===O.callId?{...ne,result:O.result}:ne);return{...G,toolCalls:z}};t(G=>{const z=G.streamingMessage;return z&&z.id===O.messageId?{streamingMessage:V(z)}:{messages:G.messages.map(X=>X.id===O.messageId?V(X):X)}});break}case"chat.vision_fallback":{if(!Gt(e,((y=n().currentSession)==null?void 0:y.id)??null)){l();break}const O=e.payload;t(V=>{const G=`${O.messageId}-${O.attachmentId}`,z={...V.visionFallbackByMessage};return z[G]={type:O.type,attachmentId:O.attachmentId,filename:O.filename,description:O.description},{visionFallbackByMessage:z}});break}case"chat.todo":{if(!Gt(e,((S=n().currentSession)==null?void 0:S.id)??null)){l();break}const O=e.payload;t({currentTodos:O.todos});break}case"chat.progress":{if(!Gt(e,((v=n().currentSession)==null?void 0:v.id)??null)){l();break}const O=e.payload;console.warn("Progress:",O.message,O.phase);break}case"chat.format_retry":{if(!Gt(e,((b=n().currentSession)==null?void 0:b.id)??null)){l();break}const O=e.payload;console.warn("Format retry:",O.attempt,"/",O.maxAttempts);break}case"chat.done":{if(!Gt(e,((E=n().currentSession)==null?void 0:E.id)??null)){l();break}const O=yi();O.messageId=null,O.deltaContent="",O.thinkingContent="",O.toolOutput=[],Df.delete(e.payload.messageId);const V=e.payload,G=V.stats;t(z=>{const X=z.streamingMessage,ne=X&&X.id===V.messageId?{...X,isStreaming:!1,stats:G??X.stats}:null;return{messages:z.messages.map(F=>F.id===V.messageId?ne??{...F,isStreaming:!1,stats:G??F.stats,completeReason:V.reason}:F),streamingMessageId:null,streamingMessage:null,visionFallbackByMessage:{}}});break}case"chat.error":{if(!Gt(e,((T=n().currentSession)==null?void 0:T.id)??null)){l();break}const O=yi(),V=e.payload;console.error("Chat error:",V.error,"recoverable:",V.recoverable),V.recoverable||(O.messageId=null,O.deltaContent="",O.thinkingContent="",O.toolOutput=[]),t(G=>({error:{code:"CHAT_ERROR",message:V.error},streamingMessageId:V.recoverable?G.streamingMessageId:null,...V.recoverable?{}:{messages:G.streamingMessage?G.messages.map(z=>z.id===G.streamingMessage.id?G.streamingMessage:z):G.messages,streamingMessage:null}}));break}case"chat.path_confirmation":{if(!Gt(e,((N=n().currentSession)==null?void 0:N.id)??null)){l();break}const O=e.payload,V={callId:O.callId,tool:O.tool,paths:O.paths,workdir:O.workdir,reason:O.reason};t(G=>({pendingPathConfirmations:[...G.pendingPathConfirmations,V]}));break}case"chat.ask_user":{if(!Gt(e,((L=n().currentSession)==null?void 0:L.id)??null)){l();return}const O=e.payload;t({pendingQuestion:{callId:O.callId,question:O.question}});break}case"mode.changed":{if(!Gt(e,((A=n().currentSession)==null?void 0:A.id)??null)){l();break}const O=e.payload;t(V=>({currentSession:V.currentSession?{...V.currentSession,mode:O.mode}:null}));break}case"phase.changed":{const O=e.payload;Ev(e,t,n,V=>({...V,phase:O.phase}));break}case"criteria.updated":{if(!Gt(e,((D=n().currentSession)==null?void 0:D.id)??null)){l();break}const O=e.payload;t(V=>({currentSession:V.currentSession?{...V.currentSession,criteria:O.criteria}:null}));break}case"metadata.updated":{if(!Gt(e,((B=n().currentSession)==null?void 0:B.id)??null)){l();break}const O=e.payload;t(V=>({currentSession:V.currentSession?{...V.currentSession,metadataEntries:{...V.currentSession.metadataEntries,[O.key]:O.entries}}:null}));break}case"context.state":{const O=e.payload,V=Gt(e,((q=n().currentSession)==null?void 0:q.id)??null);O.subAgentId?V&&n().updateSubAgentContextState(O.subAgentId,O.context):V?t({contextState:O.context}):l();break}case"session.name_generated":{const O=e.payload,V=e.sessionId,G=(W=n().currentSession)==null?void 0:W.id;t(z=>{const X=z.sessions.map(F=>F.id===V?{...F,title:O.name,updatedAt:new Date().toISOString()}:F),ne=G===V?z.currentSession?{...z.currentSession,title:O.name,updatedAt:new Date().toISOString()}:null:z.currentSession;return{sessions:X,currentSession:ne}});break}case"queue.state":{const O=e.payload;t({queuedMessages:O.messages??[]});break}case"git.status":{const O=e.payload;t({gitStatus:{branch:O.branch,diff:O.diff}});break}case"devServer.output":case"devServer.state":{Rr.getState().handleMessage(e);break}case"backgroundProcess.started":case"backgroundProcess.output":case"backgroundProcess.exited":case"backgroundProcess.removed":{Zo.getState().handleMessage(e.type,e.payload);break}case"error":{const O=e.payload;console.error("Server error:",O),t({error:{code:O.code,message:O.message},streamingMessageId:null});break}}}let $o=!1,Nr=null;const Rf=new Set,Uc=new Map;function Nv(e,t,n){return e==null?void 0:e.map(s=>{const a=t.filter(l=>l.callId===s.id);return a.length===0?s:(n.add(s.id),{...s,streamingOutput:[...s.streamingOutput??[],...a.map(l=>({stream:l.stream,content:l.content,timestamp:Date.now()}))]})})}async function Tv(e,t,n,s,a){try{const u=await(await Ne(`/api/sessions/${e}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:t,attachments:n,messageKind:s})})).json();u.queueState&&a({queuedMessages:u.queueState})}catch(l){console.error("Error queueing message:",l)}}const we=qn((e,t)=>(q2(()=>{const n=yi();if(!n.messageId)return;const s=n.deltaContent.length>0,a=n.thinkingContent.length>0,l=n.toolOutput.length>0;if(!s&&!a&&!l)return;const u=n.deltaContent,c=n.thinkingContent,h=n.toolOutput;n.deltaContent="",n.thinkingContent="",n.toolOutput=[],e(f=>{const p=f.streamingMessage;if(p&&p.id===n.messageId){const m={...p};if(s&&(m.content=m.content+u),a&&(m.thinkingContent=(m.thinkingContent??"")+c),l){const _=new Set;m.toolCalls=Nv(m.toolCalls,h,_);const x=h.filter(w=>!_.has(w.callId));x.length>0&&n.toolOutput.push(...x)}return{streamingMessage:m}}if(l){const m=new Set,_=f.messages.map(w=>w.id!==n.messageId?w:{...w,toolCalls:Nv(w.toolCalls,h,m)}),x=h.filter(w=>!m.has(w.callId));return x.length>0&&n.toolOutput.push(...x),{messages:_}}return f})}),{connectionStatus:"disconnected",showPasswordModal:!1,passwordModalRetry:!1,sessions:[],currentSession:null,unreadSessionIds:[],messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,subAgentContextStates:{},pendingPathConfirmations:[],pendingQuestion:null,visionFallbackByMessage:{},gitStatus:null,queuedMessages:[],abortInProgress:!1,error:null,sessionsHasMore:!0,sessionsPaginationLoading:!1,pendingSessionCreate:!1,connect:async()=>{if(t().connectionStatus==="connected")return;e({connectionStatus:"reconnecting"});let s=!1;try{s=(await(await Ne("/api/auth")).json()).requiresAuth}catch{}if(s&&!zt.hasToken()){e({showPasswordModal:!0,passwordModalRetry:!1,connectionStatus:"reconnecting"});return}zt.onStatusChange(a=>{var l;if(e({connectionStatus:a}),a==="connected"){t().listSessions(void 0),Lt.getState().listProjects();const u=(l=t().currentSession)==null?void 0:l.id;u&&t().loadSession(u)}});try{await zt.connect(),$o||($o=!0,Nr=zt.subscribe(a=>{jv(a,e,t)}))}catch(a){console.error("Failed to connect:",a);const l=zt.getLastCloseCode();if(!zt.hasToken()&&(l===1006||l===4e3)){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}Nr&&(Nr(),Nr=null),$o=!1,e({connectionStatus:"disconnected"})}},reconnect:()=>{zt.disconnect(),Nr&&(Nr(),Nr=null),$o=!1,e({connectionStatus:"disconnected"}),t().connect()},disconnect:()=>{zt.disconnect(),Nr&&(Nr(),Nr=null),$o=!1,e({connectionStatus:"disconnected",showPasswordModal:!1})},submitPassword:async n=>{try{const s=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:n})});if(!s.ok){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}const{token:a}=await s.json();zt.setToken(a),e({showPasswordModal:!1}),t().connect();const{listProjects:l}=Lt.getState(),{fetchConfig:u}=Bt.getState();l(),u(),t().connect()}catch{e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"})}},cancelPassword:()=>{zt.clearToken(),e({showPasswordModal:!1,connectionStatus:"disconnected"})},createSession:async(n,s)=>{if(t().pendingSessionCreate)return null;try{e({pendingSessionCreate:!0});const l=await Ne("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectId:n,title:s})});if(!l.ok)return e({pendingSessionCreate:!1}),null;const u=await l.json();try{zt.send("session.load",{sessionId:u.session.id})}catch{}return u.session}catch{return e({pendingSessionCreate:!1}),null}},loadSession:async n=>{if(!Rf.has(n)){Rf.add(n);try{const s=t().currentSession;!s||s.id!==n?e({currentSession:null,unreadSessionIds:t().unreadSessionIds.filter(u=>u!==n),subAgentContextStates:{},messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,pendingPathConfirmations:[],queuedMessages:[],abortInProgress:!1,error:null,pendingSessionCreate:!1}):e({unreadSessionIds:t().unreadSessionIds.filter(u=>u!==n)});const a=await Ne(`/api/sessions/${n}`);if(!a.ok)return;const l=await a.json();e({currentSession:l.session,messages:l.messages??[],contextState:l.contextState,queuedMessages:l.queueState??[]}),zt.send("session.load",{sessionId:n});try{const u=await Ne(`/api/sessions/${n}/background-processes`);if(u.ok){const c=await u.json();Zo.getState().setProcesses(c.processes??[])}}catch{}}catch{}finally{Rf.delete(n)}}},listSessions:async(n,s=20)=>{const a=n??"global";if(Uc.has(a))return Uc.get(a);const l=(async()=>{try{const u=new URLSearchParams;u.set("limit",String(s)),n&&u.set("projectId",n);const h=await(await Ne(`/api/sessions?${u.toString()}`)).json(),f=h.sessions??[];e(p=>({sessions:f.map(m=>{var x,w;const _=p.sessions.find(k=>k.id===m.id);return{...m,title:m.title??(_==null?void 0:_.title),mode:((x=p.currentSession)==null?void 0:x.id)===m.id?p.currentSession.mode:(_==null?void 0:_.mode)??m.mode,phase:((w=p.currentSession)==null?void 0:w.id)===m.id?p.currentSession.phase:(_==null?void 0:_.phase)??m.phase,isRunning:m.isRunning&&(_==null?void 0:_.isRunning)!==!1,messageCount:m.messageCount,recentUserPrompts:m.recentUserPrompts}}),sessionsHasMore:n?h.hasMore??!1:!0}))}catch{}finally{Uc.delete(a)}})();return Uc.set(a,l),l},loadMoreSessions:async n=>{const s=t();if(!(s.sessionsPaginationLoading||!s.sessionsHasMore)){e({sessionsPaginationLoading:!0});try{const a=new URLSearchParams;a.set("limit","20"),a.set("offset",String(s.sessions.length)),a.set("projectId",n);const u=await(await Ne(`/api/sessions?${a.toString()}`)).json(),c=u.sessions??[];e(h=>({sessions:[...h.sessions,...c.map(f=>{const p=h.sessions.find(m=>m.id===f.id);return(p==null?void 0:p.isRunning)===!1?{...f,isRunning:!1}:f})],sessionsHasMore:u.hasMore??!1,sessionsPaginationLoading:!1}))}catch{e({sessionsPaginationLoading:!1})}}},deleteSession:async n=>{var s;try{return(await Ne(`/api/sessions/${n}`,{method:"DELETE"})).ok?(await t().listSessions(),((s=t().currentSession)==null?void 0:s.id)===n&&t().clearSession(),!0):!1}catch{return!1}},renameSession:async(n,s)=>{var a;try{const l=await Ne(`/api/sessions/${n}/title`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:s})});if(!l.ok)return!1;if(await t().listSessions(),((a=t().currentSession)==null?void 0:a.id)===n){const c=await l.json();c.session&&e({currentSession:c.session})}return!0}catch{return!1}},deleteAllSessions:async n=>{try{return(await Ne(`/api/projects/${n}/sessions`,{method:"DELETE"})).ok?(await t().listSessions(),!0):!1}catch{return!1}},clearSession:()=>{e(n=>({currentSession:null,messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,pendingSessionCreate:!1,unreadSessionIds:n.currentSession?n.unreadSessionIds.filter(s=>s!==n.currentSession.id):n.unreadSessionIds}))},sendMessage:async(n,s,a)=>{var u;const l=(u=t().currentSession)==null?void 0:u.id;if(l){e({streamingMessageId:null});try{const h=await(await Ne(`/api/sessions/${l}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:n,attachments:s,messageKind:a==null?void 0:a.messageKind})})).json();h.queueState&&e({queuedMessages:h.queueState})}catch(c){console.error("Error sending message:",c)}}},stopGeneration:async()=>{var s;const n=(s=t().currentSession)==null?void 0:s.id;if(n&&!t().abortInProgress){e({abortInProgress:!0});try{await Ne(`/api/sessions/${n}/stop`,{method:"POST"})}catch(a){console.error("Error stopping generation:",a)}}},continueGeneration:async()=>{var s;const n=(s=t().currentSession)==null?void 0:s.id;if(n){e({streamingMessageId:null});try{await Ne(`/api/sessions/${n}/continue`,{method:"POST"})}catch(a){console.error("Error continuing generation:",a)}}},launchRunner:(n,s,a,l)=>{e({streamingMessageId:null});const u={};n!=null&&n.trim()&&(u.content=n),s&&s.length>0&&(u.attachments=s),a&&(u.workflowId=a),l&&(u.subGroup=l),zt.send("runner.launch",u)},switchMode:async n=>{var a;const s=(a=t().currentSession)==null?void 0:a.id;if(s)try{const l=await Ne(`/api/sessions/${s}/mode`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:n})});if(!l.ok){console.error("Failed to switch mode:",await l.json());return}const u=await l.json();u.session&&e({currentSession:u.session})}catch(l){console.error("Error switching mode:",l)}},switchDangerLevel:async n=>{var a;const s=(a=t().currentSession)==null?void 0:a.id;if(s)try{const l=await Ne(`/api/sessions/${s}/danger-level`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({dangerLevel:n})});if(!l.ok){console.error("Failed to switch danger level:",await l.json());return}const u=await l.json();u.session&&e({currentSession:u.session})}catch(l){console.error("Error switching danger level:",l)}},acceptAndBuild:(n,s,a,l)=>{var h;e({streamingMessageId:null});const u={};n&&(u.workflowId=n),s!=null&&s.trim()&&(u.content=s),a&&a.length>0&&(u.attachments=a),l&&(u.subGroup=l);const c=(h=t().currentSession)==null?void 0:h.id;c&&Ne(`/api/sessions/${c}/mode`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:"builder"})}).then(()=>{zt.send("runner.launch",u)})},editCriteria:async n=>{var a;const s=(a=t().currentSession)==null?void 0:a.id;if(s)try{const l=await Ne(`/api/sessions/${s}/criteria`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({criteria:n})});l.ok||console.error("Failed to update criteria:",await l.json())}catch(l){console.error("Error updating criteria:",l)}},compactContext:()=>{zt.send("context.compact",{})},setSessionProvider:async(n,s)=>{var a,l;try{const u=(a=t().currentSession)==null?void 0:a.id;if(!u)return null;const c=await Ne(`/api/sessions/${u}/provider`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerId:n,...s?{model:s}:{}})});if(!c.ok)return null;const h=await c.json();if(e({currentSession:h.session,messages:h.messages??[],contextState:h.contextState}),(l=h.session)!=null&&l.providerId){const f=Bt.getState();f.providers.find(m=>m.id===h.session.providerId)&&f.syncFromSession(h.session.providerId,h.session.providerModel??"")}return h.session}catch{return null}},updateContextState:n=>{e({contextState:n})},updateSubAgentContextState:(n,s)=>{e(a=>({subAgentContextStates:{...a.subAgentContextStates,[n]:s}}))},clearSubAgentContextState:n=>{e(s=>{const a={...s.subAgentContextStates};return delete a[n],{subAgentContextStates:a}})},confirmPath:async(n,s,a=!1)=>{var u;const l=(u=t().currentSession)==null?void 0:u.id;if(l)try{await Ne(`/api/sessions/${l}/confirm-path`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:n,approved:s,alwaysAllow:a})})}catch(c){console.error("Error confirming path:",c)}},answerQuestion:async(n,s)=>{var l;const a=(l=t().currentSession)==null?void 0:l.id;if(a){try{await Ne(`/api/sessions/${a}/answer`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:n,answer:s})})}catch(u){console.error("Error answering question:",u)}e({pendingQuestion:null})}},queueAsap:async(n,s,a)=>{var u;const l=(u=t().currentSession)==null?void 0:u.id;l&&await Tv(l,n,s,a,e)},queueCompletion:async(n,s,a)=>{var u;const l=(u=t().currentSession)==null?void 0:u.id;l&&await Tv(l,n,s,a,e)},cancelQueued:async n=>{var a;const s=(a=t().currentSession)==null?void 0:a.id;if(s)try{const u=await(await Ne(`/api/sessions/${s}/queue/${n}`,{method:"DELETE"})).json();u.queueState&&e({queuedMessages:u.queueState})}catch(l){console.error("Error canceling queued message:",l)}},clearError:()=>{e({error:null})},resetPendingSessionCreate:()=>{e({pendingSessionCreate:!1})},handleServerMessage:n=>{jv(n,e,t)}}));function Pu(){return we(e=>{var t;return((t=e.currentSession)==null?void 0:t.isRunning)??!1})}function uj(){return we(e=>e.abortInProgress)}function dj(){const e=we(s=>s.connect),t=we(s=>s.connectionStatus),n=bi(s=>s.load);return R.useEffect(()=>{e()},[e]),R.useEffect(()=>{t==="connected"&&n()},[t,n]),{connectionStatus:t}}const hj="modulepreload",fj=function(e){return"/"+e},Av={},Z=function(t,n,s){let a=Promise.resolve();if(n&&n.length>0){let u=function(f){return Promise.all(f.map(p=>Promise.resolve(p).then(m=>({status:"fulfilled",value:m}),m=>({status:"rejected",reason:m}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),h=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));a=u(n.map(f=>{if(f=fj(f),f in Av)return;Av[f]=!0;const p=f.endsWith(".css"),m=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${m}`))return;const _=document.createElement("link");if(_.rel=p?"stylesheet":hj,p||(_.as="script"),_.crossOrigin="",_.href=f,h&&_.setAttribute("nonce",h),document.head.appendChild(_),p)return new Promise((x,w)=>{_.addEventListener("load",x),_.addEventListener("error",()=>w(new Error(`Unable to preload CSS for ${f}`)))})}))}function l(u){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=u,window.dispatchEvent(c),!c.defaultPrevented)throw u}return a.then(u=>{for(const c of u||[])c.status==="rejected"&&l(c.reason);return t().catch(l)})},fS=[{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"}],Or=[{id:"system",name:"System",tokens:{}},{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":"255 255 255","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 Lv(){try{const e=localStorage.getItem("openfox:userPresets");if(e)return JSON.parse(e)}catch{}return[]}const Ut=qn((e,t)=>({currentPreset:"dark",basePreset:"",customTokens:{},isCustom:!1,isCustomizing:!1,userPresets:Lv(),followSystemTheme:!0,isSystem:!1,applySavedTheme:()=>{const{getSavedTheme:n,applyPreset:s,applyTokens:a}=t(),l=n();if(l)try{const u=JSON.parse(l);u.preset&&u.tokens?(s(u.preset),e({basePreset:u.preset}),a(u.tokens)):u.preset?s(u.preset):u.tokens&&a(u.tokens)}catch{s("dark")}else s("dark")},applyPreset:n=>{if(Or.find(a=>a.id===n))if(n==="system"){const l=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";e({basePreset:"system",currentPreset:l,customTokens:{},isCustom:!1,isCustomizing:!1,isSystem:!0}),t().applyTheme()}else e({currentPreset:n,basePreset:"",customTokens:{},isCustom:!1,isCustomizing:!1,isSystem:!1}),t().applyTheme()},startCustomizing:()=>{var a;const{currentPreset:n}=t(),s=((a=Or.find(l=>l.id===n))==null?void 0:a.tokens)??{};e({basePreset:n,customTokens:{...s},isCustom:!0,isCustomizing:!0})},setCustomToken:(n,s)=>{e(a=>({customTokens:{...a.customTokens,[n]:s}})),t().applyTheme()},cancelCustomizing:()=>{t().applyPreset(t().basePreset||t().currentPreset)},saveCustomTheme:()=>{const{customTokens:n}=t();t().saveTheme(JSON.stringify({tokens:n})).catch(()=>{}),e({isCustomizing:!1})},applyTokens:n=>{e({customTokens:n,isCustom:!0,isCustomizing:!1}),t().applyTheme()},getActiveTheme:()=>{var u,c;const{basePreset:n,customTokens:s,isCustom:a}=t();if(a&&n)return{...((u=Or.find(f=>f.id===n))==null?void 0:u.tokens)??{},...s};if(a)return{...fS.reduce((h,f)=>({...h,[f.key]:f.defaultValue}),{}),...s};const l=Or.find(h=>h.id===t().currentPreset);return(l==null?void 0:l.tokens)??((c=Or[0])==null?void 0:c.tokens)??{}},applyTheme:()=>{if(typeof document>"u")return;const n=t().getActiveTheme(),s=document.documentElement;Object.entries(n).forEach(([a,l])=>{s.style.setProperty(`--${a}`,l)})},getSavedTheme:()=>{try{const n=localStorage.getItem("openfox:theme");if(!n)return null;if(n[0]!=="{")return JSON.stringify({preset:n});const s=JSON.parse(n);if(s.preset)return JSON.stringify({preset:s.preset});if(s.tokens)return JSON.stringify({tokens:s.tokens})}catch{return null}return null},saveTheme:async n=>{localStorage.setItem("openfox:theme",n);const{useSettingsStore:s}=await Z(async()=>{const{useSettingsStore:a}=await Promise.resolve().then(()=>jf);return{useSettingsStore:a}},void 0);await s.getState().setSetting(ze.DISPLAY_THEME,n)},clearCustomTheme:()=>{localStorage.removeItem("openfox:theme"),e({isCustom:!1,isCustomizing:!1,basePreset:""})},setFollowSystemTheme:n=>{e({followSystemTheme:n}),Z(async()=>{const{useSettingsStore:s,SETTINGS_KEYS:a}=await Promise.resolve().then(()=>jf);return{useSettingsStore:s,SETTINGS_KEYS:a}},void 0).then(({useSettingsStore:s,SETTINGS_KEYS:a})=>{s.getState().setSetting(a.DISPLAY_FOLLOW_SYSTEM_THEME,String(n))})},initSystemThemeListener:()=>{if(typeof window>"u")return()=>{};const n=window.matchMedia("(prefers-color-scheme: dark)"),s=l=>{const{followSystemTheme:u}=t();u&&(t().applyPreset(l?"dark":"light"),t().saveTheme(JSON.stringify({preset:l?"dark":"light"})))},a=l=>s(l.matches);return n.addEventListener("change",a),()=>n.removeEventListener("change",a)},reset:()=>{e({currentPreset:"dark",basePreset:"",customTokens:{},isCustom:!1,isCustomizing:!1,userPresets:[],followSystemTheme:!0})},addUserPreset:n=>{const{basePreset:s,customTokens:a,currentPreset:l}=t(),u={id:"custom-"+Date.now(),name:n,basePreset:s||l,tokens:{...a}},c=[...t().userPresets,u];e({userPresets:c}),t().saveUserPresets()},applyUserPreset:n=>{const s=t().userPresets[n];s&&(e({currentPreset:s.basePreset,basePreset:s.basePreset,customTokens:{...s.tokens},isCustom:!0,isCustomizing:!1}),t().applyTheme(),t().saveTheme(JSON.stringify({preset:s.basePreset,tokens:s.tokens})).catch(()=>{}))},deleteUserPreset:n=>{const s=t().userPresets.filter((a,l)=>l!==n);e({userPresets:s}),t().saveUserPresets()},loadUserPresets:()=>{e({userPresets:Lv()})},saveUserPresets:()=>{localStorage.setItem("openfox:userPresets",JSON.stringify(t().userPresets)),Z(async()=>{const{useSettingsStore:n}=await Promise.resolve().then(()=>jf);return{useSettingsStore:n}},void 0).then(({useSettingsStore:n})=>{n.getState().setSetting(ze.DISPLAY_USER_PRESETS,JSON.stringify(t().userPresets)).catch(()=>{})})}}));function mj({canLoad:e,projectId:t,currentProjectId:n}){const s=Lt(u=>u.loadProject),a=we(u=>u.listSessions),l=we(u=>u.clearSession);R.useEffect(()=>{e&&t&&(n!==t&&s(t),a(t),l())},[e,t,n,s,a,l])}function pj({canLoad:e,projectId:t,sessionId:n,currentProjectId:s,currentSessionId:a}){const l=we(f=>f.loadSession),u=Lt(f=>f.loadProject),c=we(f=>f.listSessions),h=we(f=>f.pendingSessionCreate);R.useEffect(()=>{e&&t&&s!==t&&u(t)},[e,t,s,u]),R.useEffect(()=>{e&&n&&a!==n&&l(n),e&&t&&c(t)},[e,n,a,l,c,h,t])}function gj({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 mS({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 xj({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 _j({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 yj({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M9.5 3.25a2.25 2.25 0 1 1 3 2.122V6A2.5 2.5 0 0 1 10 8.5H6a1 1 0 0 0-1 1v1.128a2.251 2.251 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.5 0v1.836A2.493 2.493 0 0 1 6 7h4a1 1 0 0 0 1-1v-.628A2.25 2.25 0 0 1 9.5 3.25Zm-6 0a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Zm8.25-.75a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM4.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z"})})}function Mr({className:e="w-3.5 h-3.5 text-text-muted"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})}function Sr({className:e="w-3 h-3 text-text-muted",rotate:t}){return o.jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:t!==void 0?{transform:`rotate(${t}deg)`}:void 0,children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"})})}function vj({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 ap({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 bj({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 op({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 uu({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 Bu({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 Sj({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 wj({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 Cj({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 pS({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 kj({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 Dv({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 gS({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 Ej({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 jj({className:e="w-3 h-3",color:t}){return o.jsx("svg",{className:e,fill:t??"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{d:"M8 5v14l11-7z"})})}function qs({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 Nj({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 lp({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 Tj({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 Aj({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 Lj({className:e="w-3.5 h-3.5 text-text-muted"}){return o.jsx("svg",{className:e,fill:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{d:"M10.788 3.21c.448-1.077 1.976-1.077 2.424 0l2.082 5.007 5.404.433c1.164.093 1.636 1.545.749 2.305l-4.117 3.527 1.257 5.273c.271 1.136-.964 2.033-1.96 1.425L12 18.354 7.373 21.18c-.996.608-2.231-.29-1.96-1.425l1.257-5.273-4.117-3.527c-.887-.76-.415-2.212.749-2.305l5.404-.433 2.082-5.006z"})})}function Dj({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:"M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"})})}function xS({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 Rj({className:e="w-3.5 h-3.5 shrink-0",color:t}){return o.jsx("svg",{className:e,fill:"none",stroke:t,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 Oj({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("polyline",{points:"4 17 10 11 4 5"}),o.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function pl({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 cp(){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 Mj({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 bm({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 gl({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 _S({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 Ij({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:"M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"})})}function Pj({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:"M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"})})}function Rv({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:"M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"})})}function Sm(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function Ov(e,t){const n=zt.ws;!n||n.readyState!==WebSocket.OPEN||n.send(JSON.stringify({id:Sm(),type:e,payload:t}))}const _r=qn((e,t)=>({isOpen:!1,sessions:[],workdir:null,setOpen:n=>e({isOpen:n}),toggleOpen:()=>e(n=>({isOpen:!n.isOpen})),setWorkdir:n=>e({workdir:n}),fetchSessions:async n=>{if(!n){e({sessions:[]});return}try{const s=await Ne(`/api/terminals?projectId=${encodeURIComponent(n)}`);if(s.ok){const a=await s.json();e({sessions:a});const l=zt.ws;if(l&&l.readyState===WebSocket.OPEN)for(const u of a)l.send(JSON.stringify({id:Sm(),type:"terminal.subscribe",payload:{sessionId:u.id}}))}}catch(s){console.error("Failed to fetch terminals:",s)}},createSession:async(n,s)=>{try{const a=await Ne("/api/terminals",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workdir:n??t().workdir??void 0,projectId:s})});if(a.ok){const l=await a.json();e(c=>({sessions:[...c.sessions,l]}));const u=zt.ws;u&&u.readyState===WebSocket.OPEN&&u.send(JSON.stringify({id:Sm(),type:"terminal.subscribe",payload:{sessionId:l.id}}))}}catch(a){console.error("Failed to create terminal:",a)}},writeSession:(n,s)=>{Ov("terminal.write",{sessionId:n,data:s})},resizeSession:(n,s,a)=>{Ov("terminal.resize",{sessionId:n,cols:s,rows:a})},killSession:async n=>{try{(await Ne(`/api/terminals/${n}`,{method:"DELETE"})).ok&&e(a=>({sessions:a.sessions.filter(l=>l.id!==n)}))}catch(s){console.error("Failed to kill terminal:",s)}},handleMessage:n=>{switch(n.type){case"terminal.exit":{const{sessionId:s}=n.payload||{};s&&e(a=>{const l=a.sessions.filter(u=>u.id!==s);return l.length===0&&a.isOpen?{sessions:[],isOpen:!1}:{sessions:l}});break}}}}));zt.subscribe(e=>{var t;(t=e.type)!=null&&t.startsWith("terminal.")&&_r.getState().handleMessage(e)});const Aa={terminalToggle:{type:"double-press",key:"Control",threshold:300},quickAction:{type:"double-press",key:"Shift",threshold:300},agentSwitching:[{type:"chord",key:"1",modifiers:["ctrl"]},{type:"chord",key:"2",modifiers:["ctrl"]},{type:"chord",key:"3",modifiers:["ctrl"]},{type:"chord",key:"4",modifiers:["ctrl"]}]};function wm(e){if(!e)return structuredClone(Aa);try{const t=JSON.parse(e);return{terminalToggle:t.terminalToggle??structuredClone(Aa.terminalToggle),quickAction:t.quickAction??structuredClone(Aa.quickAction),agentSwitching:t.agentSwitching??structuredClone(Aa.agentSwitching)}}catch{return structuredClone(Aa)}}function Mv(e){return e.code.startsWith("Digit")?e.code.slice(-1):e.code.startsWith("Key")?e.code.slice(3).toLowerCase():e.key}function yS(e){if(e.type==="double-press")return`Double ${e.key==="Control"?"Ctrl":e.key==="Shift"?"Shift":e.key==="Alt"?"Alt":e.key==="Meta"?"Meta":e.key}`;const t=e.modifiers.map(s=>{switch(s){case"ctrl":return"Ctrl";case"meta":return"⌘";case"alt":return"Alt";case"shift":return"Shift"}}),n=e.key.length===1?e.key.toUpperCase():e.key;return[...t,n].join("+")}function Bj(e){return e.type==="double-press"}function vS(e){return e.type==="chord"}function zj(e,t){return t.length===1&&/^[a-z]$/i.test(t)?e.code===`Key${t.toUpperCase()}`:t.length===1&&/^[0-9]$/.test(t)?e.code===`Digit${t}`:e.key.toLowerCase()===t.toLowerCase()}function bS(e,t){const n=t.modifiers.includes("ctrl"),s=t.modifiers.includes("meta"),a=t.modifiers.includes("alt"),l=t.modifiers.includes("shift");return zj(e,t.key)&&e.ctrlKey===n&&e.metaKey===s&&e.altKey===a&&e.shiftKey===l}function up(){const e=an(t=>t.settings[ze.KEYBINDINGS]);return wm(e)}function Hj(e,t,n){const s=R.useRef(0),a=R.useRef(t);a.current=t,R.useEffect(()=>{if(!e)return;const l=e.threshold??300,u=c=>{if(c.key!==e.key)return;const h=e.key==="Control",f=e.key==="Shift",p=e.key==="Alt",m=e.key==="Meta";if(!h&&c.ctrlKey||!f&&c.shiftKey||!p&&c.altKey||!m&&c.metaKey)return;const _=Date.now();_-s.current<l?(c.preventDefault(),c.stopPropagation(),a.current(),s.current=0):s.current=_};return window.addEventListener("keydown",u,n!=null&&n.capture?!0:void 0),()=>window.removeEventListener("keydown",u,n!=null&&n.capture?!0:void 0)},[e,n==null?void 0:n.capture])}function $j(e,t){const n=R.useRef(t);n.current=t,R.useEffect(()=>{if(!e)return;const s=a=>{bS(a,e)&&(a.preventDefault(),n.current())};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e])}function SS(e,t,n){Hj(e&&Bj(e)?e:void 0,t,n),$j(e&&vS(e)?e:void 0,t)}function Uj(e,t,n){const s=R.useRef(n);s.current=n,R.useEffect(()=>{const a=l=>{for(let u=0;u<e.length;u++){const c=e[u];if(!c)continue;const h=t[u];if(h&&vS(c)&&bS(l,c)){l.preventDefault(),s.current(h.id);return}}};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[e,t])}var $a=Q0();const zu=R.forwardRef(({icon:e,iconSize:t="w-3.5 h-3.5",className:n="",...s},a)=>o.jsx("button",{ref:a,type:"button",className:`p-1 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors ${n}`,...s,children:o.jsx("svg",{className:t,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:e})})}));zu.displayName="IconButton";const Fj="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",Fs=R.forwardRef((e,t)=>o.jsx(zu,{ref:t,icon:Fj,title:"Edit",...e}));Fs.displayName="EditButton";const Vj="M6 18L18 6M6 6l12 12",dp=R.forwardRef((e,t)=>o.jsx(zu,{ref:t,icon:Vj,...e}));dp.displayName="CloseButton";const Gj={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 Dt({label:e,title:t,size:n="md",minHeight:s,children:a,footer:l,className:u,onClose:c,isOpen:h,closeOnBackdropClick:f=!0,closeOnEscape:p=!0,showCloseButton:m=!0}){const[_,x]=R.useState(!1),w=h!==void 0,k=w?h:_,y=R.useCallback(()=>{w||x(!0)},[w]),S=R.useCallback(()=>{w||x(!1),c==null||c()},[w,c]);R.useEffect(()=>{if(!k||!p)return;const b=E=>{E.key==="Escape"&&(E.stopPropagation(),S())};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[k,S,p]);const v=e&&(typeof e=="string"?o.jsx("button",{type:"button",onClick:y,className:u,children:e}):o.jsx("span",{onClick:y,className:u,style:{cursor:"pointer"},children:e}));return o.jsxs(o.Fragment,{children:[v,k&&(typeof document<"u"?$a.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:f?S:void 0}),o.jsxs("div",{className:`relative w-full ${Gj[n]} max-h-[90vh] bg-bg-secondary border border-border rounded shadow-xl flex flex-col`,children:[(t||m)&&o.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border",children:[t&&o.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:t}),m&&o.jsx(dp,{onClick:S,className:"ml-auto","aria-label":"Close"})]}),o.jsx("div",{className:"p-4 overflow-y-auto flex-1 min-h-0",style:s?{minHeight:s}:void 0,children:a}),l&&o.jsx("div",{className:"px-4 py-3 border-t border-border",children:l})]})]}),document.body):null)]})}function Wj({value:e,defaultUrl:t,disabled:n,onChange:s}){const a=e??t;return o.jsxs("div",{className:"relative",children:[o.jsx("select",{value:a,disabled:n,onChange:l=>{const u=l.target.value;s(u===t?null:u)},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:Y2.map(({url:l,label:u})=>o.jsx("option",{value:l,title:u,children:u.split(" ")[0]},l))}),o.jsx(Sr,{className:"absolute right-0.5 top-1/2 -translate-y-1/2 w-3 h-3 pointer-events-none text-text-muted"})]})}const Iv=[{key:"general",label:"General"},{key:"build",label:"Agent"},{key:"sub-agent",label:"Sub-agent"}];function qj(){const e=bi(h=>h.settings),t=bi(h=>h.update),n=bi(h=>h.updateEvent),s=bi(h=>h.updateAgentOverride),a=bi(h=>h.load);R.useEffect(()=>{a()},[a]);const l=async()=>{await Q2()==="granted"&&t({...e,browserNotificationEnabled:!0})},u=(h,f,p,m)=>{h==="general"?n(f,{[p]:m}):s(h,f,{[p]:m})},c=(h,f,p)=>{h==="general"?n(f,{customSoundUrl:p}):s(h,f,{customSoundUrl:p})};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(Pv,{label:"Sound notifications",description:"Play sounds when events occur",checked:e.soundEnabled,onChange:h=>t({...e,soundEnabled:h})}),o.jsx(Pv,{label:"Browser notifications",description:"Show desktop notifications when the window is not focused",checked:e.browserNotificationEnabled,onChange:h=>{h&&typeof Notification<"u"&&Notification.permission!=="granted"?l():t({...e,browserNotificationEnabled:h})}}),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"}),Iv.map(h=>o.jsx("th",{className:"text-center px-2 py-2 text-text-primary font-medium",children:h.label},h.key))]})}),o.jsx("tbody",{children:K2.map(h=>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:h.label})}),Iv.map(f=>{const p=dS(e,h.key,f.key==="general"?void 0:f.key),m=cS[h.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:p.soundEnabled,onChange:_=>u(f.key,h.key,"soundEnabled",_.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:p.browserNotification,onChange:_=>u(f.key,h.key,"browserNotification",_.target.checked),disabled:!e.browserNotificationEnabled,className:"rounded border-border",title:"Browser"})})]}),p.soundEnabled&&e.soundEnabled&&o.jsx(Wj,{value:p.customSoundUrl,defaultUrl:m,disabled:!e.soundEnabled,onChange:_=>c(f.key,h.key,_)})]})},f.key)})]},h.key))})]})})]})]})}function Pv({label:e,description:t,checked:n,onChange:s}){return o.jsxs("label",{className:"flex items-start justify-between gap-3 cursor-pointer group",children:[o.jsxs("div",{className:"flex-1 min-w-0",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 mt-0.5",children:t})]}),o.jsx("div",{className:"flex-shrink-0 pt-0.5",children:o.jsx("div",{className:`relative w-9 h-5 rounded-full transition-colors ${n?"bg-accent-primary":"bg-bg-tertiary border border-border"}`,onClick:a=>{a.preventDefault(),s(!n)},children:o.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white shadow transition-transform ${n?"translate-x-4":"translate-x-0.5"}`})})})]})}const tt=R.forwardRef(({variant:e="secondary",size:t="md",className:n="",children:s,...a},l)=>{const u="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"},h={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:l,className:`${u} ${c[e]} ${h[t]} ${n}`,...a,children:s})});tt.displayName="Button";async function hp(e,t,n){t({loading:!0});try{const a=await(await Ne(e)).json();t({defaults:a.defaults??[],userItems:a.userItems??[],...n?{projectItems:a.projectItems??[]}:{},loading:!1})}catch{t({loading:!1})}}const Tr=qn((e,t)=>({defaults:[],userItems:[],projectItems:[],loading:!1,fetchSkills:async()=>{await hp("/api/skills",e,!0)},toggleSkill:async n=>{try{const a=await(await Ne(`/api/skills/${n}/toggle`,{method:"POST"})).json();e(l=>({defaults:l.defaults.map(u=>u.id===n?{...u,enabled:a.enabled}:u),userItems:l.userItems.map(u=>u.id===n?{...u,enabled:a.enabled}:u)}))}catch{}},fetchSkill:async n=>{try{const s=await Ne(`/api/skills/${n}`);return s.ok?await s.json():null}catch{return null}},fetchDefaultContent:async n=>{try{const s=await Ne(`/api/skills/defaults/${n}`);return s.ok?await s.json():null}catch{return null}},createSkill:async(n,s)=>{const a=await Ws("POST","/api/skills",{...n,destination:s});return a.success&&await t().fetchSkills(),a},updateSkill:async(n,s)=>{const a=await Ws("PUT",`/api/skills/${n}`,s);return a.success&&await t().fetchSkills(),a},deleteSkill:async n=>{try{const s=await Ne(`/api/skills/${n}`,{method:"DELETE"}),a=await s.json();return s.ok?(e(l=>({userItems:l.userItems.filter(u=>u.id!==n)})),{success:!0}):{success:!1,error:a.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateSkill:async(n,s)=>Iu(`/api/skills/${n}/duplicate`,()=>t().fetchSkills(),s)}));function fp(){const[e,t]=R.useState({id:null,type:null}),n=R.useCallback(l=>t({id:l,type:"delete"}),[]),s=R.useCallback(()=>t({id:null,type:null}),[]),a=R.useCallback((l,u)=>e.id===l&&e.type===u,[e.id,e.type]);return{requestDelete:n,clearConfirm:s,isConfirming:a}}function mp({onConfirm:e,onCancel:t}){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:t,className:"px-1.5 py-0.5 rounded text-text-muted text-xs hover:bg-bg-primary transition-colors",children:"Cancel"})]})}function pp({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(pl,{})})}function du({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(ap,{})})}function ji({label:e,value:t,onChange:n,placeholder:s,readOnly:a,hint:l,mono:u}){return o.jsxs("div",{children:[o.jsxs("label",{className:"block text-xs text-text-secondary mb-1",children:[e,l&&o.jsx("span",{className:"text-text-muted ml-1",children:l})]}),o.jsx("input",{value:t,onChange:c=>n(c.target.value),readOnly:a,placeholder:s,className:`w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary ${u?"font-mono":""} ${a?"opacity-60":""}`})]})}function Kj({onCancel:e,onSave:t,saving:n,saveDisabled:s}){return o.jsxs("div",{className:"flex justify-end gap-2 pt-2 border-t border-border",children:[o.jsx(tt,{variant:"secondary",onClick:e,children:"Cancel"}),o.jsx(tt,{variant:"primary",onClick:t,disabled:n||s,children:n?"Saving...":"Save"})]})}function gp({message:e}){return o.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded",children:e})}function wS({description:e,onNew:t,loading:n,hasItems:s,children:a}){return o.jsxs(o.Fragment,{children:[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(tt,{variant:"primary",size:"sm",onClick:t,children:"+ New"})})]}),n&&!s?o.jsx("div",{className:"text-text-muted text-sm",children:"Loading..."}):s?a:o.jsx("div",{className:"text-text-muted text-sm",children:"No items defined."})]})}function CS({label:e="Custom",children:t}){return o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:e}),o.jsx("div",{className:"space-y-2",children:t})]})}function kS({description:e,onNew:t,newLabel:n="+ 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(tt,{variant:"primary",size:"sm",onClick:t,children:n})})]})}function ES({isBuiltIn:e,isConfirmingDelete:t,onView:n,onEdit:s,onDuplicate:a,onDelete:l,children:u}){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:u}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[e&&n&&o.jsx("button",{onClick:n,className:"p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",title:"View",children:o.jsx(uu,{})}),o.jsx(du,{onClick:a}),!e&&s&&o.jsx(Fs,{onClick:s}),!e&&(t?o.jsx(mp,{onConfirm:()=>{l==null||l()},onCancel:()=>{}}):o.jsx(pp,{onClick:()=>l==null?void 0:l()}))]})]})}function Yj({id:e,name:t,description:n,isBuiltIn:s,isConfirmingDelete:a,onView:l,onEdit:u,onDuplicate:c,onDelete:h}){return o.jsxs(ES,{isBuiltIn:s,isConfirmingDelete:a,onView:l,onEdit:u,onDuplicate:c,onDelete:h,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-text-primary text-sm font-medium",children:t}),o.jsx("span",{className:"text-text-muted text-xs font-mono",children:e})]}),n&&o.jsx("p",{className:"text-text-muted text-xs truncate",children:n})]})}function jS({loading:e,hasItems:t,loadingLabel:n,emptyLabel:s,children:a}){return e&&!t?o.jsx("div",{className:"text-text-muted text-sm",children:n}):t?o.jsx("div",{className:"space-y-4",children:a}):s?o.jsx("div",{className:"text-text-muted text-sm",children:s}):null}function NS({name:e,id:t,nameLabel:n="Name",idLabel:s="ID",namePlaceholder:a="My Item",idPlaceholder:l="my-item",nameHint:u,readOnlyId:c=!1,readOnlyHint:h="(read-only)",onNameChange:f,onIdChange:p}){return o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(ji,{label:n,value:e,onChange:f,placeholder:a,hint:u}),o.jsx(ji,{label:s,value:t,onChange:p,readOnly:c,placeholder:l,hint:c?h:void 0,mono:!0})]})}function TS(e={}){const{initialData:t={}}=e,[n,s]=R.useState("list"),[a,l]=R.useState(null),[u,c]=R.useState(""),[h,f]=R.useState(!1),[p,m]=R.useState(t),_=R.useCallback(()=>{m(t),c(""),l(null)},[t]),x=R.useCallback(S=>{s(S),S==="list"&&_()},[_]),w=R.useCallback(S=>{m(v=>typeof S=="function"?S(v):S)},[]),k=R.useCallback((S,v={})=>{l(S),s("edit"),m({...v}),c("")},[]),y=R.useCallback(()=>{l(null),s("edit"),m(t),c("")},[t]);return{view:n,editingId:a,formError:u,saving:h,formData:p,setView:x,setEditingId:l,setFormError:c,setFormData:w,setSaving:f,resetForm:_,startEditing:k,startNew:y}}function Bv({skill:e,isBuiltIn:t,isConfirmingDelete:n,onView:s,onEdit:a,onDuplicate:l,onDelete:u}){return o.jsx(Yj,{id:e.id,name:e.name,description:e.description,isBuiltIn:t,isConfirmingDelete:n,onView:s,onEdit:a,onDuplicate:l,onDelete:u})}function Xj({isOpen:e}){const t=Tr(z=>z.defaults),n=Tr(z=>z.userItems),s=Tr(z=>z.projectItems),a=Tr(z=>z.loading),l=Tr(z=>z.fetchSkills),u=Tr(z=>z.fetchSkill),c=Tr(z=>z.fetchDefaultContent),h=Tr(z=>z.createSkill),f=Tr(z=>z.updateSkill),p=Tr(z=>z.deleteSkill),{view:m,editingId:_,formError:x,saving:w,formData:k,setView:y,setEditingId:S,setFormError:v,setFormData:b,setSaving:E}=TS(),{clearConfirm:T}=fp();R.useEffect(()=>{e&&(l(),y("list"),S(null),T())},[e,l,T]);const N=(z,X,ne,F)=>{b({name:F??z.metadata.name,id:ne??z.metadata.id,description:z.metadata.description??"",version:z.metadata.version??"1.0.0",prompt:z.prompt,isReadOnly:X,destination:"user"})},L=async z=>{if(t.some(ne=>ne.id===z)){const ne=await c(z);if(!ne)return;N(ne,!0),S(z),v(""),y("edit")}else{const ne=await u(z);if(!ne)return;N(ne,!0),S(z),v(""),y("edit")}},A=async z=>{const ne=t.some(M=>M.id===z)?await c(z):await u(z);if(!ne)return;const F=`${z}-copy-${Date.now()}`;N(ne,!1,F,`${ne.metadata.name} (copy)`),S(null),v(""),y("edit")},D=()=>{b({name:"",id:"",description:"",version:"1.0.0",prompt:"",isReadOnly:!1,destination:"user"}),y("edit")},B=async z=>{const X=await u(z);X&&(N(X,!1),S(z),v(""),y("edit"))},q=async z=>{await p(z),T()},W=async()=>{const z=_??k.id;if(!z||!k.name||!k.prompt){v("Name, ID, and prompt are required.");return}E(!0),v("");const X={metadata:{id:z,name:k.name,description:k.description,version:k.version},prompt:k.prompt},ne=_?await f(_,X):await h(X,k.destination);if(E(!1),!ne.success){v(ne.error??"Failed to save skill.");return}y("list")},O=z=>{b(X=>({...X,name:z})),_||b(X=>({...X,id:z.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}))},V=k.isReadOnly;if(m==="edit")return 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:V?k.name:_?"Edit Skill":"New Skill"}),o.jsx("button",{onClick:()=>y("list"),className:"text-text-muted hover:text-text-primary",children:"Cancel"})]}),x&&o.jsx(gp,{message:x}),o.jsxs("div",{className:"space-y-3 mb-3",children:[o.jsx(NS,{name:k.name,id:k.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Skill",idPlaceholder:"my-skill",readOnlyId:!0,onNameChange:O,onIdChange:()=>{}}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(ji,{label:"Description",value:k.description,onChange:z=>b(X=>({...X,description:z})),placeholder:"What this skill does...",readOnly:V}),o.jsx(ji,{label:"Version",value:k.version,onChange:z=>b(X=>({...X,version:z})),placeholder:"1.0.0",readOnly:V})]})]}),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:z=>b(X=>({...X,prompt:z.target.value})),readOnly:V,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.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[o.jsx("label",{className:"text-xs text-text-secondary",children:"Save to:"}),o.jsxs("select",{value:k.destination,onChange:z=>b(X=>({...X,destination:z.target.value})),className:"px-2 py-1 bg-bg-tertiary border border-border rounded text-xs focus:outline-none focus:ring-1 focus:ring-accent-primary",children:[o.jsx("option",{value:"user",children:"Global config"}),o.jsx("option",{value:"project",children:"Project (.openfox/)"})]})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 border-t border-border flex-shrink-0",children:[o.jsx(tt,{variant:"secondary",onClick:()=>y("list"),children:"Cancel"}),V?o.jsx(tt,{variant:"primary",onClick:()=>{b(z=>({...z,name:z.name+" (copy)",id:`${_}-copy-${Date.now()}`,isReadOnly:!1})),S(null)},children:"Duplicate & Customize"}):o.jsx(tt,{variant:"primary",onClick:W,disabled:w||!k.name||!k.id||!k.prompt,children:w?"Saving...":"Save"})]})]});function G({items:z}){return z.map(X=>o.jsx(Bv,{skill:X,isBuiltIn:!1,isConfirmingDelete:!1,onView:()=>L(X.id),onEdit:()=>B(X.id),onDuplicate:()=>A(X.id),onDelete:()=>q(X.id)},X.id))}return o.jsxs("div",{children:[o.jsx(kS,{description:"Skills provide domain-specific knowledge that agents can load on demand.",onNew:D}),o.jsxs(jS,{loading:a,hasItems:t.length>0||n.length>0,loadingLabel:"Loading skills...",emptyLabel:"No skills created yet.",children:[t.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:t.map(z=>o.jsx(Bv,{skill:z,isBuiltIn:!0,isConfirmingDelete:!1,onView:()=>L(z.id),onDuplicate:()=>A(z.id)},z.id))})]}),n.length>0&&o.jsx(CS,{children:o.jsx(G,{items:n})}),s.length>0&&o.jsxs("div",{className:"mt-4",children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Project"}),o.jsx("div",{className:"space-y-2",children:o.jsx(G,{items:s})})]})]})]})}function Hu(){const e=an(a=>a.settings),t=an(a=>a.loading),n=an(a=>a.getSetting),s=an(a=>a.setSetting);return{settings:e,loading:t,getSetting:n,setSetting:s}}function Qj({isOpen:e}){const{settings:t,loading:n,getSetting:s,setSetting:a}=Hu(),l=t[ze.GLOBAL_INSTRUCTIONS]??"",u=n[ze.GLOBAL_INSTRUCTIONS]??!1,[c,h]=R.useState(l),[f,p]=R.useState(!1),[m,_]=R.useState(!1);R.useEffect(()=>{e&&s(ze.GLOBAL_INSTRUCTIONS)},[e,s]),R.useEffect(()=>{h(l),p(!1)},[l]);const x=async()=>{_(!0),await a(ze.GLOBAL_INSTRUCTIONS,c),_(!1),p(!1)},w=()=>{h(l),p(!1)},k=u||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=>{h(y.target.value),p(!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:k})]}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(tt,{variant:"secondary",onClick:w,disabled:!f,children:"Discard"}),o.jsx(tt,{variant:"primary",onClick:x,disabled:!f||k,children:m?"Saving...":"Save"})]})]})}function Jj(e){const t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);if(t){const n=parseInt(t[1]??"0",16),s=parseInt(t[2]??"0",16),a=parseInt(t[3]??"0",16);return`${n} ${s} ${a}`}return e}function vi(e){const t=e.split(" ").map(n=>parseInt(n,10));return t.length===3&&t.every(n=>!isNaN(n))?`#${t.map(n=>(n??0).toString(16).padStart(2,"0")).join("")}`:e}function Zj({isOpen:e,isNew:t,basePresetId:n,presetName:s,initialTokens:a,onClose:l,onSave:u}){const[c,h]=R.useState(a),[f,p]=R.useState(s);R.useEffect(()=>{h(a),p(s)},[a,s]);const m=(y,S)=>{const v=S.startsWith("#")?Jj(S):S;h(b=>({...b,[y]:v}))},_=()=>{u(f.trim()||"Untitled",{...c})},x=fS.reduce((y,S)=>{const v=S.category;return y[v]||(y[v]=[]),y[v].push(S),y},{}),w={background:"Backgrounds",surface:"Surfaces",text:"Text",accent:"Accents",border:"Border"},k=Or.find(y=>y.id===n);return o.jsx(Dt,{isOpen:e,onClose:l,size:"lg",title:t?"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:l,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:_,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:f,onChange:y=>p(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"})]}),!t&&o.jsxs("div",{className:"text-xs text-text-muted",children:["Based on ",o.jsx("span",{className:"text-text-primary",children:k==null?void 0:k.name})]}),Object.entries(x).map(([y,S])=>o.jsxs("div",{className:"space-y-3",children:[o.jsx("h4",{className:"text-xs font-medium text-text-muted uppercase",children:w[y]??y}),o.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:S.map(v=>o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("label",{htmlFor:v.key,className:"text-xs text-text-muted",children:v.label}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"color",id:v.key,value:vi(c[v.key]??v.defaultValue),onChange:b=>m(v.key,b.target.value),className:"w-8 h-8 rounded cursor-pointer border border-border bg-transparent flex-shrink-0"}),o.jsx("input",{type:"text",value:c[v.key]??v.defaultValue,onChange:b=>m(v.key,b.target.value),className:"flex-1 min-w-0 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"})]})]},v.key))})]},y))]})})}function eN(){const[e,t]=R.useState(null),n=Ut(b=>b.currentPreset),s=Ut(b=>b.isCustom),a=Ut(b=>b.basePreset),l=Ut(b=>b.isSystem),u=Ut(b=>b.applyPreset),c=Ut(b=>b.applyUserPreset),h=Ut(b=>b.deleteUserPreset),f=Ut(b=>b.saveTheme),p=Ut(b=>b.userPresets),m=b=>{b==="system"?(u(b),f(JSON.stringify({preset:"system"})).catch(()=>{})):(u(b),f(JSON.stringify({preset:b})).catch(()=>{}))},_=b=>{c(b)},x=b=>{const E=Or.find(T=>T.id===b);E&&t({type:"new",presetIndex:p.length,basePresetId:b,presetName:E.name+" Copy",tokens:{...E.tokens}})},w=b=>{const E=p[b];if(!E)return;const T=Or.find(L=>L.id===E.basePreset),N=T?{...T.tokens,...E.tokens}:E.tokens;t({type:"edit",presetIndex:b,basePresetId:E.basePreset,presetName:E.name,tokens:N})},k=(b,E)=>{if(!e)return;const T=[...p];if(e.type==="new"){const N={id:"custom-"+Date.now(),name:b,basePreset:e.basePresetId,tokens:E};T.push(N);const L=T.length-1;Ut.setState({userPresets:T}),Ut.getState().saveUserPresets(),Ut.getState().applyUserPreset(L)}else{const N=T[e.presetIndex];N&&(T[e.presetIndex]={...N,name:b,tokens:E}),Ut.setState({userPresets:T}),Ut.getState().saveUserPresets(),Ut.getState().applyUserPreset(e.presetIndex)}t(null)},y=()=>{t(null)},S=(b,E)=>{b.stopPropagation(),h(E)},v=l?"system":s?a:n;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:"flex flex-wrap gap-2 pb-2",children:Or.map(b=>{const E=b.id===v&&!s;return o.jsxs("div",{className:"relative group",children:[o.jsxs("button",{type:"button",onClick:()=>m(b.id),className:`flex flex-col items-center gap-2 px-3 py-3 rounded-lg border transition-colors min-w-[80px] ${E?"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:b.id==="system"?"transparent":vi(b.tokens["color-bg-primary"]??"#000"),borderColor:vi(b.tokens["color-border"]??"#000")},children:b.id==="system"?o.jsx("div",{className:"w-4 h-4 rounded-full",style:{background:"linear-gradient(135deg, #000 50%, #fff 50%)"}}):o.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:vi(b.tokens["color-text-primary"]??"#fff")}})}),o.jsx("span",{className:"text-xs",children:b.name})]}),b.id!=="system"&&o.jsx("button",{type:"button",onClick:T=>{T.stopPropagation(),x(b.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:"✎"})})]},b.id)})}),p.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:p.map((b,E)=>{const T=Or.find(L=>L.id===b.basePreset),N=T?{...T.tokens,...b.tokens}:b.tokens;return o.jsxs("div",{className:"relative group",children:[o.jsxs("button",{type:"button",onClick:()=>_(E),className:`w-full flex flex-col items-center gap-2 px-3 py-3 rounded-lg border transition-colors ${s&&a===b.basePreset&&v===b.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:vi(N["color-bg-primary"]??"#000"),borderColor:vi(N["color-border"]??"#000")},children:o.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:vi(N["color-text-primary"]??"#fff")}})}),o.jsx("span",{className:"text-xs truncate w-full text-center",children:b.name})]}),o.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),w(E)},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:L=>S(L,E),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(gl,{className:"w-3 h-3"})})]},b.id)})})]}),e&&o.jsx(Zj,{isOpen:!0,isNew:e.type==="new",presetIndex:e.presetIndex,basePresetId:e.basePresetId,presetName:e.presetName,initialTokens:e.tokens,onClose:y,onSave:k})]})}function tN(){return o.jsx(eN,{})}function nN(){const{settings:e,loading:t,getSetting:n,setSetting:s}=Hu(),a=t[ze.DISPLAY_SHOW_THINKING]??!1,l=[{key:ze.DISPLAY_SHOW_THINKING,label:"Show thinking blocks",description:"Display AI reasoning content in the feed"},{key:ze.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT,label:"Show expanded tool output",description:"Always show full tool call details instead of compact view"},{key:ze.DISPLAY_SHOW_STATS,label:"Show stats bar",description:"Display model, tokens, and timing information"},{key:ze.DISPLAY_SHOW_AGENT_DEFINITIONS,label:"Show agent definitions",description:"Display agent definition injections in the feed"},{key:ze.DISPLAY_SHOW_WORKFLOW_BARS,label:"Show workflow bars",description:"Display workflow start and end markers"},{key:ze.DISPLAY_SHOW_SYNTAX_HIGHLIGHTING,label:"Show syntax highlighting",description:"Nicer formatting, but very slow - does not affect red/green diff coloring"}],u=Object.fromEntries(l.map(p=>[p.key,e[p.key]??"true"])),[c,h]=R.useState(()=>Object.fromEntries(l.map(p=>[p.key,u[p.key]==="true"])));R.useEffect(()=>{l.forEach(p=>n(p.key))},[n]),R.useEffect(()=>{h(Object.fromEntries(l.map(p=>[p.key,u[p.key]==="true"])))},[JSON.stringify(u)]);const f=async p=>{const m=String(!c[p]);h(_=>({..._,[p]:!_[p]})),await s(p,m)};return a?o.jsx("div",{className:"text-sm text-text-muted",children:"Loading..."}):o.jsxs("div",{className:"space-y-6",children:[o.jsx(tN,{}),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:l.map(({key:p,label:m,description:_})=>o.jsxs("label",{className:"flex items-start justify-between gap-3 cursor-pointer",children:[o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("div",{className:"text-sm text-text-primary font-medium",children:m}),o.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:_})]}),o.jsx("button",{type:"button",onClick:()=>f(p),className:`relative inline-flex h-6 w-11 flex-shrink-0 items-center rounded-full transition-colors ${c[p]?"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[p]?"translate-x-6":"translate-x-1"}`})})]},p))})]})]})}function rN({enabled:e,onClick:t}){return o.jsx("button",{type:"button",onClick:t,className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${e?"bg-accent-primary":"bg-bg-tertiary"}`,children:o.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${e?"translate-x-6":"translate-x-1"}`})})}function sN(e){try{return new RegExp(e),!0}catch{return!1}}function iN({value:e,onChange:t}){const[n,s]=R.useState({}),a=(h,f)=>{const p=e.patterns.map((m,_)=>_===h?{...m,...f}:m);t({...e,patterns:p})},l=h=>{const f=e.patterns.filter((p,m)=>m!==h);t({...e,patterns:f})},u=()=>{const h={field:"content",pattern:"",action:"retry",active:!0};t({...e,patterns:[...e.patterns,h]})},c=(h,f)=>{s(p=>({...p,[h]:f.length>0&&!sN(f)})),a(h,{pattern:f})};return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-sm font-medium text-text-primary",children:"Max Retries Per Turn"}),o.jsx("input",{type:"number",min:1,max:100,value:e.maxRetriesPerTurn,onChange:h=>{const f=parseInt(h.target.value,10),p=isNaN(f)?10:Math.max(1,Math.min(100,f));t({...e,maxRetriesPerTurn:p})},className:"mt-1 block w-24 px-2 py-1 text-sm bg-bg-secondary border border-border rounded"})]}),e.patterns.length===0?o.jsx("p",{className:"text-sm text-text-muted",children:"No retry patterns configured."}):o.jsxs("table",{className:"w-full text-sm",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"text-left text-text-muted border-b border-border",children:[o.jsx("th",{className:"pb-2 pr-2 w-12",children:"Active"}),o.jsx("th",{className:"pb-2 pr-2",children:"Field"}),o.jsx("th",{className:"pb-2 pr-2",children:"Pattern"}),o.jsx("th",{className:"pb-2 pr-2",children:"Action"}),o.jsx("th",{className:"pb-2 w-8"})]})}),o.jsx("tbody",{children:e.patterns.map((h,f)=>o.jsxs("tr",{className:"border-b border-border",children:[o.jsx("td",{className:"py-2 pr-2",children:o.jsx("input",{type:"checkbox",checked:h.active,onChange:()=>a(f,{active:!h.active}),className:"accent-accent-primary","aria-label":`Toggle pattern ${f+1}`})}),o.jsx("td",{className:"py-2 pr-2",children:o.jsxs("select",{value:h.field,onChange:p=>a(f,{field:p.target.value}),className:"px-2 py-1 bg-bg-secondary border border-border rounded text-sm",children:[o.jsx("option",{value:"content",children:"content"}),o.jsx("option",{value:"thinking",children:"thinking"}),o.jsx("option",{value:"both",children:"both"})]})}),o.jsx("td",{className:"py-2 pr-2",children:o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("input",{type:"text",value:h.pattern,onChange:p=>c(f,p.target.value),placeholder:"regex pattern",className:"flex-1 px-2 py-1 bg-bg-secondary border border-border rounded text-sm font-mono"}),h.pattern.length>0&&o.jsx("span",{className:`text-sm ${n[f]?"text-red-500":"text-green-500"}`,children:n[f]?"✗":"✓"})]})}),o.jsx("td",{className:"py-2 pr-2 text-text-muted",children:"retry"}),o.jsx("td",{className:"py-2",children:o.jsx("button",{onClick:()=>l(f),title:"Remove pattern",className:"text-text-muted hover:text-red-500 transition-colors",children:"×"})})]},f))})]}),o.jsx(tt,{variant:"secondary",onClick:u,children:"Add Pattern"})]})}function aN({onClose:e}){const[,t]=cr(),{settings:n,getSetting:s,setSetting:a}=Hu(),l=n[ze.DISPLAY_SHOW_OPEN_IN_EDITOR]==="true",u=n[ze.LLM_DYNAMIC_SYSTEM_PROMPT]==="true",[c,h]=R.useState({openInEditor:l,dynamicPrompt:u}),[f,p]=R.useState({patterns:[],maxRetriesPerTurn:10});R.useEffect(()=>{h({openInEditor:l,dynamicPrompt:u})},[l,u]),R.useEffect(()=>{s(ze.DISPLAY_SHOW_OPEN_IN_EDITOR),s(ze.LLM_DYNAMIC_SYSTEM_PROMPT),s(ze.RETRY_PATTERNS)},[s]),R.useEffect(()=>{const k=n[ze.RETRY_PATTERNS];if(k)try{p(JSON.parse(k))}catch{}},[n]);const m=R.useCallback(k=>{p(k),a(ze.RETRY_PATTERNS,JSON.stringify(k))},[a]),_=()=>{const k=!c.openInEditor;h(y=>({...y,openInEditor:k})),a(ze.DISPLAY_SHOW_OPEN_IN_EDITOR,String(k))},x=()=>{const k=!c.dynamicPrompt;h(y=>({...y,dynamicPrompt:k})),a(ze.LLM_DYNAMIC_SYSTEM_PROMPT,String(k))};function w(){e(),t("/onboarding")}return o.jsxs("div",{className:"space-y-6",children:[o.jsx(zv,{title:"Dynamic System Prompt",description:"Rebuild the system prompt on every turn. When disabled, changes are applied on demand via the context header for better cache performance.",enabled:c.dynamicPrompt,onToggle:x,boldTitle:!0}),o.jsx("hr",{className:"border-border"}),o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary mb-3",children:"Auto-Retry Patterns"}),o.jsx("p",{className:"text-xs text-text-muted mb-3",children:'Define regex patterns that, when matched against LLM responses mid-stream, trigger an automatic retry with a "continue" prompt. The content that triggered the match is preserved in the chat feed.'}),o.jsx(iN,{value:f,onChange:m})]}),o.jsx("hr",{className:"border-border"}),o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary mb-3",children:"Integrations"}),o.jsx(zv,{title:'Show "Open in VSCode" links',description:"Display a link on file reads to open the file directly in VS Code.",enabled:c.openInEditor,onToggle:_})]}),o.jsx("hr",{className:"border-border"}),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(tt,{variant:"secondary",onClick:w,children:"Launch Onboarding"})]})]})}function zv({title:e,description:t,enabled:n,onToggle:s,boldTitle:a}){return o.jsxs("label",{className:"flex items-start justify-between gap-3 cursor-pointer",children:[o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("div",{className:`text-sm ${a?"font-medium":""} text-text-primary`,children:e}),o.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:t})]}),o.jsx("div",{className:"flex-shrink-0",children:o.jsx(rN,{enabled:n,onClick:s})})]})}function oN({label:e,binding:t,isRecording:n,onStartRecording:s,onBindingRecorded:a,onCancelRecording:l}){const u=R.useRef(null),c=R.useRef(0),h=R.useRef("");return R.useEffect(()=>{if(!n)return;const f=new Set(["Control","Shift","Alt","Meta"]);let p=[];const m=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){l();return}if(f.has(x.key)){x.ctrlKey&&!p.includes("ctrl")&&p.push("ctrl"),x.metaKey&&!p.includes("meta")&&p.push("meta"),x.altKey&&!p.includes("alt")&&p.push("alt"),x.shiftKey&&!p.includes("shift")&&p.push("shift");return}if(p.length>0||x.ctrlKey||x.metaKey||x.altKey||x.shiftKey){const y=[...p];x.ctrlKey&&!y.includes("ctrl")&&y.push("ctrl"),x.metaKey&&!y.includes("meta")&&y.push("meta"),x.altKey&&!y.includes("alt")&&y.push("alt"),x.shiftKey&&!y.includes("shift")&&y.push("shift"),a({type:"chord",key:Mv(x),modifiers:y});return}const w=Date.now(),k=Mv(x);if(k===h.current&&w-c.current<400){a({type:"double-press",key:k,threshold:300});return}c.current=w,h.current=k},_=x=>{x.key==="Control"&&(p=p.filter(w=>w!=="ctrl")),x.key==="Shift"&&(p=p.filter(w=>w!=="shift")),x.key==="Alt"&&(p=p.filter(w=>w!=="alt")),x.key==="Meta"&&(p=p.filter(w=>w!=="meta"))};return window.addEventListener("keydown",m,!0),window.addEventListener("keyup",_,!0),()=>{window.removeEventListener("keydown",m,!0),window.removeEventListener("keyup",_,!0)}},[n,a,l]),o.jsxs("div",{ref:u,className:`flex items-center justify-between px-3 py-2 rounded transition-colors ${n?"bg-accent-primary/10 ring-1 ring-accent-primary":"hover:bg-bg-tertiary"}`,children:[o.jsx("span",{className:"text-sm text-text-primary",children:e}),o.jsx("div",{className:"flex items-center gap-2",children:n?o.jsx("span",{className:"text-xs text-accent-primary font-medium animate-pulse",children:"Press shortcut..."}):o.jsx("button",{type:"button",onClick:s,className:"px-2 py-0.5 text-xs font-mono bg-bg-tertiary text-text-secondary rounded border border-border hover:border-accent-primary hover:text-accent-primary transition-colors",children:yS(t)})})]})}function lN(){const{settings:e,loading:t,setSetting:n}=Hu(),s=e[ze.KEYBINDINGS],a=t[ze.KEYBINDINGS]??!1,l=wm(s),[u,c]=R.useState(null),h=[{id:"terminalToggle",label:"Toggle Terminal",binding:l.terminalToggle},{id:"quickAction",label:"Quick Action",binding:l.quickAction},...l.agentSwitching.map((_,x)=>({id:`agentSwitching.${x}`,label:`Switch to Agent ${x+1}`,binding:_}))],f=_=>{c(_)},p=R.useCallback(_=>{if(!u)return;const x=wm(s),w=structuredClone(x);if(u.startsWith("agentSwitching.")){const k=parseInt(u.split(".")[1],10);w.agentSwitching[k]=_}else u==="terminalToggle"?w.terminalToggle=_:u==="quickAction"&&(w.quickAction=_);c(null),n(ze.KEYBINDINGS,JSON.stringify(w))},[u,s,n]),m=()=>{n(ze.KEYBINDINGS,JSON.stringify(Aa))};return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Keyboard Shortcuts"}),o.jsx("button",{type:"button",onClick:m,disabled:a,className:"text-xs text-text-muted hover:text-text-primary px-2 py-1 rounded hover:bg-bg-tertiary transition-colors disabled:opacity-30",children:"Reset to defaults"})]}),a?o.jsx("div",{className:"text-sm text-text-muted",children:"Loading..."}):o.jsx("div",{className:"space-y-1",children:h.map(_=>o.jsx(oN,{label:_.label,binding:_.binding,isRecording:u===_.id,onStartRecording:()=>f(_.id),onBindingRecorded:p,onCancelRecording:()=>c(null)},_.id))})]})}function cN({isOpen:e,onClose:t}){const[n,s]=R.useState("instructions"),a=()=>{try{zt.send("context.checkDynamic",{})}catch{}t()};return o.jsx(Dt,{isOpen:e,onClose:a,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 overflow-x-auto scrollbar-hide",children:[o.jsx(Sa,{label:"Instructions",active:n==="instructions",onClick:()=>s("instructions")}),o.jsx(Sa,{label:"Skills",active:n==="skills",onClick:()=>s("skills")}),o.jsx(Sa,{label:"Notifications",active:n==="notifications",onClick:()=>s("notifications")}),o.jsx(Sa,{label:"Display",active:n==="display",onClick:()=>s("display")}),o.jsx(Sa,{label:"Keybindings",active:n==="keybindings",onClick:()=>s("keybindings")}),o.jsx(Sa,{label:"Advanced",active:n==="advanced",onClick:()=>s("advanced")})]}),n==="instructions"&&o.jsx(Qj,{isOpen:e}),n==="skills"&&o.jsx(Xj,{isOpen:e}),n==="notifications"&&o.jsx("div",{className:"max-h-[60vh] overflow-y-auto",children:o.jsx(qj,{})}),n==="display"&&o.jsx(nN,{}),n==="keybindings"&&o.jsx(lN,{}),n==="advanced"&&o.jsx(aN,{onClose:t})]})})}function Sa({label:e,active:t,onClick:n}){return o.jsx("button",{onClick:n,className:`px-4 py-2 text-sm font-medium border-b-2 transition-colors whitespace-nowrap ${t?"border-accent-primary text-accent-primary":"border-transparent text-text-muted hover:text-text-secondary hover:border-border"}`,children:e})}var Of={exports:{}},Hv;function uN(){return Hv||(Hv=1,(function(e,t){(function(n,s){e.exports=s()})(globalThis,(()=>(()=>{var n={4567:function(u,c,h){var f=this&&this.__decorate||function(v,b,E,T){var N,L=arguments.length,A=L<3?b:T===null?T=Object.getOwnPropertyDescriptor(b,E):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(v,b,E,T);else for(var D=v.length-1;D>=0;D--)(N=v[D])&&(A=(L<3?N(A):L>3?N(b,E,A):N(b,E))||A);return L>3&&A&&Object.defineProperty(b,E,A),A},p=this&&this.__param||function(v,b){return function(E,T){b(E,T,v)}};Object.defineProperty(c,"__esModule",{value:!0}),c.AccessibilityManager=void 0;const m=h(9042),_=h(9924),x=h(844),w=h(4725),k=h(2585),y=h(3656);let S=c.AccessibilityManager=class extends x.Disposable{constructor(v,b,E,T){super(),this._terminal=v,this._coreBrowserService=E,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 _.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(`
|
|
59
59
|
`)))),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,x.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(v){for(let b=0;b<v;b++)this._handleChar(" ")}_handleChar(v){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==v&&(this._charsToAnnounce+=v):this._charsToAnnounce+=v,v===`
|
|
60
60
|
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=m.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(v){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(v)||this._charsToConsume.push(v)}_refreshRows(v,b){this._liveRegionDebouncer.refresh(v,b,this._terminal.rows)}_renderRows(v,b){const E=this._terminal.buffer,T=E.lines.length.toString();for(let N=v;N<=b;N++){const L=E.lines.get(E.ydisp+N),A=[],D=(L==null?void 0:L.translateToString(!0,void 0,void 0,A))||"",B=(E.ydisp+N+1).toString(),q=this._rowElements[N];q&&(D.length===0?(q.innerText=" ",this._rowColumns.set(q,[0,1])):(q.textContent=D,this._rowColumns.set(q,A)),q.setAttribute("aria-posinset",B),q.setAttribute("aria-setsize",T))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(v,b){const E=v.target,T=this._rowElements[b===0?1:this._rowElements.length-2];if(E.getAttribute("aria-posinset")===(b===0?"1":`${this._terminal.buffer.lines.length}`)||v.relatedTarget!==T)return;let N,L;if(b===0?(N=E,L=this._rowElements.pop(),this._rowContainer.removeChild(L)):(N=this._rowElements.shift(),L=E,this._rowContainer.removeChild(N)),N.removeEventListener("focus",this._topBoundaryFocusListener),L.removeEventListener("focus",this._bottomBoundaryFocusListener),b===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(b===0?-1:1),this._rowElements[b===0?1:this._rowElements.length-2].focus(),v.preventDefault(),v.stopImmediatePropagation()}_handleSelectionChange(){var D;if(this._rowElements.length===0)return;const v=document.getSelection();if(!v)return;if(v.isCollapsed)return void(this._rowContainer.contains(v.anchorNode)&&this._terminal.clearSelection());if(!v.anchorNode||!v.focusNode)return void console.error("anchorNode and/or focusNode are null");let b={node:v.anchorNode,offset:v.anchorOffset},E={node:v.focusNode,offset:v.focusOffset};if((b.node.compareDocumentPosition(E.node)&Node.DOCUMENT_POSITION_PRECEDING||b.node===E.node&&b.offset>E.offset)&&([b,E]=[E,b]),b.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(b={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(b.node))return;const T=this._rowElements.slice(-1)[0];if(E.node.compareDocumentPosition(T)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(E={node:T,offset:((D=T.textContent)==null?void 0:D.length)??0}),!this._rowContainer.contains(E.node))return;const N=({node:B,offset:q})=>{const W=B instanceof Text?B.parentNode:B;let O=parseInt(W==null?void 0:W.getAttribute("aria-posinset"),10)-1;if(isNaN(O))return console.warn("row is invalid. Race condition?"),null;const V=this._rowColumns.get(W);if(!V)return console.warn("columns is null. Race condition?"),null;let G=q<V.length?V[q]:V.slice(-1)[0]+1;return G>=this._terminal.cols&&(++O,G=0),{row:O,column:G}},L=N(b),A=N(E);if(L&&A){if(L.row>A.row||L.row===A.row&&L.column>=A.column)throw new Error("invalid range");this._terminal.select(L.column,L.row,(A.row-L.row)*this._terminal.cols-L.column+A.column)}}_handleResize(v){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let b=this._rowContainer.children.length;b<this._terminal.rows;b++)this._rowElements[b]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[b]);for(;this._rowElements.length>v;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const v=this._coreBrowserService.mainDocument.createElement("div");return v.setAttribute("role","listitem"),v.tabIndex=-1,this._refreshRowDimensions(v),v}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let v=0;v<this._terminal.rows;v++)this._refreshRowDimensions(this._rowElements[v])}}_refreshRowDimensions(v){v.style.height=`${this._renderService.dimensions.css.cell.height}px`}};c.AccessibilityManager=S=f([p(1,k.IInstantiationService),p(2,w.ICoreBrowserService),p(3,w.IRenderService)],S)},3614:(u,c)=>{function h(_){return _.replace(/\r?\n/g,"\r")}function f(_,x){return x?"\x1B[200~"+_+"\x1B[201~":_}function p(_,x,w,k){_=f(_=h(_),w.decPrivateModes.bracketedPasteMode&&k.rawOptions.ignoreBracketedPasteMode!==!0),w.triggerDataEvent(_,!0),x.value=""}function m(_,x,w){const k=w.getBoundingClientRect(),y=_.clientX-k.left-10,S=_.clientY-k.top-10;x.style.width="20px",x.style.height="20px",x.style.left=`${y}px`,x.style.top=`${S}px`,x.style.zIndex="1000",x.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=h,c.bracketTextForPaste=f,c.copyHandler=function(_,x){_.clipboardData&&_.clipboardData.setData("text/plain",x.selectionText),_.preventDefault()},c.handlePasteEvent=function(_,x,w,k){_.stopPropagation(),_.clipboardData&&p(_.clipboardData.getData("text/plain"),x,w,k)},c.paste=p,c.moveTextAreaUnderMouseCursor=m,c.rightClickHandler=function(_,x,w,k,y){m(_,x,w),y&&k.rightClickSelect(_),x.value=k.selectionText,x.select()}},7239:(u,c,h)=>{Object.defineProperty(c,"__esModule",{value:!0}),c.ColorContrastCache=void 0;const f=h(1505);c.ColorContrastCache=class{constructor(){this._color=new f.TwoKeyMap,this._css=new f.TwoKeyMap}setCss(p,m,_){this._css.set(p,m,_)}getCss(p,m){return this._css.get(p,m)}setColor(p,m,_){this._color.set(p,m,_)}getColor(p,m){return this._color.get(p,m)}clear(){this._color.clear(),this._css.clear()}}},3656:(u,c)=>{Object.defineProperty(c,"__esModule",{value:!0}),c.addDisposableDomListener=void 0,c.addDisposableDomListener=function(h,f,p,m){h.addEventListener(f,p,m);let _=!1;return{dispose:()=>{_||(_=!0,h.removeEventListener(f,p,m))}}}},3551:function(u,c,h){var f=this&&this.__decorate||function(S,v,b,E){var T,N=arguments.length,L=N<3?v:E===null?E=Object.getOwnPropertyDescriptor(v,b):E;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")L=Reflect.decorate(S,v,b,E);else for(var A=S.length-1;A>=0;A--)(T=S[A])&&(L=(N<3?T(L):N>3?T(v,b,L):T(v,b))||L);return N>3&&L&&Object.defineProperty(v,b,L),L},p=this&&this.__param||function(S,v){return function(b,E){v(b,E,S)}};Object.defineProperty(c,"__esModule",{value:!0}),c.Linkifier=void 0;const m=h(3656),_=h(8460),x=h(844),w=h(2585),k=h(4725);let y=c.Linkifier=class extends x.Disposable{get currentLink(){return this._currentLink}constructor(S,v,b,E,T){super(),this._element=S,this._mouseService=v,this._renderService=b,this._bufferService=E,this._linkProviderService=T,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new _.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new _.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,x.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,x.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(S){this._lastMouseEvent=S;const v=this._positionFromMouseEvent(S,this._element,this._mouseService);if(!v)return;this._isMouseOut=!1;const b=S.composedPath();for(let E=0;E<b.length;E++){const T=b[E];if(T.classList.contains("xterm"))break;if(T.classList.contains("xterm-hover"))return}this._lastBufferCell&&v.x===this._lastBufferCell.x&&v.y===this._lastBufferCell.y||(this._handleHover(v),this._lastBufferCell=v)}_handleHover(S){if(this._activeLine!==S.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(S,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,S)||(this._clearCurrentLink(),this._askForLink(S,!0))}_askForLink(S,v){var E,T;this._activeProviderReplies&&v||((E=this._activeProviderReplies)==null||E.forEach((N=>{N==null||N.forEach((L=>{L.link.dispose&&L.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=S.y);let b=!1;for(const[N,L]of this._linkProviderService.linkProviders.entries())v?(T=this._activeProviderReplies)!=null&&T.get(N)&&(b=this._checkLinkProviderResult(N,S,b)):L.provideLinks(S.y,(A=>{var B,q;if(this._isMouseOut)return;const D=A==null?void 0:A.map((W=>({link:W})));(B=this._activeProviderReplies)==null||B.set(N,D),b=this._checkLinkProviderResult(N,S,b),((q=this._activeProviderReplies)==null?void 0:q.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(S.y,this._activeProviderReplies)}))}_removeIntersectingLinks(S,v){const b=new Set;for(let E=0;E<v.size;E++){const T=v.get(E);if(T)for(let N=0;N<T.length;N++){const L=T[N],A=L.link.range.start.y<S?0:L.link.range.start.x,D=L.link.range.end.y>S?this._bufferService.cols:L.link.range.end.x;for(let B=A;B<=D;B++){if(b.has(B)){T.splice(N--,1);break}b.add(B)}}}}_checkLinkProviderResult(S,v,b){var N;if(!this._activeProviderReplies)return b;const E=this._activeProviderReplies.get(S);let T=!1;for(let L=0;L<S;L++)this._activeProviderReplies.has(L)&&!this._activeProviderReplies.get(L)||(T=!0);if(!T&&E){const L=E.find((A=>this._linkAtPosition(A.link,v)));L&&(b=!0,this._handleNewLink(L))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!b)for(let L=0;L<this._activeProviderReplies.size;L++){const A=(N=this._activeProviderReplies.get(L))==null?void 0:N.find((D=>this._linkAtPosition(D.link,v)));if(A){b=!0,this._handleNewLink(A);break}}return b}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(S){if(!this._currentLink)return;const v=this._positionFromMouseEvent(S,this._element,this._mouseService);v&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,v)&&this._currentLink.link.activate(S,this._currentLink.link.text)}_clearCurrentLink(S,v){this._currentLink&&this._lastMouseEvent&&(!S||!v||this._currentLink.link.range.start.y>=S&&this._currentLink.link.range.end.y<=v)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,x.disposeArray)(this._linkCacheDisposables))}_handleNewLink(S){if(!this._lastMouseEvent)return;const v=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);v&&this._linkAtPosition(S.link,v)&&(this._currentLink=S,this._currentLink.state={decorations:{underline:S.link.decorations===void 0||S.link.decorations.underline,pointerCursor:S.link.decorations===void 0||S.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,S.link,this._lastMouseEvent),S.link.decorations={},Object.defineProperties(S.link.decorations,{pointerCursor:{get:()=>{var b,E;return(E=(b=this._currentLink)==null?void 0:b.state)==null?void 0:E.decorations.pointerCursor},set:b=>{var E;(E=this._currentLink)!=null&&E.state&&this._currentLink.state.decorations.pointerCursor!==b&&(this._currentLink.state.decorations.pointerCursor=b,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",b))}},underline:{get:()=>{var b,E;return(E=(b=this._currentLink)==null?void 0:b.state)==null?void 0:E.decorations.underline},set:b=>{var E,T,N;(E=this._currentLink)!=null&&E.state&&((N=(T=this._currentLink)==null?void 0:T.state)==null?void 0:N.decorations.underline)!==b&&(this._currentLink.state.decorations.underline=b,this._currentLink.state.isHovered&&this._fireUnderlineEvent(S.link,b))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((b=>{if(!this._currentLink)return;const E=b.start===0?0:b.start+1+this._bufferService.buffer.ydisp,T=this._bufferService.buffer.ydisp+1+b.end;if(this._currentLink.link.range.start.y>=E&&this._currentLink.link.range.end.y<=T&&(this._clearCurrentLink(E,T),this._lastMouseEvent)){const N=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);N&&this._askForLink(N,!1)}}))))}_linkHover(S,v,b){var E;(E=this._currentLink)!=null&&E.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(v,!0),this._currentLink.state.decorations.pointerCursor&&S.classList.add("xterm-cursor-pointer")),v.hover&&v.hover(b,v.text)}_fireUnderlineEvent(S,v){const b=S.range,E=this._bufferService.buffer.ydisp,T=this._createLinkUnderlineEvent(b.start.x-1,b.start.y-E-1,b.end.x,b.end.y-E-1,void 0);(v?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(T)}_linkLeave(S,v,b){var E;(E=this._currentLink)!=null&&E.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(v,!1),this._currentLink.state.decorations.pointerCursor&&S.classList.remove("xterm-cursor-pointer")),v.leave&&v.leave(b,v.text)}_linkAtPosition(S,v){const b=S.range.start.y*this._bufferService.cols+S.range.start.x,E=S.range.end.y*this._bufferService.cols+S.range.end.x,T=v.y*this._bufferService.cols+v.x;return b<=T&&T<=E}_positionFromMouseEvent(S,v,b){const E=b.getCoords(S,v,this._bufferService.cols,this._bufferService.rows);if(E)return{x:E[0],y:E[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(S,v,b,E,T){return{x1:S,y1:v,x2:b,y2:E,cols:this._bufferService.cols,fg:T}}};c.Linkifier=y=f([p(1,k.IMouseService),p(2,k.IRenderService),p(3,w.IBufferService),p(4,k.ILinkProviderService)],y)},9042:(u,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(u,c,h){var f=this&&this.__decorate||function(k,y,S,v){var b,E=arguments.length,T=E<3?y:v===null?v=Object.getOwnPropertyDescriptor(y,S):v;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")T=Reflect.decorate(k,y,S,v);else for(var N=k.length-1;N>=0;N--)(b=k[N])&&(T=(E<3?b(T):E>3?b(y,S,T):b(y,S))||T);return E>3&&T&&Object.defineProperty(y,S,T),T},p=this&&this.__param||function(k,y){return function(S,v){y(S,v,k)}};Object.defineProperty(c,"__esModule",{value:!0}),c.OscLinkProvider=void 0;const m=h(511),_=h(2585);let x=c.OscLinkProvider=class{constructor(k,y,S){this._bufferService=k,this._optionsService=y,this._oscLinkService=S}provideLinks(k,y){var D;const S=this._bufferService.buffer.lines.get(k-1);if(!S)return void y(void 0);const v=[],b=this._optionsService.rawOptions.linkHandler,E=new m.CellData,T=S.getTrimmedLength();let N=-1,L=-1,A=!1;for(let B=0;B<T;B++)if(L!==-1||S.hasContent(B)){if(S.loadCell(B,E),E.hasExtendedAttrs()&&E.extended.urlId){if(L===-1){L=B,N=E.extended.urlId;continue}A=E.extended.urlId!==N}else L!==-1&&(A=!0);if(A||L!==-1&&B===T-1){const q=(D=this._oscLinkService.getLinkData(N))==null?void 0:D.uri;if(q){const W={start:{x:L+1,y:k},end:{x:B+(A||B!==T-1?0:1),y:k}};let O=!1;if(!(b!=null&&b.allowNonHttpProtocols))try{const V=new URL(q);["http:","https:"].includes(V.protocol)||(O=!0)}catch{O=!0}O||v.push({text:q,range:W,activate:(V,G)=>b?b.activate(V,G,W):w(0,G),hover:(V,G)=>{var z;return(z=b==null?void 0:b.hover)==null?void 0:z.call(b,V,G,W)},leave:(V,G)=>{var z;return(z=b==null?void 0:b.leave)==null?void 0:z.call(b,V,G,W)}})}A=!1,E.hasExtendedAttrs()&&E.extended.urlId?(L=B,N=E.extended.urlId):(L=-1,N=-1)}}y(v)}};function w(k,y){if(confirm(`Do you want to navigate to ${y}?
|
|
61
61
|
|
|
@@ -292,7 +292,7 @@ XID_Start XIDS`.split(/\s/).map(e=>[id(e),e])),EP=new Map([["s",sn(383)],[sn(383
|
|
|
292
292
|
`,children:n?"Reconnecting...":"Reconnect"})]})}const nn=qn((e,t)=>({defaults:[],userItems:[],projectItems:[],loading:!1,fetchCommands:async()=>{await hp("/api/commands",e,!0)},fetchCommand:async n=>{try{const s=await Ne(`/api/commands/${n}`);return s.ok?await s.json():null}catch{return null}},fetchDefaultContent:async n=>{try{const s=await Ne(`/api/commands/defaults/${n}`);return s.ok?await s.json():null}catch{return null}},createCommand:async(n,s)=>{const a=await Ws("POST","/api/commands",{...n,destination:s});return a.success&&await t().fetchCommands(),a},updateCommand:async(n,s)=>{const a=await Ws("PUT",`/api/commands/${n}`,s);return a.success&&await t().fetchCommands(),a},deleteCommand:async n=>{try{const s=await Ne(`/api/commands/${n}`,{method:"DELETE"}),a=await s.json();return s.ok?(e(l=>({userItems:l.userItems.filter(u=>u.id!==n)})),{success:!0}):{success:!1,error:a.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateCommand:async(n,s)=>Iu(`/api/commands/${n}/duplicate`,()=>t().fetchCommands(),s)}));function lB(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function cB({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(uu,{})})}function LC({isOpen:e,onClose:t,initialEditId:n}){const s=nn(me=>me.defaults),a=nn(me=>me.userItems),l=nn(me=>me.projectItems),u=nn(me=>me.loading),c=nn(me=>me.fetchCommands),h=nn(me=>me.fetchCommand),f=nn(me=>me.fetchDefaultContent),p=nn(me=>me.createCommand),m=nn(me=>me.updateCommand),_=nn(me=>me.deleteCommand),[x,w]=R.useState(null),[k,y]=R.useState(null),{view:S,editingId:v,formError:b,saving:E,formData:T,setView:N,setEditingId:L,setFormError:A,setFormData:D,setSaving:B}=TS(),{requestDelete:q,clearConfirm:W,isConfirming:O}=fp(),V=R.useRef(!1),G=mt(me=>me.defaults),z=mt(me=>me.userItems),X=mt(me=>me.fetchAgents),F=[...G,...z].filter(me=>!me.subagent),M=R.useRef(c),$=R.useRef(X),P=R.useRef(h),U=R.useRef(f),J=R.useRef(n),Q=R.useRef(N),se=R.useRef(L),Y=R.useRef(A),H=R.useRef(W);R.useEffect(()=>{M.current=c,$.current=X,P.current=h,U.current=f,J.current=n,Q.current=N,se.current=L,Y.current=A,H.current=W}),R.useEffect(()=>{if(e)if(M.current(),$.current(),V.current||(H.current(),V.current=!0),J.current){const me=s.some(je=>je.id===J.current);Q.current("edit"),se.current(J.current),Y.current(""),me?U.current(J.current).then(je=>{je&&D({name:je.metadata.name+" (copy)",id:`${J.current}-copy-${Date.now()}`,prompt:je.prompt,agentMode:je.metadata.agentMode??"",isDefault:!0,destination:"user"})}):P.current(J.current).then(je=>{je&&D({name:je.metadata.name,id:je.metadata.id,prompt:je.prompt,agentMode:je.metadata.agentMode??"",isDefault:!1,destination:"user"})})}else Q.current("list"),se.current(null);else V.current=!1},[e]);const ee=async me=>{w(me);const je=await f(me);y((je==null?void 0:je.prompt)??null)},te=async me=>{if(s.some(nt=>nt.id===me)){const nt=await f(me);nt&&(L(null),D({name:`${nt.metadata.name} (copy)`,id:`${me}-copy-${Date.now()}`,prompt:nt.prompt,agentMode:nt.metadata.agentMode??"",isDefault:!0,destination:"user"}),A(""),N("edit"))}else{const nt=await h(me);nt&&(L(null),D({name:`${nt.metadata.name} (copy)`,id:`${me}-copy-${Date.now()}`,prompt:nt.prompt,agentMode:nt.metadata.agentMode??"",isDefault:!1,destination:"user"}),A(""),N("edit"))}},ce=()=>{D({name:"",id:"",prompt:"",agentMode:"",isDefault:!1,destination:"user"}),L(null),N("edit")},he=async me=>{const je=await h(me);je&&(L(me),D({name:je.metadata.name,id:je.metadata.id,prompt:je.prompt,agentMode:je.metadata.agentMode??"",isDefault:!1,destination:"user"}),A(""),N("edit"))},Te=async me=>{await _(me),W()},Ae=async()=>{const me=v??T.id;if(!me||!T.name||!T.prompt){A("Name and message are required.");return}B(!0),A("");const je={metadata:{id:me,name:T.name,...T.agentMode?{agentMode:T.agentMode}:{}},prompt:T.prompt},nt=v?await m(v,je):await p(je,T.destination);if(B(!1),!nt.success){A(nt.error??"Failed to save command.");return}n?t():N("list")},Le=()=>{n?t():(N("list"),w(null),y(null))},Pe=me=>{D(je=>({...je,name:me})),(!v||T.isDefault)&&D(je=>({...je,id:lB(me)}))},de=()=>{w(null),y(null),N("list")},Ie=()=>{x&&(w(null),N("edit"),L(x),f(x).then(me=>{me&&D({name:`${me.metadata.name} (copy)`,id:`${x}-copy-${Date.now()}`,prompt:me.prompt,agentMode:me.metadata.agentMode??"",isDefault:!0,destination:"user"})}))};if(x){const me=s.find(je=>je.id===x);return o.jsx(Dt,{isOpen:e,onClose:de,title:`Default: ${(me==null?void 0:me.name)??x}`,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:x})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Name"}),o.jsx("div",{className:"px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm",children:me==null?void 0:me.name})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Agent Mode"}),o.jsx("div",{className:"px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm text-text-muted",children:(me==null?void 0:me.agentMode)||"None"})]})]}),o.jsxs("div",{className:"flex-1 min-h-[120px] border-t border-border pt-3 flex flex-col",children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Message"}),o.jsx("textarea",{value:k??"",readOnly:!0,placeholder:"...",className:"flex-1 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-none opacity-60"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 mt-3 border-t border-border flex-shrink-0",children:[o.jsx(tt,{variant:"secondary",onClick:de,children:"Close"}),o.jsx(tt,{variant:"primary",onClick:Ie,children:"Duplicate & Customize"})]})]})})}if(S==="edit")return o.jsx(Dt,{isOpen:e,onClose:Le,title:v?"Edit Command":"New Command",size:"xl",children:o.jsxs("div",{className:"flex flex-col h-full",children:[b&&o.jsx(gp,{message:b}),o.jsxs("div",{className:"space-y-3 mb-3",children:[o.jsx(NS,{name:T.name,id:T.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Command",idPlaceholder:"my-command",readOnlyId:!!v&&!T.isDefault,onNameChange:Pe,onIdChange:me=>D(je=>({...je,id:me}))}),o.jsxs("div",{children:[o.jsxs("label",{className:"block text-xs text-text-secondary mb-1",children:["Agent Mode ",o.jsx("span",{className:"text-text-muted",children:"(optional)"})]}),o.jsxs("select",{value:T.agentMode,onChange:me=>D(je=>({...je,agentMode:me.target.value})),className:"w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",children:[o.jsx("option",{value:"",children:"None (keep current mode)"}),F.map(me=>o.jsx("option",{value:me.id,children:me.name},me.id))]})]}),!v&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("label",{className:"text-xs text-text-secondary",children:"Save to:"}),o.jsxs("select",{value:T.destination,onChange:me=>D(je=>({...je,destination:me.target.value})),className:"px-2 py-1 bg-bg-tertiary border border-border rounded text-xs focus:outline-none focus:ring-1 focus:ring-accent-primary",children:[o.jsx("option",{value:"user",children:"Global config"}),o.jsx("option",{value:"project",children:"Project (.openfox/)"})]})]})]}),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:T.prompt,onChange:me=>D(je=>({...je,prompt:me.target.value})),placeholder:"The message that will be sent when this command is triggered...",className:"h-80 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 mt-3 border-t border-border flex-shrink-0",children:[o.jsx(tt,{variant:"secondary",onClick:Le,children:"Cancel"}),o.jsx(tt,{variant:"primary",onClick:Ae,disabled:E||!T.name||!T.prompt,children:E?"Saving...":"Save"})]})]})});const Se=me=>me.map(je=>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:je.name})})}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx(Fs,{onClick:()=>he(je.id)}),o.jsx(du,{onClick:()=>te(je.id)}),O(je.id,"delete")?o.jsx(mp,{onConfirm:()=>Te(je.id),onCancel:W}):o.jsx(pp,{onClick:()=>q(je.id)})]})]},je.id));return o.jsxs(Dt,{isOpen:e,onClose:t,title:"Commands",size:"lg",children:[o.jsx(kS,{description:"Commands are pre-defined messages you can send with a single click.",onNew:ce}),o.jsxs(jS,{loading:u,hasItems:s.length>0||a.length>0||l.length>0,loadingLabel:"Loading commands...",emptyLabel:"No commands created yet.",children:[s.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Built-in"}),o.jsx("div",{className:"space-y-2",children:s.map(me=>o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsx("div",{className:"min-w-0 flex-1 mr-3",children:o.jsx("span",{className:"text-text-primary text-sm font-medium",children:me.name})}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx(cB,{onClick:()=>ee(me.id)}),o.jsx(du,{onClick:()=>te(me.id)})]})]},me.id))})]}),a.length>0&&o.jsx(CS,{children:Se(a)}),l.length>0&&o.jsxs("div",{className:"mt-4",children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Project"}),o.jsx("div",{className:"space-y-2",children:Se(l)})]})]})]})}const gi=150,ss=54,ru=80,gr=30,ja=70,I0=100,xi=50,su=50,P0=4,DC={step_result:"Result",metadata_all_match:"Metadata match",metadata_all_in:"Metadata in",always:"otherwise"},RC=[{value:"step_result",label:"Step result is..."},{value:"metadata_all_match",label:"Metadata all match (key=value)"},{value:"metadata_all_in",label:"Metadata all in list"},{value:"always",label:"Always (fallback)"}],uB=[{value:"agent",label:"Agent"},{value:"sub_agent",label:"Sub-Agent"},{value:"shell",label:"Shell"}];function ng(e,t){if(e.type==="agent"){const n=t.find(s=>s.id===e.agentId);return{name:(n==null?void 0:n.name)??(e.agentId||"Agent"),color:(n==null?void 0:n.color)||"#3b82f6"}}if(e.type==="sub_agent"){const n=t.find(s=>s.id===e.subAgentType);return{name:(n==null?void 0:n.name)??(e.subAgentType||"Sub-Agent"),color:(n==null?void 0:n.color)||"#a855f7"}}return{name:"Shell",color:"#22c55e"}}function dB(e,t,n,s){const a=su+xi+gi+I0+gi+xi+su,l=a/2,u=su+xi+gi/2,c=su+xi+gi+I0+gi/2,h=[],f=[],p=new Map,m=e.filter(G=>G.type==="agent"||G.type==="shell"),_=e.filter(G=>G.type==="sub_agent"),x=_.length>0,w=x?u:l,k=m.length>0?c:l,y=xi+gr/2;h.push({id:"$start",type:"terminal",label:"Start",cx:w,cy:y,w:ru,h:gr}),p.set("$start",{cx:w,cy:y,w:ru,h:gr});const S=G=>{h.push({id:"$done",type:"terminal",label:"Done",cx:w,cy:G,w:ru,h:gr}),p.set("$done",{cx:w,cy:G,w:ru,h:gr})};if(e.length===0){const G=y+gr/2+ja*2+gr/2;return S(G),{nodes:h,edges:f,width:a,height:G+gr/2+xi,posMap:p}}const v=y+gr/2+ja,b=(G,z)=>{G.forEach((X,ne)=>{const F=v+ne*(ss+ja)+ss/2,{name:M,color:$}=ng(X,s);h.push({id:X.id,type:"step",label:M,color:$,cx:z,cy:F,w:gi,h:ss}),p.set(X.id,{cx:z,cy:F,w:gi,h:ss})})};b(m,w),b(_,k);const E=m.length>0?v+(m.length-1)*(ss+ja)+ss/2:y,T=x?v+(_.length-1)*(ss+ja)+ss/2:y,N=Math.max(E,T)+ss/2+ja+gr/2;S(N);const L=[];t&&p.has(t)&&L.push({from:"$start",to:t,label:n,edgeKey:"start",direction:"down",backEdgeIndex:0});let A=0;for(const G of e)G.transitions.forEach((z,X)=>{var U;if(!z.goto||!p.has(z.goto))return;const ne=p.get(G.id),F=p.get(z.goto),M=z.when.type==="step_result"?`${z.when.result}`:z.when.type==="metadata_all_match"?`${z.when.key??"?"}=${z.when.value??"?"}`:z.when.type==="metadata_all_in"?`${z.when.key??"?"} in [${((U=z.when.values)==null?void 0:U.join(","))??"?"}]`:DC[z.when.type]??z.when.type,$=G.id===z.goto;let P;$?P="back":F.cy>ne.cy+1?P="down":F.cy<ne.cy-1?P="back":P="same",L.push({from:G.id,to:z.goto,label:M,edgeKey:`${G.id}:${X}`,direction:P,backEdgeIndex:P==="back"?A++:0})});const D=new Map,B=new Map,q=new Map,W=new Map;for(const G of L)G.direction==="down"&&(D.set(G.from,(D.get(G.from)??0)+1),B.set(G.to,(B.get(G.to)??0)+1));const O=new Map,V=new Map;for(const G of L){if(G.direction!=="same")continue;const z=[G.from,G.to].sort().join("|");O.set(z,(O.get(z)??0)+1)}for(const G of L){if(G.direction==="back"||G.direction==="same"){let P=0;if(G.direction==="same"){const U=[G.from,G.to].sort().join("|");P=V.get(U)??0,V.set(U,P+1)}f.push({...G,fromPort:0,toPort:0,sameEdgeIndex:P});continue}const z=D.get(G.from)??1,X=B.get(G.to)??1,ne=q.get(G.from)??0,F=W.get(G.to)??0;q.set(G.from,ne+1),W.set(G.to,F+1);const M=z===1?0:-.6+1.2*ne/(z-1),$=X===1?0:-.6+1.2*F/(X-1);f.push({...G,fromPort:M,toPort:$,sameEdgeIndex:0})}return{nodes:h,edges:f,width:a,height:N+gr/2+xi,posMap:p}}function hB({steps:e,entryStep:t,selectedNodeId:n,selectedEdgeKey:s,startConditionLabel:a,agentTypes:l,isReadOnly:u,onSelectNode:c,onSelectEdge:h,onRemoveStep:f,onCreateTransition:p,onReconnectTo:m,onReconnectFrom:_,onDeleteTransition:x}){const w=R.useRef(null),k=R.useRef(!1),[y,S]=R.useState(null),[v,b]=R.useState(null),[E,T]=R.useState(null),{nodes:N,edges:L,width:A,height:D,posMap:B}=R.useMemo(()=>dB(e,t,a,l),[e,t,a,l]),q=R.useCallback(Q=>{var te;const se=w.current;if(!se)return{x:0,y:0};const Y=se.createSVGPoint();Y.x=Q.clientX,Y.y=Q.clientY;const H=(te=se.getScreenCTM())==null?void 0:te.inverse();if(!H)return{x:0,y:0};const ee=Y.matrixTransform(H);return{x:ee.x,y:ee.y}},[]),W=R.useCallback(Q=>!Q||!v||Q==="$start"?!1:v.type==="reconnect-from"?Q!=="$done":!0,[v]),O=R.useCallback((Q,se)=>{if(u)return;Q.stopPropagation(),Q.preventDefault();const Y=q(Q);b({type:"new",fromNodeId:se,mouseX:Y.x,mouseY:Y.y})},[q,u]),V=R.useCallback((Q,se)=>{if(u)return;Q.stopPropagation(),Q.preventDefault();const Y=q(Q);b({type:"reconnect-to",fromNodeId:se.from,edgeKey:se.edgeKey,mouseX:Y.x,mouseY:Y.y})},[q,u]),G=R.useCallback((Q,se)=>{if(u)return;Q.stopPropagation(),Q.preventDefault();const Y=q(Q);b({type:"reconnect-from",fromNodeId:se.from,fixedTargetId:se.to,edgeKey:se.edgeKey,mouseX:Y.x,mouseY:Y.y})},[q,u]),z=R.useCallback(Q=>{if(!v)return;const se=q(Q);b(Y=>Y?{...Y,mouseX:se.x,mouseY:se.y}:null)},[v,q]),X=R.useCallback(()=>{v&&(k.current=!0,E&&W(E)&&(v.type==="new"?p(v.fromNodeId,E):v.type==="reconnect-to"?m(v.edgeKey,E):v.type==="reconnect-from"&&_(v.edgeKey,E)),b(null),T(null))},[v,E,W,p,m,_]),ne=R.useCallback(()=>{if(k.current){k.current=!1;return}c(null),h(null)},[c,h]);R.useEffect(()=>{if(u)return;const Q=se=>{se.target instanceof HTMLInputElement||se.target instanceof HTMLTextAreaElement||se.target instanceof HTMLSelectElement||(se.key==="Delete"||se.key==="Backspace")&&s&&s!=="start"&&(se.preventDefault(),x(s),h(null))};return document.addEventListener("keydown",Q),()=>document.removeEventListener("keydown",Q)},[u,s,x,h]);const F=Q=>{const se=B.get(Q.from),Y=B.get(Q.to);if(!se||!Y)return null;let H,ee,te,ce="middle",he,Te;if(Q.direction==="down"){const Ae=se.cx+Q.fromPort*(se.w/2-10),Le=se.cy+se.h/2,Pe=Y.cx+Q.toPort*(Y.w/2-10),de=Y.cy-Y.h/2,Ie=de-Le,Se=Pe-Ae;H=`M ${Ae} ${Le} C ${Ae} ${Le+Ie*.4}, ${Pe-Se*.2} ${de-Ie*.1}, ${Pe} ${de}`,ee=Ae+(Pe-Ae)*.5,te=Le+Ie*.6,he={x:Ae,y:Le},Te={x:Pe,y:de}}else if(Q.direction==="back"){const Ae=Q.from===Q.to,Le=se.cx>=A/2,Pe=Q.backEdgeIndex*16,de=Le?A-20-Pe:20+Pe;if(Ae){const Ie=se.cx>=A/2,Se=30+Q.backEdgeIndex*14,me=se.cy-se.h/2,je=Ie?se.cx+se.w/2:se.cx-se.w/2,nt=Ie?je+Se:je-Se,Mt=se.cx+(Ie?se.w/4:-se.w/4),gt=me-20-Q.backEdgeIndex*10;H=`M ${je} ${se.cy} C ${nt} ${se.cy}, ${nt} ${gt}, ${Mt} ${me}`,ee=nt+10,te=gt+4,ce="middle",he={x:je,y:se.cy},Te={x:Mt,y:me}}else{const Ie=Le?se.cx+se.w/2:se.cx-se.w/2,Se=Y.cx+(Le?Y.w/4:-Y.w/4),me=Math.min(se.cy,Y.cy)-Y.h/2-18-Q.backEdgeIndex*14;H=`M ${Ie} ${se.cy} L ${de} ${se.cy} L ${de} ${me} L ${Se} ${me} L ${Se} ${Y.cy-Y.h/2}`,ee=de,te=(se.cy+me)/2,ce=Le?"start":"end",he={x:Ie,y:se.cy},Te={x:Se,y:Y.cy-Y.h/2}}}else{const Ae=Y.cx>se.cx,Le=Q.sameEdgeIndex===0?-12:12,Pe=Ae?se.cx+se.w/2:se.cx-se.w/2,de=Ae?Y.cx-Y.w/2:Y.cx+Y.w/2,Ie=se.cy+Le,Se=Y.cy+Le,me=(Pe+de)/2;H=`M ${Pe} ${Ie} C ${me} ${Ie}, ${me} ${Se}, ${de} ${Se}`,ee=me,te=(Ie+Se)/2-6,he={x:Pe,y:Ie},Te={x:de,y:Se}}return{path:H,labelX:ee,labelY:te,labelAnchor:ce,fromPt:he,toPt:Te}},M=(Q,se)=>{const Y=F(Q);if(!Y)return null;const{path:H,labelX:ee,labelY:te,labelAnchor:ce}=Y,he=s===Q.edgeKey,Te=Q.label&&Q.label!=="otherwise";return o.jsxs("g",{children:[o.jsx("path",{d:H,fill:"none",stroke:"transparent",strokeWidth:14,className:"cursor-pointer",onClick:Ae=>{Ae.stopPropagation(),u||h(he?null:Q.edgeKey)}}),o.jsx("path",{d:H,fill:"none",stroke:he?"#58a6ff":"#484f58",strokeWidth:he?2.2:1.2,markerEnd:he?"url(#arrow-selected)":"url(#arrow)",pointerEvents:"none"}),Te&&o.jsx("text",{x:ee+(ce==="start"?5:ce==="end"?-5:0),y:te+3,textAnchor:ce,className:"text-[8px]",fill:he?"#79c0ff":"#8b949e",style:{paintOrder:"stroke",stroke:"#0d1117",strokeWidth:3,strokeLinejoin:"round"},pointerEvents:"none",children:Q.label})]},se)},$=()=>{if(!s||v)return null;const Q=L.find(te=>te.edgeKey===s);if(!Q)return null;const se=F(Q);if(!se)return null;const{fromPt:Y,toPt:H}=se,ee=6;return o.jsxs(o.Fragment,{children:[Q.edgeKey!=="start"&&o.jsx("circle",{cx:Y.x,cy:Y.y,r:ee,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:te=>G(te,Q)}),o.jsx("circle",{cx:H.x,cy:H.y,r:ee,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:te=>V(te,Q)})]})},P=()=>{if(!v)return null;let Q,se,Y,H;if(v.type==="reconnect-from"){const ce=B.get(v.fixedTargetId);if(!ce)return null;Q=v.mouseX,se=v.mouseY,Y=ce.cx,H=ce.cy-ce.h/2}else{const ce=B.get(v.fromNodeId);if(!ce)return null;Q=ce.cx,se=ce.cy+ce.h/2,Y=v.mouseX,H=v.mouseY}const ee=H-se,te=Math.abs(ee)>10?`M ${Q} ${se} C ${Q} ${se+ee*.4}, ${Y} ${H-ee*.4}, ${Y} ${H}`:`M ${Q} ${se} L ${Y} ${H}`;return o.jsx("path",{d:te,fill:"none",stroke:"#58a6ff",strokeWidth:2,strokeDasharray:"6 3",strokeOpacity:.7,pointerEvents:"none"})},U=Q=>{const se=Q.cy+Q.h/2,Y=(v==null?void 0:v.fromNodeId)===Q.id;return o.jsx("circle",{cx:Q.cx,cy:se,r:P0,fill:Y?"#58a6ff":"#1c2128",stroke:Y?"#58a6ff":"#484f58",strokeWidth:1.5,strokeOpacity:Y?1:.5,className:"cursor-crosshair",onMouseDown:H=>O(H,Q.id)})},J=Q=>{const se=Q.cy-Q.h/2,Y=v&&E===Q.id&&W(Q.id);return o.jsx("circle",{cx:Q.cx,cy:se,r:P0,fill:Y?"#3fb950":"#1c2128",stroke:Y?"#3fb950":"#484f58",strokeWidth:1.5,strokeOpacity:Y?1:.5})};return o.jsxs("svg",{ref:w,viewBox:`0 0 ${A} ${D}`,className:"block w-full",preserveAspectRatio:"xMidYMin meet",onMouseMove:z,onMouseUp:X,onClick:ne,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"})})]}),L.map((Q,se)=>M(Q,se)),N.map(Q=>{const se=n===Q.id,Y=Q.cx-Q.w/2,H=Q.cy-Q.h/2,ee=y===Q.id,te=v&&E===Q.id&&W(Q.id);if(Q.type==="terminal"){const he=Q.id==="$start",Te=he?"#58a6ff":"#3fb950",Ae=he,Le=!he;return o.jsxs("g",{onClick:Pe=>{Pe.stopPropagation(),he&&!u&&h("start")},className:he&&!u?"cursor-pointer":void 0,children:[te&&o.jsx("rect",{x:Y-3,y:H-3,width:Q.w+6,height:Q.h+6,rx:Q.h/2+3,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),he&&s==="start"&&o.jsx("rect",{x:Y-3,y:H-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:H,width:Q.w,height:Q.h,rx:Q.h/2,fill:Te,fillOpacity:.08,stroke:Te,strokeOpacity:.4,strokeWidth:1.5}),o.jsx("text",{x:Q.cx,y:Q.cy+4,textAnchor:"middle",fill:Te,className:"text-[10px] font-medium",pointerEvents:"none",children:Q.label}),Ae&&U(Q),Le&&J(Q)]},Q.id)}const ce=Q.color??"#6b7280";return o.jsxs("g",{onClick:he=>{he.stopPropagation(),u||c(se?null:Q.id)},onMouseEnter:()=>S(Q.id),onMouseLeave:()=>S(null),className:u?void 0:"cursor-pointer",children:[te&&o.jsx("rect",{x:Y-3,y:H-3,width:Q.w+6,height:Q.h+6,rx:12,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),se&&o.jsx("rect",{x:Y-3,y:H-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:H,width:Q.w,height:Q.h,rx:10,fill:ce,fillOpacity:.08,stroke:ce,strokeOpacity:.6,strokeWidth:se?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}),!u&&U(Q),!u&&J(Q),ee&&!v&&!u&&o.jsxs("g",{onClick:he=>{he.stopPropagation(),f(Q.id)},className:"cursor-pointer",children:[o.jsx("circle",{cx:Y+Q.w-2,cy:H+2,r:8,fill:"#0d1117",fillOpacity:.9,stroke:"#f85149",strokeOpacity:.5,strokeWidth:1}),o.jsx("line",{x1:Y+Q.w-5,y1:H-1,x2:Y+Q.w+1,y2:H+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"}),o.jsx("line",{x1:Y+Q.w+1,y1:H-1,x2:Y+Q.w-5,y2:H+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"})]})]},Q.id)}),v&&N.map(Q=>W(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:se=>{se.stopPropagation(),X()}},`drop-${Q.id}`):null),P(),$()]})}function fB({name:e,id:t,color:n,description:s,isBuiltIn:a,actions:l}){return o.jsxs("div",{className:"flex items-center justify-between bg-bg-secondary rounded-lg p-4 border border-border",children:[o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0",style:{backgroundColor:n}}),o.jsx("span",{className:"text-text-primary text-sm font-medium",children:e}),o.jsx("span",{className:"text-text-muted text-xs font-mono",children:t}),a&&o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-medium bg-bg-primary text-text-muted",children:"Built-in"})]}),s&&o.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:s})]}),o.jsx("div",{className:"flex items-center gap-1 flex-shrink-0 ml-3",children:l})]})}function B0({title:e,items:t,renderActions:n}){return t.length===0?null:o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:e}),o.jsx("div",{className:"space-y-2",children:t.map(s=>o.jsx(fB,{name:s.name,id:s.id,color:s.color??"#3b82f6",description:s.description,actions:n(s)},s.id))})]})}const Na="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",pm="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",is="block text-[11px] text-text-secondary mb-0.5";function gm({variables:e,onInsert:t}){return e.length===0?null:o.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:e.map(n=>o.jsx("button",{type:"button",onClick:()=>t(n.name),title:n.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:`{{${n.name}}}`},n.name))})}function mB({step:e,isEntry:t,agentTypes:n,transitionCount:s,templateVariables:a,onUpdate:l,onRemove:u,onSetEntry:c}){const{color:h,name:f}=ng(e,n);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:h+"20",color:h},children:f}),t&&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:[!t&&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:u,className:"p-1 rounded text-text-muted hover:text-accent-error text-xs",children:"Delete"})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:is,children:"Type"}),o.jsx("select",{value:e.type,onChange:p=>{const m=p.target.value,_=m==="sub_agent"?"verification":"build";if(m==="agent"){const x=n.find(w=>!w.subagent);l({...e,type:m,phase:_,agentId:(x==null?void 0:x.id)??"builder",name:(x==null?void 0:x.name)??"Agent"})}else if(m==="sub_agent"){const x=n.find(w=>w.subagent);l({...e,type:m,phase:_,subAgentType:(x==null?void 0:x.id)??"",name:(x==null?void 0:x.name)??"Sub-Agent"})}else l({...e,type:m,phase:_,name:"Shell"})},className:pm,children:uB.map(p=>o.jsx("option",{value:p.value,children:p.label},p.value))})]}),e.type==="agent"&&o.jsxs("div",{children:[o.jsx("label",{className:is,children:"Agent Type"}),o.jsx("select",{value:e.agentId??"builder",onChange:p=>{const m=n.find(_=>_.id===p.target.value);l({...e,agentId:p.target.value,name:(m==null?void 0:m.name)??p.target.value})},className:pm,children:n.filter(p=>!p.subagent).map(p=>o.jsx("option",{value:p.id,children:p.name},p.id))})]}),e.type==="sub_agent"&&o.jsxs("div",{children:[o.jsx("label",{className:is,children:"Sub-Agent Type"}),o.jsxs("select",{value:e.subAgentType??"",onChange:p=>{const m=n.find(_=>_.id===p.target.value);l({...e,subAgentType:p.target.value,name:(m==null?void 0:m.name)??p.target.value})},className:pm,children:[o.jsx("option",{value:"",children:"— select —"}),n.filter(p=>p.subagent).map(p=>o.jsx("option",{value:p.id,children:p.name},p.id))]})]}),(e.type==="agent"||e.type==="sub_agent")&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("label",{className:is,children:"Prompt"}),o.jsx("textarea",{value:e.prompt??"",onChange:p=>l({...e,prompt:p.target.value||void 0}),rows:6,className:`${Na} resize-y text-xs`,placeholder:"Injected on first entry..."}),o.jsx(gm,{variables:a,onInsert:p=>l({...e,prompt:(e.prompt??"")+`{{${p}}}`})})]}),o.jsxs("div",{children:[o.jsx("label",{className:is,children:"Nudge Prompt"}),o.jsx("textarea",{value:e.nudgePrompt??"",onChange:p=>l({...e,nudgePrompt:p.target.value||void 0}),rows:6,className:`${Na} resize-y text-xs`,placeholder:"Injected on re-entry..."}),o.jsx(gm,{variables:a,onInsert:p=>l({...e,nudgePrompt:(e.nudgePrompt??"")+`{{${p}}}`})})]})]}),e.type==="shell"&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("label",{className:is,children:"Command"}),o.jsx("textarea",{value:e.command??"",onChange:p=>l({...e,command:p.target.value}),rows:3,className:`${Na} font-mono text-xs resize-y`,placeholder:"cd {{workdir}} && npm run lint"}),o.jsx(gm,{variables:a,onInsert:p=>l({...e,command:(e.command??"")+`{{${p}}}`})})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsx("label",{className:is,children:"Timeout (ms)"}),o.jsx("input",{type:"number",value:e.timeout??6e4,onChange:p=>l({...e,timeout:Number(p.target.value)}),className:`${Na} font-mono text-xs`})]}),o.jsxs("div",{children:[o.jsx("label",{className:is,children:"Success Codes"}),o.jsx("input",{value:(e.successExitCodes??[0]).join(", "),onChange:p=>l({...e,successExitCodes:p.target.value.split(",").map(m=>Number(m.trim())).filter(m=>!isNaN(m))}),className:`${Na} font-mono text-xs`})]})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:is,children:"Sub-group"}),o.jsx("input",{value:e.subGroup??"",onChange:p=>l({...e,subGroup:p.target.value||void 0}),placeholder:"e.g. build, verify, review",className:Na})]}),o.jsx("div",{className:"pt-1 border-t border-border/50",children:o.jsxs("p",{className:"text-text-muted text-[10px]",children:[s," outgoing transition",s!==1?"s":""," — drag from the bottom port to connect."]})})]})}const Ta="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",z0="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",_i="block text-[11px] text-text-secondary mb-0.5";function pB({fromLabel:e,toLabel:t,condition:n,subGroup:s,fromStep:a,agentTypes:l,transitionIndex:u,totalTransitions:c,onUpdateCondition:h,onUpdateSubGroup:f,onDelete:p,onMoveUp:m,onMoveDown:_}){var k;const x=a&&(a.type==="sub_agent"||a.type==="agent")?l.find(y=>y.id===(a.type==="sub_agent"?a.subAgentType:a.agentId)):void 0,w=(x==null?void 0:x.results)&&x.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.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsxs("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-blue-500/15 text-blue-300",children:["#",u+1]}),c>1&&o.jsxs("div",{className:"flex items-center gap-0.5",children:[o.jsx("button",{onClick:m,disabled:u===0,className:"p-0.5 rounded text-text-muted hover:text-text-primary disabled:opacity-20 disabled:cursor-not-allowed",title:"Move up (higher priority)",children:o.jsx(Sr,{className:"w-3 h-3",rotate:180})}),o.jsx("button",{onClick:_,disabled:u===c-1,className:"p-0.5 rounded text-text-muted hover:text-text-primary disabled:opacity-20 disabled:cursor-not-allowed",title:"Move down (lower priority)",children:o.jsx(Sr,{className:"w-3 h-3"})})]})]}),o.jsx("button",{onClick:p,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(mS,{}),o.jsx("span",{className:"font-medium text-text-primary",children:t})]}),o.jsxs("div",{children:[o.jsx("label",{className:_i,children:"Condition"}),o.jsx("select",{value:n.type,onChange:y=>{h(y.target.value==="step_result"?{type:"step_result",result:"success"}:{type:y.target.value})},className:z0,children:RC.map(y=>o.jsx("option",{value:y.value,children:y.label},y.value))})]}),n.type==="step_result"&&o.jsxs("div",{children:[o.jsx("label",{className:_i,children:"Result"}),w?o.jsx("select",{value:n.result??x.results[0],onChange:y=>{h({type:"step_result",result:y.target.value})},className:z0,children:x.results.map(y=>o.jsx("option",{value:y,children:y},y))}):o.jsx("input",{type:"text",value:n.result??"success",onChange:y=>h({type:"step_result",result:y.target.value}),placeholder:"e.g. success, passed, failed",className:Ta})]}),(n.type==="metadata_all_match"||n.type==="metadata_all_in")&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("label",{className:_i,children:"Metadata Key"}),o.jsx("input",{type:"text",value:n.key??"",onChange:y=>h({...n,key:y.target.value}),placeholder:"e.g. criteria, todos, review_findings",className:Ta})]}),o.jsxs("div",{children:[o.jsx("label",{className:_i,children:"Field"}),o.jsx("input",{type:"text",value:n.field??"",onChange:y=>h({...n,field:y.target.value}),placeholder:"e.g. status",className:Ta})]}),n.type==="metadata_all_match"?o.jsxs("div",{children:[o.jsx("label",{className:_i,children:"Value"}),o.jsx("input",{type:"text",value:n.value??"",onChange:y=>h({...n,value:y.target.value}),placeholder:"e.g. passed, resolved",className:Ta})]}):o.jsxs("div",{children:[o.jsx("label",{className:_i,children:"Values (comma-separated)"}),o.jsx("input",{type:"text",value:((k=n.values)==null?void 0:k.join(", "))??"",onChange:y=>h({...n,values:y.target.value.split(",").map(S=>S.trim()).filter(Boolean)}),placeholder:"e.g. resolved, dismissed",className:Ta})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:_i,children:"Sub-group"}),o.jsx("input",{type:"text",value:s??"",onChange:y=>f(y.target.value||void 0),placeholder:"e.g. build, verify",className:Ta})]}),o.jsx("p",{className:"text-text-muted text-[10px]",children:"Drag handles to reconnect. Order determines evaluation priority. Press Delete to remove."})]})}function gB(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function xB(e){let t=1;for(;e.some(n=>n.id===`s${t}`);)t++;return`s${t}`}const as="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",H0="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",xr="block text-[11px] text-text-secondary mb-0.5",$0=[];function OC({isOpen:e,onClose:t,initialEditId:n}){var Pi,hs;const s=Et(ye=>ye.defaults),a=Et(ye=>ye.userItems),l=Et(ye=>ye.loading),u=Et(ye=>ye.templateVariables),c=Et(ye=>ye.fetchWorkflows),h=Et(ye=>ye.fetchWorkflow),f=Et(ye=>ye.fetchDefaultContent),p=Et(ye=>ye.fetchTemplateVariables),m=Et(ye=>ye.createWorkflow),_=Et(ye=>ye.updateWorkflow),x=Et(ye=>ye.deleteWorkflow),{requestDelete:w,clearConfirm:k,isConfirming:y}=fp(),[S,v]=R.useState("list"),[b,E]=R.useState(null),[T,N]=R.useState(!1),[L,A]=R.useState(null),[D,B]=R.useState(null),[q,W]=R.useState(""),[O,V]=R.useState(""),[G,z]=R.useState(""),[X,ne]=R.useState("1.0.0"),[F,M]=R.useState("#3b82f6"),[$,P]=R.useState(""),[U,J]=R.useState(50),[Q,se]=R.useState($0),[Y,H]=R.useState({type:"always"}),[ee,te]=R.useState(""),[ce,he]=R.useState(!1),Te=mt(ye=>ye.defaults),Ae=mt(ye=>ye.userItems),Le=mt(ye=>ye.projectItems),Pe=R.useMemo(()=>[...Te,...Ae,...Le],[Te,Ae,Le]),de=mt(ye=>ye.fetchAgents),[Ie]=R.useState(null);R.useEffect(()=>{e&&(c(),p(),de(),A(null),B(null),n?s.some(_e=>_e.id===n)?f(n).then(_e=>{_e&&Se({..._e,metadata:{..._e.metadata,name:_e.metadata.name+" (copy)",id:`${n}-copy-${Date.now()}`}},{editingId:null,isReadOnly:!1})}):h(n).then(_e=>{_e&&Se(_e,{editingId:n,isReadOnly:!1})}):(v("list"),E(null),N(!1)))},[e,c,h,f,p,n]);const Se=(ye,_e)=>{W(ye.metadata.name),V(ye.metadata.id),z(ye.metadata.description),ne(ye.metadata.version),M(ye.metadata.color??"#3b82f6"),P(ye.entryStep),J(ye.settings.maxIterations),se(ye.steps),H(ye.startCondition??{type:"always"}),te(""),(_e==null?void 0:_e.editingId)!==void 0&&E(_e.editingId),(_e==null?void 0:_e.isReadOnly)!==void 0&&N(_e.isReadOnly),(_e==null?void 0:_e.selectedNodeKey)!==void 0&&A(null),(_e==null?void 0:_e.selectedEdgeKey)!==void 0&&B(null),v("edit")},me=async ye=>{const _e=await h(ye);_e&&Se(_e,{editingId:ye,isReadOnly:!1,selectedNodeKey:null,selectedEdgeKey:null})},je=async()=>{var et;const ye=b??O;if(!ye||!q)return te("Name is required."),!1;if(Q.length===0)return te("Add at least one step."),!1;let _e=$;if(!_e||!Q.some(qe=>qe.id===_e)){if(_e=((et=Q.find(qe=>qe.id))==null?void 0:et.id)??"",!_e)return te("All steps need an ID."),!1;P(_e)}he(!0),te("");const De={metadata:{id:ye,name:q,description:G,version:X||"1.0.0",color:F},entryStep:_e,settings:{maxIterations:U},steps:Q,startCondition:Y},$e=b?await _(b,De):await m(De);return he(!1),$e.success?(b||E(ye),!0):(te($e.error??"Failed to save."),!1)},nt=async()=>{await je()},Mt=async()=>{await je()&&(n?t():v("list"))},gt=()=>{n?t():v("list")},Zt=ye=>{W(ye),b||V(gB(ye))},ge=async ye=>s.some(De=>De.id===ye)?await f(ye):await h(ye),Ce=async ye=>{const _e=await ge(ye);_e&&Se(_e,{editingId:ye,isReadOnly:!0})},Oe=async ye=>{const _e=await ge(ye);_e&&Se({..._e,metadata:{..._e.metadata,name:_e.metadata.name+" (copy)",id:`${ye}-copy-${Date.now()}`}},{editingId:null,isReadOnly:!1})},Ve=()=>{E(null),W(""),V(""),z(""),ne("1.0.0"),M("#3b82f6"),P(""),J(50),se(structuredClone($0)),H({type:"always"}),te(""),A(null),B(null),N(!1),v("edit")},Ge=async ye=>{await x(ye),k()},vt=R.useCallback(ye=>{A(ye),B(null)},[]),Xe=R.useCallback(ye=>{B(ye),A(null)},[]),bt=L!==null?Number(L):-1,ct=bt>=0?Q[bt]??null:null,en=R.useCallback(ye=>{se(_e=>_e.map((De,$e)=>$e===bt?ye:De))},[bt]),He=Y.type==="step_result"?`${Y.result}`:Y.type==="metadata_all_match"?`${Y.key??"?"}=${Y.value??"?"}`:Y.type==="metadata_all_in"?`${Y.key??"?"} in [${((Pi=Y.values)==null?void 0:Pi.join(","))??"?"}]`:DC[Y.type]??Y.type,ur=()=>{const ye=Q.length,_e=xB(Q),De=Pe.find($e=>!$e.subagent);se([...Q,{id:_e,name:(De==null?void 0:De.name)??"Agent",type:"agent",phase:"build",agentId:(De==null?void 0:De.id)??"builder",transitions:[]}]),$||P(_e),vt(String(ye))},Mn=R.useCallback((ye,_e)=>{ye==="$start"?(P(_e),Xe("start")):se(De=>{const $e=De.find(qe=>qe.id===ye),et=$e?$e.transitions.length:0;return Xe(`${ye}:${et}`),De.map(qe=>qe.id===ye?{...qe,transitions:[...qe.transitions,{when:{type:"always"},goto:_e}]}:qe)})},[Xe]),Ri=ye=>{if(ye==="start")return null;const _e=ye.lastIndexOf(":"),De=ye.slice(0,_e),$e=parseInt(ye.slice(_e+1));return{stepId:De,transIdx:$e}},dr=R.useCallback((ye,_e)=>{const De=Ri(ye);De&&se($e=>$e.map(et=>et.id===De.stepId?{...et,transitions:et.transitions.map((qe,dt)=>dt===De.transIdx?_e(qe):qe)}:et))},[]),Oi=R.useCallback((ye,_e)=>{if(ye==="start"){P(_e);return}dr(ye,De=>({...De,goto:_e}))},[dr]),Mi=R.useCallback((ye,_e)=>{const De=Ri(ye);De&&(se($e=>{const et=$e.find(dt=>dt.id===De.stepId);if(!et)return $e;const qe=et.transitions[De.transIdx];return qe?$e.map(dt=>dt.id===De.stepId?{...dt,transitions:dt.transitions.filter((hn,It)=>It!==De.transIdx)}:dt.id===_e?{...dt,transitions:[...dt.transitions,qe]}:dt):$e}),B(null))},[]),wr=R.useCallback(ye=>{if(ye==="start"){P(""),B(null);return}const _e=Ri(ye);_e&&(se(De=>De.map($e=>$e.id===_e.stepId?{...$e,transitions:$e.transitions.filter((et,qe)=>qe!==_e.transIdx)}:$e)),B(null))},[]),Ii=R.useCallback((ye,_e)=>{if(ye==="start"){H(_e);return}dr(ye,De=>({...De,when:_e}))},[dr]),Ys=R.useCallback((ye,_e)=>{ye!=="start"&&dr(ye,De=>({...De,subGroup:_e||void 0}))},[dr]),qa=ye=>ng(ye,Pe).name,El=()=>{if(!D)return null;if(D==="start"){const hn=Q.find(It=>It.id===$);return{type:"start",fromLabel:"Start",toLabel:hn?qa(hn):"(none)",condition:Y}}const ye=D.lastIndexOf(":"),_e=D.slice(0,ye),De=parseInt(D.slice(ye+1)),$e=Q.find(hn=>hn.id===_e);if(!$e)return null;const et=$e.transitions[De];if(!et)return null;const qe=Q.find(hn=>hn.id===et.goto),dt=et.goto==="$done"?"Done":qe?qa(qe):et.goto;return{type:"step",fromLabel:qa($e),toLabel:dt,condition:et.when,subGroup:et.subGroup}};if(S==="edit"){const ye=El();return o.jsxs(Dt,{isOpen:e,onClose:gt,title:T?q:b?"Edit Workflow":"New Workflow",size:"full",children:[ee&&o.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded mb-3",children:ee}),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:xr,children:"Name"}),o.jsx("input",{value:q,onChange:_e=>Zt(_e.target.value),placeholder:"Workflow name",className:`${as} ${T?"opacity-50":""}`,readOnly:T})]}),o.jsxs("div",{className:"min-w-[100px]",children:[o.jsx("label",{className:xr,children:"ID"}),o.jsx("input",{value:O,readOnly:!0,className:`${as} font-mono opacity-50`})]}),o.jsxs("div",{className:"flex-1 min-w-[140px]",children:[o.jsx("label",{className:xr,children:"Description"}),o.jsx("input",{value:G,onChange:_e=>!T&&z(_e.target.value),readOnly:T,placeholder:"What does this workflow do?",className:`${as} ${T?"opacity-50":""}`})]}),o.jsxs("div",{className:"w-20",children:[o.jsx("label",{className:xr,children:"Max Iter."}),o.jsx("input",{type:"number",value:U,onChange:_e=>!T&&J(Number(_e.target.value)),readOnly:T,className:`${as} font-mono ${T?"opacity-50":""}`})]}),o.jsxs("div",{children:[o.jsx("label",{className:xr,children:"Color"}),o.jsx("input",{type:"color",value:F,onChange:_e=>!T&&M(_e.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:ur,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(hB,{steps:Q,entryStep:$,selectedNodeId:(ct==null?void 0:ct.id)??null,selectedEdgeKey:D,startConditionLabel:He,agentTypes:Pe,isReadOnly:T,onSelectNode:_e=>{if(_e===null){vt(null);return}const De=Q.findIndex($e=>$e.id===_e);vt(De>=0?String(De):null)},onSelectEdge:Xe,onRemoveStep:_e=>{var $e;const De=Q.findIndex(et=>et.id===_e);if(se(et=>et.filter(qe=>qe.id!==_e)),bt===De&&vt(null),$===_e){const et=Q.filter(qe=>qe.id!==_e);P((($e=et[0])==null?void 0:$e.id)??"")}},onCreateTransition:Mn,onReconnectTo:Oi,onReconnectFrom:Mi,onDeleteTransition:wr}),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:ur,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&&(ye||ct)?o.jsx("p",{className:"text-text-muted text-xs text-center py-8",children:'View only — click "Duplicate & Customize" to edit.'}):ye?ye.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"})}),$&&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(mS,{}),o.jsx("span",{className:"text-text-primary font-medium",children:ye.toLabel})]}),o.jsxs("div",{children:[o.jsx("label",{className:xr,children:"Activation Condition"}),o.jsx("select",{value:Y.type,onChange:_e=>H(_e.target.value==="step_result"?{type:"step_result",result:"success"}:_e.target.value==="metadata_all_match"?{type:"metadata_all_match",key:"",field:"",value:""}:_e.target.value==="metadata_all_in"?{type:"metadata_all_in",key:"",field:"",values:[]}:{type:_e.target.value}),className:H0,children:RC.map(_e=>o.jsx("option",{value:_e.value,children:_e.label},_e.value))})]}),Y.type==="step_result"&&o.jsxs("div",{children:[o.jsx("label",{className:xr,children:"Result"}),$&&(()=>{const _e=Q.find(qe=>qe.id===$),De=_e&&(_e.type==="sub_agent"||_e.type==="agent")?Pe.find(qe=>qe.id===(_e.type==="sub_agent"?_e.subAgentType:_e.agentId)):void 0,$e=(De==null?void 0:De.results)&&De.results.length>0,et=(De==null?void 0:De.results)??[];return $e?o.jsx("select",{value:Y.result??et[0],onChange:qe=>H({type:"step_result",result:qe.target.value}),className:H0,children:et.map(qe=>o.jsx("option",{value:qe,children:qe},qe))}):o.jsx("input",{type:"text",value:Y.result??"success",onChange:qe=>H({type:"step_result",result:qe.target.value}),placeholder:"e.g. success, passed, failed",className:as})})()]}),(Y.type==="metadata_all_match"||Y.type==="metadata_all_in")&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("label",{className:xr,children:"Metadata Key"}),o.jsx("input",{type:"text",value:Y.key??"",onChange:_e=>H({...Y,key:_e.target.value}),placeholder:"e.g. criteria, todos, review_findings",className:as})]}),o.jsxs("div",{children:[o.jsx("label",{className:xr,children:"Field"}),o.jsx("input",{type:"text",value:Y.field??"",onChange:_e=>H({...Y,field:_e.target.value}),placeholder:"e.g. status",className:as})]}),Y.type==="metadata_all_match"?o.jsxs("div",{children:[o.jsx("label",{className:xr,children:"Value"}),o.jsx("input",{type:"text",value:Y.value??"",onChange:_e=>H({...Y,value:_e.target.value}),placeholder:"e.g. passed, resolved",className:as})]}):o.jsxs("div",{children:[o.jsx("label",{className:xr,children:"Values (comma-separated)"}),o.jsx("input",{type:"text",value:((hs=Y.values)==null?void 0:hs.join(", "))??"",onChange:_e=>H({...Y,values:_e.target.value.split(",").map(De=>De.trim()).filter(Boolean)}),placeholder:"e.g. resolved, dismissed",className:as})]})]}),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."})]}):(()=>{const _e=Ri(D),De=_e==null?void 0:_e.stepId,$e=(_e==null?void 0:_e.transIdx)??0,et=De?Q.find(dt=>dt.id===De):void 0,qe=(et==null?void 0:et.transitions.length)??0;return o.jsx(pB,{fromLabel:ye.fromLabel,toLabel:ye.toLabel,condition:ye.condition,subGroup:"subGroup"in ye?ye.subGroup:void 0,fromStep:ye.type==="step"?Q.find(dt=>dt.id===ye.fromLabel):void 0,agentTypes:Pe,transitionIndex:$e,totalTransitions:qe,onUpdateCondition:dt=>Ii(D,dt),onUpdateSubGroup:dt=>Ys(D,dt),onDelete:()=>wr(D),onMoveUp:()=>{se(dt=>{const hn=dt.find(xt=>xt.id===De);if(!hn||$e===0)return dt;const It=[...hn.transitions];return[It[$e-1],It[$e]]=[It[$e],It[$e-1]],dt.map(xt=>xt.id===De?{...xt,transitions:It}:xt)}),B(`${De}:${$e-1}`)},onMoveDown:()=>{se(dt=>{const hn=dt.find(xt=>xt.id===De);if(!hn||$e===hn.transitions.length-1)return dt;const It=[...hn.transitions];return[It[$e],It[$e+1]]=[It[$e+1],It[$e]],dt.map(xt=>xt.id===De?{...xt,transitions:It}:xt)}),B(`${De}:${$e+1}`)}})})():ct?o.jsx(mB,{step:ct,isEntry:ct.id===$,agentTypes:Pe,transitionCount:ct.transitions.length,templateVariables:u,onUpdate:en,onRemove:()=>{var _e;if(ct&&(se(Q.filter((De,$e)=>$e!==bt)),vt(null),$===ct.id)){const De=Q.filter(($e,et)=>et!==bt);P(((_e=De[0])==null?void 0:_e.id)??"")}},onSetEntry:()=>P(ct.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(tt,{variant:"secondary",onClick:gt,children:"Close"}),T?o.jsx(tt,{variant:"primary",onClick:()=>{W(q+" (copy)"),V(`${b}-copy-${Date.now()}`),E(null),N(!1)},children:"Duplicate & Customize"}):o.jsxs(o.Fragment,{children:[o.jsx(tt,{variant:"primary",onClick:nt,children:"Save"}),o.jsx(tt,{variant:"primary",onClick:Mt,children:"Save & Close"})]})]})]})}return o.jsx(Dt,{isOpen:e,onClose:t,title:"Workflows",size:"lg",children:o.jsx(wS,{description:"Workflows define multi-step agentic processes with branching transitions.",onNew:Ve,loading:l,hasItems:s.length>0||a.length>0,children:o.jsxs("div",{className:"space-y-4",children:[o.jsx(B0,{title:"Built-in",items:s,renderActions:ye=>o.jsx(o.Fragment,{children:o.jsx(Fs,{onClick:()=>Oe(ye.id),children:o.jsx(uu,{})})})}),o.jsx(B0,{title:"Custom",items:a,renderActions:ye=>o.jsxs(o.Fragment,{children:[o.jsx(Fs,{onClick:()=>Ce(ye.id),children:o.jsx(uu,{})}),o.jsx(Fs,{onClick:()=>me(ye.id),children:o.jsx("span",{className:"text-[10px]",children:"Edit"})}),o.jsx(du,{onClick:()=>Oe(ye.id)}),y(ye.id,"delete")?o.jsx(mp,{onConfirm:()=>Ge(ye.id),onCancel:k}):o.jsx(pp,{onClick:()=>w(ye.id)})]})})]})})})}function MC(e,t){if(!t)return!0;const n=t.toLowerCase().split(/\s+/),s=e.toLowerCase().split(/\s+/);return n.every(a=>{for(const l of s){let u=0;for(let c=0;c<l.length&&u<a.length;c++)l[c]===a[u]&&u++;if(u===a.length)return!0}return!1})}function IC(e,t,n,s,a){switch(e.key){case"ArrowDown":e.preventDefault(),n(l=>Math.min(l+1,t));break;case"ArrowUp":e.preventDefault(),n(l=>Math.max(l-1,0));break;case"Enter":e.preventDefault(),s();break;case"Escape":e.preventDefault(),a();break}}function _B(e){const t=e.match(/^\/p\/([^/]+)/);return t==null?void 0:t[1]}function yB({isOpen:e,onClose:t,onCloseComplete:n,onSelectCommand:s,onSelectWorkflow:a,onCloseCompleteAction:l,textareaContent:u,onSearchMessages:c,onToggleAutoScroll:h,isAutoScrollActive:f}){const[,p]=cr(),m=nn(J=>J.fetchCommands),_=Et(J=>J.fetchWorkflows),x=mt(J=>J.fetchAgents),w=nn(J=>J.defaults),k=nn(J=>J.userItems),y=nn(J=>J.projectItems),S=Et(J=>J.defaults),v=Et(J=>J.userItems),b=Et(J=>J.projectItems),E=mt(J=>J.defaults),T=mt(J=>J.userItems),N=mt(J=>J.projectItems),L=we(J=>{var Q;return(Q=J.currentSession)==null?void 0:Q.mode}),A=we(J=>{var Q;return((Q=J.currentSession)==null?void 0:Q.dangerLevel)??"normal"}),D=we(J=>J.switchMode),B=we(J=>J.switchDangerLevel),q=we(J=>{var Q;return(Q=J.currentSession)==null?void 0:Q.projectId}),W=R.useRef(void 0),[O,V]=R.useState(""),[G,z]=R.useState(0),X=R.useRef(null),ne=R.useRef(!1);R.useEffect(()=>{e&&(ne.current=!0)},[e]),R.useEffect(()=>{if(e){m(),_(),x(),V(""),z(0);const J=setTimeout(()=>{var Q;return(Q=X.current)==null?void 0:Q.focus()},50);return()=>clearTimeout(J)}},[e,m,_,x]),R.useEffect(()=>{var J;!e&&ne.current&&(n==null||n(),(J=W.current)==null||J.call(W),W.current=void 0)},[e,n]);const F=(J,Q)=>{const se=new Set(Q.map(Y=>Y.id));return[...J.filter(Y=>!se.has(Y.id)),...Q]},$=[{id:"create-session",name:"New Session",prefix:"Action > Create",action:()=>{const J=q??_B(window.location.pathname);J&&p(`/p/${J}/new`)}},{id:"navigate-session",name:"Another Session",prefix:"Action > Navigate to",action:()=>{W.current=l,t()}},{id:"search-messages",name:"Messages",prefix:"Action > Search",action:()=>{t(),c==null||c()}},{id:"toggle-autoscroll",name:f?"Auto-scroll Off":"Auto-scroll On",prefix:"Action > Toggle",action:()=>{t(),h==null||h(!f)}},...F(F(E,T),N).filter(J=>!J.subagent&&J.id!==L).map(J=>({id:J.id,name:J.name,prefix:"Agent > Switch to",action:()=>D(J.id)})),...F(F(w,k),y).map(J=>({id:J.id,name:J.name,prefix:"Command > Launch",action:()=>s(J.id,u)})),...F(F(S,v),b).map(J=>({id:J.id,name:J.name,prefix:"Workflow > Run",action:()=>a(J.id)})),...["normal","dangerous"].filter(J=>J!==A).map(J=>({id:J,name:J.charAt(0).toUpperCase()+J.slice(1),prefix:"Mode > Switch to",action:()=>B(J)}))].filter(J=>MC(`${J.prefix} ${J.name}`,O)),P=$.length-1,U=J=>{IC(J,P,z,()=>{var Q;(Q=$[G])==null||Q.action(),t()},t)};return e?$a.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:t}),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:X,type:"text",value:O,onChange:J=>{V(J.target.value),z(0)},onKeyDown:U,placeholder:"Search...",className:"flex-1 bg-transparent text-sm focus:outline-none placeholder:text-text-muted"}),o.jsx(dp,{onClick:t,className:"shrink-0","aria-label":"Close"})]}),o.jsx("div",{className:"overflow-y-auto max-h-[60vh] p-2",children:$.length===0?o.jsx("div",{className:"px-3 py-4 text-center text-text-muted text-sm",children:w.length+k.length+S.length+v.length>0?"No matches":"No agents, commands, or workflows yet"}):$.map((J,Q)=>o.jsxs("button",{type:"button",onClick:()=>{J.action(),t()},className:`w-full text-left px-3 py-2 rounded text-sm transition-colors ${Q===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:[J.prefix," "]}),o.jsx("span",{children:J.name})]},J.id))})]})]}),document.body):null}function vB(e){const t=new Date(e),n=new Date;if(t.getDate()===n.getDate()&&t.getMonth()===n.getMonth()&&t.getFullYear()===n.getFullYear())return t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1});const a=t.getFullYear(),l=String(t.getMonth()+1).padStart(2,"0"),u=String(t.getDate()).padStart(2,"0"),c=String(t.getHours()).padStart(2,"0"),h=String(t.getMinutes()).padStart(2,"0");return`${a}/${l}/${u} ${c}:${h}`}function bB(e){var t;if(e.type==="message")return e.message.timestamp;if(e.type==="subagent")return(t=e.messages[0])==null?void 0:t.timestamp}function SB(e){var t,n;if(e.type==="message"){const s=e.message;if(s.role==="assistant"){const a=(t=s.content)==null?void 0:t.trim();return((n=s.thinkingContent)==null?void 0:n.trim())&&!a?"italic text-text-muted":""}if(s.role==="user")return"font-bold"}return""}function wB(e){var n,s;if(e.type!=="message")return o.jsx(Rv,{className:"w-3.5 h-3.5"});const t=e.message;return t.role==="assistant"?(n=t.thinkingContent)!=null&&n.trim()&&!((s=t.content)!=null&&s.trim())?o.jsx(Pj,{className:"w-3.5 h-3.5"}):o.jsx(Rv,{className:"w-3.5 h-3.5"}):o.jsx(Ij,{className:"w-3.5 h-3.5"})}function U0(e){var t;if(e.type==="message"){const n=e.message,s=n.content||"",a=s.replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();if(n.messageKind==="workflow-started")try{return`Workflow: ${JSON.parse(s).workflowName}`}catch{return"Workflow started"}if(n.messageKind==="task-completed")return"Task completed";if(n.messageKind==="auto-prompt")return"Auto-prompt";if(n.messageKind==="correction")return"Correction";if(n.messageKind==="context-reset")return"Context reset";if(n.messageKind==="command")return"Command executed";if(n.role==="assistant")return a?a.slice(0,200):(t=n.thinkingContent)!=null&&t.trim()?n.thinkingContent.slice(0,200):"";const l=a.slice(0,200);return l.length<a.length?`${l}...`:l}return e.type==="subagent"?`Sub-agent: ${e.subAgentType}`:e.type==="criteria-batch"?"Acceptance Criteria":""}function CB({isOpen:e,onClose:t,displayItems:n,onNavigate:s}){const[a,l]=R.useState(""),[u,c]=R.useState(0),h=R.useRef(null),f=R.useRef(null),p=R.useMemo(()=>n.filter(y=>{var S,v;return!(y.type==="context-divider"||y.type==="message"&&y.message.role==="assistant"&&!((S=y.message.content)!=null&&S.trim())&&!((v=y.message.thinkingContent)!=null&&v.trim()))}),[n]),m=R.useMemo(()=>a?p.filter(y=>{const S=U0(y);return MC(S,a)}):p,[p,a]),_=m.length-1;R.useEffect(()=>{if(e){l(""),c(0);const y=setTimeout(()=>{var S;return(S=h.current)==null?void 0:S.focus()},50);return()=>clearTimeout(y)}},[e]),R.useEffect(()=>{e&&f.current&&(f.current.scrollTop=f.current.scrollHeight)},[e]);const x=y=>{IC(y,_,c,()=>{const S=m[u];if(S){const v=n.indexOf(S);v>=0&&s(v),t()}},t)},w=y=>{const S=n.indexOf(y);S>=0&&s(S),t()},k=y=>n.indexOf(y);return e?$a.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:t}),o.jsxs("div",{className:"relative w-full max-w-lg 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(cp,{}),o.jsx("input",{ref:h,type:"text",value:a,onChange:y=>{l(y.target.value),c(0)},onKeyDown:x,placeholder:"Search timeline...",className:"flex-1 bg-transparent text-sm focus:outline-none placeholder:text-text-muted"}),o.jsx("button",{type:"button",onClick:t,className:"p-0.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors","aria-label":"Close",children:o.jsx(gl,{className:"w-4 h-4"})})]}),o.jsx("div",{ref:f,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:p.length>0?"No matches":"No messages yet"}):m.map((y,S)=>{const v=k(y),b=wB(y),E=U0(y),T=SB(y),N=bB(y),L=y.type==="message"&&y.message.role==="user";return o.jsx("button",{type:"button",onClick:()=>w(y),className:`w-full text-left px-3 py-2 rounded text-sm transition-colors ${S===u?"bg-accent-primary/20 text-text-primary":L?"bg-accent-primary/5 text-text-secondary hover:bg-accent-primary/10 hover: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.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:[o.jsx("span",{className:"flex-shrink-0",children:b}),o.jsx("span",{className:`truncate flex-1 ${T}`,children:E})]}),N&&o.jsx("span",{className:"text-text-muted text-xs shrink-0",children:vB(N)})]})},`${v}-${y.type}`)})})]})]}),document.body):null}function kB({attachment:e,onRemove:t}){const n=s=>s<1024?`${s} B`:s<1048576?`${(s/1024).toFixed(1)} KB`:`${(s/1048576).toFixed(1)} MB`;return o.jsxs("div",{className:"relative inline-flex flex-col items-center p-2 bg-bg-tertiary rounded-lg border border-border",children:[o.jsx(yl,{onClick:()=>t(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:n(e.size)})]})}function EB({history:e,selectedIndex:t,onSelect:n,onEscape:s,onNavigate:a}){const l=R.useRef(null),u=R.useRef(null);R.useEffect(()=>{u.current&&l.current&&u.current.scrollIntoView({block:"nearest",behavior:"smooth"})},[t]);const c=f=>{switch(f.key){case"Enter":f.preventDefault(),e[t]&&n(e[t].content);break;case"Escape":f.preventDefault(),s();break;case"ArrowUp":f.preventDefault(),a("up");break;case"ArrowDown":f.preventDefault(),a("down");break}},h=f=>{n(f)};return o.jsx("div",{ref:l,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((f,p)=>o.jsxs("div",{ref:p===t?u:null,role:"listitem",onClick:()=>h(f.content),className:`
|
|
293
293
|
p-2 rounded cursor-pointer transition-colors
|
|
294
294
|
${p===t?"bg-accent-primary/20 border border-accent-primary":"hover:bg-bg-tertiary"}
|
|
295
|
-
`,children:[o.jsxs("div",{className:"text-xs text-text-muted font-mono",children:[f.formattedTimestamp,f.sessionName&&o.jsxs(o.Fragment,{children:[" | ",o.jsx("span",{className:"text-accent-primary font-medium",children:f.sessionName})]})]}),o.jsx("div",{className:"text-sm text-text-primary mt-1",children:f.trimmedContent})]},f.id))})}function jB(){const e=uj(),t=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 ${t}`,style:{animationDelay:"0ms"}}),o.jsx("span",{className:`w-1 h-1 rounded-full animate-bounce ${t}`,style:{animationDelay:"150ms"}}),o.jsx("span",{className:`w-1 h-1 rounded-full animate-bounce ${t}`,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"})]})}const NB={maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576};async function TB(e,t={}){const n={...NB,...t};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<=n.maxSizeBytes){const a=await e.arrayBuffer(),l=IB(a),u=`data:${e.type};base64,${l}`,c=await PC(u);return{dataUrl:u,mimeType:e.type,size:e.size,width:c.width,height:c.height}}return await AB(e,n)}async function AB(e,t){const n=await DB(e),s=await PC(n),{width:a,height:l}=LB(s.width,s.height,t.maxWidth,t.maxHeight),u=RB();u.width=a,u.height=l;const c=u.getContext("2d");if(!c)throw new Error("Failed to get canvas context");c.imageSmoothingEnabled=!0,c.imageSmoothingQuality="high",c.drawImage(s,0,0,a,l);let h=t.quality,f="";for(let m=0;m<10&&(f=u.toDataURL(e.type.startsWith("image/gif")?"image/png":e.type,h),!(F0(f)<=t.maxSizeBytes||h<=.3));m++)h-=.1;const p=F0(f);return{dataUrl:f,mimeType:e.type.startsWith("image/gif")?"image/png":e.type,size:p,width:a,height:l}}function LB(e,t,n,s){const a=e/t;return e>t&&e>n?{width:n,height:Math.round(n/a)}:t>e&&t>s?{width:Math.round(s*a),height:s}:{width:e,height:t}}function DB(e){return new Promise((t,n)=>{const s=MB(),a=new s;a.onload=()=>t(a.result),a.onerror=()=>n(new Error("Failed to read file")),a.readAsDataURL(e)})}function PC(e){return new Promise((t,n)=>{const s=OB(),a=new s;a.onload=()=>t(a),a.onerror=()=>n(new Error("Failed to load image")),a.src=e})}function RB(){var t;const e=rg();if(!((t=e.document)!=null&&t.createElement))throw new Error("Image compression requires browser canvas APIs");return e.document.createElement("canvas")}function OB(){const e=rg();if(!e.Image)throw new Error("Image compression requires browser image APIs");return e.Image}function MB(){const e=rg();if(!e.FileReader)throw new Error("Image compression requires browser file APIs");return e.FileReader}function rg(){return globalThis}function IB(e){const t=new Uint8Array(e);let n="";for(let s=0;s<t.byteLength;s++){const a=t[s];a!==void 0&&(n+=String.fromCharCode(a))}return btoa(n)}function F0(e){const n=e.split(",")[1];return n?Math.round(n.length*3/4):0}function PB(e){return["image/png","image/jpeg","image/gif"].includes(e.type)}function BB(e,t=50*1024*1024){return e.size>t?{valid:!1,error:`Image file is too large (${V0(e.size)}). Maximum size is ${V0(t)}.`}:{valid:!0}}function V0(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}async function xm(e,t,n,s={}){const{maxSizeBytes:a=50*1024*1024,filename:l}=s;if(!PB(e)){n(`Unsupported file type: ${e.type}. Only PNG, JPG, and GIF are supported.`);return}const u=BB(e,a);if(!u.valid){n(u.error??"Image file is too large");return}try{const c=await TB(e,{maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576}),h={id:oS(),filename:l??e.name,mimeType:c.mimeType,size:c.size,data:c.dataUrl};t(h)}catch(c){const h=c instanceof Error?c.message??"Failed to process image":"Failed to process image";n(h)}}function zB({children:e}){return $a.createPortal(e,document.body)}function HB(e){const t=e.startCondition;if(!t||t.type==="always")return!0;switch(t.type){case"step_result":case"metadata_all_match":case"metadata_all_in":return null;default:return null}}function $B({onSendCommand:e,onSelectWorkflow:t,onSelectWorkflowWithSubGroup:n,onOpenCommandsManager:s,onOpenWorkflowsManager:a,onAttach:l,textareaContent:u,attachments:c}){const[h,f]=R.useState(!1),[p,m]=R.useState("commands"),[_,x]=R.useState(""),[w,k]=R.useState(0),[y,S]=R.useState(null),[v,b]=R.useState(null),E=R.useRef(null),T=R.useRef(null),N=nn(P=>P.defaults),L=nn(P=>P.userItems),A=nn(P=>P.fetchCommands),D=Et(P=>P.defaults),B=Et(P=>P.userItems),q=Et(P=>P.fetchWorkflows),W=[...N,...L],O=[...D,...B];R.useEffect(()=>{h&&(p==="commands"?A():p==="workflows"&&q())},[h,p,A,q]),R.useEffect(()=>{h&&(x(""),k(0),requestAnimationFrame(()=>{var P;return(P=E.current)==null?void 0:P.focus()}))},[h,p]),R.useEffect(()=>{if(!h)return;const P=U=>{var J;(J=T.current)!=null&&J.contains(U.target)||f(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[h]);const V=P=>{switch(P.key){case"ArrowDown":P.preventDefault(),k(U=>{const Q=(p==="commands"?W:O).filter(se=>{const Y=_.toLowerCase();return!Y||se.name.toLowerCase().includes(Y)});return Math.min(U+1,Q.length-1)});break;case"ArrowUp":P.preventDefault(),k(U=>Math.max(U-1,0));break;case"Enter":P.preventDefault();break;case"Escape":P.preventDefault(),f(!1);break}},G=P=>{x(P),k(0)},z=W.filter(P=>!_||P.name.toLowerCase().includes(_.toLowerCase())),X=O.filter(P=>!_||P.name.toLowerCase().includes(_.toLowerCase())),ne=async P=>{const U=await nn.getState().fetchCommand(P);U&&e(U.prompt,U.metadata.agentMode,u,c),f(!1)},F=P=>{t(P),f(!1)},M=(P,U)=>{U.stopPropagation(),f(!1),S(P)},$=(P,U)=>{U.stopPropagation(),f(!1),b(P)};return o.jsxs("div",{ref:T,className:"relative",children:[o.jsx("button",{type:"button",onClick:()=>f(!h),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(gS,{className:"w-4 h-4"})}),h&&o.jsxs("div",{className:"absolute bottom-full right-0 mb-1 w-80 max-w-[calc(100vw-2rem)] 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"),x(""),k(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${p==="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"),x(""),k(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${p==="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 ${p==="attach"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Attach"})]}),p!=="attach"&&o.jsx("div",{className:"p-2 border-b border-border",children:o.jsx("input",{ref:E,value:_,onChange:P=>G(P.target.value),onKeyDown:V,placeholder:p==="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:p==="commands"?z.length===0?o.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:W.length===0?"No commands yet":"No matches"}):z.map((P,U)=>o.jsxs("div",{className:`flex items-center gap-1 px-3 py-2 rounded transition-colors group ${U===w?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[o.jsx("button",{type:"button",onClick:()=>ne(P.id),className:"flex-1 text-left",children:o.jsx("div",{className:"text-sm text-text-primary font-medium",children:P.name})}),o.jsx(Fs,{className:"opacity-0 group-hover:opacity-100",onClick:J=>M(P.id,J)})]},P.id)):p==="workflows"?X.length===0?o.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:O.length===0?"No workflows yet":"No matches"}):X.map((P,U)=>{const J=HB(P),Q=P.color??"#3b82f6";return o.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 rounded transition-colors group ${U===w?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[o.jsxs("button",{type:"button",onClick:()=>F(P.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:P.name}),J!==null&&o.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:J?"#22c55e":"#6b7280"},title:J?"Entry condition met":"Entry condition not met"})]}),o.jsxs("div",{className:"flex items-center gap-1",children:[P.subGroups&&P.subGroups.length>0&&o.jsx(UB,{subGroups:P.subGroups,onSelect:se=>{f(!1),n(P.id,se)}}),o.jsx(Fs,{className:"opacity-0 group-hover:opacity-100",onClick:se=>$(P.id,se)})]})]},P.id)}):o.jsxs("div",{className:"p-4 flex flex-col items-center gap-3",children:[o.jsxs("button",{type:"button",onClick:()=>{l(),f(!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(xj,{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"})]})}),p!=="attach"&&o.jsx("div",{className:"border-t border-border p-1",children:o.jsx("button",{type:"button",onClick:()=>{f(!1),p==="commands"?s():a()},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:p==="commands"?"Manage Commands...":"Manage Workflows..."})})]}),o.jsx(LC,{isOpen:!!y,onClose:()=>S(null),initialEditId:y}),o.jsx(OC,{isOpen:!!v,onClose:()=>b(null),initialEditId:v})]})}function UB({subGroups:e,onSelect:t}){const[n,s]=R.useState(!1),[a,l]=R.useState({top:0,right:0}),u=R.useRef(null),c=R.useRef(null);AC(c,()=>s(!1),n);const h=f=>{if(f.stopPropagation(),!n&&u.current){const p=u.current.getBoundingClientRect();l({top:p.bottom+4,right:window.innerWidth-p.right})}s(!n)};return o.jsxs(o.Fragment,{children:[o.jsx("button",{ref:u,type:"button",onClick:h,className:"p-1 rounded text-text-muted hover:text-text-primary transition-colors",title:"Sub-groups",children:"⋮"}),n&&o.jsx(zB,{children:o.jsx("div",{ref:c,onMouseDown:f=>f.stopPropagation(),className:"fixed w-40 bg-bg-secondary border border-border rounded-lg shadow-xl z-[100] overflow-hidden",style:{top:a.top,right:a.right},children:e.map(f=>o.jsx("button",{type:"button",onClick:p=>{p.stopPropagation(),t(f)},className:"w-full text-left px-3 py-2 text-sm text-text-primary hover:bg-bg-tertiary transition-colors",children:f},f))})})]})}function FB({messages:e,onCancel:t}){return e.length===0?null:o.jsx("div",{className:"mb-2 flex flex-wrap gap-1.5",children:e.map(n=>o.jsxs("div",{className:`inline-flex items-center gap-1.5 px-2 py-1 rounded text-xs ${n.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:[n.mode==="asap"?"ASAP":"Queue",":"]}),o.jsx("span",{className:"truncate max-w-[200px]",children:n.content}),o.jsx(yl,{onClick:()=>t(n.queueId),size:"sm"})]},n.queueId))})}function VB({agent:e,isBuiltIn:t,isConfirmingDelete:n,onView:s,onEdit:a,onDuplicate:l,onDelete:u}){return o.jsxs(ES,{isBuiltIn:t,isConfirmingDelete:n,onView:s,onEdit:a,onDuplicate:l,onDelete:u,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0",style:{backgroundColor:e.color??"#6b7280"}}),o.jsx("span",{className:"text-text-primary text-sm font-medium",children:e.name}),o.jsx("span",{className:"text-text-muted text-xs font-mono",children:e.id}),t&&o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-medium bg-bg-primary text-text-muted",children:"Built-in"})]}),e.description&&o.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:e.description}),o.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[e.allowedTools.slice(0,5).map(c=>o.jsx("span",{className:"text-[10px] font-mono text-text-muted bg-bg-primary px-1 py-0.5 rounded",children:c},c)),e.allowedTools.length>5&&o.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",e.allowedTools.length-5," more"]})]})]})}function G0({title:e,agents:t,subagents:n,isBuiltIn:s,onView:a,onDuplicate:l,onEdit:u,onDelete:c}){if(t.length===0&&n.length===0)return null;const h=f=>o.jsx(VB,{agent:f,isBuiltIn:s,isConfirmingDelete:!1,onView:()=>a(f.id),onEdit:s?void 0:()=>u==null?void 0:u(f.id),onDuplicate:()=>l(f.id),onDelete:s?void 0:()=>c==null?void 0:c(f.id)},f.id);return o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:e}),o.jsxs("div",{className:"space-y-2",children:[t.map(h),n.length>0&&o.jsxs("div",{className:"mt-3",children:[o.jsx("div",{className:"text-xs text-text-muted uppercase tracking-wider mb-1.5",children:"Sub-agents"}),o.jsx("div",{className:"space-y-2",children:n.map(h)})]})]})]})}function GB(e){const t=new Map;for(const n of e){const s=n.indexOf(":");if(s===-1)t.set(n,new Set);else{const a=n.slice(0,s),u=n.slice(s+1).split(",").filter(Boolean);t.set(a,new Set(u))}}return t}function _m(e){const t=[];for(const[n,s]of e)s.size===0?t.push(n):t.push(`${n}:${[...s].join(",")}`);return t}function WB({formName:e,formId:t,formDescription:n,formSubagent:s,formTools:a,formColor:l,formPrompt:u,formError:c,saving:h,isReadOnly:f,availableTools:p,onNameChange:m,onIdChange:_,onDescriptionChange:x,onSubagentChange:w,onColorChange:k,onPromptChange:y,onSave:S,onCancel:v,onDuplicate:b}){const E=GB(a),T=(A,D)=>{const B=new Map(E),q=B.get(A)||new Set,W=new Set(q);W.has(D)?W.delete(D):W.add(D),W.size===0?B.set(A,new Set):B.set(A,W),L(_m(B))},N=A=>{const D=new Map(E);D.has(A)?D.delete(A):D.set(A,new Set),L(_m(D))},L=A=>{};return o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"space-y-3",children:[c&&o.jsx(gp,{message:c}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(ji,{label:"Name",value:e,onChange:m,placeholder:"My Agent",readOnly:f}),o.jsx(ji,{label:"ID",value:t,onChange:_,readOnly:!0,placeholder:"my_agent",hint:"(read-only)",mono:!0})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(ji,{label:"Description",value:n,onChange:x,placeholder:"What this agent does",readOnly:f}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Type"}),o.jsxs("div",{className:"flex items-center gap-3 h-[34px]",children:[o.jsx("button",{onClick:()=>!f&&w(!0),className:`px-2.5 py-1 rounded text-xs font-medium transition-colors ${s?"bg-accent-primary/25 text-accent-primary":"bg-bg-tertiary text-text-muted hover:text-text-secondary"} ${f?"pointer-events-none opacity-60":""}`,children:"Sub-agent"}),o.jsx("button",{onClick:()=>!f&&w(!1),className:`px-2.5 py-1 rounded text-xs font-medium transition-colors ${s?"bg-bg-tertiary text-text-muted hover:text-text-secondary":"bg-accent-primary/25 text-accent-primary"} ${f?"pointer-events-none opacity-60":""}`,children:"Top-level"}),o.jsxs("div",{className:"flex items-center gap-1.5 ml-auto",children:[o.jsx("label",{className:"text-xs text-text-secondary",children:"Color"}),o.jsx("input",{type:"color",value:l,onChange:A=>!f&&k(A.target.value),disabled:f,className:"w-6 h-6 rounded cursor-pointer border border-border bg-transparent"})]})]})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Tools"}),o.jsx("div",{className:"flex flex-wrap gap-1.5 p-2 bg-bg-tertiary border border-border rounded max-h-32 overflow-y-auto",children:p.map(A=>{const D=E.has(A.name),B=A.actions.length>0,q=E.get(A.name)||new Set;return B?f?o.jsxs("button",{className:"px-1.5 py-0.5 rounded text-xs font-mono flex items-center gap-1 bg-bg-primary text-text-muted pointer-events-none opacity-60",children:[o.jsx("span",{children:A.name}),o.jsx("span",{className:"text-[10px]",children:"*"})]},A.name):o.jsx(xl,{trigger:o.jsxs("button",{className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${D?"bg-accent-primary/25 text-accent-primary":"bg-bg-primary text-text-muted"}`,children:[o.jsx("span",{children:A.name}),B&&o.jsx("span",{className:`text-[10px] ${D&&q.size>0?"text-accent-primary":"text-text-muted"}`,children:"*"})]}),minWidth:"160px",items:[...A.actions.map(W=>({label:o.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",htmlFor:`${A.name}-${W}`,children:[o.jsx("input",{type:"checkbox",id:`${A.name}-${W}`,checked:q.has(W),onChange:()=>T(A.name,W),disabled:f,className:"w-3 h-3 rounded accent-accent-primary"}),o.jsx("span",{children:W})]}),closeOnClick:!1})),{label:D?"Deselect all":"Select all",closeOnClick:!1,onClick:()=>{if(D)N(A.name);else{const W=new Map(E);W.set(A.name,new Set(A.actions)),L(_m(W))}}}]},A.name):o.jsx("button",{onClick:()=>!f&&N(A.name),className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${D?"bg-accent-primary/25 text-accent-primary":"bg-bg-primary text-text-muted hover:text-text-secondary"} ${f?"pointer-events-none":"cursor-pointer"}`,children:o.jsx("span",{children:A.name})},A.name)})})]})]}),o.jsxs("div",{className:"flex-1 min-h-[150px] border-t border-border pt-3 flex flex-col",children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Prompt"}),o.jsx("textarea",{value:u,onChange:A=>!f&&y(A.target.value),readOnly:f,placeholder:"Instructions for this agent...",className:`h-80 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary ${f?"opacity-60":""}`})]}),o.jsx(Kj,{onCancel:v,onSave:S,saving:h,saveDisabled:!e||!u||f}),f&&o.jsx("div",{className:"flex justify-end mt-2",children:o.jsx("button",{onClick:b,className:"px-3 py-1.5 rounded bg-accent-primary/20 text-sm text-accent-primary font-medium hover:bg-accent-primary/30 transition-colors",children:"Duplicate & Customize"})})]})}function qB(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"")}function KB({isOpen:e,onClose:t,initialEditId:n}){const s=mt(de=>de.defaults),a=mt(de=>de.userItems),l=mt(de=>de.loading),u=mt(de=>de.fetchAgents),c=mt(de=>de.fetchAgent),h=mt(de=>de.fetchDefaultContent),f=mt(de=>de.createAgent),p=mt(de=>de.updateAgent),m=mt(de=>de.deleteAgent),[_,x]=R.useState("list"),[w,k]=R.useState(null),[y,S]=R.useState(!1),[v,b]=R.useState(""),[E,T]=R.useState(""),[N,L]=R.useState(""),[A,D]=R.useState(!0),[B,q]=R.useState([]),[W,O]=R.useState("#6b7280"),[V,G]=R.useState(""),[z,X]=R.useState(""),[ne,F]=R.useState(!1),[M,$]=R.useState([]),P=de=>{b(de.metadata.name),T(de.metadata.id),L(de.metadata.description),D(de.metadata.subagent),q(de.metadata.allowedTools),O(de.metadata.color??"#6b7280"),G(de.prompt),X("")},U=(de,Ie,Se)=>{b(de.metadata.name+" (copy)"),T(`${Ie}-copy-${Date.now()}`),L(de.metadata.description),D(de.metadata.subagent),q(de.metadata.allowedTools),O(de.metadata.color??"#6b7280"),G(de.prompt),X(""),k(null),S(!1),x("edit")},J=(de,Ie)=>{P(de),k(Ie),S(!0),x("edit")};R.useEffect(()=>{e&&(u(),Ne("/api/tools").then(de=>de.json()).then(de=>$(de.tools||[])).catch(()=>$([])),n?s.some(Ie=>Ie.id===n)?h(n).then(Ie=>{Ie&&U(Ie,n)}):c(n).then(Ie=>{Ie&&(P(Ie),k(n),S(!1),x("edit"))}):(x("list"),k(null),S(!1)))},[e,u,c,h,n]);const Q=async de=>{if(s.some(Se=>Se.id===de)){const Se=await h(de);if(!Se)return;J(Se,de)}else{const Se=await c(de);if(!Se)return;J(Se,de)}},se=async de=>{const Ie=await h(de);Ie&&U(Ie,de)},Y=()=>{k(null),b(""),T(""),L(""),D(!0),q(["read_file"]),O("#6b7280"),G(""),X(""),S(!1),x("edit")},H=async de=>{const Ie=await c(de);Ie&&(P(Ie),k(de),S(!1),x("edit"))},ee=async de=>{await m(de)},te=async()=>{const de=w??E;if(!de||!v||!V){X("Name and prompt are required.");return}F(!0),X("");const Ie={metadata:{id:de,name:v,description:N,subagent:A,allowedTools:B,color:W},prompt:V},Se=w?await p(w,Ie):await f(Ie);if(F(!1),!Se.success){X(Se.error??"Failed to save agent.");return}n?t():x("list")},ce=()=>{n?t():(x("list"),S(!1))},he=de=>{b(de),w||T(qB(de))},Te=s.filter(de=>de.subagent),Ae=s.filter(de=>!de.subagent),Le=a.filter(de=>de.subagent),Pe=a.filter(de=>!de.subagent);return _==="edit"?o.jsx(Dt,{isOpen:e,onClose:ce,title:y?`${v}`:w?"Edit Agent":"New Agent",size:"xl",children:o.jsx(WB,{formName:v,formId:E,formDescription:N,formSubagent:A,formTools:B,formColor:W,formPrompt:V,formError:z,saving:ne,isReadOnly:y,availableTools:M,onNameChange:he,onIdChange:T,onDescriptionChange:L,onSubagentChange:D,onColorChange:O,onPromptChange:G,onSave:te,onCancel:ce,onDuplicate:()=>{b(v+" (copy)"),T(`${w}-copy-${Date.now()}`),k(null),S(!1)}})}):o.jsx(Dt,{isOpen:e,onClose:t,title:"Agents",size:"lg",children:o.jsx(wS,{description:"Agents define behavior, tools, and prompts for top-level modes and sub-agents.",onNew:Y,loading:l,hasItems:s.length>0||a.length>0,children:o.jsxs("div",{className:"space-y-4",children:[s.length>0&&o.jsx(G0,{title:"Built-in",agents:Ae,subagents:Te,isBuiltIn:!0,onView:Q,onDuplicate:se}),a.length>0&&o.jsx(G0,{title:"Custom",agents:Pe,subagents:Le,isBuiltIn:!1,onView:Q,onDuplicate:se,onEdit:H,onDelete:ee})]})})})}function YB(){const e=we(v=>{var b;return(b=v.currentSession)==null?void 0:b.mode}),t=we(v=>v.switchMode),n=mt(v=>v.defaults),s=mt(v=>v.userItems),a=mt(v=>v.fetchAgents),l=[...n,...s],[u,c]=R.useState(!1),[h,f]=R.useState(!1),[p,m]=R.useState(null),_=R.useRef(null);R.useEffect(()=>{a()},[a]),R.useEffect(()=>{function v(b){_.current&&!_.current.contains(b.target)&&c(!1)}return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[]);const x=up();if(!e)return null;const w=l.filter(v=>!v.subagent),k=w.find(v=>v.id===e),y=(k==null?void 0:k.name)??e,S=il(l,e);return o.jsxs("div",{className:"relative",ref:_,children:[o.jsxs("button",{type:"button",onClick:()=>c(!u),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors",title:"Switch agent",children:[o.jsx("span",{className:"text-sm font-medium",style:{color:S},children:y}),o.jsx(Sr,{className:`w-3 h-3 text-text-muted transition-transform ${u?"rotate-180":""}`})]}),u&&w.length>0&&o.jsxs("div",{className:"absolute bottom-full left-0 mb-1 w-56 bg-bg-secondary border border-border rounded-lg shadow-lg overflow-hidden z-50",children:[w.map((v,b)=>{const E=v.id===e,T=il(l,v.id),N=x.agentSwitching[b],L=N?yS(N):null;return o.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 text-sm transition-colors group ${E?"bg-bg-tertiary":"hover:bg-bg-tertiary cursor-pointer"}`,children:[o.jsxs("button",{type:"button",onClick:()=>{E||t(v.id),c(!1)},className:"flex-1 text-left flex items-center gap-2 min-w-0",children:[o.jsx("span",{className:"font-medium truncate",style:{color:T},children:v.name}),E&&o.jsx(Mr,{className:"w-3.5 h-3.5 text-text-muted shrink-0"})]}),L&&o.jsx("span",{className:"shrink-0 px-1.5 py-0.5 text-[10px] bg-bg-tertiary text-text-muted rounded",children:L})]},v.id)}),o.jsx("div",{className:"border-t border-border p-1",children:o.jsx("button",{type:"button",onClick:()=>{c(!1),f(!0)},className:"w-full text-left px-3 py-1.5 rounded text-sm text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors",children:"Manage Agents..."})})]}),o.jsx(KB,{isOpen:h,onClose:()=>{f(!1),m(null)},initialEditId:p})]})}function XB(){const e=we(s=>s.currentSession),t=we(s=>s.switchDangerLevel);if(!e)return null;const n=e.dangerLevel??"normal";return o.jsxs("div",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-bg-tertiary/50",children:[o.jsx("button",{type:"button",onClick:()=>t("normal"),className:`px-2 py-0.5 text-xs font-medium rounded transition-colors ${n==="normal"?"bg-accent-success/20 text-accent-success":"text-text-muted hover:text-text-primary hover:bg-bg-tertiary"}`,title:"Normal mode - requires path confirmation",children:"Normal"}),o.jsx("button",{type:"button",onClick:()=>t("dangerous"),className:`px-2 py-0.5 text-xs font-medium rounded transition-colors ${n==="dangerous"?"bg-red-500/20 text-red-400":"text-text-muted hover:text-text-primary hover:bg-bg-tertiary"}`,title:"Dangerous mode - bypasses all confirmations",children:"Dangerous"})]})}function W0({message:e,field:t,label:n}){const s=e==null?void 0:e[t];return o.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[o.jsx("span",{className:s!=null?"text-accent-success":"text-red-500",children:s!=null?"✓":"✗"}),o.jsxs("span",{className:"text-text-secondary",children:[n,":"]}),o.jsx("span",{className:"text-text-primary font-mono truncate max-w-[200px]",children:JSON.stringify(s??"undefined")})]})}function q0({kwargs:e,onChange:t,mode:n,modelId:s,testResults:a,thinkingField:l,onSeeRaw:u,onTest:c}){var f,p,m,_,x;const h=s+"-"+n;return o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Extra kwargs"}),o.jsx("input",{type:"text",value:e,onChange:w=>t(w.target.value),className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary font-mono"})]}),o.jsxs("div",{className:"flex gap-2 items-start",children:[o.jsx("button",{onClick:c,disabled:(f=a[h])==null?void 0:f.loading,className:"px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-muted hover:text-text-secondary disabled:opacity-50",children:(p=a[h])!=null&&p.loading?"Testing...":"Test"}),((m=a[h])==null?void 0:m.result)&&o.jsx(QB,{testKey:h,testResults:a,thinkingField:l,onSeeRaw:u}),((_=a[h])==null?void 0:_.error)&&o.jsx("span",{className:"text-xs text-red-500",children:(x=a[h])==null?void 0:x.error})]})]})}function QB({testKey:e,testResults:t,thinkingField:n,onSeeRaw:s}){const a=t[e];if(!(a!=null&&a.result))return null;const l=a.message,u=n||(l!=null&&l.reasoning?"reasoning":l!=null&&l.reasoning_content?"reasoning_content":l!=null&&l.thinking?"thinking":void 0);return o.jsxs("div",{className:"flex-1 space-y-1",children:[a.message&&o.jsxs(o.Fragment,{children:[o.jsx(W0,{message:a.message,field:"content",label:"content"}),u&&o.jsx(W0,{message:a.message,field:u,label:u})]}),o.jsx("button",{onClick:()=>s(a.result??""),className:"text-xs text-accent-primary hover:underline",children:"See raw output"})]})}const JB=[8e3,11434,8080],ZB=[{value:"auto",label:"Auto-detect"},{value:"vllm",label:"vLLM"},{value:"sglang",label:"SGLang"},{value:"ollama",label:"Ollama"},{value:"llamacpp",label:"llama.cpp"},{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"opencode-go",label:"OpenCode Go"}];function BC({isOpen:e,onClose:t,onSave:n,initialStep:s=1,editProvider:a,editModelId:l}){const[u,c]=R.useState(s),[h,f]=R.useState(""),[p,m]=R.useState(""),[_,x]=R.useState("auto"),[w,k]=R.useState(""),[y,S]=R.useState(!1),[v,b]=R.useState(!1),[E,T]=R.useState(null),[N,L]=R.useState([]),[A,D]=R.useState(null),[B,q]=R.useState(!1),[W,O]=R.useState(""),[V,G]=R.useState({}),[z,X]=R.useState('{"enable_thinking": true}'),[ne,F]=R.useState('{"enable_thinking": false}'),[M,$]=R.useState({}),[P,U]=R.useState(null);function J(H,ee){G(te=>({...te,[H]:{...te[H],...ee}}))}R.useEffect(()=>{var H,ee;if(e)if(c(s),f((a==null?void 0:a.name)??""),m((a==null?void 0:a.url)??""),x((a==null?void 0:a.backend)??"auto"),k((a==null?void 0:a.apiKey)??""),S((a==null?void 0:a.isLocal)??!1),T(null),O((a==null?void 0:a.thinkingField)??""),$({}),U(null),(H=a==null?void 0:a.models)!=null&&H.length){const te={};for(const ce of a.models)te[ce.id]={contextWindow:ce.contextWindow,supportsVision:ce.supportsVision,thinkingEnabled:ce.thinkingEnabled,thinkingLevel:ce.thinkingLevel??(ce.thinkingEnabled?"max":void 0),nonThinkingEnabled:ce.nonThinkingEnabled,thinkingExtraKwargs:ce.thinkingExtraKwargs,nonThinkingExtraKwargs:ce.nonThinkingExtraKwargs,defaultTemperature:ce.defaultTemperature,defaultTopP:ce.defaultTopP,defaultTopK:ce.defaultTopK,defaultMaxTokens:ce.defaultMaxTokens};G(te),L(a.models.map(ce=>({id:ce.id,contextWindow:ce.contextWindow}))),D(l??((ee=a.models[0])==null?void 0:ee.id)??null)}else L([]),G({}),D(null)},[e,s,a,l]),R.useEffect(()=>{u===2&&p&&N.length===0&&!v&&!E&&Q(p)},[u]);async function Q(H){var ee,te;b(!0),T(null),L([]);try{const ce=await Ne(`/api/providers/models?url=${encodeURIComponent(H)}`);if(ce.ok){const he=await ce.json();if((ee=he.models)!=null&&ee.length){L(he.models),D(((te=he.models[0])==null?void 0:te.id)??null);const Te={};for(const Ae of he.models)Te[Ae.id]={contextWindow:Ae.contextWindow,thinkingEnabled:!0,thinkingLevel:"max",defaultTemperature:Ae.defaultTemperature,defaultTopP:Ae.defaultTopP,defaultTopK:Ae.defaultTopK,defaultMaxTokens:Ae.defaultMaxTokens};G(Te)}}else{const he=await ce.json();T(he.error??`Failed to fetch models from ${H}`)}}catch(ce){T(`Failed to fetch models from ${H}: ${ce instanceof Error?ce.message:"Unknown error"}`)}b(!1)}async function se(H,ee){const te=H+"-"+ee;$(Te=>({...Te,[te]:{loading:!0}}));const ce=V[H],he={};if(ee==="thinking"){if(he.reasoning_effort=(ce==null?void 0:ce.thinkingLevel)??"low",z)try{he.chat_template_kwargs=JSON.parse(z)}catch{}}else if(he.reasoning_effort="none",ne)try{he.chat_template_kwargs=JSON.parse(ne)}catch{}try{const Te=await Ne("/api/providers/test-params",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:p,model:H,params:he,apiKey:w||void 0})}),Ae=await Te.json();Te.ok?$(Le=>({...Le,[te]:{loading:!1,result:JSON.stringify(Ae,null,2),message:Ae.message}})):$(Le=>({...Le,[te]:{loading:!1,error:Ae.error??"Test failed"}}))}catch(Te){$(Ae=>({...Ae,[te]:{loading:!1,error:Te instanceof Error?Te.message:"Request failed"}}))}}function Y(){const H=h||"Provider",ee=(a==null?void 0:a.id)??`temp-${Date.now()}`;n({id:ee,name:H,url:p,backend:_,apiKey:w||void 0,isLocal:y||void 0,thinkingField:W||void 0,models:N.map(te=>{var ce,he,Te,Ae,Le,Pe,de;return{id:te.id,contextWindow:((ce=V[te.id])==null?void 0:ce.contextWindow)??te.contextWindow,supportsVision:(he=V[te.id])==null?void 0:he.supportsVision,thinkingEnabled:(Te=V[te.id])==null?void 0:Te.thinkingEnabled,thinkingLevel:(Ae=V[te.id])==null?void 0:Ae.thinkingLevel,nonThinkingEnabled:(Le=V[te.id])==null?void 0:Le.nonThinkingEnabled,thinkingExtraKwargs:(Pe=V[te.id])==null?void 0:Pe.thinkingExtraKwargs,nonThinkingExtraKwargs:(de=V[te.id])==null?void 0:de.nonThinkingExtraKwargs}})}),t()}return e?o.jsxs("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50",onClick:H=>{H.target===H.currentTarget&&t()},children:[o.jsxs("div",{className:"bg-bg-secondary border border-border rounded-xl w-[640px] max-h-[85vh] overflow-y-auto shadow-2xl",children:[o.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border",children:[o.jsx("h3",{className:"text-lg font-semibold text-text-primary",children:a?"Edit Provider":"Add Provider"}),o.jsx("button",{onClick:t,className:"text-text-muted hover:text-text-primary text-xl leading-none p-1",children:"×"})]}),o.jsx("div",{className:"flex gap-1.5 px-6 pt-4",children:[1,2,3].map(H=>o.jsx("div",{className:`h-1 flex-1 rounded-full transition-colors ${H<u?"bg-accent-success":H===u?"bg-accent-primary":"bg-border"}`},H))}),u===1&&o.jsxs("div",{className:"px-6 py-4 space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-2",children:"Common URLs"}),o.jsx("div",{className:"grid grid-cols-3 gap-2",children:JB.map(H=>o.jsxs("button",{type:"button",onClick:()=>{f(""),m(`http://localhost:${H}`),x("auto"),T(null)},className:`p-2 rounded border text-center text-sm transition-colors ${p===`http://localhost:${H}`?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:["localhost:",H]},H))})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"API URL"}),o.jsx("input",{type:"text",value:p,"data-testid":"provider-modal-url",onChange:H=>{m(H.target.value),T(null),L([]),G({})},placeholder:"http://localhost:8000",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Provider name"}),o.jsx("input",{type:"text",value:h,onChange:H=>f(H.target.value),placeholder:"My LLM Server",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),o.jsxs("div",{children:[o.jsxs("label",{className:"block text-sm text-text-secondary mb-1",children:["API key ",o.jsx("span",{className:"text-text-muted",children:"(optional)"})]}),o.jsx("input",{type:"password",value:w,onChange:H=>k(H.target.value),placeholder:"sk-...",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),o.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:y,onChange:H=>S(H.target.checked),className:"w-4 h-4 rounded border-border bg-bg-primary accent-accent-primary"}),o.jsx("span",{className:"text-sm text-text-secondary",children:"This is a local provider"})]})]}),u===2&&o.jsxs("div",{className:"px-6 py-4 space-y-4",children:[o.jsx("div",{children:o.jsxs("div",{className:"flex items-end gap-2",children:[o.jsxs("div",{className:"flex-1",children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Backend type"}),o.jsx("select",{value:_,onChange:H=>x(H.target.value),"data-testid":"provider-modal-backend",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-text-primary focus:outline-none focus:border-accent-primary",children:ZB.map(H=>o.jsx("option",{value:H.value,children:H.label},H.value))})]}),o.jsx("button",{onClick:()=>q(!0),className:"px-3 h-[38px] bg-bg-primary border border-border rounded-lg hover:border-text-muted transition-colors flex items-center justify-center",title:"Provider-level defaults",children:o.jsx("svg",{className:"w-4 h-4 text-text-muted",viewBox:"0 0 20 20",fill:"currentColor",children:o.jsx("path",{fillRule:"evenodd",d:"M11.49 3.17c-.38-1.56-2.6-1.56-2.98 0a1.532 1.532 0 01-2.286.948c-1.372-.836-2.942.734-2.106 2.106.54.886.061 2.042-.947 2.287-1.561.379-1.561 2.6 0 2.978a1.532 1.532 0 01.947 2.287c-.836 1.372.734 2.942 2.106 2.106a1.532 1.532 0 012.287.947c.379 1.561 2.6 1.561 2.978 0a1.533 1.533 0 012.287-.947c1.372.836 2.942-.734 2.106-2.106a1.533 1.533 0 01.947-2.287c1.561-.379 1.561-2.6 0-2.978a1.532 1.532 0 01-.947-2.287c.836-1.372-.734-2.942-2.106-2.106a1.532 1.532 0 01-2.287-.947zM10 13a3 3 0 100-6 3 3 0 000 6z",clipRule:"evenodd"})})})]})}),v&&o.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-muted",children:[o.jsx("span",{className:"w-4 h-4 border-2 border-accent-primary border-t-transparent rounded-full animate-spin"}),"Fetching models..."]}),E&&o.jsxs("div",{className:"p-3 rounded-lg text-sm bg-red-500/10 text-red-500 border border-red-500/20",children:[o.jsx("p",{children:E}),o.jsxs("p",{className:"text-xs text-text-muted mt-1",children:["URL: ",p]}),o.jsx("button",{onClick:()=>Q(p),className:"mt-2 text-xs text-accent-primary hover:underline",children:"Retry"})]}),N.length>0&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("h4",{className:"text-sm font-medium text-text-primary mb-1",children:"Available Models"}),o.jsx("p",{className:"text-xs text-text-muted mb-3",children:"Configure each model's thinking behavior and parameters. Models without explicit config use provider defaults."})]}),o.jsx("div",{className:"space-y-2",children:N.map(H=>{var ee,te,ce,he,Te,Ae,Le,Pe,de,Ie,Se,me,je,nt,Mt,gt,Zt,ge,Ce,Oe,Ve,Ge,vt,Xe,bt,ct,en;return o.jsxs("div",{className:"bg-bg-primary border border-border rounded-lg overflow-hidden",children:[o.jsxs("button",{onClick:()=>D(A===H.id?null:H.id),className:"w-full flex items-center justify-between px-4 py-3 hover:bg-bg-tertiary transition-colors text-left",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("span",{className:"text-sm font-medium text-text-primary",children:H.id.split("/").pop()}),o.jsxs("span",{className:"text-xs text-text-muted bg-bg-tertiary px-2 py-0.5 rounded",children:[H.contextWindow.toLocaleString()," ctx"]})]}),o.jsx(Sr,{className:`w-4 h-4 text-text-muted transition-transform ${A===H.id?"rotate-180":""}`})]}),A===H.id&&o.jsxs("div",{className:"px-4 pb-4 border-t border-border pt-3 space-y-3",children:[o.jsxs("div",{className:"flex gap-3 items-end",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Context window (tokens)"}),o.jsx("input",{type:"number",value:((ee=V[H.id])==null?void 0:ee.contextWindow)??H.contextWindow,onChange:He=>J(H.id,{contextWindow:parseInt(He.target.value)||H.contextWindow}),className:"w-32 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"})]}),o.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-text-secondary pb-1",children:[o.jsx("input",{type:"checkbox",checked:((te=V[H.id])==null?void 0:te.supportsVision)??!1,onChange:He=>J(H.id,{supportsVision:He.target.checked}),className:"accent-accent-primary"})," ","Supports vision"]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:((ce=V[H.id])==null?void 0:ce.thinkingEnabled)??!1,onChange:He=>J(H.id,{thinkingEnabled:He.target.checked}),className:"w-4 h-4 rounded border-border bg-bg-tertiary accent-accent-primary"}),o.jsx("span",{className:"text-xs font-medium text-text-primary",children:"Thinking"})]}),((he=V[H.id])==null?void 0:he.thinkingEnabled)&&o.jsxs("div",{className:"ml-6 space-y-2 pl-3 border-l-2 border-accent-primary/30",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Reasoning effort"}),o.jsx("input",{type:"text",value:((Te=V[H.id])==null?void 0:Te.thinkingLevel)??"max",onChange:He=>J(H.id,{thinkingLevel:He.target.value}),className:"w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-xs text-text-primary"})]}),o.jsx(q0,{kwargs:z,onChange:X,mode:"thinking",modelId:H.id,testResults:M,thinkingField:W,onSeeRaw:U,onTest:()=>se(H.id,"thinking")})]}),o.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:((Ae=V[H.id])==null?void 0:Ae.nonThinkingEnabled)??!1,onChange:He=>J(H.id,{nonThinkingEnabled:He.target.checked}),className:"w-4 h-4 rounded border-border bg-bg-tertiary accent-accent-primary"}),o.jsx("span",{className:"text-xs font-medium text-text-primary",children:"Non-thinking"})]}),((Le=V[H.id])==null?void 0:Le.nonThinkingEnabled)&&o.jsx("div",{className:"ml-6 space-y-2 pl-3 border-l-2 border-accent-warning/30",children:o.jsx(q0,{kwargs:ne,onChange:F,mode:"non-thinking",modelId:H.id,testResults:M,thinkingField:W,onSeeRaw:U,onTest:()=>se(H.id,"non-thinking")})})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-xs text-accent-primary cursor-pointer hover:underline",onClick:()=>{var He;return(He=document.getElementById(`adv-${H.id}`))==null?void 0:He.classList.toggle("hidden")},children:"▸ Advanced parameters"}),o.jsxs("div",{id:`adv-${H.id}`,className:"hidden mt-2 space-y-2",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Temperature"}),o.jsx("input",{type:"number",step:"0.1",value:((Pe=V[H.id])==null?void 0:Pe.temperature)??"",onChange:He=>J(H.id,{temperature:He.target.value?parseFloat(He.target.value):void 0}),placeholder:((Ie=(de=V[H.id])==null?void 0:de.defaultTemperature)==null?void 0:Ie.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary text-text-secondary"}),((Se=V[H.id])==null?void 0:Se.defaultTemperature)!==void 0&&o.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(me=V[H.id])==null?void 0:me.defaultTemperature]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Top P"}),o.jsx("input",{type:"number",step:"0.05",value:((je=V[H.id])==null?void 0:je.topP)??"",onChange:He=>J(H.id,{topP:He.target.value?parseFloat(He.target.value):void 0}),placeholder:((Mt=(nt=V[H.id])==null?void 0:nt.defaultTopP)==null?void 0:Mt.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((gt=V[H.id])==null?void 0:gt.defaultTopP)!==void 0&&o.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(Zt=V[H.id])==null?void 0:Zt.defaultTopP]})]})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Top K"}),o.jsx("input",{type:"number",value:((ge=V[H.id])==null?void 0:ge.topK)??"",onChange:He=>J(H.id,{topK:He.target.value?parseInt(He.target.value):void 0}),placeholder:((Oe=(Ce=V[H.id])==null?void 0:Ce.defaultTopK)==null?void 0:Oe.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((Ve=V[H.id])==null?void 0:Ve.defaultTopK)!==void 0&&o.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(Ge=V[H.id])==null?void 0:Ge.defaultTopK]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Max tokens"}),o.jsx("input",{type:"number",value:((vt=V[H.id])==null?void 0:vt.maxTokens)??"",onChange:He=>J(H.id,{maxTokens:He.target.value?parseInt(He.target.value):void 0}),placeholder:((bt=(Xe=V[H.id])==null?void 0:Xe.defaultMaxTokens)==null?void 0:bt.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((ct=V[H.id])==null?void 0:ct.defaultMaxTokens)!==void 0&&o.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(en=V[H.id])==null?void 0:en.defaultMaxTokens]})]})]})]})]})]})]},H.id)})})]})]}),u===3&&o.jsx("div",{className:"px-6 py-4 space-y-4",children:o.jsxs("div",{className:"bg-bg-primary border border-border rounded-lg p-4",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[o.jsx("span",{className:"text-sm font-medium text-text-primary",children:h||"Provider"}),o.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-accent-primary/20 text-accent-primary",children:ip(_)})]}),o.jsx("p",{className:"text-xs text-text-muted mb-3",children:p}),N.length>0&&o.jsxs("div",{className:"border-t border-border pt-3",children:[o.jsxs("p",{className:"text-xs text-text-secondary mb-2",children:["Models configured: ",o.jsx("strong",{children:N.length})]}),o.jsx("div",{className:"space-y-1",children:N.map(H=>{var ee,te;return o.jsxs("div",{className:"text-xs text-text-muted flex items-center gap-2",children:[o.jsxs("span",{children:["• ",H.id.split("/").pop()]}),o.jsxs("span",{className:"text-text-secondary",children:[H.contextWindow.toLocaleString()," ctx"]}),((ee=V[H.id])==null?void 0:ee.thinkingEnabled)&&o.jsx("span",{className:"text-accent-success",children:"thinking"}),((te=V[H.id])==null?void 0:te.nonThinkingEnabled)&&o.jsx("span",{className:"text-accent-warning",children:"non-thinking"})]},H.id)})})]})]})}),o.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-t border-border",children:[o.jsx("div",{children:u>1&&o.jsx("button",{onClick:()=>c(u-1),className:"text-sm text-text-muted hover:text-text-secondary transition-colors",children:"← Back"})}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx("button",{onClick:t,className:"px-4 py-2 text-sm text-text-muted hover:text-text-secondary transition-colors",children:"Cancel"}),u<3?o.jsx("button",{onClick:()=>c(u+1),disabled:u===1&&!p,"data-testid":"provider-modal-next",className:"px-5 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 disabled:opacity-50 transition-colors",children:u===1?"Next — Test & Configure":"Next — Review"}):o.jsx("button",{onClick:Y,"data-testid":"provider-modal-save",className:"px-5 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 transition-colors",children:"Save Provider"})]})]})]}),B&&o.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-[60]",onClick:H=>{H.target===H.currentTarget&&q(!1)},children:o.jsxs("div",{className:"bg-bg-secondary border border-border rounded-xl w-[480px] shadow-2xl",children:[o.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border",children:[o.jsx("h3",{className:"text-base font-semibold text-text-primary",children:"Provider-Level Defaults"}),o.jsx("button",{onClick:()=>q(!1),className:"text-text-muted hover:text-text-primary text-xl leading-none p-1",children:"×"})]}),o.jsxs("div",{className:"px-6 py-4 space-y-4",children:[o.jsx("p",{className:"text-xs text-text-muted",children:"These apply to all models unless overridden per-model."}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Non-thinking mode params"}),o.jsx("input",{type:"text",defaultValue:'reasoning_effort: "none"',readOnly:!0,className:"w-full px-3 py-2 bg-bg-primary border border-border rounded text-sm text-text-secondary font-mono"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Thinking mode params"}),o.jsx("input",{type:"text",defaultValue:'reasoning_effort: "low"',readOnly:!0,className:"w-full px-3 py-2 bg-bg-primary border border-border rounded text-sm text-text-secondary font-mono"})]}),o.jsxs("div",{children:[o.jsxs("label",{className:"text-xs text-text-secondary block mb-1",children:["Thinking response field ",o.jsx("span",{className:"text-text-muted",children:"(override)"})]}),o.jsx("input",{type:"text",value:W,onChange:H=>O(H.target.value),placeholder:"Leave blank for auto-detect",className:"w-full px-3 py-2 bg-bg-primary border border-border rounded text-sm text-text-primary font-mono"}),o.jsx("p",{className:"text-xs text-text-muted mt-1",children:"Field name the backend uses for reasoning/thinking content (e.g. reasoning, reasoning_content, thinking)."})]})]}),o.jsx("div",{className:"flex justify-end px-6 py-4 border-t border-border",children:o.jsx("button",{onClick:()=>q(!1),className:"px-5 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 transition-colors",children:"Done"})})]})}),P&&o.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-[70]",onClick:H=>{H.target===H.currentTarget&&U(null)},children:o.jsxs("div",{className:"bg-bg-secondary border border-border rounded-xl w-[600px] max-h-[70vh] shadow-2xl flex flex-col",children:[o.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border flex-shrink-0",children:[o.jsx("h3",{className:"text-base font-semibold text-text-primary",children:"Raw Response"}),o.jsx("button",{onClick:()=>U(null),className:"text-text-muted hover:text-text-primary text-xl leading-none p-1",children:"×"})]}),o.jsx("pre",{className:"px-6 py-4 overflow-y-auto text-xs text-text-secondary font-mono whitespace-pre-wrap flex-1",children:P})]})})]}):null}function e8(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function t8(){var $;const[,e]=cr(),t=we(P=>P.currentSession),n=we(P=>P.setSessionProvider),[s,a]=R.useState(!1),[l,u]=R.useState([]),[c,h]=R.useState(null),f=R.useRef(null),[p,m]=R.useState(null),[_,x]=R.useState(!1),w=R.useRef(new Set),k=Bt(P=>P.providers),y=Bt(P=>P.activeProviderId),S=Bt(P=>P.defaultModelSelection),v=Bt(P=>P.activating),b=Bt(P=>P.activateProvider),E=Bt(P=>P.refreshModel),T=Bt(P=>P.refreshProviderModels);R.useEffect(()=>{function P(U){f.current&&!f.current.contains(U.target)&&(a(!1),u([]),w.current=new Set)}return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[]),R.useEffect(()=>{if(s){const P=k.map(U=>U.id);u(P),P.forEach(U=>{w.current.has(U)||(w.current.add(U),q(U))})}},[s,k]);const N=k.find(P=>P.id===y),L=(N==null?void 0:N.status)==="disconnected",A=S?S.split("/").pop()??null:null,D=A?(($=A.split("/").pop())==null?void 0:$.replace(/-/g," "))??A:"detecting...",B=(P,U)=>S?S===`${P}/${U}`:!1,q=async P=>{h(P);try{await T(P)}catch{}finally{h(null)}},W=P=>{l.includes(P.id)?u(l.filter(U=>U!==P.id)):(u([...l,P.id]),q(P.id))},O=async P=>{if(P.id===y){W(P);return}t?(n(P.id,void 0),Bt.getState().syncFromSession(P.id,""),a(!1),u([])):await b(P.id)&&(a(!1),u([]))},V=P=>{W(P)},G=async(P,U)=>{P.stopPropagation(),w.current.delete(U),await q(U)},z=(P,U)=>{m({providerId:P,model:U}),x(!0)},X=p?k.find(P=>P.id===p.providerId):void 0,ne=()=>{m(null),x(!1)},F=async P=>{try{if(!(await Ne(`/api/providers/${P.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:P.name,url:P.url,backend:P.backend,apiKey:P.apiKey,isLocal:P.isLocal,thinkingField:P.thinkingField,models:P.models})})).ok)throw new Error("Failed to update provider");for(const J of P.models){const Q={};if(J.contextWindow!==void 0&&(Q.contextWindow=J.contextWindow),J.supportsVision!==void 0&&(Q.supportsVision=J.supportsVision),J.thinkingEnabled!==void 0&&(Q.thinkingEnabled=J.thinkingEnabled),J.thinkingLevel!==void 0&&(Q.thinkingLevel=J.thinkingLevel),J.nonThinkingEnabled!==void 0&&(Q.nonThinkingEnabled=J.nonThinkingEnabled),J.thinkingExtraKwargs!==void 0&&(Q.thinkingExtraKwargs=J.thinkingExtraKwargs),J.nonThinkingExtraKwargs!==void 0&&(Q.nonThinkingExtraKwargs=J.nonThinkingExtraKwargs),Object.keys(Q).length>0&&!(await Ne(`/api/providers/${P.id}/models/${encodeURIComponent(J.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Q)})).ok)throw new Error(`Failed to update model: ${J.id}`)}await Bt.getState().fetchConfig()}catch{}m(null),x(!1)},M=async(P,U)=>{if(t){n(P,U),Bt.getState().syncFromSession(P,U),u([]),a(!1);return}h("activating");try{Bt.getState().syncFromSession(P,U),u([]),a(!1);const J=await Ne(`/api/providers/${P}/activate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:U})});if(J.ok){const Q=await J.json();Bt.getState().syncFromSession(Q.activeProviderId,Q.model)}}catch{}finally{h(null)}};return k.length===0?o.jsxs("button",{type:"button",onClick:()=>E(),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors group",title:L?"LLM server is offline. Click to retry.":A??"Click to refresh model",children:[L?o.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"LLM offline"}):o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-sm text-accent-primary",children:D}),o.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${N!=null&&N.isLocal?"text-accent-success bg-accent-success/10":"text-accent-warning bg-accent-warning/10"}`,children:N!=null&&N.isLocal?"local":"api"})]}),o.jsx("span",{className:"text-text-muted opacity-0 group-hover:opacity-100 transition-opacity",children:"↻"})]}):o.jsxs("div",{className:"relative",ref:f,children:[o.jsxs("button",{type:"button",onClick:()=>a(!s),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors group",title:"Click to switch provider or model",children:[L?o.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"offline"}):o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-sm text-accent-primary",children:D}),o.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${N!=null&&N.isLocal?"text-accent-success bg-accent-success/10":"text-accent-warning bg-accent-warning/10"}`,children:N!=null&&N.isLocal?"local":"api"})]}),o.jsx(Sr,{className:"w-3 h-3 text-text-muted transition-transform",rotate:s?180:0})]}),s&&o.jsxs("div",{className:"absolute bottom-full right-0 mb-1 w-72 bg-bg-secondary border border-border rounded-lg shadow-lg z-50 overflow-hidden max-h-[80vh] overflow-y-auto",children:[o.jsx("div",{className:"py-1",children:k.map(P=>{var U;return o.jsxs("div",{children:[o.jsxs("div",{className:`px-3 py-2 flex items-center justify-between ${P.id===y?"bg-bg-tertiary":"hover:bg-bg-tertiary"} ${v?"opacity-50 cursor-wait":"cursor-pointer"}`,children:[o.jsxs("div",{onClick:()=>!v&&O(P),className:"flex flex-col min-w-0 flex-1 cursor-pointer",children:[o.jsx("span",{className:`text-sm font-medium truncate ${P.id===y?"text-accent-primary":"text-text-primary"}`,children:P.name}),o.jsx("span",{className:"text-xs text-text-muted truncate",children:P.backend!=="auto"&&ip(P.backend)})]}),o.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[P.id===y?o.jsx("span",{className:"text-accent-success",title:"Active",children:o.jsx(Mr,{className:"w-4 h-4"})}):o.jsx("span",{className:"w-4"}),o.jsx("button",{type:"button",onClick:J=>{J.stopPropagation(),G(J,P.id)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Refresh models",children:o.jsx(lp,{className:`w-4 h-4 ${c===P.id?"animate-spin":""} ${P.id===y?"text-accent-primary":"text-text-muted"}`})}),o.jsx("button",{type:"button",onClick:J=>{J.stopPropagation(),V(P)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Show models",children:o.jsx(Sr,{className:`w-4 h-4 transition-transform ${l.includes(P.id)?"rotate-180":""} ${P.id===y?"text-accent-primary":"text-text-muted"}`})})]})]}),l.includes(P.id)&&o.jsx("div",{className:"bg-bg-primary border-t border-border max-h-40 overflow-y-auto",children:c===P.id?o.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"Loading models..."}):(U=P.models)!=null&&U.length?P.models.map(J=>{var Q;return o.jsxs("button",{type:"button",onClick:()=>M(P.id,J.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":""} ${B(P.id,J.id)?"text-accent-primary":"text-text-secondary"}`,children:[o.jsx("span",{className:"truncate flex-1",children:((Q=J.id.split("/").pop())==null?void 0:Q.replace(/-/g," "))??J.id}),o.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[o.jsx("span",{className:"text-xs text-text-muted",children:e8(J.contextWindow)}),o.jsx("button",{type:"button",onClick:se=>{se.stopPropagation(),z(P.id,J)},className:"opacity-0 group-hover:opacity-100 p-0.5 hover:bg-bg-tertiary rounded transition-opacity",title:"Edit model context",children:o.jsx(bj,{className:"w-3 h-3 text-text-muted"})})]}),B(P.id,J.id)&&o.jsx("span",{className:"text-accent-success flex-shrink-0 ml-1",children:o.jsx(Mr,{className:"w-3.5 h-3.5"})})]},J.id)}):o.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"No models available"})})]},P.id)})}),o.jsx("div",{className:"border-t border-border px-3 py-2",children:o.jsx("button",{onClick:()=>e("/onboarding"),className:"text-xs text-accent-primary hover:underline",children:"Manage providers"})})]}),p&&_&&o.jsx(BC,{isOpen:!0,onClose:ne,onSave:F,initialStep:2,editProvider:{id:p.providerId,name:(X==null?void 0:X.name)??"",url:(X==null?void 0:X.url)??"",backend:(X==null?void 0:X.backend)??"auto",apiKey:X==null?void 0:X.apiKey,isLocal:X==null?void 0:X.isLocal,thinkingField:X==null?void 0:X.thinkingField,models:X==null?void 0:X.models},editModelId:p.model.id})]})}function n8({input:e,setInput:t,attachments:n,setAttachments:s,dragOver:a,setDragOver:l,errorMessage:u,setErrorMessage:c,scrollContainerRef:h,sessionId:f,sessionMode:p,showHistory:m,history:_,selectedIndex:x,openHistory:w,closeHistory:k,navigateUp:y,navigateDown:S,selectCurrent:v,isAutoScrollActive:b,setAutoScroll:E,onOpenMessageSearch:T,onOpenCommandsModal:N,onOpenWorkflowsModal:L,onSelectWorkflow:A,onSelectWorkflowWithSubGroup:D,clearInput:B}){const q=R.useRef(null),W=R.useRef(null),O=R.useRef(0),V=Pu(),G=we(ee=>ee.sendMessage),z=we(ee=>ee.stopGeneration),X=we(ee=>ee.cancelQueued),ne=we(ee=>ee.queuedMessages),F=R.useCallback(()=>{const ee=q.current;if(!ee)return;const te=e.length>=O.current;O.current=e.length,te||(ee.style.height="auto"),ee.style.height=`${Math.min(200,ee.scrollHeight)}px`},[e]);R.useEffect(()=>{if(!f)return;const ee=`openfox:draft:${f}`,te=localStorage.getItem(ee);te!==null&&t(te)},[f,t]),R.useEffect(()=>{var ee;(ee=q.current)==null||ee.focus(),F()},[f,F]),R.useEffect(()=>{if(!f)return;const ee=`openfox:draft:${f}`,te=setTimeout(()=>{e?localStorage.setItem(ee,e):localStorage.removeItem(ee)},500);return()=>clearTimeout(te)},[f,e]),R.useEffect(()=>{F()},[e,F]),R.useEffect(()=>{const ee=q.current;if(!ee)return;const te=async ce=>{var Te;if(document.activeElement!==ee)return;const he=(Te=ce.clipboardData)==null?void 0:Te.items;if(he){for(const Ae of Array.from(he))if(Ae.type.startsWith("image/")){ce.preventDefault();const Le=Ae.getAsFile();if(!Le)continue;await xm(Le,Pe=>s([...n,Pe]),c,{filename:"pasted-image"})}}};return ee.addEventListener("paste",te),()=>ee.removeEventListener("paste",te)},[n,s,c]);const M=ee=>{ee.preventDefault(),!(!e.trim()&&n.length===0)&&(G(e,n.length>0?n:void 0),B())},$=ee=>{if(m)switch(ee.key){case"Enter":{ee.preventDefault();const te=v();te&&(t(te),k());return}case"Escape":ee.preventDefault(),k(),V&&z();return;case"ArrowUp":ee.preventDefault(),y();return;case"ArrowDown":ee.preventDefault(),S();return}if(ee.key==="ArrowUp"&&e.trim()===""&&!m){ee.preventDefault(),w();return}ee.key==="Enter"&&!ee.shiftKey&&(ee.preventDefault(),M(ee))},P=R.useCallback(async ee=>{const te=ee.target.files;if(!(!te||te.length===0)){c(null);for(const ce of Array.from(te))await xm(ce,he=>s([...n,he]),c);W.current&&(W.current.value="")}},[n,s,c]),U=R.useCallback(ee=>{ee.preventDefault(),ee.stopPropagation(),l(!0)},[l]),J=R.useCallback(ee=>{ee.preventDefault(),ee.stopPropagation(),l(!1)},[l]),Q=R.useCallback(async ee=>{ee.preventDefault(),ee.stopPropagation(),l(!1),c(null);const te=ee.dataTransfer.files;if(!(!te||te.length===0))for(const ce of Array.from(te))await xm(ce,he=>s([...n,he]),c)},[n,s,l,c]),se=R.useCallback(ee=>{s(n.filter(te=>te.id!==ee))},[n,s]),Y=R.useCallback(()=>{var ee;(ee=W.current)==null||ee.click()},[]),H=()=>{var ee;!e.trim()&&n.length===0||((ee=h.current)==null||ee.scrollTo({top:h.current.scrollHeight,behavior:"smooth"}),G(e,n),B())};return o.jsxs("form",{onSubmit:M,className:"relative p-2 md:p-4 bg-secondary",children:[V&&o.jsx("div",{className:"absolute -top-8 left-2 md:left-4 z-10",children:o.jsx(jB,{})}),o.jsxs("div",{className:"absolute -top-8 right-2 md:right-4 z-10 flex items-center gap-2",children:[o.jsxs("button",{type:"button",className:"text-sm text-text-muted hover:text-text-primary flex items-center gap-1.5 px-2 py-0.5 rounded hover:bg-bg-tertiary transition-colors",onClick:()=>E(!b),children:[b?o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-success"}):o.jsx(Sr,{className:"w-3 h-3 text-text-muted"}),b?"live":"scroll to bottom"]}),o.jsxs("button",{type:"button",onClick:T,className:"text-sm text-text-muted hover:text-text-primary flex items-center gap-1.5 px-2 py-0.5 rounded hover:bg-bg-tertiary transition-colors","aria-label":"Browse history",children:[o.jsx(cp,{}),"Browse history"]})]}),o.jsx("input",{ref:W,type:"file",accept:".png,.jpg,.jpeg,.gif",onChange:P,className:"hidden",multiple:!0}),u&&o.jsx("div",{className:"mb-2 p-2 bg-red-500/10 border border-red-500/50 rounded text-red-300 text-sm",children:u}),n.length>0&&o.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:n.map(ee=>o.jsx(kB,{attachment:ee,onRemove:se},ee.id))}),m&&o.jsx(EB,{history:_,selectedIndex:x,onSelect:ee=>{t(ee),k()},onEscape:k,onNavigate:ee=>{ee==="up"?y():S()}}),o.jsx(FB,{messages:ne,onCancel:X}),o.jsxs("div",{className:`flex items-end gap-3 p-3 rounded transition-colors ${a?"bg-accent-primary/10":"bg-primary"}`,onDragOver:U,onDragLeave:J,onDrop:Q,children:[o.jsx("textarea",{id:LS,ref:q,value:e,onChange:ee=>{t(ee.target.value),m&&k()},onKeyDown:$,placeholder:"What would you like to build?","data-testid":"chat-input-textarea",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 gap-1.5",children:[V&&o.jsxs("button",{type:"button",onClick:()=>z(),"data-testid":"chat-stop-button",className:"flex items-center gap-1 px-4 py-1.5 rounded bg-accent-error/20 text-sm text-accent-error font-medium hover:bg-accent-error/30 transition-colors whitespace-nowrap",children:[o.jsx(xS,{}),"Abort"]}),o.jsxs("div",{className:"flex items-center",children:[o.jsx("button",{type:"button",onClick:H,disabled:!e.trim()&&n.length===0,"data-testid":"chat-send-button",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($B,{onSendCommand:(ee,te,ce,he)=>{var Ae;te&&p!==te&&we.getState().switchMode(te);const Te=ce&&ce.trim()?`${ce.trim()}
|
|
295
|
+
`,children:[o.jsxs("div",{className:"text-xs text-text-muted font-mono",children:[f.formattedTimestamp,f.sessionName&&o.jsxs(o.Fragment,{children:[" | ",o.jsx("span",{className:"text-accent-primary font-medium",children:f.sessionName})]})]}),o.jsx("div",{className:"text-sm text-text-primary mt-1",children:f.trimmedContent})]},f.id))})}function jB(){const e=uj(),t=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 ${t}`,style:{animationDelay:"0ms"}}),o.jsx("span",{className:`w-1 h-1 rounded-full animate-bounce ${t}`,style:{animationDelay:"150ms"}}),o.jsx("span",{className:`w-1 h-1 rounded-full animate-bounce ${t}`,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"})]})}const NB={maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576};async function TB(e,t={}){const n={...NB,...t};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<=n.maxSizeBytes){const a=await e.arrayBuffer(),l=IB(a),u=`data:${e.type};base64,${l}`,c=await PC(u);return{dataUrl:u,mimeType:e.type,size:e.size,width:c.width,height:c.height}}return await AB(e,n)}async function AB(e,t){const n=await DB(e),s=await PC(n),{width:a,height:l}=LB(s.width,s.height,t.maxWidth,t.maxHeight),u=RB();u.width=a,u.height=l;const c=u.getContext("2d");if(!c)throw new Error("Failed to get canvas context");c.imageSmoothingEnabled=!0,c.imageSmoothingQuality="high",c.drawImage(s,0,0,a,l);let h=t.quality,f="";for(let m=0;m<10&&(f=u.toDataURL(e.type.startsWith("image/gif")?"image/png":e.type,h),!(F0(f)<=t.maxSizeBytes||h<=.3));m++)h-=.1;const p=F0(f);return{dataUrl:f,mimeType:e.type.startsWith("image/gif")?"image/png":e.type,size:p,width:a,height:l}}function LB(e,t,n,s){const a=e/t;return e>t&&e>n?{width:n,height:Math.round(n/a)}:t>e&&t>s?{width:Math.round(s*a),height:s}:{width:e,height:t}}function DB(e){return new Promise((t,n)=>{const s=MB(),a=new s;a.onload=()=>t(a.result),a.onerror=()=>n(new Error("Failed to read file")),a.readAsDataURL(e)})}function PC(e){return new Promise((t,n)=>{const s=OB(),a=new s;a.onload=()=>t(a),a.onerror=()=>n(new Error("Failed to load image")),a.src=e})}function RB(){var t;const e=rg();if(!((t=e.document)!=null&&t.createElement))throw new Error("Image compression requires browser canvas APIs");return e.document.createElement("canvas")}function OB(){const e=rg();if(!e.Image)throw new Error("Image compression requires browser image APIs");return e.Image}function MB(){const e=rg();if(!e.FileReader)throw new Error("Image compression requires browser file APIs");return e.FileReader}function rg(){return globalThis}function IB(e){const t=new Uint8Array(e);let n="";for(let s=0;s<t.byteLength;s++){const a=t[s];a!==void 0&&(n+=String.fromCharCode(a))}return btoa(n)}function F0(e){const n=e.split(",")[1];return n?Math.round(n.length*3/4):0}function PB(e){return["image/png","image/jpeg","image/gif"].includes(e.type)}function BB(e,t=50*1024*1024){return e.size>t?{valid:!1,error:`Image file is too large (${V0(e.size)}). Maximum size is ${V0(t)}.`}:{valid:!0}}function V0(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}async function xm(e,t,n,s={}){const{maxSizeBytes:a=50*1024*1024,filename:l}=s;if(!PB(e)){n(`Unsupported file type: ${e.type}. Only PNG, JPG, and GIF are supported.`);return}const u=BB(e,a);if(!u.valid){n(u.error??"Image file is too large");return}try{const c=await TB(e,{maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576}),h={id:oS(),filename:l??e.name,mimeType:c.mimeType,size:c.size,data:c.dataUrl};t(h)}catch(c){const h=c instanceof Error?c.message??"Failed to process image":"Failed to process image";n(h)}}function zB({children:e}){return $a.createPortal(e,document.body)}function HB(e){const t=e.startCondition;if(!t||t.type==="always")return!0;switch(t.type){case"step_result":case"metadata_all_match":case"metadata_all_in":return null;default:return null}}function $B({onSendCommand:e,onSelectWorkflow:t,onSelectWorkflowWithSubGroup:n,onOpenCommandsManager:s,onOpenWorkflowsManager:a,onAttach:l,textareaContent:u,attachments:c}){const[h,f]=R.useState(!1),[p,m]=R.useState("commands"),[_,x]=R.useState(""),[w,k]=R.useState(0),[y,S]=R.useState(null),[v,b]=R.useState(null),E=R.useRef(null),T=R.useRef(null),N=nn(P=>P.defaults),L=nn(P=>P.userItems),A=nn(P=>P.fetchCommands),D=Et(P=>P.defaults),B=Et(P=>P.userItems),q=Et(P=>P.fetchWorkflows),W=[...N,...L],O=[...D,...B];R.useEffect(()=>{h&&(p==="commands"?A():p==="workflows"&&q())},[h,p,A,q]),R.useEffect(()=>{h&&(x(""),k(0),requestAnimationFrame(()=>{var P;return(P=E.current)==null?void 0:P.focus()}))},[h,p]),R.useEffect(()=>{if(!h)return;const P=U=>{var J;(J=T.current)!=null&&J.contains(U.target)||f(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[h]);const V=P=>{switch(P.key){case"ArrowDown":P.preventDefault(),k(U=>{const Q=(p==="commands"?W:O).filter(se=>{const Y=_.toLowerCase();return!Y||se.name.toLowerCase().includes(Y)});return Math.min(U+1,Q.length-1)});break;case"ArrowUp":P.preventDefault(),k(U=>Math.max(U-1,0));break;case"Enter":P.preventDefault();break;case"Escape":P.preventDefault(),f(!1);break}},G=P=>{x(P),k(0)},z=W.filter(P=>!_||P.name.toLowerCase().includes(_.toLowerCase())),X=O.filter(P=>!_||P.name.toLowerCase().includes(_.toLowerCase())),ne=async P=>{const U=await nn.getState().fetchCommand(P);U&&e(U.prompt,U.metadata.agentMode,u,c),f(!1)},F=P=>{t(P),f(!1)},M=(P,U)=>{U.stopPropagation(),f(!1),S(P)},$=(P,U)=>{U.stopPropagation(),f(!1),b(P)};return o.jsxs("div",{ref:T,className:"relative",children:[o.jsx("button",{type:"button",onClick:()=>f(!h),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(gS,{className:"w-4 h-4"})}),h&&o.jsxs("div",{className:"absolute bottom-full right-0 mb-1 w-80 max-w-[calc(100vw-2rem)] 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"),x(""),k(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${p==="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"),x(""),k(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${p==="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 ${p==="attach"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Attach"})]}),p!=="attach"&&o.jsx("div",{className:"p-2 border-b border-border",children:o.jsx("input",{ref:E,value:_,onChange:P=>G(P.target.value),onKeyDown:V,placeholder:p==="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:p==="commands"?z.length===0?o.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:W.length===0?"No commands yet":"No matches"}):z.map((P,U)=>o.jsxs("div",{className:`flex items-center gap-1 px-3 py-2 rounded transition-colors group ${U===w?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[o.jsx("button",{type:"button",onClick:()=>ne(P.id),className:"flex-1 text-left",children:o.jsx("div",{className:"text-sm text-text-primary font-medium",children:P.name})}),o.jsx(Fs,{className:"opacity-0 group-hover:opacity-100",onClick:J=>M(P.id,J)})]},P.id)):p==="workflows"?X.length===0?o.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:O.length===0?"No workflows yet":"No matches"}):X.map((P,U)=>{const J=HB(P),Q=P.color??"#3b82f6";return o.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 rounded transition-colors group ${U===w?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[o.jsxs("button",{type:"button",onClick:()=>F(P.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:P.name}),J!==null&&o.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:J?"#22c55e":"#6b7280"},title:J?"Entry condition met":"Entry condition not met"})]}),o.jsxs("div",{className:"flex items-center gap-1",children:[P.subGroups&&P.subGroups.length>0&&o.jsx(UB,{subGroups:P.subGroups,onSelect:se=>{f(!1),n(P.id,se)}}),o.jsx(Fs,{className:"opacity-0 group-hover:opacity-100",onClick:se=>$(P.id,se)})]})]},P.id)}):o.jsxs("div",{className:"p-4 flex flex-col items-center gap-3",children:[o.jsxs("button",{type:"button",onClick:()=>{l(),f(!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(xj,{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"})]})}),p!=="attach"&&o.jsx("div",{className:"border-t border-border p-1",children:o.jsx("button",{type:"button",onClick:()=>{f(!1),p==="commands"?s():a()},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:p==="commands"?"Manage Commands...":"Manage Workflows..."})})]}),o.jsx(LC,{isOpen:!!y,onClose:()=>S(null),initialEditId:y}),o.jsx(OC,{isOpen:!!v,onClose:()=>b(null),initialEditId:v})]})}function UB({subGroups:e,onSelect:t}){const[n,s]=R.useState(!1),[a,l]=R.useState({top:0,right:0}),u=R.useRef(null),c=R.useRef(null);AC(c,()=>s(!1),n);const h=f=>{if(f.stopPropagation(),!n&&u.current){const p=u.current.getBoundingClientRect();l({top:p.bottom+4,right:window.innerWidth-p.right})}s(!n)};return o.jsxs(o.Fragment,{children:[o.jsx("button",{ref:u,type:"button",onClick:h,className:"p-1 rounded text-text-muted hover:text-text-primary transition-colors",title:"Sub-groups",children:"⋮"}),n&&o.jsx(zB,{children:o.jsx("div",{ref:c,onMouseDown:f=>f.stopPropagation(),className:"fixed w-40 bg-bg-secondary border border-border rounded-lg shadow-xl z-[100] overflow-hidden",style:{top:a.top,right:a.right},children:e.map(f=>o.jsx("button",{type:"button",onClick:p=>{p.stopPropagation(),t(f)},className:"w-full text-left px-3 py-2 text-sm text-text-primary hover:bg-bg-tertiary transition-colors",children:f},f))})})]})}function FB({messages:e,onCancel:t}){return e.length===0?null:o.jsx("div",{className:"mb-2 flex flex-wrap gap-1.5",children:e.map(n=>o.jsxs("div",{className:`inline-flex items-center gap-1.5 px-2 py-1 rounded text-xs ${n.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:[n.mode==="asap"?"ASAP":"Queue",":"]}),o.jsx("span",{className:"truncate max-w-[200px]",children:n.content}),o.jsx(yl,{onClick:()=>t(n.queueId),size:"sm"})]},n.queueId))})}function VB({agent:e,isBuiltIn:t,isConfirmingDelete:n,onView:s,onEdit:a,onDuplicate:l,onDelete:u}){return o.jsxs(ES,{isBuiltIn:t,isConfirmingDelete:n,onView:s,onEdit:a,onDuplicate:l,onDelete:u,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0",style:{backgroundColor:e.color??"#6b7280"}}),o.jsx("span",{className:"text-text-primary text-sm font-medium",children:e.name}),o.jsx("span",{className:"text-text-muted text-xs font-mono",children:e.id}),t&&o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-medium bg-bg-primary text-text-muted",children:"Built-in"})]}),e.description&&o.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:e.description}),o.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[e.allowedTools.slice(0,5).map(c=>o.jsx("span",{className:"text-[10px] font-mono text-text-muted bg-bg-primary px-1 py-0.5 rounded",children:c},c)),e.allowedTools.length>5&&o.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",e.allowedTools.length-5," more"]})]})]})}function G0({title:e,agents:t,subagents:n,isBuiltIn:s,onView:a,onDuplicate:l,onEdit:u,onDelete:c}){if(t.length===0&&n.length===0)return null;const h=f=>o.jsx(VB,{agent:f,isBuiltIn:s,isConfirmingDelete:!1,onView:()=>a(f.id),onEdit:s?void 0:()=>u==null?void 0:u(f.id),onDuplicate:()=>l(f.id),onDelete:s?void 0:()=>c==null?void 0:c(f.id)},f.id);return o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:e}),o.jsxs("div",{className:"space-y-2",children:[t.map(h),n.length>0&&o.jsxs("div",{className:"mt-3",children:[o.jsx("div",{className:"text-xs text-text-muted uppercase tracking-wider mb-1.5",children:"Sub-agents"}),o.jsx("div",{className:"space-y-2",children:n.map(h)})]})]})]})}function GB(e){const t=new Map;for(const n of e){const s=n.indexOf(":");if(s===-1)t.set(n,new Set);else{const a=n.slice(0,s),u=n.slice(s+1).split(",").filter(Boolean);t.set(a,new Set(u))}}return t}function _m(e){const t=[];for(const[n,s]of e)s.size===0?t.push(n):t.push(`${n}:${[...s].join(",")}`);return t}function WB({formName:e,formId:t,formDescription:n,formSubagent:s,formTools:a,formColor:l,formPrompt:u,formError:c,saving:h,isReadOnly:f,availableTools:p,onNameChange:m,onIdChange:_,onDescriptionChange:x,onSubagentChange:w,onColorChange:k,onPromptChange:y,onSave:S,onCancel:v,onDuplicate:b}){const E=GB(a),T=(A,D)=>{const B=new Map(E),q=B.get(A)||new Set,W=new Set(q);W.has(D)?W.delete(D):W.add(D),W.size===0?B.set(A,new Set):B.set(A,W),L(_m(B))},N=A=>{const D=new Map(E);D.has(A)?D.delete(A):D.set(A,new Set),L(_m(D))},L=A=>{};return o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"space-y-3",children:[c&&o.jsx(gp,{message:c}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(ji,{label:"Name",value:e,onChange:m,placeholder:"My Agent",readOnly:f}),o.jsx(ji,{label:"ID",value:t,onChange:_,readOnly:!0,placeholder:"my_agent",hint:"(read-only)",mono:!0})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(ji,{label:"Description",value:n,onChange:x,placeholder:"What this agent does",readOnly:f}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Type"}),o.jsxs("div",{className:"flex items-center gap-3 h-[34px]",children:[o.jsx("button",{onClick:()=>!f&&w(!0),className:`px-2.5 py-1 rounded text-xs font-medium transition-colors ${s?"bg-accent-primary/25 text-accent-primary":"bg-bg-tertiary text-text-muted hover:text-text-secondary"} ${f?"pointer-events-none opacity-60":""}`,children:"Sub-agent"}),o.jsx("button",{onClick:()=>!f&&w(!1),className:`px-2.5 py-1 rounded text-xs font-medium transition-colors ${s?"bg-bg-tertiary text-text-muted hover:text-text-secondary":"bg-accent-primary/25 text-accent-primary"} ${f?"pointer-events-none opacity-60":""}`,children:"Top-level"}),o.jsxs("div",{className:"flex items-center gap-1.5 ml-auto",children:[o.jsx("label",{className:"text-xs text-text-secondary",children:"Color"}),o.jsx("input",{type:"color",value:l,onChange:A=>!f&&k(A.target.value),disabled:f,className:"w-6 h-6 rounded cursor-pointer border border-border bg-transparent"})]})]})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Tools"}),o.jsx("div",{className:"flex flex-wrap gap-1.5 p-2 bg-bg-tertiary border border-border rounded max-h-32 overflow-y-auto",children:p.map(A=>{const D=E.has(A.name),B=A.actions.length>0,q=E.get(A.name)||new Set;return B?f?o.jsxs("button",{className:"px-1.5 py-0.5 rounded text-xs font-mono flex items-center gap-1 bg-bg-primary text-text-muted pointer-events-none opacity-60",children:[o.jsx("span",{children:A.name}),o.jsx("span",{className:"text-[10px]",children:"*"})]},A.name):o.jsx(xl,{trigger:o.jsxs("button",{className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${D?"bg-accent-primary/25 text-accent-primary":"bg-bg-primary text-text-muted"}`,children:[o.jsx("span",{children:A.name}),B&&o.jsx("span",{className:`text-[10px] ${D&&q.size>0?"text-accent-primary":"text-text-muted"}`,children:"*"})]}),minWidth:"160px",items:[...A.actions.map(W=>({label:o.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",htmlFor:`${A.name}-${W}`,children:[o.jsx("input",{type:"checkbox",id:`${A.name}-${W}`,checked:q.has(W),onChange:()=>T(A.name,W),disabled:f,className:"w-3 h-3 rounded accent-accent-primary"}),o.jsx("span",{children:W})]}),closeOnClick:!1})),{label:D?"Deselect all":"Select all",closeOnClick:!1,onClick:()=>{if(D)N(A.name);else{const W=new Map(E);W.set(A.name,new Set(A.actions)),L(_m(W))}}}]},A.name):o.jsx("button",{onClick:()=>!f&&N(A.name),className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${D?"bg-accent-primary/25 text-accent-primary":"bg-bg-primary text-text-muted hover:text-text-secondary"} ${f?"pointer-events-none":"cursor-pointer"}`,children:o.jsx("span",{children:A.name})},A.name)})})]})]}),o.jsxs("div",{className:"flex-1 min-h-[150px] border-t border-border pt-3 flex flex-col",children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Prompt"}),o.jsx("textarea",{value:u,onChange:A=>!f&&y(A.target.value),readOnly:f,placeholder:"Instructions for this agent...",className:`h-80 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary ${f?"opacity-60":""}`})]}),o.jsx(Kj,{onCancel:v,onSave:S,saving:h,saveDisabled:!e||!u||f}),f&&o.jsx("div",{className:"flex justify-end mt-2",children:o.jsx("button",{onClick:b,className:"px-3 py-1.5 rounded bg-accent-primary/20 text-sm text-accent-primary font-medium hover:bg-accent-primary/30 transition-colors",children:"Duplicate & Customize"})})]})}function qB(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"")}function KB({isOpen:e,onClose:t,initialEditId:n}){const s=mt(de=>de.defaults),a=mt(de=>de.userItems),l=mt(de=>de.loading),u=mt(de=>de.fetchAgents),c=mt(de=>de.fetchAgent),h=mt(de=>de.fetchDefaultContent),f=mt(de=>de.createAgent),p=mt(de=>de.updateAgent),m=mt(de=>de.deleteAgent),[_,x]=R.useState("list"),[w,k]=R.useState(null),[y,S]=R.useState(!1),[v,b]=R.useState(""),[E,T]=R.useState(""),[N,L]=R.useState(""),[A,D]=R.useState(!0),[B,q]=R.useState([]),[W,O]=R.useState("#6b7280"),[V,G]=R.useState(""),[z,X]=R.useState(""),[ne,F]=R.useState(!1),[M,$]=R.useState([]),P=de=>{b(de.metadata.name),T(de.metadata.id),L(de.metadata.description),D(de.metadata.subagent),q(de.metadata.allowedTools),O(de.metadata.color??"#6b7280"),G(de.prompt),X("")},U=(de,Ie,Se)=>{b(de.metadata.name+" (copy)"),T(`${Ie}-copy-${Date.now()}`),L(de.metadata.description),D(de.metadata.subagent),q(de.metadata.allowedTools),O(de.metadata.color??"#6b7280"),G(de.prompt),X(""),k(null),S(!1),x("edit")},J=(de,Ie)=>{P(de),k(Ie),S(!0),x("edit")};R.useEffect(()=>{e&&(u(),Ne("/api/tools").then(de=>de.json()).then(de=>$(de.tools||[])).catch(()=>$([])),n?s.some(Ie=>Ie.id===n)?h(n).then(Ie=>{Ie&&U(Ie,n)}):c(n).then(Ie=>{Ie&&(P(Ie),k(n),S(!1),x("edit"))}):(x("list"),k(null),S(!1)))},[e,u,c,h,n]);const Q=async de=>{if(s.some(Se=>Se.id===de)){const Se=await h(de);if(!Se)return;J(Se,de)}else{const Se=await c(de);if(!Se)return;J(Se,de)}},se=async de=>{const Ie=await h(de);Ie&&U(Ie,de)},Y=()=>{k(null),b(""),T(""),L(""),D(!0),q(["read_file"]),O("#6b7280"),G(""),X(""),S(!1),x("edit")},H=async de=>{const Ie=await c(de);Ie&&(P(Ie),k(de),S(!1),x("edit"))},ee=async de=>{await m(de)},te=async()=>{const de=w??E;if(!de||!v||!V){X("Name and prompt are required.");return}F(!0),X("");const Ie={metadata:{id:de,name:v,description:N,subagent:A,allowedTools:B,color:W},prompt:V},Se=w?await p(w,Ie):await f(Ie);if(F(!1),!Se.success){X(Se.error??"Failed to save agent.");return}n?t():x("list")},ce=()=>{n?t():(x("list"),S(!1))},he=de=>{b(de),w||T(qB(de))},Te=s.filter(de=>de.subagent),Ae=s.filter(de=>!de.subagent),Le=a.filter(de=>de.subagent),Pe=a.filter(de=>!de.subagent);return _==="edit"?o.jsx(Dt,{isOpen:e,onClose:ce,title:y?`${v}`:w?"Edit Agent":"New Agent",size:"xl",children:o.jsx(WB,{formName:v,formId:E,formDescription:N,formSubagent:A,formTools:B,formColor:W,formPrompt:V,formError:z,saving:ne,isReadOnly:y,availableTools:M,onNameChange:he,onIdChange:T,onDescriptionChange:L,onSubagentChange:D,onColorChange:O,onPromptChange:G,onSave:te,onCancel:ce,onDuplicate:()=>{b(v+" (copy)"),T(`${w}-copy-${Date.now()}`),k(null),S(!1)}})}):o.jsx(Dt,{isOpen:e,onClose:t,title:"Agents",size:"lg",children:o.jsx(wS,{description:"Agents define behavior, tools, and prompts for top-level modes and sub-agents.",onNew:Y,loading:l,hasItems:s.length>0||a.length>0,children:o.jsxs("div",{className:"space-y-4",children:[s.length>0&&o.jsx(G0,{title:"Built-in",agents:Ae,subagents:Te,isBuiltIn:!0,onView:Q,onDuplicate:se}),a.length>0&&o.jsx(G0,{title:"Custom",agents:Pe,subagents:Le,isBuiltIn:!1,onView:Q,onDuplicate:se,onEdit:H,onDelete:ee})]})})})}function YB(){const e=we(v=>{var b;return(b=v.currentSession)==null?void 0:b.mode}),t=we(v=>v.switchMode),n=mt(v=>v.defaults),s=mt(v=>v.userItems),a=mt(v=>v.fetchAgents),l=[...n,...s],[u,c]=R.useState(!1),[h,f]=R.useState(!1),[p,m]=R.useState(null),_=R.useRef(null);R.useEffect(()=>{a()},[a]),R.useEffect(()=>{function v(b){_.current&&!_.current.contains(b.target)&&c(!1)}return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[]);const x=up();if(!e)return null;const w=l.filter(v=>!v.subagent),k=w.find(v=>v.id===e),y=(k==null?void 0:k.name)??e,S=il(l,e);return o.jsxs("div",{className:"relative",ref:_,children:[o.jsxs("button",{type:"button",onClick:()=>c(!u),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors",title:"Switch agent",children:[o.jsx("span",{className:"text-sm font-medium",style:{color:S},children:y}),o.jsx(Sr,{className:`w-3 h-3 text-text-muted transition-transform ${u?"rotate-180":""}`})]}),u&&w.length>0&&o.jsxs("div",{className:"absolute bottom-full left-0 mb-1 w-56 bg-bg-secondary border border-border rounded-lg shadow-lg overflow-hidden z-50",children:[w.map((v,b)=>{const E=v.id===e,T=il(l,v.id),N=x.agentSwitching[b],L=N?yS(N):null;return o.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 text-sm transition-colors group ${E?"bg-bg-tertiary":"hover:bg-bg-tertiary cursor-pointer"}`,children:[o.jsxs("button",{type:"button",onClick:()=>{E||t(v.id),c(!1)},className:"flex-1 text-left flex items-center gap-2 min-w-0",children:[o.jsx("span",{className:"font-medium truncate",style:{color:T},children:v.name}),E&&o.jsx(Mr,{className:"w-3.5 h-3.5 text-text-muted shrink-0"})]}),L&&o.jsx("span",{className:"shrink-0 px-1.5 py-0.5 text-[10px] bg-bg-tertiary text-text-muted rounded",children:L})]},v.id)}),o.jsx("div",{className:"border-t border-border p-1",children:o.jsx("button",{type:"button",onClick:()=>{c(!1),f(!0)},className:"w-full text-left px-3 py-1.5 rounded text-sm text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors",children:"Manage Agents..."})})]}),o.jsx(KB,{isOpen:h,onClose:()=>{f(!1),m(null)},initialEditId:p})]})}function XB(){const e=we(s=>s.currentSession),t=we(s=>s.switchDangerLevel);if(!e)return null;const n=e.dangerLevel??"normal";return o.jsxs("div",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-bg-tertiary/50",children:[o.jsx("button",{type:"button",onClick:()=>t("normal"),className:`px-2 py-0.5 text-xs font-medium rounded transition-colors ${n==="normal"?"bg-accent-success/20 text-accent-success":"text-text-muted hover:text-text-primary hover:bg-bg-tertiary"}`,title:"Normal mode - requires path confirmation",children:"Normal"}),o.jsx("button",{type:"button",onClick:()=>t("dangerous"),className:`px-2 py-0.5 text-xs font-medium rounded transition-colors ${n==="dangerous"?"bg-red-500/20 text-red-400":"text-text-muted hover:text-text-primary hover:bg-bg-tertiary"}`,title:"Dangerous mode - bypasses all confirmations",children:"Dangerous"})]})}function W0({message:e,field:t,label:n}){const s=e==null?void 0:e[t];return o.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[o.jsx("span",{className:s!=null?"text-accent-success":"text-red-500",children:s!=null?"✓":"✗"}),o.jsxs("span",{className:"text-text-secondary",children:[n,":"]}),o.jsx("span",{className:"text-text-primary font-mono truncate max-w-[200px]",children:JSON.stringify(s??"undefined")})]})}function q0({kwargs:e,onChange:t,mode:n,modelId:s,testResults:a,thinkingField:l,onSeeRaw:u,onTest:c}){var f,p,m,_,x;const h=s+"-"+n;return o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Extra kwargs"}),o.jsx("input",{type:"text",value:e,onChange:w=>t(w.target.value),className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary font-mono"})]}),o.jsxs("div",{className:"flex gap-2 items-start",children:[o.jsx("button",{onClick:c,disabled:(f=a[h])==null?void 0:f.loading,className:"px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-muted hover:text-text-secondary disabled:opacity-50",children:(p=a[h])!=null&&p.loading?"Testing...":"Test"}),((m=a[h])==null?void 0:m.result)&&o.jsx(QB,{testKey:h,testResults:a,thinkingField:l,onSeeRaw:u}),((_=a[h])==null?void 0:_.error)&&o.jsx("span",{className:"text-xs text-red-500",children:(x=a[h])==null?void 0:x.error})]})]})}function QB({testKey:e,testResults:t,thinkingField:n,onSeeRaw:s}){const a=t[e];if(!(a!=null&&a.result))return null;const l=a.message,u=n||(l!=null&&l.reasoning?"reasoning":l!=null&&l.reasoning_content?"reasoning_content":l!=null&&l.thinking?"thinking":void 0);return o.jsxs("div",{className:"flex-1 space-y-1",children:[a.message&&o.jsxs(o.Fragment,{children:[o.jsx(W0,{message:a.message,field:"content",label:"content"}),u&&o.jsx(W0,{message:a.message,field:u,label:u})]}),o.jsx("button",{onClick:()=>s(a.result??""),className:"text-xs text-accent-primary hover:underline",children:"See raw output"})]})}const JB=[8e3,11434,8080],ZB=[{value:"vllm",label:"vLLM"},{value:"sglang",label:"SGLang"},{value:"ollama",label:"Ollama"},{value:"llamacpp",label:"llama.cpp"},{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"opencode-go",label:"OpenCode Go"}];function BC({isOpen:e,onClose:t,onSave:n,initialStep:s=1,editProvider:a,editModelId:l}){const[u,c]=R.useState(s),[h,f]=R.useState(""),[p,m]=R.useState(""),[_,x]=R.useState("unknown"),[w,k]=R.useState(""),[y,S]=R.useState(!1),[v,b]=R.useState(!1),[E,T]=R.useState(null),[N,L]=R.useState([]),[A,D]=R.useState(null),[B,q]=R.useState(!1),[W,O]=R.useState(""),[V,G]=R.useState({}),[z,X]=R.useState('{"enable_thinking": true}'),[ne,F]=R.useState('{"enable_thinking": false}'),[M,$]=R.useState({}),[P,U]=R.useState(null);function J(H,ee){G(te=>({...te,[H]:{...te[H],...ee}}))}R.useEffect(()=>{var H,ee;if(e)if(c(s),f((a==null?void 0:a.name)??""),m((a==null?void 0:a.url)??""),x((a==null?void 0:a.backend)??"unknown"),k((a==null?void 0:a.apiKey)??""),S((a==null?void 0:a.isLocal)??!1),T(null),O((a==null?void 0:a.thinkingField)??""),$({}),U(null),(H=a==null?void 0:a.models)!=null&&H.length){const te={};for(const ce of a.models)te[ce.id]={contextWindow:ce.contextWindow,supportsVision:ce.supportsVision,thinkingEnabled:ce.thinkingEnabled,thinkingLevel:ce.thinkingLevel??(ce.thinkingEnabled?"max":void 0),nonThinkingEnabled:ce.nonThinkingEnabled,thinkingExtraKwargs:ce.thinkingExtraKwargs,nonThinkingExtraKwargs:ce.nonThinkingExtraKwargs,defaultTemperature:ce.defaultTemperature,defaultTopP:ce.defaultTopP,defaultTopK:ce.defaultTopK,defaultMaxTokens:ce.defaultMaxTokens};G(te),L(a.models.map(ce=>({id:ce.id,contextWindow:ce.contextWindow}))),D(l??((ee=a.models[0])==null?void 0:ee.id)??null)}else L([]),G({}),D(null)},[e,s,a==null?void 0:a.id,l]),R.useEffect(()=>{u===2&&p&&N.length===0&&!v&&!E&&Q(p)},[u]);async function Q(H){var ee,te;b(!0),T(null),L([]);try{const ce=await Ne(`/api/providers/models?url=${encodeURIComponent(H)}`);if(ce.ok){const he=await ce.json();if((ee=he.models)!=null&&ee.length){L(he.models),D(((te=he.models[0])==null?void 0:te.id)??null);const Te={};for(const Ae of he.models)Te[Ae.id]={contextWindow:Ae.contextWindow,thinkingEnabled:!0,thinkingLevel:"max",defaultTemperature:Ae.defaultTemperature,defaultTopP:Ae.defaultTopP,defaultTopK:Ae.defaultTopK,defaultMaxTokens:Ae.defaultMaxTokens};G(Te)}}else{const he=await ce.json();T(he.error??`Failed to fetch models from ${H}`)}}catch(ce){T(`Failed to fetch models from ${H}: ${ce instanceof Error?ce.message:"Unknown error"}`)}b(!1)}async function se(H,ee){const te=H+"-"+ee;$(Te=>({...Te,[te]:{loading:!0}}));const ce=V[H],he={};if(ee==="thinking"){if(he.reasoning_effort=(ce==null?void 0:ce.thinkingLevel)??"low",z)try{he.chat_template_kwargs=JSON.parse(z)}catch{}}else if(he.reasoning_effort="none",ne)try{he.chat_template_kwargs=JSON.parse(ne)}catch{}try{const Te=await Ne("/api/providers/test-params",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:p,model:H,params:he,apiKey:w||void 0})}),Ae=await Te.json();Te.ok?$(Le=>({...Le,[te]:{loading:!1,result:JSON.stringify(Ae,null,2),message:Ae.message}})):$(Le=>({...Le,[te]:{loading:!1,error:Ae.error??"Test failed"}}))}catch(Te){$(Ae=>({...Ae,[te]:{loading:!1,error:Te instanceof Error?Te.message:"Request failed"}}))}}function Y(){const H=h||"Provider",ee=(a==null?void 0:a.id)??`temp-${Date.now()}`;n({id:ee,name:H,url:p,backend:_,apiKey:w||void 0,isLocal:y||void 0,thinkingField:W||void 0,models:N.map(te=>{var ce,he,Te,Ae,Le,Pe,de;return{id:te.id,contextWindow:((ce=V[te.id])==null?void 0:ce.contextWindow)??te.contextWindow,supportsVision:(he=V[te.id])==null?void 0:he.supportsVision,thinkingEnabled:(Te=V[te.id])==null?void 0:Te.thinkingEnabled,thinkingLevel:(Ae=V[te.id])==null?void 0:Ae.thinkingLevel,nonThinkingEnabled:(Le=V[te.id])==null?void 0:Le.nonThinkingEnabled,thinkingExtraKwargs:(Pe=V[te.id])==null?void 0:Pe.thinkingExtraKwargs,nonThinkingExtraKwargs:(de=V[te.id])==null?void 0:de.nonThinkingExtraKwargs}})}),t()}return e?o.jsxs("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50",onClick:H=>{H.target===H.currentTarget&&t()},children:[o.jsxs("div",{className:"bg-bg-secondary border border-border rounded-xl w-[640px] max-h-[85vh] overflow-y-auto shadow-2xl",children:[o.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border",children:[o.jsx("h3",{className:"text-lg font-semibold text-text-primary",children:a?"Edit Provider":"Add Provider"}),o.jsx("button",{onClick:t,className:"text-text-muted hover:text-text-primary text-xl leading-none p-1",children:"×"})]}),o.jsx("div",{className:"flex gap-1.5 px-6 pt-4",children:[1,2,3].map(H=>o.jsx("div",{className:`h-1 flex-1 rounded-full transition-colors ${H<u?"bg-accent-success":H===u?"bg-accent-primary":"bg-border"}`},H))}),u===1&&o.jsxs("div",{className:"px-6 py-4 space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-2",children:"Common URLs"}),o.jsx("div",{className:"grid grid-cols-3 gap-2",children:JB.map(H=>o.jsxs("button",{type:"button",onClick:()=>{f(""),m(`http://localhost:${H}`),x("unknown"),T(null)},className:`p-2 rounded border text-center text-sm transition-colors ${p===`http://localhost:${H}`?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:["localhost:",H]},H))})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"API URL"}),o.jsx("input",{type:"text",value:p,"data-testid":"provider-modal-url",onChange:H=>{m(H.target.value),T(null),L([]),G({})},placeholder:"http://localhost:8000",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Provider name"}),o.jsx("input",{type:"text",value:h,onChange:H=>f(H.target.value),placeholder:"My LLM Server",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),o.jsxs("div",{children:[o.jsxs("label",{className:"block text-sm text-text-secondary mb-1",children:["API key ",o.jsx("span",{className:"text-text-muted",children:"(optional)"})]}),o.jsx("input",{type:"password",value:w,onChange:H=>k(H.target.value),placeholder:"sk-...",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),o.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:y,onChange:H=>S(H.target.checked),className:"w-4 h-4 rounded border-border bg-bg-primary accent-accent-primary"}),o.jsx("span",{className:"text-sm text-text-secondary",children:"This is a local provider"})]})]}),u===2&&o.jsxs("div",{className:"px-6 py-4 space-y-4",children:[o.jsx("div",{children:o.jsxs("div",{className:"flex items-end gap-2",children:[o.jsxs("div",{className:"flex-1",children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Backend type"}),o.jsx("select",{value:_,onChange:H=>x(H.target.value),"data-testid":"provider-modal-backend",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-text-primary focus:outline-none focus:border-accent-primary",children:ZB.map(H=>o.jsx("option",{value:H.value,children:H.label},H.value))})]}),o.jsx("button",{onClick:()=>q(!0),className:"px-3 h-[38px] bg-bg-primary border border-border rounded-lg hover:border-text-muted transition-colors flex items-center justify-center",title:"Provider-level defaults",children:o.jsx("svg",{className:"w-4 h-4 text-text-muted",viewBox:"0 0 20 20",fill:"currentColor",children:o.jsx("path",{fillRule:"evenodd",d:"M11.49 3.17c-.38-1.56-2.6-1.56-2.98 0a1.532 1.532 0 01-2.286.948c-1.372-.836-2.942.734-2.106 2.106.54.886.061 2.042-.947 2.287-1.561.379-1.561 2.6 0 2.978a1.532 1.532 0 01.947 2.287c-.836 1.372.734 2.942 2.106 2.106a1.532 1.532 0 012.287.947c.379 1.561 2.6 1.561 2.978 0a1.533 1.533 0 012.287-.947c1.372.836 2.942-.734 2.106-2.106a1.533 1.533 0 01.947-2.287c1.561-.379 1.561-2.6 0-2.978a1.532 1.532 0 01-.947-2.287c.836-1.372-.734-2.942-2.106-2.106a1.532 1.532 0 01-2.287-.947zM10 13a3 3 0 100-6 3 3 0 000 6z",clipRule:"evenodd"})})})]})}),v&&o.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-muted",children:[o.jsx("span",{className:"w-4 h-4 border-2 border-accent-primary border-t-transparent rounded-full animate-spin"}),"Fetching models..."]}),E&&o.jsxs("div",{className:"p-3 rounded-lg text-sm bg-red-500/10 text-red-500 border border-red-500/20",children:[o.jsx("p",{children:E}),o.jsxs("p",{className:"text-xs text-text-muted mt-1",children:["URL: ",p]}),o.jsx("button",{onClick:()=>Q(p),className:"mt-2 text-xs text-accent-primary hover:underline",children:"Retry"})]}),N.length>0&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("h4",{className:"text-sm font-medium text-text-primary mb-1",children:"Available Models"}),o.jsx("p",{className:"text-xs text-text-muted mb-3",children:"Configure each model's thinking behavior and parameters. Models without explicit config use provider defaults."})]}),o.jsx("div",{className:"space-y-2",children:N.map(H=>{var ee,te,ce,he,Te,Ae,Le,Pe,de,Ie,Se,me,je,nt,Mt,gt,Zt,ge,Ce,Oe,Ve,Ge,vt,Xe,bt,ct,en;return o.jsxs("div",{className:"bg-bg-primary border border-border rounded-lg overflow-hidden",children:[o.jsxs("button",{onClick:()=>D(A===H.id?null:H.id),className:"w-full flex items-center justify-between px-4 py-3 hover:bg-bg-tertiary transition-colors text-left",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("span",{className:"text-sm font-medium text-text-primary",children:H.id.split("/").pop()}),o.jsxs("span",{className:"text-xs text-text-muted bg-bg-tertiary px-2 py-0.5 rounded",children:[H.contextWindow.toLocaleString()," ctx"]})]}),o.jsx(Sr,{className:`w-4 h-4 text-text-muted transition-transform ${A===H.id?"rotate-180":""}`})]}),A===H.id&&o.jsxs("div",{className:"px-4 pb-4 border-t border-border pt-3 space-y-3",children:[o.jsxs("div",{className:"flex gap-3 items-end",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Context window (tokens)"}),o.jsx("input",{type:"number",value:((ee=V[H.id])==null?void 0:ee.contextWindow)??H.contextWindow,onChange:He=>J(H.id,{contextWindow:parseInt(He.target.value)||H.contextWindow}),className:"w-32 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"})]}),o.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-text-secondary pb-1",children:[o.jsx("input",{type:"checkbox",checked:((te=V[H.id])==null?void 0:te.supportsVision)??!1,onChange:He=>J(H.id,{supportsVision:He.target.checked}),className:"accent-accent-primary"})," ","Supports vision"]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:((ce=V[H.id])==null?void 0:ce.thinkingEnabled)??!1,onChange:He=>J(H.id,{thinkingEnabled:He.target.checked}),className:"w-4 h-4 rounded border-border bg-bg-tertiary accent-accent-primary"}),o.jsx("span",{className:"text-xs font-medium text-text-primary",children:"Thinking"})]}),((he=V[H.id])==null?void 0:he.thinkingEnabled)&&o.jsxs("div",{className:"ml-6 space-y-2 pl-3 border-l-2 border-accent-primary/30",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Reasoning effort"}),o.jsx("input",{type:"text",value:((Te=V[H.id])==null?void 0:Te.thinkingLevel)??"max",onChange:He=>J(H.id,{thinkingLevel:He.target.value}),className:"w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-xs text-text-primary"})]}),o.jsx(q0,{kwargs:z,onChange:X,mode:"thinking",modelId:H.id,testResults:M,thinkingField:W,onSeeRaw:U,onTest:()=>se(H.id,"thinking")})]}),o.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:((Ae=V[H.id])==null?void 0:Ae.nonThinkingEnabled)??!1,onChange:He=>J(H.id,{nonThinkingEnabled:He.target.checked}),className:"w-4 h-4 rounded border-border bg-bg-tertiary accent-accent-primary"}),o.jsx("span",{className:"text-xs font-medium text-text-primary",children:"Non-thinking"})]}),((Le=V[H.id])==null?void 0:Le.nonThinkingEnabled)&&o.jsx("div",{className:"ml-6 space-y-2 pl-3 border-l-2 border-accent-warning/30",children:o.jsx(q0,{kwargs:ne,onChange:F,mode:"non-thinking",modelId:H.id,testResults:M,thinkingField:W,onSeeRaw:U,onTest:()=>se(H.id,"non-thinking")})})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-xs text-accent-primary cursor-pointer hover:underline",onClick:()=>{var He;return(He=document.getElementById(`adv-${H.id}`))==null?void 0:He.classList.toggle("hidden")},children:"▸ Advanced parameters"}),o.jsxs("div",{id:`adv-${H.id}`,className:"hidden mt-2 space-y-2",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Temperature"}),o.jsx("input",{type:"number",step:"0.1",value:((Pe=V[H.id])==null?void 0:Pe.temperature)??"",onChange:He=>J(H.id,{temperature:He.target.value?parseFloat(He.target.value):void 0}),placeholder:((Ie=(de=V[H.id])==null?void 0:de.defaultTemperature)==null?void 0:Ie.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary text-text-secondary"}),((Se=V[H.id])==null?void 0:Se.defaultTemperature)!==void 0&&o.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(me=V[H.id])==null?void 0:me.defaultTemperature]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Top P"}),o.jsx("input",{type:"number",step:"0.05",value:((je=V[H.id])==null?void 0:je.topP)??"",onChange:He=>J(H.id,{topP:He.target.value?parseFloat(He.target.value):void 0}),placeholder:((Mt=(nt=V[H.id])==null?void 0:nt.defaultTopP)==null?void 0:Mt.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((gt=V[H.id])==null?void 0:gt.defaultTopP)!==void 0&&o.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(Zt=V[H.id])==null?void 0:Zt.defaultTopP]})]})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Top K"}),o.jsx("input",{type:"number",value:((ge=V[H.id])==null?void 0:ge.topK)??"",onChange:He=>J(H.id,{topK:He.target.value?parseInt(He.target.value):void 0}),placeholder:((Oe=(Ce=V[H.id])==null?void 0:Ce.defaultTopK)==null?void 0:Oe.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((Ve=V[H.id])==null?void 0:Ve.defaultTopK)!==void 0&&o.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(Ge=V[H.id])==null?void 0:Ge.defaultTopK]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Max tokens"}),o.jsx("input",{type:"number",value:((vt=V[H.id])==null?void 0:vt.maxTokens)??"",onChange:He=>J(H.id,{maxTokens:He.target.value?parseInt(He.target.value):void 0}),placeholder:((bt=(Xe=V[H.id])==null?void 0:Xe.defaultMaxTokens)==null?void 0:bt.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((ct=V[H.id])==null?void 0:ct.defaultMaxTokens)!==void 0&&o.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(en=V[H.id])==null?void 0:en.defaultMaxTokens]})]})]})]})]})]})]},H.id)})})]})]}),u===3&&o.jsx("div",{className:"px-6 py-4 space-y-4",children:o.jsxs("div",{className:"bg-bg-primary border border-border rounded-lg p-4",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[o.jsx("span",{className:"text-sm font-medium text-text-primary",children:h||"Provider"}),o.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-accent-primary/20 text-accent-primary",children:ip(_)})]}),o.jsx("p",{className:"text-xs text-text-muted mb-3",children:p}),N.length>0&&o.jsxs("div",{className:"border-t border-border pt-3",children:[o.jsxs("p",{className:"text-xs text-text-secondary mb-2",children:["Models configured: ",o.jsx("strong",{children:N.length})]}),o.jsx("div",{className:"space-y-1",children:N.map(H=>{var ee,te;return o.jsxs("div",{className:"text-xs text-text-muted flex items-center gap-2",children:[o.jsxs("span",{children:["• ",H.id.split("/").pop()]}),o.jsxs("span",{className:"text-text-secondary",children:[H.contextWindow.toLocaleString()," ctx"]}),((ee=V[H.id])==null?void 0:ee.thinkingEnabled)&&o.jsx("span",{className:"text-accent-success",children:"thinking"}),((te=V[H.id])==null?void 0:te.nonThinkingEnabled)&&o.jsx("span",{className:"text-accent-warning",children:"non-thinking"})]},H.id)})})]})]})}),o.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-t border-border",children:[o.jsx("div",{children:u>1&&o.jsx("button",{onClick:()=>c(u-1),className:"text-sm text-text-muted hover:text-text-secondary transition-colors",children:"← Back"})}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx("button",{onClick:t,className:"px-4 py-2 text-sm text-text-muted hover:text-text-secondary transition-colors",children:"Cancel"}),u<3?o.jsx("button",{onClick:()=>c(u+1),disabled:u===1&&!p,"data-testid":"provider-modal-next",className:"px-5 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 disabled:opacity-50 transition-colors",children:u===1?"Next — Test & Configure":"Next — Review"}):o.jsx("button",{onClick:Y,"data-testid":"provider-modal-save",className:"px-5 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 transition-colors",children:"Save Provider"})]})]})]}),B&&o.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-[60]",onClick:H=>{H.target===H.currentTarget&&q(!1)},children:o.jsxs("div",{className:"bg-bg-secondary border border-border rounded-xl w-[480px] shadow-2xl",children:[o.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border",children:[o.jsx("h3",{className:"text-base font-semibold text-text-primary",children:"Provider-Level Defaults"}),o.jsx("button",{onClick:()=>q(!1),className:"text-text-muted hover:text-text-primary text-xl leading-none p-1",children:"×"})]}),o.jsxs("div",{className:"px-6 py-4 space-y-4",children:[o.jsx("p",{className:"text-xs text-text-muted",children:"These apply to all models unless overridden per-model."}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Non-thinking mode params"}),o.jsx("input",{type:"text",defaultValue:'reasoning_effort: "none"',readOnly:!0,className:"w-full px-3 py-2 bg-bg-primary border border-border rounded text-sm text-text-secondary font-mono"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Thinking mode params"}),o.jsx("input",{type:"text",defaultValue:'reasoning_effort: "low"',readOnly:!0,className:"w-full px-3 py-2 bg-bg-primary border border-border rounded text-sm text-text-secondary font-mono"})]}),o.jsxs("div",{children:[o.jsxs("label",{className:"text-xs text-text-secondary block mb-1",children:["Thinking response field ",o.jsx("span",{className:"text-text-muted",children:"(override)"})]}),o.jsx("input",{type:"text",value:W,onChange:H=>O(H.target.value),placeholder:"Leave blank for auto-detect",className:"w-full px-3 py-2 bg-bg-primary border border-border rounded text-sm text-text-primary font-mono"}),o.jsx("p",{className:"text-xs text-text-muted mt-1",children:"Field name the backend uses for reasoning/thinking content (e.g. reasoning, reasoning_content, thinking)."})]})]}),o.jsx("div",{className:"flex justify-end px-6 py-4 border-t border-border",children:o.jsx("button",{onClick:()=>q(!1),className:"px-5 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 transition-colors",children:"Done"})})]})}),P&&o.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-[70]",onClick:H=>{H.target===H.currentTarget&&U(null)},children:o.jsxs("div",{className:"bg-bg-secondary border border-border rounded-xl w-[600px] max-h-[70vh] shadow-2xl flex flex-col",children:[o.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border flex-shrink-0",children:[o.jsx("h3",{className:"text-base font-semibold text-text-primary",children:"Raw Response"}),o.jsx("button",{onClick:()=>U(null),className:"text-text-muted hover:text-text-primary text-xl leading-none p-1",children:"×"})]}),o.jsx("pre",{className:"px-6 py-4 overflow-y-auto text-xs text-text-secondary font-mono whitespace-pre-wrap flex-1",children:P})]})})]}):null}function e8(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function t8(){var $;const[,e]=cr(),t=we(P=>P.currentSession),n=we(P=>P.setSessionProvider),[s,a]=R.useState(!1),[l,u]=R.useState([]),[c,h]=R.useState(null),f=R.useRef(null),[p,m]=R.useState(null),[_,x]=R.useState(!1),w=R.useRef(new Set),k=Bt(P=>P.providers),y=Bt(P=>P.activeProviderId),S=Bt(P=>P.defaultModelSelection),v=Bt(P=>P.activating),b=Bt(P=>P.activateProvider),E=Bt(P=>P.refreshModel),T=Bt(P=>P.refreshProviderModels);R.useEffect(()=>{function P(U){f.current&&!f.current.contains(U.target)&&(a(!1),u([]),w.current=new Set)}return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[]),R.useEffect(()=>{if(s){const P=k.map(U=>U.id);u(P),P.forEach(U=>{w.current.has(U)||(w.current.add(U),q(U))})}},[s,k]);const N=k.find(P=>P.id===y),L=(N==null?void 0:N.status)==="disconnected",A=S?S.split("/").pop()??null:null,D=A?(($=A.split("/").pop())==null?void 0:$.replace(/-/g," "))??A:"detecting...",B=(P,U)=>S?S===`${P}/${U}`:!1,q=async P=>{h(P);try{await T(P)}catch{}finally{h(null)}},W=P=>{l.includes(P.id)?u(l.filter(U=>U!==P.id)):(u([...l,P.id]),q(P.id))},O=async P=>{if(P.id===y){W(P);return}t?(n(P.id,void 0),Bt.getState().syncFromSession(P.id,""),a(!1),u([])):await b(P.id)&&(a(!1),u([]))},V=P=>{W(P)},G=async(P,U)=>{P.stopPropagation(),w.current.delete(U),await q(U)},z=(P,U)=>{m({providerId:P,model:U}),x(!0)},X=p?k.find(P=>P.id===p.providerId):void 0,ne=()=>{m(null),x(!1)},F=async P=>{try{if(!(await Ne(`/api/providers/${P.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:P.name,url:P.url,backend:P.backend,apiKey:P.apiKey,isLocal:P.isLocal,thinkingField:P.thinkingField,models:P.models})})).ok)throw new Error("Failed to update provider");for(const J of P.models){const Q={};if(J.contextWindow!==void 0&&(Q.contextWindow=J.contextWindow),J.supportsVision!==void 0&&(Q.supportsVision=J.supportsVision),J.thinkingEnabled!==void 0&&(Q.thinkingEnabled=J.thinkingEnabled),J.thinkingLevel!==void 0&&(Q.thinkingLevel=J.thinkingLevel),J.nonThinkingEnabled!==void 0&&(Q.nonThinkingEnabled=J.nonThinkingEnabled),J.thinkingExtraKwargs!==void 0&&(Q.thinkingExtraKwargs=J.thinkingExtraKwargs),J.nonThinkingExtraKwargs!==void 0&&(Q.nonThinkingExtraKwargs=J.nonThinkingExtraKwargs),Object.keys(Q).length>0&&!(await Ne(`/api/providers/${P.id}/models/${encodeURIComponent(J.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Q)})).ok)throw new Error(`Failed to update model: ${J.id}`)}await Bt.getState().fetchConfig()}catch{}m(null),x(!1)},M=async(P,U)=>{if(t){n(P,U),Bt.getState().syncFromSession(P,U),u([]),a(!1);return}h("activating");try{Bt.getState().syncFromSession(P,U),u([]),a(!1);const J=await Ne(`/api/providers/${P}/activate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:U})});if(J.ok){const Q=await J.json();Bt.getState().syncFromSession(Q.activeProviderId,Q.model)}}catch{}finally{h(null)}};return k.length===0?o.jsxs("button",{type:"button",onClick:()=>E(),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors group",title:L?"LLM server is offline. Click to retry.":A??"Click to refresh model",children:[L?o.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"LLM offline"}):o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-sm text-accent-primary",children:D}),o.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${N!=null&&N.isLocal?"text-accent-success bg-accent-success/10":"text-accent-warning bg-accent-warning/10"}`,children:N!=null&&N.isLocal?"local":"api"})]}),o.jsx("span",{className:"text-text-muted opacity-0 group-hover:opacity-100 transition-opacity",children:"↻"})]}):o.jsxs("div",{className:"relative",ref:f,children:[o.jsxs("button",{type:"button",onClick:()=>a(!s),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors group",title:"Click to switch provider or model",children:[L?o.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"offline"}):o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-sm text-accent-primary",children:D}),o.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${N!=null&&N.isLocal?"text-accent-success bg-accent-success/10":"text-accent-warning bg-accent-warning/10"}`,children:N!=null&&N.isLocal?"local":"api"})]}),o.jsx(Sr,{className:"w-3 h-3 text-text-muted transition-transform",rotate:s?180:0})]}),s&&o.jsxs("div",{className:"absolute bottom-full right-0 mb-1 w-72 bg-bg-secondary border border-border rounded-lg shadow-lg z-50 overflow-hidden max-h-[80vh] overflow-y-auto",children:[o.jsx("div",{className:"py-1",children:k.map(P=>{var U;return o.jsxs("div",{children:[o.jsxs("div",{className:`px-3 py-2 flex items-center justify-between ${P.id===y?"bg-bg-tertiary":"hover:bg-bg-tertiary"} ${v?"opacity-50 cursor-wait":"cursor-pointer"}`,children:[o.jsxs("div",{onClick:()=>!v&&O(P),className:"flex flex-col min-w-0 flex-1 cursor-pointer",children:[o.jsx("span",{className:`text-sm font-medium truncate ${P.id===y?"text-accent-primary":"text-text-primary"}`,children:P.name}),o.jsx("span",{className:"text-xs text-text-muted truncate",children:P.backend!=="unknown"&&ip(P.backend)})]}),o.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[P.id===y?o.jsx("span",{className:"text-accent-success",title:"Active",children:o.jsx(Mr,{className:"w-4 h-4"})}):o.jsx("span",{className:"w-4"}),o.jsx("button",{type:"button",onClick:J=>{J.stopPropagation(),G(J,P.id)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Refresh models",children:o.jsx(lp,{className:`w-4 h-4 ${c===P.id?"animate-spin":""} ${P.id===y?"text-accent-primary":"text-text-muted"}`})}),o.jsx("button",{type:"button",onClick:J=>{J.stopPropagation(),V(P)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Show models",children:o.jsx(Sr,{className:`w-4 h-4 transition-transform ${l.includes(P.id)?"rotate-180":""} ${P.id===y?"text-accent-primary":"text-text-muted"}`})})]})]}),l.includes(P.id)&&o.jsx("div",{className:"bg-bg-primary border-t border-border max-h-40 overflow-y-auto",children:c===P.id?o.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"Loading models..."}):(U=P.models)!=null&&U.length?P.models.map(J=>{var Q;return o.jsxs("button",{type:"button",onClick:()=>M(P.id,J.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":""} ${B(P.id,J.id)?"text-accent-primary":"text-text-secondary"}`,children:[o.jsx("span",{className:"truncate flex-1",children:((Q=J.id.split("/").pop())==null?void 0:Q.replace(/-/g," "))??J.id}),o.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[o.jsx("span",{className:"text-xs text-text-muted",children:e8(J.contextWindow)}),o.jsx("button",{type:"button",onClick:se=>{se.stopPropagation(),z(P.id,J)},className:"opacity-0 group-hover:opacity-100 p-0.5 hover:bg-bg-tertiary rounded transition-opacity",title:"Edit model context",children:o.jsx(bj,{className:"w-3 h-3 text-text-muted"})})]}),B(P.id,J.id)&&o.jsx("span",{className:"text-accent-success flex-shrink-0 ml-1",children:o.jsx(Mr,{className:"w-3.5 h-3.5"})})]},J.id)}):o.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"No models available"})})]},P.id)})}),o.jsx("div",{className:"border-t border-border px-3 py-2",children:o.jsx("button",{onClick:()=>e("/onboarding"),className:"text-xs text-accent-primary hover:underline",children:"Manage providers"})})]}),p&&_&&o.jsx(BC,{isOpen:!0,onClose:ne,onSave:F,initialStep:2,editProvider:{id:p.providerId,name:(X==null?void 0:X.name)??"",url:(X==null?void 0:X.url)??"",backend:(X==null?void 0:X.backend)??"unknown",apiKey:X==null?void 0:X.apiKey,isLocal:X==null?void 0:X.isLocal,thinkingField:X==null?void 0:X.thinkingField,models:X==null?void 0:X.models},editModelId:p.model.id})]})}function n8({input:e,setInput:t,attachments:n,setAttachments:s,dragOver:a,setDragOver:l,errorMessage:u,setErrorMessage:c,scrollContainerRef:h,sessionId:f,sessionMode:p,showHistory:m,history:_,selectedIndex:x,openHistory:w,closeHistory:k,navigateUp:y,navigateDown:S,selectCurrent:v,isAutoScrollActive:b,setAutoScroll:E,onOpenMessageSearch:T,onOpenCommandsModal:N,onOpenWorkflowsModal:L,onSelectWorkflow:A,onSelectWorkflowWithSubGroup:D,clearInput:B}){const q=R.useRef(null),W=R.useRef(null),O=R.useRef(0),V=Pu(),G=we(ee=>ee.sendMessage),z=we(ee=>ee.stopGeneration),X=we(ee=>ee.cancelQueued),ne=we(ee=>ee.queuedMessages),F=R.useCallback(()=>{const ee=q.current;if(!ee)return;const te=e.length>=O.current;O.current=e.length,te||(ee.style.height="auto"),ee.style.height=`${Math.min(200,ee.scrollHeight)}px`},[e]);R.useEffect(()=>{if(!f)return;const ee=`openfox:draft:${f}`,te=localStorage.getItem(ee);te!==null&&t(te)},[f,t]),R.useEffect(()=>{var ee;(ee=q.current)==null||ee.focus(),F()},[f,F]),R.useEffect(()=>{if(!f)return;const ee=`openfox:draft:${f}`,te=setTimeout(()=>{e?localStorage.setItem(ee,e):localStorage.removeItem(ee)},500);return()=>clearTimeout(te)},[f,e]),R.useEffect(()=>{F()},[e,F]),R.useEffect(()=>{const ee=q.current;if(!ee)return;const te=async ce=>{var Te;if(document.activeElement!==ee)return;const he=(Te=ce.clipboardData)==null?void 0:Te.items;if(he){for(const Ae of Array.from(he))if(Ae.type.startsWith("image/")){ce.preventDefault();const Le=Ae.getAsFile();if(!Le)continue;await xm(Le,Pe=>s([...n,Pe]),c,{filename:"pasted-image"})}}};return ee.addEventListener("paste",te),()=>ee.removeEventListener("paste",te)},[n,s,c]);const M=ee=>{ee.preventDefault(),!(!e.trim()&&n.length===0)&&(G(e,n.length>0?n:void 0),B())},$=ee=>{if(m)switch(ee.key){case"Enter":{ee.preventDefault();const te=v();te&&(t(te),k());return}case"Escape":ee.preventDefault(),k(),V&&z();return;case"ArrowUp":ee.preventDefault(),y();return;case"ArrowDown":ee.preventDefault(),S();return}if(ee.key==="ArrowUp"&&e.trim()===""&&!m){ee.preventDefault(),w();return}ee.key==="Enter"&&!ee.shiftKey&&(ee.preventDefault(),M(ee))},P=R.useCallback(async ee=>{const te=ee.target.files;if(!(!te||te.length===0)){c(null);for(const ce of Array.from(te))await xm(ce,he=>s([...n,he]),c);W.current&&(W.current.value="")}},[n,s,c]),U=R.useCallback(ee=>{ee.preventDefault(),ee.stopPropagation(),l(!0)},[l]),J=R.useCallback(ee=>{ee.preventDefault(),ee.stopPropagation(),l(!1)},[l]),Q=R.useCallback(async ee=>{ee.preventDefault(),ee.stopPropagation(),l(!1),c(null);const te=ee.dataTransfer.files;if(!(!te||te.length===0))for(const ce of Array.from(te))await xm(ce,he=>s([...n,he]),c)},[n,s,l,c]),se=R.useCallback(ee=>{s(n.filter(te=>te.id!==ee))},[n,s]),Y=R.useCallback(()=>{var ee;(ee=W.current)==null||ee.click()},[]),H=()=>{var ee;!e.trim()&&n.length===0||((ee=h.current)==null||ee.scrollTo({top:h.current.scrollHeight,behavior:"smooth"}),G(e,n),B())};return o.jsxs("form",{onSubmit:M,className:"relative p-2 md:p-4 bg-secondary",children:[V&&o.jsx("div",{className:"absolute -top-8 left-2 md:left-4 z-10",children:o.jsx(jB,{})}),o.jsxs("div",{className:"absolute -top-8 right-2 md:right-4 z-10 flex items-center gap-2",children:[o.jsxs("button",{type:"button",className:"text-sm text-text-muted hover:text-text-primary flex items-center gap-1.5 px-2 py-0.5 rounded hover:bg-bg-tertiary transition-colors",onClick:()=>E(!b),children:[b?o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-success"}):o.jsx(Sr,{className:"w-3 h-3 text-text-muted"}),b?"live":"scroll to bottom"]}),o.jsxs("button",{type:"button",onClick:T,className:"text-sm text-text-muted hover:text-text-primary flex items-center gap-1.5 px-2 py-0.5 rounded hover:bg-bg-tertiary transition-colors","aria-label":"Browse history",children:[o.jsx(cp,{}),"Browse history"]})]}),o.jsx("input",{ref:W,type:"file",accept:".png,.jpg,.jpeg,.gif",onChange:P,className:"hidden",multiple:!0}),u&&o.jsx("div",{className:"mb-2 p-2 bg-red-500/10 border border-red-500/50 rounded text-red-300 text-sm",children:u}),n.length>0&&o.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:n.map(ee=>o.jsx(kB,{attachment:ee,onRemove:se},ee.id))}),m&&o.jsx(EB,{history:_,selectedIndex:x,onSelect:ee=>{t(ee),k()},onEscape:k,onNavigate:ee=>{ee==="up"?y():S()}}),o.jsx(FB,{messages:ne,onCancel:X}),o.jsxs("div",{className:`flex items-end gap-3 p-3 rounded transition-colors ${a?"bg-accent-primary/10":"bg-primary"}`,onDragOver:U,onDragLeave:J,onDrop:Q,children:[o.jsx("textarea",{id:LS,ref:q,value:e,onChange:ee=>{t(ee.target.value),m&&k()},onKeyDown:$,placeholder:"What would you like to build?","data-testid":"chat-input-textarea",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 gap-1.5",children:[V&&o.jsxs("button",{type:"button",onClick:()=>z(),"data-testid":"chat-stop-button",className:"flex items-center gap-1 px-4 py-1.5 rounded bg-accent-error/20 text-sm text-accent-error font-medium hover:bg-accent-error/30 transition-colors whitespace-nowrap",children:[o.jsx(xS,{}),"Abort"]}),o.jsxs("div",{className:"flex items-center",children:[o.jsx("button",{type:"button",onClick:H,disabled:!e.trim()&&n.length===0,"data-testid":"chat-send-button",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($B,{onSendCommand:(ee,te,ce,he)=>{var Ae;te&&p!==te&&we.getState().switchMode(te);const Te=ce&&ce.trim()?`${ce.trim()}
|
|
296
296
|
|
|
297
297
|
${ee}`:ee;(Ae=h.current)==null||Ae.scrollTo({top:h.current.scrollHeight,behavior:"smooth"}),G(Te,he!=null&&he.length?he:void 0,{messageKind:"command",isSystemGenerated:!0}),B()},onSelectWorkflow:A,onSelectWorkflowWithSubGroup:D,onOpenCommandsManager:N,onOpenWorkflowsManager:L,onAttach:Y,textareaContent:e,attachments:n.length>0?n:void 0})]})]})]}),o.jsxs("div",{className:"mt-3 flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(YB,{}),o.jsx(XB,{})]}),o.jsx(t8,{})]})]})}function r8(e){return e==="criterion"||e==="session_metadata"}function s8(e){var t,n;return e.role!=="assistant"||e.subAgentId||(t=e.content)!=null&&t.trim()||(n=e.thinkingContent)!=null&&n.trim()||!e.toolCalls||e.toolCalls.length===0?!1:e.toolCalls.every(s=>r8(s.name))}function i8(e,t=[]){const n=[];let s=null,a=[],l,u=1;const c=new Map,h=new Map,f=[];for(const x of t)x.type==="message"?c.set(x.message.id,x):x.type==="subagent"?h.set(x.subAgentId,x):x.type==="criteria-batch"&&f.push(x);let p=0;const m=()=>{if(a.length>0){const x=f[p];x&&x.type==="criteria-batch"&&x.toolCalls.length===a.length&&x.toolCalls.every((k,y)=>{var S;return k.id===((S=a[y])==null?void 0:S.id)})?n.push(x):n.push({type:"criteria-batch",toolCalls:[...a]}),p++,a=[]}},_=()=>{if(!s)return;const x=s,w=h.get(x.subAgentId);w&&w.type==="subagent"&&w.messages.length===x.messages.length&&w.messages.every((y,S)=>y===x.messages[S])?n.push(w):n.push({type:"subagent",subAgentId:x.subAgentId,subAgentType:x.subAgentType,messages:x.messages}),s=null};for(const x of e)if(x.role!=="tool"){if(x.contextWindowId&&l&&x.contextWindowId!==l&&(m(),_(),u++,n.push({type:"context-divider",windowSequence:u})),l=x.contextWindowId,s8(x)){_();for(const w of x.toolCalls)a.push(w);continue}if(m(),x.subAgentId&&x.subAgentType)s&&s.subAgentId===x.subAgentId?s.messages.push(x):(_(),s={subAgentId:x.subAgentId,subAgentType:x.subAgentType,messages:[x]});else{_();const w=c.get(x.id);w&&w.type==="message"&&w.message===x?n.push(w):n.push({type:"message",message:x})}}return m(),_(),n}function a8(e){const{year:t,month:n,day:s}=PS(e);return`${t}/${n}/${s} ${Uu(e)}`}function o8(e,t){return e.length<=t?e:e.substring(0,t)+"..."}const l8=10,c8=150;function u8(e){const t=[];if(e.recentUserPrompts)for(const n of e.recentUserPrompts)t.push({id:n.id,content:n.content,timestamp:n.timestamp,sessionId:e.id,sessionName:e.title||e.id});return t}function d8(e){return[...e].sort((s,a)=>new Date(a.timestamp).getTime()-new Date(s.timestamp).getTime()).slice(0,l8).reverse().map(s=>({id:s.id,content:s.content,timestamp:s.timestamp,formattedTimestamp:a8(s.timestamp),trimmedContent:o8(s.content,c8),sessionId:s.sessionId,sessionName:s.sessionName}))}function h8(e,t,n){const s=[],a=e.filter(l=>l.role==="user"&&!l.isSystemGenerated&&l.messageKind!=="auto-prompt");for(const l of a)s.push({id:l.id,content:l.content,timestamp:l.timestamp,sessionId:n??"",sessionName:"This session"});for(const l of t)n&&l.id===n||s.push(...u8(l));return d8(s)}function f8(e,t=[],n=null){const[s,a]=R.useState(0),[l,u]=R.useState(!1),c=R.useMemo(()=>h8(e,t,n),[e,t,n]),h=R.useCallback(()=>{c.length>0&&(a(c.length-1),u(!0))},[c.length]),f=R.useCallback(()=>{u(!1),a(0)},[]),p=R.useCallback(()=>{a(x=>c.length===0?x:x===0?c.length-1:x-1)},[c.length]),m=R.useCallback(()=>{a(x=>c.length===0?x:x===c.length-1?0:x+1)},[c.length]),_=R.useCallback(()=>{if(c.length===0||!l)return null;const x=c[s];return(x==null?void 0:x.content)??null},[c,s,l]);return{history:c,selectedIndex:s,showHistory:l,openHistory:h,closeHistory:f,navigateUp:p,navigateDown:m,selectCurrent:_}}R.memo(function({item:t}){const[n,s]=R.useState(!1);return t.type==="start"?o.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-amber-500/10 border border-amber-500/30 rounded text-amber-300 text-sm",children:[o.jsx("span",{className:"animate-pulse",children:"●"}),o.jsx("span",{children:"Delegating image to fallback vision model..."}),t.filename&&o.jsxs("span",{className:"text-amber-400/70",children:["(",t.filename,")"]})]}):o.jsxs("div",{className:"flex items-start gap-2 px-3 py-2 bg-accent-success/10 border border-accent-success/30 rounded",children:[o.jsx("span",{className:"text-accent-success",children:"✓"}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("span",{className:"text-accent-success text-sm",children:"Image description done"}),o.jsx("button",{type:"button",onClick:()=>s(!n),className:"text-xs text-accent-primary hover:text-accent-primary/80 transition-colors",children:n?"Hide":"Show"})]}),n&&t.description&&o.jsx("div",{className:"mt-2 text-xs prose prose-invert prose-sm max-w-none",children:o.jsx(us,{content:t.description})})]})]})});function m8({criteriaSidebarOpen:e,onCriteriaSidebarToggle:t}={}){const n=e??!0,[s,a]=R.useState(""),[l,u]=R.useState([]),[c,h]=R.useState(!1),[f,p]=R.useState(null),[m,_]=R.useState(!1),[x,w]=R.useState(!1),[k,y]=R.useState(!1),[S,v]=R.useState(!1),[b,E]=R.useState(null),T=R.useRef(null),N=we(Se=>Se.currentSession),L=we(Se=>Se.messages),A=we(Se=>Se.streamingMessage),D=we(Se=>Se.sessions),B=we(Se=>Se.pendingQuestion),q=Pu(),W=we(Se=>Se.sendMessage),O=we(Se=>Se.acceptAndBuild),V=we(Se=>Se.stopGeneration),G=we(Se=>Se.launchRunner),z=mt(Se=>Se.defaults),X=mt(Se=>Se.userItems),ne=[...z,...X].filter(Se=>!Se.subagent),{history:F,selectedIndex:M,showHistory:$,openHistory:P,closeHistory:U,navigateUp:J,navigateDown:Q,selectCurrent:se}=f8(L,D,N==null?void 0:N.id);R.useEffect(()=>{const Se=me=>{E(me.detail.stats)};return window.addEventListener("open-turn-stats",Se),()=>window.removeEventListener("open-turn-stats",Se)},[]),R.useEffect(()=>{Et.getState().fetchWorkflows()},[]);const Y=R.useMemo(()=>A?L.map(Se=>Se.id===A.id?A:Se):L,[L,A]),H=R.useRef([]),ee=R.useMemo(()=>{const Se=i8(Y,H.current);return H.current=Se,Se},[Y]),{isAutoScrollActive:te,setAutoScroll:ce}=TC(T,N),he=R.useCallback(Se=>{var je;ce(!1);const me=document.querySelector(`[data-item-index="${Se}"]`);me&&(me.scrollIntoView({behavior:"smooth",block:"start"}),(je=me.closest('[data-testid="chat-scroll-container"]'))==null||je.scrollBy(0,-80))},[ce]);R.useEffect(()=>{const Se=me=>{const je=k||m||x||S||b;me.key==="Escape"&&q&&!je&&V(),me.key==="ScrollLock"&&ce(!te)};return window.addEventListener("keydown",Se),()=>window.removeEventListener("keydown",Se)},[q,V,te,k,m,x,S,b]);const Te=up();SS(Te.quickAction,()=>{y(!0)}),Uj(Te.agentSwitching,ne,Se=>{we.getState().switchMode(Se)});const Ae=(N==null?void 0:N.mode)==="planner",Le=(N==null?void 0:N.mode)==="builder",Pe=Se=>{const me=s.trim()?s:void 0,je=l.length>0?l:void 0;Ae?O(Se,me,je):Le&&G(me,je,Se),Ie()},de=(Se,me)=>{const je=s.trim()?s:void 0,nt=l.length>0?l:void 0;Ae?O(Se,je,nt,me):Le&&G(je,nt,Se,me),Ie()},Ie=()=>{a(""),u([]),N!=null&&N.id&&localStorage.removeItem(`openfox:draft:${N.id}`)};return o.jsxs(o.Fragment,{children:[o.jsxs(wT,{criteriaSidebarOpen:n,onCriteriaSidebarToggle:t,messages:Y,children:[B&&o.jsx(aB,{question:B}),o.jsx(ET,{}),b&&o.jsx(jT,{stats:b,onClose:()=>E(null)}),o.jsx(oB,{}),o.jsx(sB,{displayItems:ee,scrollContainerRef:T,highlightedMessageId:null}),o.jsx(n8,{input:s,setInput:a,attachments:l,setAttachments:u,dragOver:c,setDragOver:h,errorMessage:f,setErrorMessage:p,scrollContainerRef:T,sessionId:N==null?void 0:N.id,sessionMode:N==null?void 0:N.mode,showHistory:$,history:F,selectedIndex:M,openHistory:P,closeHistory:U,navigateUp:J,navigateDown:Q,selectCurrent:se,isAutoScrollActive:te,setAutoScroll:ce,onOpenMessageSearch:()=>v(!0),onOpenCommandsModal:()=>_(!0),onOpenWorkflowsModal:()=>w(!0),onSelectWorkflow:Pe,onSelectWorkflowWithSubGroup:de,clearInput:Ie}),o.jsx(LC,{isOpen:m,onClose:()=>_(!1)}),o.jsx(OC,{isOpen:x,onClose:()=>w(!1)}),o.jsx(yB,{isOpen:k,onClose:()=>y(!1),onSearchMessages:()=>v(!0),isAutoScrollActive:te,onToggleAutoScroll:ce,textareaContent:s,onCloseComplete:DS,onCloseCompleteAction:()=>window.dispatchEvent(new CustomEvent("open-session-dropdown")),onSelectCommand:async(Se,me)=>{const je=await nn.getState().fetchCommand(Se);if(je){const nt=me!=null&&me.trim()?`${me.trim()}
|
|
298
298
|
|